Pytest Freezer

0.4.9 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

The `freezer` fixture is automatically available in your pytest tests. It is an instance of `freezegun.api.FrozenDateTimeFactory`, allowing direct use of its methods like `move_to()` or `freeze()` as a context manager. Time is frozen to the current moment by default when the fixture is injected, and can be manipulated thereafter.

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

view raw JSON →