Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monkeypatch builtin function datetime.datetime.now?

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'

like image 998
bigblind Avatar asked Apr 19 '13 19:04

bigblind


1 Answers

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
like image 89
abarnert Avatar answered Sep 26 '22 00:09

abarnert