Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/15277.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed negative durations being reported for subtests when the clock is mocked or frozen.
15 changes: 6 additions & 9 deletions src/_pytest/subtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
from contextlib import ExitStack
from contextlib import nullcontext
import dataclasses
import time
from types import TracebackType
from typing import Any
from typing import TYPE_CHECKING

import pluggy

from _pytest import timing
from _pytest._code import ExceptionInfo
from _pytest._io.saferepr import saferepr
from _pytest.capture import CaptureFixture
Expand Down Expand Up @@ -216,8 +216,7 @@ class _SubTestContextManager:
def __enter__(self) -> None:
__tracebackhide__ = True

self._start = time.time()
self._precise_start = time.perf_counter()
self._timing = timing.Instant()
self._exc_info = None

self._exit_stack = ExitStack()
Expand All @@ -242,16 +241,14 @@ def __exit__(

self._exit_stack.close()

precise_stop = time.perf_counter()
duration = precise_stop - self._precise_start
stop = time.time()
duration = self._timing.elapsed()

call_info = CallInfo[None](
None,
exc_info,
start=self._start,
stop=stop,
duration=duration,
start=duration.start.time,
stop=duration.stop.time,
duration=duration.seconds,
when="call",
_ispytest=True,
)
Expand Down
21 changes: 21 additions & 0 deletions testing/test_subtests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1096,3 +1096,24 @@ def test(self):
pytester.syspathinsert()
result = pytester.runpytest("-n1", "-pxdist.plugin")
result.assert_outcomes(passed=2)


def test_subtest_with_mocked_clock(pytester: pytest.Pytester) -> None:
pytester.makepyfile(
"""
import time

def test_with_subtest(subtests, monkeypatch):
real_sleep = time.sleep
monkeypatch.setattr(time, "perf_counter", lambda: 0.0)
monkeypatch.setattr(time, "time", lambda: 0.0)

with subtests.test("frozen clock"):
real_sleep(0.01)
"""
)
result = pytester.runpytest("--junitxml=report.xml")
result.assert_outcomes(passed=1)

xml = pytester.path.joinpath("report.xml").read_text()
assert 'time="-' not in xml
Loading