Testing time-dependent functions can be challenging and unreliable as the results may vary based on when the test is executed. This results in flaky tests that pass or fail inconsistently.
With FreezeGun, you can freeze time at a particular point, ensuring your tests always run with the same date context.
# test_get_date.py
from freezegun import freeze_time
import datetime
def get_day_of_week():
return datetime.datetime.now().weekday()
@freeze_time("2024-10-13")
def test_get_day_of_week():
assert get_day_of_week() == 6
$ pytest test_get_date.py
======================== 1 passed in 0.07s ========================
This code uses get_day_of_week()
to return the current weekday (0-6). The @freeze_time("2024-10-13")
decorator sets a fixed date (Sunday, October 13, 2024).
The test calls get_day_of_week()
and checks if it returns 6 (Sunday). This test will consistently pass because FreezeGun ensures datetime.datetime.now()
always returns the specified frozen date.