This is the 4th time in a row that I’ve wasted time figuring out how to mock out a function
during testing that calls the chained methods of a datetime.datetime object in the
function body. So I thought I’d document it here. Consider this function:
# src.py
from __future__ import annotations
import datetime
def get_utcnow_isoformat() -> str:
"""Get UTCnow as an isoformat compliant string."""
return datetime.datetime.utcnow().isoformat()
How’d you test it? Mocking out datetime.datetime is tricky because of its immutable
nature. Third-party libraries like freezegun make it easier to mock and test functions
like the one above. However, it’s not too difficult to cover this simple case without any
additional dependencies. Here’s one way to achieve the goal: