如何monkeypatch内置函数datetime.datetime.now?

big*_*ind 9 python datetime unit-testing monkeypatching pytest

我想确保datetime.datetime.now()返回一个特定的日期时间用于测试目的,我该怎么做?我试过pytest的monkeypatch

monkeypatch.setattr(datetime.datetime,"now", nowfunc)
Run Code Online (Sandbox Code Playgroud)

但这给了我错误 TypeError: can't set attributes of built-in/extension type 'datetime.datetime'

aba*_*ert 9

正如错误告诉您的那样,您无法对C中实现的许多扩展类型的属性进行monkeypatch.(其他Python实现可能具有与CPython不同的规则,但它们通常具有类似的限制.)

解决这个问题的方法是创建一个子类,猴补丁的.

例如(未经测试,因为我没有pytest方便...但它适用于手动monkeypatching):

class patched_datetime(datetime.datetime): pass
monkeypatch.setattr(patched_datetime, "now", nowfunc)
datetime.datetime = patched_datetime
Run Code Online (Sandbox Code Playgroud)