python
runtime_error
ai_generated
true
AssertionError: assert '2026-03-01' == '2024-01-01' # 测试内 datetime.now() 未被冻结
AssertionError: assert '2026-03-01' == '2024-01-01' # datetime.now() not frozen inside test
ID: python/pytest-freeze-time-not-active
80%修复率
83%置信度
0证据数
2024-11-29首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.x | active | — | — | — |
根因分析
freezegun 的 freeze_time 装饰器在导入时补丁 datetime,但被测代码使用 'from datetime import datetime' 导入,在补丁之前就绑定了原始类。被补丁的模块级 datetime 未被使用。
English
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.
解决方案
-
92% 成功率
import datetime def get_date(): return datetime.datetime.now().date() -
88% 成功率
import time_machine from datetime import datetime @time_machine.travel('2024-01-01') def test_date(): assert datetime.now().date().isoformat() == '2024-01-01'
无效尝试
常见但无效的做法:
-
80% 失败
Time is not the issue; the reference is bound to the unpatched class regardless of duration.
-
70% 失败
time-machine also patches the datetime module; the pre-bound reference still points to the original.