Note that I came across a scene where I wanted to test a method that returns the current time in Python The freezegun that can fix the date is convenient!
For pytest, there is pytest-freezegun
as a plugin for pytest.
@ Pytest.mark.freeze_time
is added as a marker for pytest.
test_sample.py
from datetime import datetime
import pytest
@pytest.mark.freeze_time('2019-11-27 11:23:23')
def test_time():
assert datetime.today() == datetime(2019, 11, 27, 11, 23, 23)
It's okay to import
get_today.py
def dateget():
return datetime.datetime.today()
test_sample.py
from datetime import datetime
import pytest
import get_today
@pytest.mark.freeze_time('2019-11-27 11:23:23')
def test_time():
assert get_today.dateget() == datetime(2019, 11, 27, 11, 23, 23)
$ python -m pytest test_sample.py
plugins: freezegun-0.3.0.post1
collected 1 item
test_sample.py .
==== 1 passed in 0.07 seconds ====
If you mess with 〇 minutes (minutes = update_span) from the current time, 〇 hours or days before
test_sample.py
@pytest.mark.freeze_time('2019-11-27 11:23:23')
def test_time():
correct_value = datetime(2019, 11, 27, 11, 20, 23)
subtracted_time = datetime.now() - timedelta(minutes=3)
assert subtracted_time == datetime(2019, 11, 27, 11, 20, 23)
Recommended Posts