Pytest Freezer
Pytest-freezer is a pytest plugin that provides a fixture interface for the `freezegun` library, allowing developers to easily freeze and manipulate time during tests. It ensures consistent testing of time-based functionality, such as scheduling, expiry mechanisms, and historical data retrieval. Maintained by the `pytest-dev` organization, the current version is 0.4.9 and is actively developed.
Warnings
- breaking The explicit `freezer.start()` and `freezer.stop()` methods for managing time freezing were removed in `pytest-freezer` 0.4.6. This change aligns with `freezegun`'s recommended approach of using context managers or relying on the fixture's default behavior.
- gotcha `pytest-freezer` requires `freezegun >= 1.1` since `pytest-freezer` 0.4.9. Earlier versions of `pytest-freezer` (e.g., 0.4.5) had a lower bound of `freezegun >= 1.0`. Using an older `freezegun` version may lead to unexpected behavior or compatibility issues.
- gotcha `pytest-freezer` is the actively maintained successor to the unmaintained `pytest-freezegun` plugin. `pytest-freezegun` has not been updated since 2020 and may cause deprecation warnings or compatibility issues with newer `pytest` or Python versions. `pytest-freezer` was transferred to the `pytest-dev` organization to provide a maintained alternative.
- deprecated Support and active testing for Python 3.6 and 3.7 were officially deprecated in `pytest-freezer` 0.4.9, aligning with their End-of-Life (EOL) status. While the `requires_python` metadata might still allow installation on these versions, continued compatibility is not guaranteed.
Install
-
pip install pytest-freezer
Imports
- freezer
def test_my_feature(freezer): # Use the freezer fixture directly
Quickstart
from datetime import datetime
import time
def test_frozen_date(freezer):
# Time is frozen by default when the fixture is injected
now = datetime.now()
time.sleep(1)
later = datetime.now()
assert now == later
assert now.year == datetime.now().year # Verify object type
# You can also move time within the frozen period
freezer.move_to('2023-01-01 10:00:00')
assert datetime.now() == datetime(2023, 1, 1, 10, 0, 0)
# Use freezer as a context manager for temporary freezes
with freezer.freeze('2022-02-02'):
assert datetime.now().day == 2