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. The datetime
package must be tested separately and a replacement used when testing our application.
One option is to design our application to avoid now()
and utcnow()
. Instead of using these methods 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...