LoginSignup
5
4

More than 3 years have passed since last update.

Pytest現在時刻テスト(日時固定)

Posted at

Pytestで時刻を固定してテストする

Pythonで現在時刻を返すメソッドをテストしたいって場面に出くわしたのでメモ
日付を固定できる freezegun が便利!

環境

  • Python 3.7.5
  • pytest-5.2.4

pytestの場合、pytestのプラグインとしてpytest-freezegunがあります。
pytestのmarkerとして@pytest.mark.freeze_timeが追加されます。

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)

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

補足:〇分前でテストしたい

現在時刻から〇分前(minutes=update_span)のところをいじれば〇時間前や〇日前も可能

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)
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4