Injectable Clock For Tests
Abstract time behind a Clock protocol, provide a fake clock that can advance instantly, and drive a TTL cache without sleeping.
Code
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Protocol
class Clock(Protocol):
def now(self) -> datetime: ...
class SystemClock:
def now(self) -> datetime:
return datetime.now(timezone.utc)
class FakeClock:
def __init__(self, start: datetime) -> None:
if start.tzinfo is None:
raise ValueError("start must be timezone aware")
self._current = start
def now(self) -> datetime:
return self._current
def advance(self, seconds: float) -> None:
self._current += timedelta(seconds=seconds)
@dataclass
class CachedValue:
clock: Clock
ttl: timedelta
value: str | None = None
expires_at: datetime | None = None
def get(self) -> str | None:
now = self.clock.now()
if self.value is None or self.expires_at is None or now >= self.expires_at:
return None
return self.value
def put(self, value: str) -> None:
self.value = value
self.expires_at = self.clock.now() + self.ttl
def main() -> None:
clock = FakeClock(datetime(2026, 10, 21, 12, 0, tzinfo=timezone.utc))
cache = CachedValue(clock=clock, ttl=timedelta(seconds=30))
cache.put("fresh")
print("immediately:", cache.get())
clock.advance(29)
print("after 29s:", cache.get())
clock.advance(2)
print("after 31s:", cache.get())
print("system clock tz:", SystemClock().now().tzinfo)
if __name__ == "__main__":
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
immediately: fresh
after 29s: fresh
after 31s: None
system clock tz: UTCInside the snippet
Injectable Clock For Tests keeps everything in the classes from, Clock and SystemClock and the functions now, __init__, advance and get.
ValueError is the guard’s signal — thrown at the branch, before any partial work happens.
Caveats
- The guard
start.tzinfo is Noneshort-circuits the flow with an earlyraisewhen its condition holds.
Putting it to use
The main signature reads def now(self) -> datetime
The demo output is labeled (immediately:, after 29s:, after 31s:), so every printed line maps back to its originating operation.
The entry point wires put, get, advance and now together — run it once and the whole demo flows.
Core lines
def __init__(self, start: datetime) -> None:
if start.tzinfo is None:
raise ValueError("start must be timezone aware")
self._current = start
def advance(self, seconds: float) -> None:
self._current += timedelta(seconds=seconds)
def put(self, value: str) -> None:
self.value = value
self.expires_at = self.clock.now() + self.ttl
Interactive Tools for This Topic
FAQ
- What happens on invalid input?
- `ValueError` is raised at the guard (`start.tzinfo is None`), so invalid state never reaches the main logic.
- What does Injectable Clock For Tests print when run?
- Invoke the file as-is — the `immediately:`, `after 29s:`, `after 31s:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.