expr icon indicating copy to clipboard operation
expr copied to clipboard

Allow mockable/predictable now()

Open rossb83 opened this issue 11 months ago • 6 comments

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?

rossb83 avatar Feb 16 '25 16:02 rossb83

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

antonmedv avatar Feb 16 '25 20:02 antonmedv

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,
			})
		}
	}
}

rossb83 avatar Feb 18 '25 03:02 rossb83

Make sense. I will add a helper.

antonmedv avatar Feb 18 '25 08:02 antonmedv

If you agree this is a good idea I can open a PR for your approval.

On Tue, Feb 18, 2025 at 3:07 AM Anton Medvedev @.***> wrote:

Make sense. I will add a helper.

— Reply to this email directly, view it on GitHub https://github.com/expr-lang/expr/issues/754#issuecomment-2664881874, or unsubscribe https://github.com/notifications/unsubscribe-auth/AARSZC2WDT7M2N4LDZRSDK32QLS3VAVCNFSM6AAAAABXHXEB52VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRUHA4DCOBXGQ . You are receiving this because you authored the thread.Message ID: @.***> [image: antonmedv]antonmedv left a comment (expr-lang/expr#754) https://github.com/expr-lang/expr/issues/754#issuecomment-2664881874

Make sense. I will add a helper.

— Reply to this email directly, view it on GitHub https://github.com/expr-lang/expr/issues/754#issuecomment-2664881874, or unsubscribe https://github.com/notifications/unsubscribe-auth/AARSZC2WDT7M2N4LDZRSDK32QLS3VAVCNFSM6AAAAABXHXEB52VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRUHA4DCOBXGQ . You are receiving this because you authored the thread.Message ID: @.***>

rossb83 avatar Feb 18 '25 10:02 rossb83

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.

antonmedv avatar Feb 18 '25 10:02 antonmedv

Mocking time can be done in many ways, it may be hard to replicate every possible use case. Why not just use expr.DisableBuiltin("now"), expr.Function("now", /* your mocking approach here ... */) in your tests?

diegommm avatar Jul 02 '25 18:07 diegommm