How is monkeypatch inline function datetime.datetime.now?

I would like to make sure datetime.datetime.now() returns a specific time-time for testing purposes, how to do this? I tried with pytest monkeypatch

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

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

+7
source share
2 answers

As it informs you of the error, you cannot secure the attributes of many types of extensions implemented in C. (Other Python implementations may have different rules than CPython, but they often have similar limitations.)

A way to create a subclass is monkeypatch.

For example (untested, because I don't have pytest handy ... but it works with manually switching to monkey):

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

You cannot, as the error shows. If you need to do this, you will need to modify the test code so that it has a utility function that calls datetime.datetime.now() , and instead changes all the links to point to this function. Then you can disable this function to return the time of your choice.

+1
source

All Articles