python runtime_error ai_generated partial

AssertionError: assert datetime.datetime(2025, 1, 1, 0, 0) == datetime.datetime(2024, 6, 1, 12, 0)

ID: python/pytest-freeze-time-inconsistent

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-01-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.4.x active — — —
1.5.x active — — —

Root Cause

freezegun's freeze_time doesn't patch datetime in C extensions, or the code uses time.monotonic / time.time_ns which freezegun doesn't override by default.

generic

中文

freezegun 的 freeze_time 未修补 C 扩展中的 datetime,或代码使用 time.monotonic / time.time_ns,而 freezegun 默认不覆盖这些。

Workarounds

  1. 85% success
    import time
    from freezegun import freeze_time
    
    def test_x(monkeypatch):
        with freeze_time('2025-01-01'):
            monkeypatch.setattr(time, 'monotonic', lambda: 0.0)
            assert run() == expected
  2. 92% success
    class Clock:
        def now(self): return datetime.now(timezone.utc)
    
    def test_x():
        c = Clock()
        with freeze_time('2025-01-01'):
            assert c.now().year == 2025

Dead Ends

Common approaches that don't work:

  1. 70% fail

    tick advances time by real elapsed seconds but doesn't patch C-level time functions; the mismatch persists.

  2. 65% fail

    Module-level freeze doesn't reach C extensions or subprocesses; portions still read the real clock.