[PYTHON] Pytest Current time test (fixed date and time)

Test with fixed time with Pytest

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!

environment

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 ====

Supplement: I want to test 〇 minutes ago

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

Pytest Current time test (fixed date and time)
Extract "current date only" and "current date and time" with python datetime.
Date and time ⇔ character string
Get the current date and time in Python, considering the time difference
Distribution and test
To represent date, time, time, and seconds in Python
Convert timezoned date and time to Unixtime in Python2.7
python get current time
[Python] Create a date and time list for a specified period
Pandas basics for beginners ④ Handling of date and time items