'How to doctest functions with volatile output?
By the time the doctest is run, the volatile output is different thus the test fails. Ideally (but not necessarily), the solution should try to avoid to write testable code outside the docstring in order to avoid impacting the test coverage.
from datetime import datetime
def get_now():
"""
>>> get_now()
datetime.datetime(2018, 3, 13, 20, 26, 44, 258862)
"""
return datetime.now()
Solution 1:[1]
You want to assert than an effect occurred, so you should patch datetime and assert that now was called.
This is untested and may not work, but should illustrate the idea:
from datetime import datetime
def get_now():
"""
>>> from unittest import mock
>>> my_module.datetime.now = lambda: datetime(2018, ...)
>>> get_now()
datetime.datetime(2018, ...)
"""
return datetime.now()
Solution 2:[2]
One way is to expose a "private" _now parameter. For example:
def get_now_year(_now: datetime | None = None) -> int:
"""
>>> from datetime import datetime
>>> now = datetime.datetime(2018, 3, 13, 20, 26, 44, 258862)
>>> get_now_year(_now=now)
2018
"""
now = _now if _now is not None else datetime.now()
return now.year
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | munk |
| Solution 2 | Mateen Ulhaq |
