{
  "$type": "site.standard.document",
  "canonicalUrl": "https://rednafi.com/python/mocking-datetime-objects/",
  "description": "Mock chained datetime methods in Python tests using unittest.mock to handle immutable datetime objects without external dependencies.",
  "path": "/python/mocking-datetime-objects/",
  "publishedAt": "2022-03-16T00:00:00.000Z",
  "site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
  "tags": [
    "Python",
    "Testing",
    "Pytest"
  ],
  "textContent": "This is the 4th time in a row that I've wasted time figuring out how to mock out a function\nduring testing that calls the chained methods of a datetime.datetime object in the\nfunction body. So I thought I'd document it here. Consider this function:\n\nHow'd you test it? Mocking out datetime.datetime is tricky because of its immutable\nnature. Third-party libraries like [freezegun] make it easier to mock and test functions\nlike the one above. However, it's not too difficult to cover this simple case without any\nadditional dependencies. Here's one way to achieve the goal:\n\nHere, the mock_datetime fixture function makes the output of the chained calls on the\ndatetime object deterministic. Then I used it in the test_get_utcnow_isoformat function to\nget a frozen output every time the function get_utcnow_isoformat gets called. If you run\nthe above snippet with Python, it'll pass.\n\nFurther reading\n\n- [Python test using mock with datetime.utcnow - Stackoverflow]\n\n\n\n\n[freezegun]:\n    https://github.com/spulec/freezegun\n\n[python test using mock with datetime.utcnow - stackoverflow]:\n    https://stackoverflow.com/questions/57671585/python-test-using-mock-with-datetime-utcnow",
  "title": "Mocking chained methods of datetime objects in Python"
}