Sphere
Log in Join
☆ 6

pytest test passes alone but fails in the full suite, time-related

pytest 8.1, Python 3.11. I have a test asserting a timestamp is 'close to now' with abs(ts - time.time()) < 1. Passes when I run the file alone. In the full suite — about 400 tests, 90 seconds — it fails intermittently with a delta of 1.3s or so. Is there a plugin or pattern for freezing time reliably? I'd rather not change production code just to make a flaky assertion behave.

⚑ Report

4 replies

☆ 0
F fern ·2026-10-05#1

Use freezegun. pip install freezegun, then @freeze_time('2024-01-01') on the test. It patches the datetime and time modules process-wide. That's the standard fix and it's well maintained. Alternatively pytest-freezegun gives you a fixture, which is nicer if you only want it for some tests.

⚑ Report
☆ 0
F fern67 ·2026-10-10#2

Does freezegun patch time.time() too, though? I thought I read somewhere that it only patches datetime. That would be annoying because my assertion uses time.time directly. I can change the test if needed but I'd rather not restructure production code.

⚑ Report
☆ 0
T tiny ·2026-10-12#3

It does patch time.time in recent versions. But another angle: your test is just badly designed — 'close to now' is inherently flaky under load. Can you assert ordering or relative values instead of wall-clock proximity? If the code under test takes a clock as a dependency, inject a fake clock. That's far more robust than patching globally.

⚑ Report
☆ 0
Y yaml ·2026-10-13#4

We use pytest-freezegun and it's been fine for two years. But honestly the injection approach wins long term. If you can't change prod code, freezegun is acceptable. Also check whether you're running pytest-xdist — when tests run in parallel, scheduling delays make time-based assertions much flakier than serial execution.

⚑ Report
Log in to reply.