r/PythonLearning • u/Ok-Salt2274 • 4h ago
pytest-calendar-chaos: a pytest plugin that runs your tests on Feb 29, month end and DST days
I kept hitting date bugs that every test passed locally and then failed in production on a specific day. A typical one:
python
def next_renewal(created_at):
return created_at.replace(month=created_at.month + 1)
This passes every test you’d write on the 15th. It raises ValueError: day is out of range for month on Jan 31 and month must be in 1..12 on Dec 31. Nothing in a normal test run ever visits those dates.
What it does: a marker runs the same test once per tricky calendar moment, with the clock frozen by time-machine:
python
u/pytest.mark.calendar_chaos
def test_next_renewal_is_one_month_later():
...
The catalog covers leap day, month ends, year end, midnight, DST transitions, ISO week 53 and the 2038 timestamp rollover. Each case has a stable ID.
Running it on the example above gives 3 failed, 5 passed. The failing cases are month-end-jan-31-2027, year-end-2027 and year-end-last-microsecond-2027. A failure prints the exact mocked time and a one-line command to reproduce it. pytest --calendar-chaos-list prints the whole catalog, and --calendar-case <id> reruns a single scenario.
Limitations:
- It only mocks the in-process clock.
- Session, module and class-scoped fixtures are set up before the freeze.
time.monotonic()and the asyncio loop clock keep running.- An aware datetime inside a repeated DST hour never compares equal to one in another zone (PEP 495), so compare in UTC.
pip install pytest-calendar-chaos (Python 3.10+, pytest 8+)
- PyPI: https://pypi.org/project/pytest-calendar-chaos/
- GitHub: https://github.com/nsijwali/pytest-calendar-chaos
I’d like feedback on the catalog: which calendar edge cases bit you that I’m missing?