Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow mockable/predictable now() #754

Open
rossb83 opened this issue Feb 16, 2025 · 5 comments
Open

Allow mockable/predictable now() #754

rossb83 opened this issue Feb 16, 2025 · 5 comments
Labels

Comments

@rossb83
Copy link

rossb83 commented Feb 16, 2025

Its hard to test out programs that rely on time for example:

now().Sub(StartTime) >= 40*duration("24h")

Would it be possible to allow a testing option for now() to give a predictable/settable time?

@antonmedv
Copy link
Member

What about a patcher what will replace now with date function calls?

@rossb83
Copy link
Author

rossb83 commented Feb 18, 2025

So yes something like that would do what I want. What about an option like expr.MockNow(time.UnixMilli(1739840603000)) to sort of hide the complexity/boilerplate vs below?

type nowPatcher struct {
	curr time.Time
}

func (p *nowPatcher) Visit(node *ast.Node) {
	if builtinNode, ok := (*node).(*ast.BuiltinNode); ok {
		if builtinNode.Name == "now" {
			ast.Patch(node, &ast.ConstantNode{
				Value: p.curr,
			})
		}
	}
}

@antonmedv
Copy link
Member

Make sense. I will add a helper.

@rossb83
Copy link
Author

rossb83 commented Feb 18, 2025 via email

@antonmedv
Copy link
Member

Sure! Please take a look at already existing patchers: https://github.com/expr-lang/expr/tree/master/patcher and follow similar semantic with naming and etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants