Reference library

Testing & modern typing

pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.

3 matches
Testing & modern typing easy

How to freeze time in Python tests with freezegun

Use the freezegun decorator to freeze datetime.now() at a fixed timestamp so tests that depend on current time run deterministically.

freezegun datetime testing
Python
from datetime import datetime
from freezegun import freeze_time


@freeze_time("2024-01-15 12:30:00")
def test_frozen_time():
    now = datetime.now()
    return now


if __name__ == "__main__":
    result = test_frozen_time()
    print(result)
15 0 Open
Testing & modern typing easy

Mock datetime with time-machine in Python

Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().

testing datetime mock
Python
from time_machine import travel
from datetime import datetime


@travel("2020-01-01 10:30:00")
def check_date():
    return datetime.utcnow()


if __name__ == "__main__":
    print(check_date())
13 0 Open
Testing & modern typing easy

Mock datetime.now to freeze time in Python

Use unittest.mock.patch to replace datetime.now with a fixed value so your code always sees the same time during tests.

datetime mock unittest
Python
from datetime import datetime
from unittest.mock import patch

def current_message():
    now = datetime.now()
    return f"Current time: {now:%Y-%m-%d %H:%M:%S}"

if __name__ == "__main__":
    with patch("__main__.datetime") as mock_dt:
        mock_dt.now.return_value = datetime(2024, 3, 15, 10, 30, 0)
        prin…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Testing & modern typing — Python code examples

What you will find here

This page collects testing & modern typing snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.