pytest-freezegun

repository·master·Indexed 41 days ago

https://github.com/ktosiek/pytest-freezegun

A pytest plugin for freezing and manipulating time during testing. It provides the `freezer` fixture with a `move_to()` method and the `@pytest.mark.freeze_time` decorator to ensure time-sensitive code behaves predictably.

Tokens
731
Snippets
5
Records
5
Agent score
2%

What's inside pytest-freezegun

  1. How `freezer` and `freeze_time` work with fixtures and classes

    master

    The freezer fixture and freeze_time mark are compatible with other pytest fixtures and can be used within class-based tests. When a test is marked with freeze_time, any fixtures requested by that test will also operate within the frozen time context.

    @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)
    
    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)
  2. Move time using the `freezer` fixture

    master

    The freezer fixture provides a move_to() method that allows you to manually advance or set the current time to a specific value during a test.

    def test_moving_date(freezer):
        now = datetime.now()
        freezer.move_to('2017-05-20')
        later = datetime.now()
        assert now != later
  3. Freeze time using the `freeze_time` mark

    master

    To freeze time to a specific moment for an entire test, use the @pytest.mark.freeze_time decorator. You can pass a date string as an argument to the mark.

    @pytest.mark.freeze_time('2017-05-21')
    def test_current_date():
        assert date.today() == date(2017, 5, 21)
  4. Freeze time using the `freezer` fixture

    master

    You can freeze time in both tests and fixtures by requesting the freezer fixture. This allows you to ensure that time remains static during a test execution, even if there are delays (like time.sleep()).

    def test_frozen_date(freezer):
        now = datetime.now()
        time.sleep(1)
        later = datetime.now()
        assert now == later