Skip to content

subtests: fix negative duration when the clock is mocked - #15277

Closed
Prasanna543210 wants to merge 3 commits into
pytest-dev:mainfrom
Prasanna543210:fix-subtest-frozen-clock
Closed

Prasanna543210 wants to merge 3 commits into
pytest-dev:mainfrom
Prasanna543210:fix-subtest-frozen-clock

Conversation

@Prasanna543210

Copy link
Copy Markdown

Subtests computed their duration from time.time()/perf_counter() directly,
so a test that freezes or mocks the clock (e.g. with monkeypatch) could get
a negative duration. That ends up in the JUnit XML as time="-0.01", which
is invalid.

This switches the duration to timing.Instant, which uses the clock
functions pytest captured at import time, so patching time in user code
no longer affects it. Same approach the rest of the runner already uses.

Added test_subtest_with_mocked_clock, which freezes time.time and
time.perf_counter inside a subtest and checks the generated report has no
negative time values.

I ran testing/test_subtests.py, test_junitxml.py and test_unittest.py
locally (Windows, Python 3.11) and they pass.

I used Claude to help with debugging my local setup and with writing the
commit message and this description. I reviewed and tested the change myself.

Prasanna543210 and others added 3 commits October 28, 2026 13:21
When a test freezes or mocks time.time/time.perf_counter (e.g. via monkeypatch), the duration computed for a subtest could end up negative, which produced invalid negative time values in the JUnit XML report.

Compute the subtest duration with timing.Instant, which uses the clock values pytest captured itself, so user code that patches the time module no longer affects the reported duration.

Add a regression test that freezes the clock inside a subtest and checks that the generated --junitxml report has no negative times.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Oct 28, 2026
@Prasanna543210
Prasanna543210 deleted the fix-subtest-frozen-clock branch October 28, 2026 08:26
@Prasanna543210
Prasanna543210 restored the fix-subtest-frozen-clock branch October 28, 2026 08:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant