python type_error ai_generated true

TypeError: 无法设置内置/扩展类型 'datetime.datetime' 的属性

TypeError: can't set attributes of built-in/extension type 'datetime.datetime'

ID: python/pytest-freezegun-datetime-conflict

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-08-30首次发现

版本兼容性

版本状态引入弃用备注
1.5.x active

根因分析

freezegun 尝试 patch datetime.datetime,但某个 C 扩展模块(如 pandas、psycopg2)更早导入了 datetime 并持有 C 层引用,无法被 monkeypatch。

English

freezegun tried to patch datetime.datetime but a C-extension module (e.g. pandas, psycopg2) imported datetime earlier and holds a C-level reference that cannot be monkeypatched.

generic

解决方案

  1. 90% 成功率
    from unittest.mock import patch
    import mypkg.service
    
    @patch('mypkg.service.datetime')
    def test_now(mock_dt):
        mock_dt.utcnow.return_value = datetime(2024, 1, 1)
        ...
  2. 95% 成功率
    # service takes a clock=datetime.utcnow parameter
    def test_now():
        svc = Service(clock=lambda: datetime(2024, 1, 1))
        assert svc.today() == date(2024, 1, 1)

无效尝试

常见但无效的做法:

  1. 70% 失败

    Import order in tests does not control the order inside application code imported at collection time.

  2. 80% 失败

    Fails for the same reason: the C extension holds a direct reference to the built-in type.