pytest-freezegun
pytest-freezegun is a pytest plugin that simplifies testing time-dependent code by integrating the `freezegun` library with pytest fixtures and marks. It allows you to freeze time during test execution using either a decorator or a dedicated fixture. The current version is 0.4.2, and it maintains a moderate release cadence, addressing compatibility and feature improvements.
Warnings
- breaking Python 3.5 and older are no longer supported. Versions prior to 0.4.1 dropped support for Python < 3.5. Version 0.3.0 dropped support for Python 3.3.
- gotcha The `freeze_time` mark was not automatically registered as a known mark in versions prior to 0.4.1. This could lead to pytest warnings about unknown marks.
- gotcha When both `@pytest.mark.freeze_time` and the `freezer` fixture are used in the same test or test scope, there were issues in older versions where `freeze_time` might not correctly freeze time in fixtures, or `freezer.move_to` might override unexpected values.
- gotcha Support for class-based tests (e.g., using `@pytest.mark.freeze_time` on a test method within a class) was added in 0.4.1. Earlier versions might not apply the time freeze correctly to methods within test classes.
Install
-
pip install pytest-freezegun
Imports
- pytest.mark.freeze_time
import pytest # accessed via pytest.mark
- freezer (fixture)
def test_example(freezer):
Quickstart
import datetime
import pytest
@pytest.mark.freeze_time("2023-01-15 12:00:00")
def test_frozen_time_decorator():
assert datetime.datetime.now() == datetime.datetime(2023, 1, 15, 12, 0, 0)
def test_frozen_time_fixture(freezer):
freezer.move_to("2024-02-29 10:30:00")
assert datetime.datetime.now() == datetime.datetime(2024, 2, 29, 10, 30, 0)
freezer.tick(datetime.timedelta(hours=1))
assert datetime.datetime.now() == datetime.datetime(2024, 2, 29, 11, 30, 0)