python runtime_error ai_generated true

AssertionError: assert '2026-03-01' == '2024-01-01' # datetime.now() not frozen inside test

ID: python/pytest-freeze-time-not-active

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-11-29First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

freezegun's freeze_time decorator patches datetime at import time, but the code under test imported datetime as 'from datetime import datetime', binding the original class before the patch. The patched module-level datetime is not used.

generic

中文

freezegun 的 freeze_time 装饰器在导入时补丁 datetime,但被测代码使用 'from datetime import datetime' 导入,在补丁之前就绑定了原始类。被补丁的模块级 datetime 未被使用。

Workarounds

  1. 92% success
    import datetime
    
    def get_date():
        return datetime.datetime.now().date()
  2. 88% success
    import time_machine
    from datetime import datetime
    
    @time_machine.travel('2024-01-01')
    def test_date():
        assert datetime.now().date().isoformat() == '2024-01-01'

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Time is not the issue; the reference is bound to the unpatched class regardless of duration.

  2. 70% fail

    time-machine also patches the datetime module; the pre-bound reference still points to the original.