chrono icon indicating copy to clipboard operation
chrono copied to clipboard

Better support for test cases: Overriding the current time

Open peteringraham opened this issue 8 years ago • 4 comments

Apologies if there's already a good solution for this out there. This is more a feature request than a bug.

In a test, it's nice to force certain dates to be returned. Sure, you can do something like add an "overrideTime" variable, set it in tests, then do this every time you'd check the time:

let current_time : i64 ; if !overrideTime { current_time = UTC::now().timestamp(); } else { current_time = forced_timestamp; }

But meh. It'd be nicer if instead there was a function similar to, say, JODA setCurrentMillisFixed : http://joda-time.sourceforge.net/api-release/org/joda/time/DateTimeUtils.html#setCurrentMillisFixed(long)

So then you'd have something like:

[test]

fn test_that_requires_a_specific_time() { // This time is 2017-02-28T10:00Z UTC::setFixed(1488276000); // UTC::now() will now lie and always return the above value. ... }

And then include a setCurrentMillisSystem() that undoes the above, for all that it'd be rarely called.

Alternatively: create a provider class, and then have it understood that classes should only ever ask the provider for the time rather than making raw now() calls. e.g. Clock has a getTime() call, and it's implemented by SystemClock & FakeClock. System Clock calls now() like normal, but if you pass in a FakeClock in a test, then that FakeClock can do whatever craziness you want. This is a bit more powerful since now people can write FakeClocks that, say, actually run forward but from a set date or the like.

peteringraham avatar Oct 28 '16 17:10 peteringraham

I don't think the process-global mock is not a good way to test time-dependent procedures. In principle you should be able to retrieve a fn() -> DateTime<UTC> or similar, which defaults to UTC::now but can be customized. There is no need for additional traits, just a function pointer.

lifthrasiir avatar Oct 30 '16 12:10 lifthrasiir

Any news on this?

pickfire avatar May 24 '20 16:05 pickfire

Just created https://github.com/mseravalli/chrono-timesource, this should allow users to set the time outside the business logic. There probably other solutions, but this should be quite easy to adopt. Probably need to rename it to Clock, which might be more standard.

mseravalli avatar Jan 04 '24 21:01 mseravalli

Does the mock function support tokio multi-thread async function?I doubt it not.

chianquan avatar Jun 27 '24 08:06 chianquan