### Travis CI Example for CI Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Integrate pytest-freezegun with Travis CI. This configuration specifies Python versions and installs dependencies before running tests. ```yaml language: python python: - "3.5" - "3.6" - "3.7" - "3.8" install: - pip install freezegun pytest-freezegun script: - pytest ``` -------------------------------- ### Create and Start Freezegun Freezer Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md Initializes and starts the freezegun time freezing mechanism using collected arguments. The `start()` method activates the freeze and returns a factory object. ```python freezer = freeze_time(*args, ignore=ignore, **kwargs) frozen_time = freezer.start() ``` -------------------------------- ### Install pytest-freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/README.rst Install the plugin using pip. ```bash pip install pytest-freezegun ``` -------------------------------- ### tox.ini Example for Testing Environments Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Set up tox for testing across multiple Python and pytest versions. Ensure all necessary dependencies, including pytest-freezegun, are installed. ```ini [tox] envlist = py35,py36,py37,py38,pypy3 [testenv] deps = pytest>=3.0.0 freezegun>0.3 pytest-freezegun commands = pytest {posargs} ``` -------------------------------- ### GitHub Actions Example for CI Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Configure GitHub Actions for continuous integration. This example sets up a matrix strategy to test against multiple Python and pytest versions. ```yaml name: Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: [3.5, 3.6, 3.7, 3.8, 3.9] pytest-version: [3.0.0, 4.0.0, 5.0.0, 6.0.0] steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install pytest==${{ matrix.pytest-version }} pip install freezegun pytest-freezegun - name: Run tests run: pytest ``` -------------------------------- ### Install and verify pytest-freezegun fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Install the pytest-freezegun package and verify that the 'freezer' fixture is available by running pytest with the --co -q flags. ```bash pip install pytest-freezegun pytest --co -q # Verify freezer fixture appears ``` -------------------------------- ### Example: pytest marker documentation format Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md Illustrates the expected format for marker documentation strings in pytest. ```text freeze_time(...): use freezegun to freeze time ``` -------------------------------- ### Usage with freezer Fixture for Time Manipulation Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/api-reference.md This example demonstrates freezing time to a specific date and then using the 'freezer' fixture to move time forward within the test. Requires 'pytest-freezegun' and 'freezegun' to be installed. ```python import pytest from datetime import date @pytest.pytest.mark.freeze_time('2017-05-20') def test_with_freezer(freezer): assert date.today() == date(2017, 5, 20) freezer.move_to('2017-12-25') assert date.today() == date(2017, 12, 25) ``` -------------------------------- ### Supported date-only and date-time strings Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Examples of string formats recognized by freezegun for setting dates and times. ```python '2017-05-20' # Date only (time = 00:00:00) '2017-05-20 15:42:00' # Date and time '2017-05-20T15:42:00' # ISO 8601 '2017-05-20 15:42:00.123456' # With microseconds ``` -------------------------------- ### Verify freezer fixture availability Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Command to check if the 'freezer' fixture is available, indicating successful installation and detection of the plugin. ```bash pytest --fixtures | grep freezer ``` -------------------------------- ### Example: pytest --markers output Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md Shows how the registered marker appears in the output of the 'pytest --markers' command. ```text @pytest.mark.freeze_time(...): use freezegun to freeze time ``` -------------------------------- ### Check Versions Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Verify the installed versions of pytest, freezegun, and pytest-freezegun. ```bash pytest --version pip show freezegun pip show pytest-freezegun ``` -------------------------------- ### Example Parameter Forwarding to freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/plugin-architecture.md Demonstrates how arguments from a pytest marker are processed and forwarded to the freezegun constructor. The 'ignore' parameter is augmented with pytest internals. ```python # Marker: @pytest.mark.freeze_time('2017-05-20', tick=True, ignore=['requests']) args = ('2017-05-20',) kwargs = {'tick': True} ignore = ['requests'] # After processing: ignore.extend(['_pytest.terminal', '_pytest.runner']) # Call to freezegun: freeze_time(*args, ignore=ignore, **kwargs) # Equivalent to: freeze_time('2017-05-20', ignore=['requests', '_pytest.terminal', '_pytest.runner'], tick=True) ``` -------------------------------- ### Verify Plugin Installation with pytest --co Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Use this command to check if the pytest-freezegun plugin is installed and discovered by pytest. It should list the 'freezer' fixture. ```bash pytest --co -q | grep freezer ``` -------------------------------- ### Supported date and datetime objects Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Examples of Python datetime and date objects that can be used with freezegun. ```python from datetime import datetime, date, timezone datetime(2017, 5, 20, 15, 42, 0) # datetime object date(2017, 5, 20) # date object ``` -------------------------------- ### Create Custom Freezer Fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Extend the base freezer fixture to initialize time to a specific value, useful for test suites that require a consistent starting date. ```python # conftest.py import pytest from datetime import datetime, timedelta @pytest.fixture def freezer_at_year_start(freezer): """Freezer fixture that starts at the beginning of the year""" freezer.move_to('2017-01-01 00:00:00') return freezer def test_with_custom_freezer(freezer_at_year_start): from datetime import date assert date.today() == date(2017, 1, 1) ``` -------------------------------- ### Using freeze_time with other fixtures Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Integrate `pytest-freezegun` with your existing fixtures. This example shows how a fixture capturing the current date interacts with time freezing and manipulation. ```python @pytest.fixture def created_date(): return date.today() @pytest.mark.freeze_time('2017-05-20') def test_with_fixtures(created_date, freezer): assert created_date == date(2017, 5, 20) freezer.move_to('2017-06-01') assert date.today() == date(2017, 6, 1) # Note: created_date is still 2017-05-20 pass ``` -------------------------------- ### Verify freezegun functionality Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Check if freezegun is working correctly by importing it and starting a freeze_time context. This helps diagnose issues where time is not frozen in tests. ```python from freezegun import freeze_time freeze_time('2017-05-20').start() ``` -------------------------------- ### Production Code with Direct freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md This example shows how to use freezegun directly within production code using a context manager. It's suitable for scenarios outside of pytest testing. ```python from freezegun import freeze_time def run_batch_job(target_date=None): if target_date: with freeze_time(target_date): return process_data() else: return process_data() ``` -------------------------------- ### Using Additional freezegun Options Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/api-reference.md This example shows how to pass additional keyword arguments to the underlying 'freezegun.freeze_time' function via the pytest marker, such as 'tick=True' to allow time to progress. ```python import pytest from datetime import datetime @pytest.mark.freeze_time('2017-05-20', tick=True) def test_with_tick(freezer): # tick=True allows time to progress, similar to real time now = datetime.now() # Some time would pass here due to tick=True ``` -------------------------------- ### Freezegun Context Manager Usage Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md Demonstrates the direct usage of freezegun's freeze_time context manager within the pytest-freezegun fixture. It shows the creation, start, yield, and stop phases. ```python freezer = freeze_time(*args, ignore=ignore, **kwargs) frozen_time = freezer.start() yield frozen_time freezer.stop() ``` -------------------------------- ### Integrate pytest-freezegun with Other Fixtures Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/README.md Combine pytest-freezegun's 'freeze_time' decorator and 'freezer' fixture with other pytest fixtures. This example shows how to use a custom fixture 'start_date' alongside time manipulation. ```python @pytest.fixture def start_date(): return date.today() @pytest.mark.freeze_time('2017-05-20') def test_with_fixtures(start_date, freezer): assert start_date == date(2017, 5, 20) freezer.move_to('2017-06-15') assert date.today() == date(2017, 6, 15) ``` -------------------------------- ### Upgrade pytest-freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Reinstall the pytest-freezegun package to resolve issues related to fixture not being found or to get the latest version. ```bash pip install --upgrade pytest-freezegun ``` -------------------------------- ### Direct freezegun with Decorator Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Apply the decorator for a cleaner syntax to freeze time for an entire test function. It still requires explicit import and setup, working with any test framework but offering less verbosity than the context manager. ```python from freezegun import freeze_time from datetime import date @freeze_time('2017-05-20') def test_decorated_freezegun(): assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Use @pytest.mark.freeze_time for Simple Tests Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md For simple tests, using the `@pytest.mark.freeze_time` decorator is faster as it avoids the overhead of fixture setup and teardown compared to manually using the `freezer` fixture. ```python # Fast: No fixture overhead @pytest.mark.freeze_time('2017-05-20') def test_simple(): assert date.today() == date(2017, 5, 20) ``` ```python # Slightly slower: Fixture overhead def test_simple(freezer): freezer.move_to('2017-05-20') assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Move Time Example Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/api-reference.md Demonstrates how to use the freezer.move_to() method to change the frozen time within a pytest test. This is useful for testing time-dependent logic. ```python import pytest from datetime import date, datetime @pytest.mark.freeze_time def test_moving_time(freezer): # Initially frozen at the time specified in the marker (or current time) freezer.move_to('2017-05-20') assert date.today() == date(2017, 5, 20) # Move forward freezer.move_to('2017-12-31') assert date.today() == date(2017, 12, 31) # Move backward freezer.move_to('2017-01-01') assert date.today() == date(2017, 1, 1) ``` -------------------------------- ### Marker with no arguments Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Call `freeze_time` without arguments to freeze time to the current moment when the test starts. This is a convenient way to test code that depends on the real-time execution. ```python # No arguments (freeze at current time) @pytest.mark.freeze_time ``` -------------------------------- ### Build and Upload Release Source: https://github.com/ktosiek/pytest-freezegun/blob/master/HACKING.md Steps to build source and wheel distributions and upload them to PyPI using twine. ```bash rm dist/* && \ .tox/flake8/bin/python setup.py sdist bdist_wheel && \ twine upload dist/* ``` -------------------------------- ### Configure freeze_time marker in setup.cfg Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Define the 'freeze_time' marker in setup.cfg for pytest configuration. ```ini [tool:pytest] markers = freeze_time: mark test to freeze time with freezegun ``` -------------------------------- ### Module Structure Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/INDEX.md Overview of the project's file and directory structure. Indicates the main plugin file and other configuration and test-related directories. ```tree pytest_freezegun/ ├── pytest_freezegun.py # Main plugin (66 lines) ├── setup.py # Build configuration ├── setup.cfg # Metadata and entry points ├── tests/ # Test suite │ ├── conftest.py │ └── test_freezegun.py ├── README.rst # Project README ├── CHANGELOG.md # Version history └── LICENSE # MIT License ``` -------------------------------- ### View Pytest Fixtures Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md List all available fixtures and plugins recognized by pytest, including those from pytest-freezegun. ```bash pytest --version && pytest --co ``` -------------------------------- ### View Pytest Options Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Display available command-line options for pytest to understand its configuration and usage. ```bash pytest -h ``` -------------------------------- ### Test with frozen time and automatic cleanup Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Demonstrates using the freeze_time marker to freeze time for a test. Time is automatically restored after the test completes. ```python @pytest.mark.freeze_time('2017-05-20') def test_frozen(): assert date.today() == date(2017, 5, 20) # Test ends here, real time automatically restored def test_real_time(): # This test sees real time assert date.today() != date(2017, 5, 20) ``` -------------------------------- ### pytest-freezegun with Marker and Fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Combine the marker to set an initial time and the fixture for dynamic time control during the test. This offers the most powerful and common pattern with a clean syntax, integrating marker-based initial freezing with fixture-based manipulation. ```python import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_marker_and_fixture(freezer): assert date.today() == date(2017, 5, 20) freezer.move_to('2017-12-25') assert date.today() == date(2017, 12, 25) ``` -------------------------------- ### See marker documentation Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Display documentation for all registered pytest markers, filtering for 'freeze_time'. ```bash pytest --markers | grep freeze_time ``` -------------------------------- ### Basic Usage: Freeze Time to a Specific Timestamp Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/api-reference.md Use this snippet to freeze time to a specific date and time for a test. Ensure 'pytest-freezegun' is installed and imported. ```python import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20 15:42') def test_frozen_date(): assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Django Testing with pytest-django Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Use pytest-freezegun within Django tests managed by pytest-django. This example demonstrates asserting the date from Django's timezone utility. ```python import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_django_view(): from django.utils import timezone today = timezone.now().date() assert today == date(2017, 5, 20) ``` -------------------------------- ### Get Closest Marker Function Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md A compatibility wrapper to retrieve the 'freeze_time' marker, handling differences in pytest's marker API across versions before and after 3.6.0. ```Python def get_closest_marker(node, name): """ Get our marker, regardless of pytest version """ if LooseVersion(pytest.__version__) < LooseVersion('3.6.0'): return node.get_marker('freeze_time') else: return node.get_closest_marker('freeze_time') ``` -------------------------------- ### Class-based tests with freezer and freeze_time Source: https://github.com/ktosiek/pytest-freezegun/blob/master/README.rst Demonstrates using the 'freezer' fixture and 'freeze_time' mark within class-based tests. ```python import pytest from datetime import date @pytest.fixture def current_date(): return date.today() class TestDate: @pytest.mark.freeze_time def test_changing_date(self, current_date, freezer): freezer.move_to('2017-05-20') assert current_date == date(2017, 5, 20) freezer.move_to('2017-05-21') assert current_date == date(2017, 5, 21) ``` -------------------------------- ### Combine freezer fixture and freeze_time mark Source: https://github.com/ktosiek/pytest-freezegun/blob/master/README.rst Use both the 'freezer' fixture and 'freeze_time' mark together, even with other fixtures. ```python import pytest from datetime import date @pytest.fixture def current_date(): return date.today() @pytest.mark.freeze_time def test_changing_date(current_date, freezer): freezer.move_to('2017-05-20') assert current_date == date(2017, 5, 20) freezer.move_to('2017-05-21') assert current_date == date(2017, 5, 21) ``` -------------------------------- ### Initialize Empty Structures for Freezer Arguments Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md Initializes empty lists and dictionaries to hold arguments that will be passed to the freezegun library. ```python args = [] kwargs = {} ignore = [] ``` -------------------------------- ### Enable pytest Verbose Output Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Use verbose output and long tracebacks to get detailed information about test failures. This helps in identifying the exact test and the cause of the error. ```bash pytest -vv --tb=long test_file.py ``` -------------------------------- ### Migrate from freezegun Time Manipulation to pytest-freezegun Fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Illustrates converting direct freezegun time manipulation within a context manager to using the 'freezer' fixture provided by pytest-freezegun. ```python # Before: Direct freezegun with time changes from freezegun import freeze_time from datetime import date def test_time_changes(): with freeze_time('2017-05-20') as freezer: assert date.today() == date(2017, 5, 20) freezer.move_to('2017-12-25') assert date.today() == date(2017, 12, 25) ``` ```python # After: pytest-freezegun with fixture import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_time_changes(freezer): assert date.today() == date(2017, 5, 20) freezer.move_to('2017-12-25') assert date.today() == date(2017, 12, 25) ``` -------------------------------- ### Run test with output visible Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Execute a specific test function and show its standard output using the '-s' flag. ```bash pytest -s test_file.py::test_name ``` -------------------------------- ### Configure freeze_time marker in pyproject.toml Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Define the 'freeze_time' marker in pyproject.toml using the TOML format. ```toml [tool.pytest.ini_options] markers = [ "freeze_time: mark test to freeze time with freezegun", ] ``` -------------------------------- ### Using Pytest-Freezegun with Other Fixtures Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/usage-patterns.md Integrate pytest-freezegun with other fixtures when your test setup requires deterministic datetime values. Fixtures will see the time frozen by the marker at the time of their initialization, but these values will not update if time is moved later in the test. ```python import pytest from datetime import date, datetime @pytest.fixture def current_date(): # This fixture runs with frozen time if the test has @pytest.mark.freeze_time return date.today() @pytest.mark.freeze_time('2017-05-20') def test_with_other_fixtures(current_date, freezer): # current_date fixture captured 2017-05-20 assert current_date == date(2017, 5, 20) # Can still move time in the test freezer.move_to('2017-06-15') assert date.today() == date(2017, 6, 15) # But current_date remains what it was at fixture initialization assert current_date == date(2017, 5, 20) ``` -------------------------------- ### Pytest Fixture for Freezing Time Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md This pytest fixture freezes time for tests. It accepts arguments and keyword arguments from a pytest marker and ensures pytest's internal modules are ignored. Time is frozen from before the test starts until it finishes, even if the test fails. ```python @pytest.fixture(name=FIXTURE_NAME) def freezer_fixture(request): """ Freeze time and make it available to the test """ args = [] kwargs = {} ignore = [] # If we've got a marker, use the arguments provided there marker = get_closest_marker(request.node, MARKER_NAME) if marker: ignore = marker.kwargs.pop('ignore', []) args = marker.args kwargs = marker.kwargs # Always want to ignore _pytest ignore.append('_pytest.terminal') ignore.append('_pytest.runner') # Freeze time around the test freezer = freeze_time(*args, ignore=ignore, **kwargs) frozen_time = freezer.start() yield frozen_time freezer.stop() ``` -------------------------------- ### Pytest Plugin Entry Point Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md This configuration declares pytest_freezegun as a pytest11 plugin, enabling automatic discovery and loading by pytest. ```ini [options.entry_points] pytest11 = freezegun = pytest_freezegun ``` -------------------------------- ### Pytest Hook Call Sequence Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md Illustrates the sequence of events from pytest startup to test execution, highlighting the role of pytest hooks and the freezer fixture. ```text pytest starts ↓ Entry point loads pytest_freezegun module ↓ pytest_configure() hook runs ├─ Registers freeze_time marker └─ No exceptions = OK to continue ↓ Test collection phase ├─ Each test is parsed ├─ Markers are attached └─ Items list is built ↓ pytest_collection_modifyitems() hook runs ├─ Iterates items ├─ Finds marked tests └─ Injects freezer fixture ↓ Test execution ├─ freezer_fixture() is called (setup) ├─ Test function runs └─ freezer_fixture() teardown (stop()) ``` -------------------------------- ### Registering pytest-freezegun Plugin Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/plugin-architecture.md This configuration snippet shows how pytest-freezegun is registered as a pytest plugin using the entry point system in setup.cfg. This makes the plugin discoverable by pytest. ```ini [options.entry_points] pytest11 = freezegun = pytest_freezegun ``` -------------------------------- ### Run All Tests with Tox Source: https://github.com/ktosiek/pytest-freezegun/blob/master/HACKING.md Execute all tests across supported Python and pytest configurations using tox. ```bash tox ``` -------------------------------- ### Test Daylight Saving Time Transitions Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Test the behavior of daylight saving time transitions by verifying the change in DST status before and after a transition. ```python import pytest from datetime import datetime import pytz @pytest.mark.freeze_time('2017-03-11 23:59:59') def test_dst_transition(freezer): tz = pytz.timezone('America/New_York') before_spring_forward = datetime.now(tz) freezer.move_to('2017-03-12 03:00:00') # After spring forward after_spring_forward = datetime.now(tz) # Verify the time jump assert before_spring_forward.dst() != after_spring_forward.dst() ``` -------------------------------- ### Marker with basic date Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Use the `freeze_time` marker with a simple date string to freeze time to that specific date. ```python # Basic date @pytest.mark.freeze_time('2017-05-20') ``` -------------------------------- ### Move time with the freezer fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/README.rst Use the 'freezer' fixture to move time to a specific point. ```python from datetime import datetime def test_moving_date(freezer): now = datetime.now() freezer.move_to('2017-05-20') later = datetime.now() assert now != later ``` -------------------------------- ### Marker + Fixture Combined for Dynamic Time Control Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/usage-patterns.md Use this pattern when you need an initial frozen time set by a marker and the ability to dynamically move time forward or backward during the test using the freezer fixture. This is the most common and flexible approach for time-dependent tests. ```python import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_changing_date(freezer): # Start at 2017-05-20 assert date.today() == date(2017, 5, 20) # Move time forward freezer.move_to('2017-12-25') assert date.today() == date(2017, 12, 25) # Move time backward freezer.move_to('2017-01-01') assert date.today() == date(2017, 1, 1) ``` -------------------------------- ### Migrate from freezegun Context Manager to pytest-freezegun Marker Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Demonstrates replacing the 'freeze_time' context manager with the '@pytest.mark.freeze_time' decorator for cleaner pytest integration. ```python # Before: Direct freezegun from freezegun import freeze_time from datetime import date def test_something(): with freeze_time('2017-05-20'): assert date.today() == date(2017, 5, 20) ``` ```python # After: pytest-freezegun import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_something(): assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Move Time with Direct Freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Demonstrates moving time to a specific date using the `move_to` method within a `freeze_time` context. ```python from freezegun import freeze_time from datetime import date with freeze_time('2017-01-01') as freezer: freezer.move_to('2017-12-31') assert date.today() == date(2017, 12, 31) ``` -------------------------------- ### Inspect freeze_time Marker Arguments Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Access and print the arguments and keyword arguments passed to the `freeze_time` marker using the `request` fixture. This is useful for verifying marker configuration. ```python @pytest.mark.freeze_time('2017-05-20', tick=True) def test_inspect_marker(request): import pytest marker = request.node.get_closest_marker('freeze_time') print(f"Marker args: {marker.args}") print(f"Marker kwargs: {marker.kwargs}") ``` -------------------------------- ### Explicitly Request Freezer in Fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Ensure other fixtures correctly see the frozen time by explicitly requesting the 'freezer' fixture as a dependency. ```python # conftest.py import pytest @pytest.fixture def my_fixture(freezer): # Explicitly request freezer from datetime import date return date.today() @pytest.mark.freeze_time('2017-05-20') def test_with_fixture(my_fixture): from datetime import date assert my_fixture == date(2017, 5, 20) assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Test with freezer fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Inject the `freezer` fixture into your test function to manually control time. Use `freezer.move_to()` to change the current time. ```python def test_something(freezer): freezer.move_to('2017-05-20') assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Marker with date and time Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Specify both date and time in the `freeze_time` marker to freeze time to a precise moment. ```python # Date and time @pytest.mark.freeze_time('2017-05-20 15:42:00') ``` -------------------------------- ### pytest-freezegun with Marker Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Utilize pytest's marker system for time freezing, eliminating the need for explicit freezegun imports. This integrates seamlessly with pytest's test lifecycle and is automatically registered. ```python import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_pytest_freezegun(): assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Ignore Modules During Time Freezing with Direct Freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Shows how to exclude specific modules from time freezing using the `ignore` parameter. The 'requests' module will see real time. ```python from freezegun import freeze_time with freeze_time('2017-05-20', ignore=['requests']): # requests module sees real time pass ``` -------------------------------- ### Autouse Fixture to Freeze Time Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Implement an autouse fixture to automatically freeze time for all tests within a module or directory. ```python # conftest.py import pytest @pytest.fixture(autouse=True) def always_frozen_time(freezer): """Auto-freeze time for all tests in this directory""" pass # Now all tests automatically have frozen time ``` -------------------------------- ### Enable Natural Time Progression (Tick=True) with Direct Freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Illustrates enabling natural time progression during a frozen period using `tick=True`. Time will advance during `time.sleep()` calls. ```python from freezegun import freeze_time import time with freeze_time('2017-05-20', tick=True) as freezer: t1 = time.time() time.sleep(0.1) t2 = time.time() assert t2 > t1 # Time progressed ``` -------------------------------- ### Converting Manual Freezegun to pytest-freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Replace manual `freeze_time` context managers with the `@pytest.mark.freeze_time` decorator for cleaner test code. ```python # Before: manual context manager from freezegun import freeze_time def test_something(): with freeze_time('2017-05-20'): assert date.today() == date(2017, 5, 20) # After: using pytest-freezegun import pytest @pytest.mark.freeze_time('2017-05-20') def test_something(): assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Mocking with Frozen Time using unittest.mock Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md When using `unittest.mock`, apply patches after the freezer is active to ensure mocks work correctly with frozen time. ```python import pytest from unittest.mock import patch from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_with_mock(freezer): with patch('mymodule.get_date', return_value=date(2017, 5, 20)): # Mock works here because freezer is already active pass ``` -------------------------------- ### Debug Marker Arguments with Print Output Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Use this Python snippet to debug issues where marker arguments are not applied correctly. Run with the '-s' flag to see the print output. ```python @pytest.mark.freeze_time('2017-05-20') def test_debug_marker(freezer): from datetime import date actual = date.today() expected = date(2017, 5, 20) print(f"Expected: {expected}, Got: {actual}") assert actual == expected ``` -------------------------------- ### Direct freezegun with Context Manager Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Use the context manager for explicit time freezing within a specific block of test code. This offers full control over the freeze duration but is more verbose and lacks test framework integration. ```python from freezegun import freeze_time from datetime import date def test_direct_freezegun(): with freeze_time('2017-05-20'): assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Main Plugin Module Imports Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/source-code-reference.md Imports necessary modules for pytest integration, version checking, and time freezing. ```Python # -*- coding: utf-8 -*- import pytest from distutils.version import LooseVersion from freezegun import freeze_time ``` -------------------------------- ### Parametrized Fixtures with Multiple Time Points Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/integration-guide.md Use parametrized fixtures to run tests with different frozen time scenarios, moving time between test runs. ```python # conftest.py import pytest @pytest.fixture(params=[ '2017-01-01', '2017-02-15', '2017-12-31', ]) def various_dates(request, freezer): """Run test with multiple date scenarios""" freezer.move_to(request.param) return request.param def test_date_handling(various_dates): # Runs 3 times with different dates from datetime import date assert str(date.today()).startswith(various_dates[:4]) # Year matches ``` -------------------------------- ### Migrate from freezegun Decorator to pytest-freezegun Marker Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Shows how to switch from the '@freeze_time' decorator to the '@pytest.mark.freeze_time' decorator for improved pytest compatibility. ```python # Before: freezegun decorator from freezegun import freeze_time from datetime import date @freeze_time('2017-05-20') def test_something(): assert date.today() == date(2017, 5, 20) ``` ```python # After: pytest-freezegun marker import pytest from datetime import date @pytest.mark.freeze_time('2017-05-20') def test_something(): assert date.today() == date(2017, 5, 20) ``` -------------------------------- ### Run tests in parallel Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Enable parallel test execution using pytest-xdist with 'auto' to determine the number of workers. ```bash pytest -n auto ``` -------------------------------- ### Freeze time with the freezer fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/README.rst Use the 'freezer' fixture to freeze time within a test. Time will not advance even after a sleep. ```python from datetime import datetime import time def test_frozen_date(freezer): now = datetime.now() time.sleep(1) later = datetime.now() assert now == later ``` -------------------------------- ### Test Time Zone Handling Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/advanced-troubleshooting.md Verify time zone conversions using timezone-aware datetimes. Use `datetime.now(tz)` for accurate timezone handling, not `datetime.utcnow()`. ```python import pytest from datetime import datetime import pytz @pytest.mark.freeze_time('2017-05-20 12:00:00') def test_timezone_handling(freezer): # UTC now_utc = datetime.now(pytz.UTC) # Move to different time freezer.move_to('2017-05-20 15:00:00') later_utc = datetime.now(pytz.UTC) # Verify time differences assert (later_utc - now_utc).total_seconds() == 10800 # 3 hours ``` -------------------------------- ### Test with marker and fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Combine the `@pytest.mark.freeze_time` marker with the `freezer` fixture. The marker sets the initial time, and the fixture can be used to manipulate it further within the test. ```python @pytest.mark.freeze_time('2017-05-20') def test_something(freezer): assert date.today() == date(2017, 5, 20) freezer.move_to('2017-12-25') assert date.today() == date(2017, 12, 25) ``` -------------------------------- ### Move Time with pytest-freezegun Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/freezegun-comparison.md Shows how to move time to a specific date using the `move_to` method provided by the `freezer` fixture in pytest. ```python import pytest from datetime import date @pytest.mark.freeze_time('2017-01-01') def test_move_time(freezer): freezer.move_to('2017-12-31') assert date.today() == date(2017, 12, 31) ``` -------------------------------- ### Freezer method: move_to with datetime and date objects Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md The `freezer.move_to()` method also accepts `datetime` and `date` objects directly. This provides a more programmatic way to set the frozen time. ```python # String, datetime, or date objects all work from datetime import datetime, date freezer.move_to(datetime(2017, 5, 20, 15, 42)) freezer.move_to(date(2017, 5, 20)) ``` -------------------------------- ### Use with Async Tests Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md For asynchronous tests, apply both the 'asyncio' and 'freeze_time' markers to ensure proper functionality. ```python @pytest.mark.asyncio @pytest.mark.freeze_time ``` -------------------------------- ### freezer Fixture Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/README.md The `freezer` fixture provides an interface to control time within your tests. It offers methods to move time forward or backward and to freeze time at a specific point. ```APIDOC ## freezer Fixture ### Description Provides an interface to control time within tests. Allows moving time, freezing it, and accessing its current state. ### Methods - **`freezer.move_to(time_to_freeze)`**: Moves the current time to the specified `time_to_freeze`. - **`freezer.tick(delta=None)`**: Advances time by a specified `delta` or by a default increment. - **`freezer.is_frozen()`**: Returns `True` if time is currently frozen, `False` otherwise. ### Parameters - **`time_to_freeze`** (datetime, str, int, float): The target time to freeze or move to. Can be a datetime object, a string parseable as a date, or a Unix timestamp. - **`delta`** (timedelta, int, float, optional): The amount of time to advance. If not provided, a default increment is used. ``` -------------------------------- ### Integration with Other Fixtures Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/api-reference.md Shows how to use @pytest.mark.freeze_time in conjunction with other custom pytest fixtures. Time is frozen, and the custom fixture's behavior is tested against the frozen time, with further manipulation possible via the 'freezer' fixture. ```python import pytest from datetime import date @pytest.fixture def current_date(): return date.today() @pytest.mark.freeze_time('2017-05-20') def test_with_other_fixtures(current_date, freezer): assert current_date == date(2017, 5, 20) freezer.move_to('2017-06-15') assert current_date == date(2017, 6, 15) ``` -------------------------------- ### Specify Freeze Time Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/quick-reference.md Use the 'freeze_time' marker with a specific date and time string to control the frozen time in your tests. ```python @pytest.mark.freeze_time('2017-05-20') ``` -------------------------------- ### Registering freeze_time Marker in pytest.ini Source: https://github.com/ktosiek/pytest-freezegun/blob/master/_autodocs/configuration.md Document the 'freeze_time' marker in your pytest configuration files (pytest.ini, pyproject.toml, or setup.cfg) to provide helpful descriptions when tests are run with the -m option or when using pytest's marker introspection. ```ini [tool:pytest] markers = freeze_time: mark test to freeze time with freezegun ``` ```ini [pytest] markers = freeze_time: mark test to freeze time with freezegun ``` ```toml [tool.pytest.ini_options] markers = [ "freeze_time: mark test to freeze time with freezegun", ] ```