timing.py


Overview

The `timing.py` module provides an abstraction layer for time-related functions used within the pytest testing framework. Its primary purpose is to isolate and control time-related operations such as retrieving the current time, measuring elapsed time intervals, and sleeping, ensuring that pytest's internal timing is not affected by external test mocks of the standard library `time` module. This is essential for reliable, deterministic test execution and accurate runtime measurement within pytest itself.

The module defines three core components:

By using this module, pytest and tests that depend on pytest's timing infrastructure can avoid unintended side effects of monkeypatching or mocking standard time functions.


Classes and Functions

Instant

@dataclasses.dataclass(frozen=True)
class Instant:
    time: float = dataclasses.field(default_factory=lambda: time(), init=False)
    perf_count: float = dataclasses.field(default_factory=lambda: perf_counter(), init=False)

    def elapsed(self) -> Duration:
        ...

    def as_utc(self) -> datetime:
        ...

Description

`Instant` encapsulates a single point in time, capturing two complementary measures:

This design is inspired by Rust’s `std::time::Instant`, which similarly distinguishes between real-world timestamps and monotonic timers for precise duration measurement.

Attributes

Methods

Usage Example

start = Instant()
# ... some operations ...
duration = start.elapsed()
print(f"Elapsed time: {duration.seconds} seconds")

print(f"Start time (UTC): {start.as_utc()}")

Duration

@dataclasses.dataclass(frozen=True)
class Duration:
    start: Instant
    stop: Instant

    @property
    def seconds(self) -> float:
        ...

Description

`Duration` represents the time span between two `Instant` objects, typically used to measure elapsed time intervals.

Attributes

Properties

Usage Example

start = Instant()
# ... some operations ...
stop = Instant()
duration = Duration(start=start, stop=stop)
print(f"Duration in seconds: {duration.seconds}")

MockTiming

@dataclasses.dataclass
class MockTiming:
    _current_time: float = datetime(2020, 5, 22, 14, 20, 50).timestamp()

    def sleep(self, seconds: float) -> None:
        ...

    def time(self) -> float:
        ...

    def patch(self, monkeypatch: MonkeyPatch) -> None:
        ...

Description

The `MockTiming` class provides a deterministic, controllable mock of timing functions. It is used in pytest's own tests to simulate the passage of time without relying on real system clocks or delays. This allows tests to run instantly and produce reproducible results regardless of system timing.

Time in `MockTiming` is static and only advances when explicitly told to via the `sleep()` method.

Attributes

Methods

Usage Example

def test_timing(monkeypatch):
    mock = MockTiming()
    mock.patch(monkeypatch)

    start = Instant()
    mock.sleep(5)  # Advance mocked time by 5 seconds
    stop = Instant()
    duration = Duration(start, stop)

    assert duration.seconds == 5

Implementation Details and Algorithms


Interaction with Other System Components


Public API

__all__ = ["perf_counter", "sleep", "time"]

The module exports the standard `perf_counter`, `sleep`, and `time` functions imported from the standard library, allowing other pytest components and plugins to use these safely.


Diagram: Class Structure of timing.py

classDiagram
    class Instant {
        +time: float
        +perf_count: float
        +elapsed() Duration
        +as_utc() datetime
    }

    class Duration {
        +start: Instant
        +stop: Instant
        +seconds : float
    }

    class MockTiming {
        -_current_time: float
        +sleep(seconds: float) void
        +time() float
        +patch(monkeypatch: MonkeyPatch) void
    }

    Duration --> Instant : start
    Duration --> Instant : stop

Summary

The `timing.py` module is a critical utility for pytest's internal timing and test time control, providing:

By encapsulating and isolating time functions, it ensures accurate, stable, and reliable timing operations across pytest's runtime and testing environment.