This article will demonstrate how to with Python mock datetime now in unit testing. Unit testing is vital to any successful and robust software product, and having the ability to mock sections of your code is a critical part of that.
The use case for mocking datetime now in this article is that of SSL Certificate Objects in Python. Expiration dates are an important data point to test with certificates, but using certificate with validity periods in the near future will eventually break tests. So, it is necessary to change the dates of the tests to be much further in the future. Setting the date forward 100 years may just be pushing the problem out further, but what software product actually lives to be 100 years old anyway?
Where to use datetime.now()
Never use datetime.now() in the body of a method. While we shouldn’t say never, at least almost never use it in the body of a method. At least not if you are writing tests. There may be mock functions specific to python out there that will mock dates, but this example will provide an easy and convenient way to mock datetime now. That is simply write it as its own method, so that the method may later be mocked.
@staticmethod
def now() -> datetime.date:
"""Provide a method for now so that now can be mocked in testing
@return: datetime now
"""
return datetime.now()
In your code where you need to set now, simply call this method instead of calling datetime.now()
directly. When testing methods that call this method, you can mock the call to return whatever date in the future (or that past) that you need to.
MagicMock to mock a method call
Let’s assume the class where the now()
method is defined is called Run. The following code will mock the now()
function defined above when it is called in the Run
class.
run = Run()
run.now = MagicMock(return_value=datetime(2100,01,01)
That is it, the methods being tested that call now
will return the datetime set as the return_value
. This examples uses the MagicMock library of Python.
Conclusion – Python mock datetime now
This article has demonstrated how to mock datetime.now in Python. Let us know in the comments if you have any questions or would like to see more examples on how to mock dates or any other objects or methods in Python.
Leave a Reply