feat: add MockNow option for deterministic now() in tests - #986
Open
ChrisJr404 wants to merge 1 commit into
Open
feat: add MockNow option for deterministic now() in tests#986ChrisJr404 wants to merge 1 commit into
ChrisJr404 wants to merge 1 commit into
Conversation
Add a WithNow patcher that replaces now() calls with a fixed time, exposed via the expr.MockNow option. This makes it easy to test expressions that depend on now() by getting deterministic results, without having to write a custom patcher or disable the builtin. It composes with Timezone. Closes expr-lang#754
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #754.
now()makes expressions hard to test because it returns a different value on every run. As suggested in the issue, this adds a small patcher (following theWithTimezonepattern) plus a public option sonow()can be pinned to a fixed time.Usage
The compiled program now always sees that fixed time for
now(), so tests are deterministic. No boilerplate patcher and no need toDisableBuiltin("now")+ re-register a function.What's included
patcher.WithNow— replacesnow()builtin calls with a constant time node while patching the AST.expr.MockNow(t time.Time)— the public option wiring the patcher, mirroringexpr.Timezone.Timezone: if a location was injected intonow(), the fixed time is returned in that location.docs/configuration.md.Notes
now().Year()), and theTimezone+MockNowcombination.go build,go vet, andgo test ./ ./patcher/ ./builtin/ ./checker/pass. (test/examplesfails to build on a cleanmastertoo — unrelated to this change.)