15.8 Testing things that involve dates or times
Many applications rely on functions like datetime.datetime.now() or time.time() to create a timestamp. When we use one of these functions with a unit test, the results are essentially impossible to predict. This is an interesting dependency injection problem here: our application depends on a class that we would like to replace only when we’re testing.
One option is to design our application to avoid functions like now(). Instead of using this method directly, we can create a factory function that emits timestamps. For test purposes, this function can be replaced with one that produces known results.
The alternative is called monkey-patching – injecting a new object at test time. This can reduce the design complexity; it tends to increase the test complexity.
In this recipe, we’ll write tests with datetime objects. We’ll need to create mock objects for datetime instances to create...