I'd like to make sure that datetime.datetime.now() returns a specific datetime for testing purposes, How do I do this? I've tried with pytest's monkeypatch

monkeypatch.setattr(datetime.datetime,"now", nowfunc)

But this gives me the error TypeError: can't set attributes of built-in/extension type 'datetime.datetime'

有帮助吗?

解决方案

As the error tells you, you can't monkeypatch the attributes of many extension types implemented in C. (Other Python implementations may have different rules than CPython, but they often have similar restrictions.)

The way around this is to create a subclass, and monkeypatch the class.

For example (untested, because I don't have pytest handy… but it works with manual monkeypatching):

class patched_datetime(datetime.datetime): pass
monkeypatch.setattr(patched_datetime, "now", nowfunc)
datetime.datetime = patched_datetime

其他提示

You can't, as the error shows. If you need to do this, you'll need to change the code under test so that it has a utility function that calls datetime.datetime.now(), and change all the references to point to that function instead. Then, you can monkeypatch that function to return a time of your choice.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top