As the title says. I want to mock an imported function from a module. In this case the module is datetime and I want to mock datetime.datetime.now. I included what I've done without success.
# main.py:
import datetime
# cannot modify
def call_me(func):
return func()
class A:
variable = call_me(datetime.datetime.now)
# conftest.py:
import pytest
import datetime
FAKE_TIME = datetime.datetime.fromisoformat("2020-03-19T03:30:00")
@pytest.fixture(autouse=True)
def patch_datetime_now(monkeypatch):
class mydatetime(datetime.datetime):
@classmethod
def now(cls):
return FAKE_TIME
monkeypatch.setattr('datetime.datetime', mydatetime)
# test_main.py:
import datetime
from main import A
def test_main():
assert A.variable == datetime.datetime.now()
❯ pytest
------------------------------------------------------------------------------------
def test_main():
> assert A.variable == datetime.datetime.now()
E AssertionError: assert datetime.datetime(2020, 3, 19, 21, 32, 39, 861956) == datetime.datetime(2020, 3, 19, 3, 30)
I searched for a workaround for this and only found this question How to monkeypatch python's datetime.datetime.now with py.test?. The code included is just a minimal example of what I need. Basically I have an app who uses sqlalchemy.orm for saving data and a specific model have a default value for the date equal to datetime.datetime.now and I need to modify the date of the default value to be able to test it. The models are defined in other file.
Thank you for your help.
Aucun commentaire:
Enregistrer un commentaire