I really wanted to fix Datetime.now (timezone.now) when I was making a Django test. That memo.
test_app/views.py
from django.utils import timezone
...
def hogehoge():
#Get the current time including the time zone ex. datetime.datetime(2020, 10, 30, 15, 35, 29, 482661, tzinfo=<UTC>)
return timezone.now()
I want to test code like this.
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 #Set return value
r = hogehoge()
return self.assertEqual(r, now)
This will replace timezone.now in your code with a mock.
PyCharm's auto test is convenient for testing. If you rewrite the code, it will be automatically re-executed.
Recommended Posts