Testing things that involve dates or times
Many applications rely on datetime.datetime.now()
to create a timestamp. When we use this with a unit test, the results are essentially impossible to predict. We have a 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 avoid now()
and utcnow()
. Instead of using these directly, we can create a factory function that emits timestamps. For test purposes, this function can be replaced with one that produces known results. It seems awkward to avoid using the now()
method in a complex application.
Another option is to avoid direct use of the datetime
class entirely. This requires designing classes and modules that wrap the datetime
class. A wrapper class that produces known values for now()
can then be used for testing. This, too, seems needlessly complex.
How can we work with datetime
stamps?
Getting ready
We'll work with a small function that creates a CSV
file. This...