TL; DR
If you mock like this, you can mock datetime.datetime.now ()
. This way you can use the other functions of datetime.datetime
as they are.
from unittest.mock import MagicMock
def test_mocking_datetime_now(monkeypatch):
datetime_mock = MagicMock(wrap=datetime.datetime)
datetime_mock.now.return_value = datetime.datetime(2020, 3, 11, 0, 0, 0)
monkeypatch.setattr(datetime, "datetime", datetime_mock)
When testing the process of getting the current time, you may want to mock datetime.datetime.now ()
. At this time, even if you simply try to mock with monkeypatch.setattr
, you cannot mock becausedatetime.datetime.now ()
is built-in.
import datetime
from unittest.mock import MagicMock
FAKE_NOW = datetime.datetime(2020, 3, 11, 0, 0, 0)
def test_mocking_datetime_now_incorrect(monkeypatch):
monkeypatch.setattr(datetime.datetime, "now", MagicMock(return_value=FAKE_NOW)
> monkeypatch.setattr(datetime.datetime, "now", MagicMock(return_value="hoge"))
E TypeError: can't set attributes of built-in/extension type 'datetime.datetime'
Therefore, use MagicMock (wrap = ...)
. You can specify the object to mock in the wrap argument and mock the required method while flowing the normal method to the wrapped object.
from unittest.mock import MagicMock
def test_mocking_datetime_now(monkeypatch):
# now()Only mocked datetime_Create mock
datetime_mock = MagicMock(wrap=datetime.datetime)
datetime_mock.now.return_value = datetime.datetime(2020, 3, 11, 0, 0, 0) #Now now()Mock
# datetime.datetime to datetime_Replaced with mock
monkeypatch.setattr(datetime, "datetime", datetime_mock)
#Below, datetime.datetime.now()Test using
Top answer of stackoverflow wasn't cool, so I was messed up [(answered) I did it](https://stackoverflow.com/a/ 60629703/7449523). I haven't reflected on it.
With the top answer method, you can't call other methods of datetime.datetime. With this method, you can call datetime.datetime.fromisoformat ()
or other methods as usual.
By the way, another solution is to use pytest-freezegun
, which is more like a major. Reference: Pytest current time test (fixed date and time) -Qiita
Recommended Posts