Stopping Time During Python Tests
When running unit tests in Python, it’s often the case that I need to “stop time” so that the current time remains the same during the entire execution of the test. For instance, in cases where I expect the result of a slow (networked) operation to return a value based on a creation time. If this creation process crosses into a new second, then the creation time of each of the objects will not be the same. This becomes a problem when there is latency associated either with the request to create the object or in the response after the object has been created (causing a potentially large difference between a the time the request was made and the time of the response). To compensate, I use a decorator for the unit test methods that need it.
Here’s the decorator function:
Here’s an example of usage in a unit test:
In this case,
b will be the same, thus demonstrating your awesome ability to alter the space-time continuum.
To further illustrate what’s occurring, here’s a picture of what you’re doing: