I'm using pytest to perform testing in a Python project that uses the datetime.datetime class, datetime.datetime.now() function, and isinstance(time, datetime.datetime) check. Where time is a DateTime object and the now() function is patched.
The time variable is not mocked, however, isinstance(time, datetime.datetime) returns false. When printing type(time):
<class 'test_Itinerarios.patch_datetime_now.<locals>.mydatetime'>
How do I properly use pytest and __instancecheck__ to pass the instance(time, datetime.datetime) test?
The patch class is defined as:
Fake_time = datetime.datetime(2024,3,7,18,00)
real_datetime_class = datetime.datetime
@pytest.fixture
def patch_datetime_now(monkeypatch):
class mydatetime(datetime.datetime):
@classmethod
def __instancecheck__(cls, obj):
return isinstance(obj, real_datetime_class)
@classmethod
def now(cls):
return Fake_time
monkeypatch.setattr(datetime,'datetime',mydatetime)
EDIT
This is different from How to monkeypatch python's datetime.datetime.now with py.test? as that answer would fail at the instance(time, datetime.datetime) test. I need the mocked now() time to past the test. Also, I don't want/can import other libraries for the testing procedures.