2
1

More than 3 years have passed since last update.

DjangoのテストでDatetime.nowを固定したい

Posted at

はじめに

Djangoのテスト作っている時にどうしてもDatetime.now(timezone.now)を固定したかった。
そのメモです。

やること

  • mock.patch で モック作る

コード

テストするコード

test_app/views.py
from django.utils import timezone
...

def hogehoge():
    # タイムゾーン込みで現在時刻を取得 ex. datetime.datetime(2020, 10, 30, 15, 35, 29, 482661, tzinfo=<UTC>)
    return timezone.now()

こんな感じのコードをテストしたい。

テストコード

test_app/tests.py
from unittest import mock
...

class TestClass(TestCase):
    @mock.patch("test_app.views.timezone.now")
    def test_hogehoge(self, mocked_now):
        now = timezone.make_aware(timezone.datetime(2020, 10, 30, 19, 30))
        mocked_now.return_value = now  # 返り値を設定
        r = hogehoge()
        return self.assertEqual(r, now)

これでコード中のtimezone.nowがモックに置き換わる。

最後に

テストはPyCharmのオートテストが便利。
コード書き換えたら自動で再実行してくれます。

2
1
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
2
1