Exemple
freezegun 1.5.5: Control frozen time programmatically with freeze_time via tick and move_to, handle timezone offsets, nested contexts, and standard datetime inheritance in freezegun 1.5.5
Échantillon vérifié pour pypi freezegun 1.5.5: Control frozen time programmatically with freeze_time via tick and move_to, handle timezone offsets, nested…
sha256:37f274f3e232a58a899ff5a81d9c660a9fa7324398d1b2731d0e5b454eef1bb6
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 3
- Clés de signature qui l’ont compilé
- 3
Environnement déclaré
python linux x64 python python pip
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-17 |
| python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-18 |
| python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104… |
2026-09-08 |
Cas
HOW- Objectif
- Control frozen time programmatically with freeze_time via tick and move_to, handle timezone offsets, nested contexts, and standard datetime inheritance in freezegun 1.5.5
- Symboles
-
- freezegun.freeze_time
- FrozenDateTimeFactory.move_to
- FrozenDateTimeFactory.tick
- freezegun.api.FakeDatetime
- freezegun.api.FakeDate
- Environnement
- python
- Créé
- 2026-08-17T13:37:37Z
Contrat
- assert freeze_time context manager enables programmatic clock manipulation via move_to and tick, applies tz_offset strictly to local time without altering UTC, and restores outer scopes upon exit
- assert calling tick() without arguments advances the frozen clock by exactly 1 second while tick(delta) supports int, float, and timedelta increments
- assert move_to() immediately updates datetime.datetime.now() and datetime.datetime.utcnow() to the specified string, datetime, or date target
- assert tz_offset shifts datetime.datetime.now() while datetime.datetime.utcnow() and time.time() remain bound to the unshifted UTC timestamp
- assert nested freeze_time context managers cleanly override the frozen clock in inner blocks and restore outer frozen state on exit
- assert FakeDatetime and FakeDate instances returned during time freezing maintain full inheritance and isinstance compatibility with datetime.datetime and datetime.date
Fichiers
- NOTES.md
- csx.json
- requirements.txt
- src/__init__.py
- src/session_manager.py
- test/contract.py
Code source
# Notes on freezegun Time Traveling and Programmatic Clock Control
## Prior Known Solution Search
A search for known solutions returned three compatible samples:
- `sha256:38d96e5f0bc7e4a9bc1e19b8579a875bcd87770979dd72ba52daf672ba73049a`: Verified decorator mechanics (`as_arg`, `as_kwarg`, class decoration exclusions, and `auto_tick_seconds`).
- `sha256:23e5961077ffa723dfb45d6ac6431978361f612671b20126ad0cb2ee5c86bacf`: Verified parameter name collision fixes (`func` and `time_factory`).
- `sha256:ced890e0926f2aeefa165f3bfa8024ec62021062b020f0443b992753f24ab74e`: Verified ignore list configuration and `real_asyncio`.
This sample focuses on the core context manager API and runtime time manipulation provided by `FrozenDateTimeFactory` (`move_to`, `tick`), timezone offset separation between local and UTC clocks, nested context isolation, and standard library datetime inheritance.
## Pinned Release
- `freezegun`: 1.5.5
- `python-dateutil`: 2.9.0.post0
- `six`: 1.17.0
## Observed Behaviour
In `freezegun` 1.5.5:
1. `freeze_time` used as a context manager yields a `FrozenDateTimeFactory` instance that provides programmatic clock manipulation.
2. `frozen_time.move_to()` accepts ISO-8601 strings, `datetime.datetime`, and `datetime.date` objects, updating `datetime.datetime.now()` and `datetime.datetime.utcnow()` synchronously.
3. `frozen_time.tick()` without arguments advances the clock by exactly 1 second. `frozen_time.tick(delta)` accepts integer/float seconds or `datetime.timedelta` objects to step time forward across minute, hour, day, and leap-year boundaries.
4. Setting `tz_offset` (integer hours or timedelta) shifts `datetime.datetime.now()` by the specified offset, while `datetime.datetime.utcnow()` and `time.time()` remain pinned to the unshifted UTC timestamp.
5. Nested `freeze_time` contexts cleanly override time for the duration of the inner block, and automatically restore the outer frozen timestamp upon exiting the inner context.
6. Patched `FakeDatetime` and `FakeDate` classes inherit directly from `datetime.datetime` and `datetime.date`, preserving `isinstance` checks and standard datetime arithmetic.
{"case":{"caseId":"case:sha256:67194d776127d3d160f0bd3abb83e19af1e0eef164950569d904c97a1f5bcadc","contract":["assert freeze_time context manager enables programmatic clock manipulation via move_to and tick, applies tz_offset strictly to local time without altering UTC, and restores outer scopes upon exit","assert calling tick() without arguments advances the frozen clock by exactly 1 second while tick(delta) supports int, float, and timedelta increments","assert move_to() immediately updates datetime.datetime.now() and datetime.datetime.utcnow() to the specified string, datetime, or date target","assert tz_offset shifts datetime.datetime.now() while datetime.datetime.utcnow() and time.time() remain bound to the unshifted UTC timestamp","assert nested freeze_time context managers cleanly override the frozen clock in inner blocks and restore outer frozen state on exit","assert FakeDatetime and FakeDate instances returned during time freezing maintain full inheritance and isinstance compatibility with datetime.datetime and datetime.date"],"goal":"Control frozen time programmatically with freeze_time via tick and move_to, handle timezone offsets, nested contexts, and standard datetime inheritance in freezegun 1.5.5","kind":"HOW","packages":["pkg:pypi/freezegun@1.5.5","pkg:pypi/python-dateutil@2.9.0.post0","pkg:pypi/six@1.17.0"],"schemaVersion":1,"symbols":["freezegun.freeze_time","FrozenDateTimeFactory.move_to","FrozenDateTimeFactory.tick","freezegun.api.FakeDatetime","freezegun.api.FakeDate"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/freezegun@1.5.5","pkg:pypi/python-dateutil@2.9.0.post0","pkg:pypi/six@1.17.0"],"schemaVersion":1,"symbols":["freezegun.freeze_time","FrozenDateTimeFactory.move_to","FrozenDateTimeFactory.tick","freezegun.api.FakeDatetime","freezegun.api.FakeDate"],"verifierAdapter":"python@1"}
freezegun==1.5.5
python-dateutil==2.9.0.post0
six==1.17.0
"""Package initialization for freezegun sample."""
"""Session manager demonstrating time-dependent operations."""
from datetime import datetime, timedelta
class SessionManager:
"""Manages session tokens with time-to-live (TTL) expiration."""
def __init__(self, ttl_seconds: int = 300):
self.ttl = timedelta(seconds=ttl_seconds)
self.sessions: dict[str, datetime] = {}
def create_session(self, user_id: str) -> None:
"""Create or refresh a session timestamped with the current time."""
self.sessions[user_id] = datetime.now()
def is_valid(self, user_id: str) -> bool:
"""Check if the user session is active and not expired."""
created_at = self.sessions.get(user_id)
if created_at is None:
return False
return (datetime.now() - created_at) < self.ttl
"""Contract test proving freezegun 1.5.5 behavior."""
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import sys
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import freezegun
from freezegun import freeze_time
from freezegun.api import FakeDate, FakeDatetime, FrozenDateTimeFactory
from src.session_manager import SessionManager
# -----------------------------------------------------------------------------
# 1. Programmatic clock control with move_to and tick via FrozenDateTimeFactory
# -----------------------------------------------------------------------------
with freeze_time("2024-02-28 23:59:50") as frozen_time:
assert isinstance(frozen_time, FrozenDateTimeFactory)
assert datetime.now() == datetime(2024, 2, 28, 23, 59, 50)
assert date.today() == date(2024, 2, 28)
# Session domain service tracks initial time
session_mgr = SessionManager(ttl_seconds=60)
session_mgr.create_session("alice")
assert session_mgr.is_valid("alice") is True
# Calling tick() without arguments advances time by exactly 1 second
frozen_time.tick()
assert datetime.now() == datetime(2024, 2, 28, 23, 59, 51)
assert session_mgr.is_valid("alice") is True
# tick(timedelta) across a leap-day boundary
frozen_time.tick(timedelta(seconds=9))
assert datetime.now() == datetime(2024, 2, 29, 0, 0, 0)
assert date.today() == date(2024, 2, 29)
assert session_mgr.is_valid("alice") is True
# tick(int/float seconds) advances across session expiration
frozen_time.tick(60)
assert datetime.now() == datetime(2024, 2, 29, 0, 1, 0)
assert session_mgr.is_valid("alice") is False
# move_to() accepts ISO formatted strings
frozen_time.move_to("2024-07-04 12:00:00")
assert datetime.now() == datetime(2024, 7, 4, 12, 0, 0)
assert datetime.utcnow() == datetime(2024, 7, 4, 12, 0, 0)
# move_to() accepts datetime objects
frozen_time.move_to(datetime(2024, 12, 31, 23, 59, 59))
assert datetime.now() == datetime(2024, 12, 31, 23, 59, 59)
# move_to() accepts date objects
frozen_time.move_to(date(2025, 1, 1))
assert datetime.now() == datetime(2025, 1, 1, 0, 0, 0)
assert date.today() == date(2025, 1, 1)
# -----------------------------------------------------------------------------
# 2. Timezone offset separation: now() shifted, utcnow() and time.time() in UTC
# -----------------------------------------------------------------------------
with freeze_time("2024-06-01 12:00:00", tz_offset=5) as ft_tz:
# datetime.now() reflects UTC + 5 hours
assert datetime.now() == datetime(2024, 6, 1, 17, 0, 0)
# datetime.utcnow() remains unshifted UTC
assert datetime.utcnow() == datetime(2024, 6, 1, 12, 0, 0)
# time.time() matches UTC epoch timestamp
expected_utc_timestamp = datetime(2024, 6, 1, 12, 0, 0, tzinfo=timezone.utc).timestamp()
assert time.time() == expected_utc_timestamp
# time.gmtime() reports UTC struct_time
gm = time.gmtime()
assert gm.tm_year == 2024 and gm.tm_mon == 6 and gm.tm_mday == 1
assert gm.tm_hour == 12 and gm.tm_min == 0 and gm.tm_sec == 0
# -----------------------------------------------------------------------------
# 3. Nested freeze_time contexts override and restore outer state cleanly
# -----------------------------------------------------------------------------
with freeze_time("2024-01-01 10:00:00"):
assert datetime.now() == datetime(2024, 1, 1, 10, 0, 0)
with freeze_time("2025-05-15 08:30:00"):
assert datetime.now() == datetime(2025, 5, 15, 8, 30, 0)
# Outer context restored upon inner context exit
assert datetime.now() == datetime(2024, 1, 1, 10, 0, 0)
# -----------------------------------------------------------------------------
# 4. Type compatibility and arithmetic preservation
# -----------------------------------------------------------------------------
with freeze_time("2024-01-01 00:00:00"):
now = datetime.now()
today = date.today()
assert isinstance(now, datetime)
assert isinstance(today, date)
assert isinstance(now, date)
assert issubclass(FakeDatetime, datetime)
assert issubclass(FakeDate, date)
# Datetime arithmetic works seamlessly
advanced = now + timedelta(days=1, hours=2)
assert advanced == datetime(2024, 1, 2, 2, 0, 0)
assert isinstance(advanced, datetime)
print(f"CONTRACT PASS: freezegun {freezegun.__version__} context manager and programmatic clock control verified")