145 points · by ingve · 2y ago · 139 comments
Define an interface for timers, which is injected into the object that depends on time. Use a wrapper implementation over the usual timer for the real code; and a simple implementation, which can be controlled parametrically, in the tests.
The best approach is separating the calling of the external dependency (getting the time) to it's own function, and pass in the results of that call to your main function. Then test your main function. Ie approach 5. This eliminates the need for mocks and creates better factored code.
There's usually a solution of some sort, it might just require a bit of rearranging and extraction of concerns.
That is the FP maximalist approach and many of us reject it.
So no, it is not the best approach.
We use a time provider interface and mock it, and have zero problems with this approach.
People generally call time functions, and a good testing setup should keep your code the same (or mostly the same).
Anything else makes testing less approachable, and requires extra time from developers.
The provider and mocking (or a fake if you got one) approach is probably the best you can get with most programming languages.
If you have code you need to run, but has no control over (such as a database library), then you will have issues.
For example, you want to test that an entry in a caching library is indeed expiring entries like you wanted. How do you change the library to consume a time interface, if that library doesn't expose it to you?
If you have first-party code that is adjacent to a third-party library in a way that the library hinders testing of that first-party code, you would substitute a (minimal) implementation that you control in for the third-party library while under test.
If the library is open source or similarly code accessible, you would fork it or coordinate control with its stakeholders to see the testing of it in that codebase (and refactor it as necessary to support that). This is where the library needs to ensure it does what the documentation claims. It is not the concern of your application.
Otherwise, if the code is truly beyond your reach, you just have to trust that the vendor's claims are true. If you cannot establish that trust, use a different library that you can trust. Testing concerns are the least of your problems when you have no trust for the library you are using.
Testing third-party code is often well within the purview of first-party integration testing. Aside from validating your code, and your understanding of the documentation, these sometimes incidentally catch third-party bugs. Working around bugs until upstream fixes their code may also be within the purview of first-party code... and perhaps catching regressions even if they've supposedly been fixed.
> Otherwise, if the code is truly beyond your reach, you just have to trust that the vendor's claims are true. If you cannot establish that trust, use a different library that you can trust. Testing concerns are the least of your problems when you have no trust for the library you are using.
We unit test our code because we can't even trust ourselves - nevermind our coworkers, nevermind third party vendors. Granted, unit tests for third party libraries are often worth upstreaming, and you may trust upstream enough to delete your downstream copies of those unit tests once you do...
What's the point of your home-made timer if it doesn't faithfully emulate the actual clock that's going to be used in your actual program? How will you have confidence that your tests are even doing anything useful?
There are plenty of things that might be out of your control. If you try to emulate time. For example, the system, when using a realistic timer may decide to do some context switches, seeing how your code is blocking waiting on some wakeup event, while if you test against a timer that tries to speed things up those context switches won't happen. And there could be plenty examples of similar things.
If not, then how are you going to implement your home-made timer? Is your home-made timer going to be an actual timer (i.e. it will have to read time, thus relying on third-party code to do it) or will it pretend that time doesn't exist (and thus test something different from what your code is actually supposed to do)?
Your ideas about "substituting" system clock with hand-written code are out of reach for most developers out there. Even those who theoretically could embark on such a task probably won't because that's just too much effort.
What I'm getting at: the whole idea of mocking time for testing is a fool's errand. You'll be testing things that you don't actually need and won't be testing that actually need testing.
$ faketime 'last friday 5 pm' sh -c "/bin/date; sleep 5; /bin/date" Fri 15 Dec 2023 17:00:00 GMT Fri 15 Dec 2023 17:00:05 GMT
Intercepting/hooking system APIs might be an option in some cases. You might even be able to use something someone else wrote. Some prior art for date/time stuff specifically (which I haven't used and thus can't vouch for:)
• https://manpages.ubuntu.com/manpages/trusty/man1/datefudge.1...
• https://www.nirsoft.net/utils/run_as_date.html
More dynamic / finer grained hooking (e.g. perhaps targeting a single thread, within a function's scope, because you're not writing a command line tool that quickly exits) is likely to require a more manual touch.
The approaches I have seen used in practical projects is:
Ignore unit testing of time-related parts, rely on integration tests.
Have unit tests be super slow so that actual system clock can be used. Get occasional false positive failures when your build system scheduled unit tests in parallel with particularly complex compilation tasks.
Wrap everything in your own wrapper, providing "production" and "testing" version of class, which "production" calling into the 3rd party library while "testing" calls into your implementation that uses debug time. This is non-trivial as "testing" implementation might be quite complex, but may be worth it for some common functionality like timers.
In our main application we pass in a function that returns `time.Now()`, and in tests we pass in a function that returns whatever time object we want.
Oh no... not at all. Here are some examples of when your approach turns out to be worthless:
* Performance testing, eg. looking for memory leaks. It doesn't matter how your timer ticks, what matters is that over time the system performance degrades.
* Any kind of hardware testing that relies on sensory input that is time-gated.
* Even "simple" stuff like testing software that does eg. desktop video recording. Still, you cannot substitute the wall clock with whatever timer you will come up with. I mean, in all those cases you "sort of" can, but that will render your tests worthless.
* Of course your home-made timers will prove useless if the tested software has third-party components that don't care about your timers.
Of course some cases can be handled by what you described, but, in my experience, when code works with time, the tests need to concentrate on special cases and those are usually hard to impossible to emulate through home-made timers. Or, they would benefit tremendously from time being real rather than a "surrogate".
All contact with outside world should happen through interfaces with replaceable implementation.
If you care about time related stuff, this should also include time, timers, schedulers, etc.
Make sure you don't circumvent the interfaces by accident. There are stupid ways to do so like getting current time in SQL or embedding current time in new objects by default.
I was confused why a passed-in timestamp would have less granularity than the return value of gettime() (or whatever) directly. The issue isn’t a loss of /precision/, but a loss of /accuracy/ due to added latency between observing the time outside the function and making the decision within the function.
* https://centrumdruku3d.pl/jak-zrozumiec-roznice-pomiedzy-dok...
* https://automatykab2b.pl/technika/54301-dokladnosc-i-precyzj...
* https://learn.microsoft.com/pl-pl/office/troubleshoot/access...
* https://pl.wikipedia.org/wiki/Dok%C5%82adno%C5%9B%C4%87_i_pr...
etc.
Here's an image that explains the difference pretty succintly: https://www.antarcticglaciers.org/wp-content/uploads/2013/11...
around { |example| Timecop.freeze("2023-12-20T12:00:00Z".to_datetime) { ex.run } }
or around { |example| travel_to("2023-12-20T12:00:00Z".to_datetime) { ex.run } }
as setup hooks to your tests and it stubs all of the relevant datetime helpers for you for each test case and properly restores everything between tests.However, one constraint was that I needed to also run this on existing data. Which led to me instead passing in time. A small thing, but suddenly this logic beame so incredibly testable. I can call it 5 times with 5 different times and see that it behaves as expected, or simulate it over a whole day of test data. Even tweak the code a bit, delete the data it generates in prod, and re-run it with the new ruleset. So flexible.
Such a small thing, but without the additional constraint I probably wouldn't have arrived at this design.
Isn't this a solved problem viz moving side effects like IO (getting the time) out of the logic parts and just unit/property testing those? Am I missing something here?
EDIT: added last sentence
Yep, and it delivers even more than what was asked, because now you can test "code that depends on X", not just time.
Why it hasn't gained much traction is the camp of coders who will "want to make it simpler" by removing such indirection and making the code ask for the time directly.
On Python, just use freezegun to inject controllable timestamps in response to calls to time methods.
https://github.com/travisjeffery/timecop
Dynamic languages have the advantage to be able to rewrite the standard library classes at runtime.
I don’t think that works anymore, but at the time I could create plain value objects and later make them class instantiations (on a small system way back when, this was a nice speed up due to a now uncommon pattern of having data first and waiting for the classes to load).
See other comments in the thread about libfaketime.
Anything which relies on time coming in as an implicit variable as internal state is doomed to have legions of undebuggable problems.
Waiting for a set amount of time (i.e. literally calling to wait(5) in the test code) is slow and, even worse than that, flaky. If the test server is busy it might take it longer than 5 seconds to do what the test needs to happen.
The best approach I have found so far is “pulling for the side effects” (i.e. if the test is awaiting the creation of a flobber object, keep pulling the list of flobber objects until a new one pops up). This is not always possible (the interface for pulling the flobber objects is not always available) and it is also inconsistent with multiple threads/processes(one thread might have the new flobber and tell your test that everything is ok, but the next step in the test you happen to be served by a different thread which doesn’t have the new flobber yet).
1. libfaketime
2. Make the test resilient to changing time
3. Dependency inject at an even higher level
Reserve Time.now or its equavlent to jobs, controllers, or what not at the edge of your application.
Watch out when using NOW() in your db. Not that you shouldn’t but it might be surprising when you do.
Would you be so kind as to elaborate on this?
It was always my thought that NOW() was the more sensible approach as it would capture time in the execution order from a more centralized source (the db server). Where having the origin of a transaction setting at time would get me when, on the origin server the query was initiated.
We use dependency injection wherever the service is required.
With this, we can manage 2 things
1. The service can go faster or slower than the real time by changing the timer's interval so we can simulate time depend behaviour in the app while testing.
2. We can mock the service when testing with a simple counter that's increased each time “.now()" is called.
https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotn...
Though most people were rolling their own version of it before this.
The standard §13.9.4 says:
> If a template [...] is explicitly specialized, a declaration of that specialization shall be reachable from every use of that specialization that would cause an implicit instantiation to take place
What's going to happen in practice is the compiler will instantiate and inline the unspecialized template in the library, and the program will silently not use the mock time. Or not, it's entirely unconstrained.
Most of the time usage need to advance time in controlled fashion. So you'll need to create a shell wrapper that runs faketime with correct FAKETIME_TIMESTAMP_FILE value, hook it up to your build system, create C++ wrapper to write to this file... If you are controlling source code, adding a "time" argument might be easier to implement and easier to understand.
My library modifies the code for the time-related vDSO functions, which is incredibly sketchy yet effective. There are also Python bindings at [1].
Stub out the calls responsible for reading system clock, then set it deterministically, and advance it programmatically where a test depends on the passage of time. This works really well, reads really well in the source, and allows to test general cases and edge cases equally easily.
And a "wall clock" or "test clock" injected using DI as needed. (equivalent to option 1 + 4)
Write your own "test clock" or use the supplied fake: (2)
In earlier versions, we rolled our own "clock" interface.
1) https://learn.microsoft.com/en-us/dotnet/api/system.timeprov...
2) https://learn.microsoft.com/en-us/dotnet/api/microsoft.exten...
This would correspond to option 3 in the blog post, except instead of clock factory you redefine individual methods.
Yes.
>`current_time` says exactly what it is needed for.
Not always.
ref: https://stackoverflow.com/questions/36997351/using-a-templat...
So not very sure how to elegantly inject our mock into the main code via the test section.
What I was hoping for was something like simulations or UIs/games. Complex user interactions like "Sarah clicked here, waited a few seconds, then clicked this, then waited for a network request to finish..."
So you are effectively testing code that will never see the light in Production. That's called a Mock and some people hate mocks.
I have no problem against it taking for granted the actual lib has its own tests.
In dynamic languages you can mock anything, even parts that are not designed to be customizable. This indeed has the effect of calcifying implementation details, as mocks don't test a public interface. I think it's harder in this environment to stay disciplined and use mocking in moderation, as the friction to only mock public interfaces is not there.
I definitely saw this in C++ vs Python mocking, mocking tends to be way overused in Python testing.
Don't worry to much about them.
Mocks are perfectly OK.
It is like putting a mechanical device in a jig for a durability test or the exhaust extractors that mechanics use when they run engines inside the workshop.
Or, unless they are expensive, just keep them. The code doesn't change so they won't break.
But for the next maintainer they will tell them a lot. One particularly nice thing about some code I maintained recently was that it allowed me to run through different scenarios in my debugger even during my first days in that code base.
Also I don't think I will ever again assume that some code that is in production will never change.
This also made it trivial to replay logs to the application and get back in the exact same state, which is great for debugging of course.
Testing code that depends on time is very complicated, and solutions aren't about whether you have factory methods or use C++ templates. That's by and large irrelevant. To the best of my knowledge there isn't any strategy that would handle all aspects of testing time-sensitive code. The goals and means are very different between different test cases.
I wouldn't even dare to try to catalogue all the possible problems with testing time-sensitive programs... this is just too big of a subject to try to cover in few paragraphs.
Makes testing trivial and operative code trivial