Skip to content

no-fixed-sleep-before-assert

Do not sleep for a fixed interval and then assert in a test.

Why

A fixed sleep followed by an assertion guesses how long the code under test needs. On a loaded CI runner the guess is too short and the test flakes; on an idle one every run pays the whole interval.

Fix

Await the signal the code exposes, such as an event, future, queue item, or fake callback, or poll the condition with a deadline. When the test deliberately proves that nothing happens during a quiet window, keep the sleep with an exact SARJ455 suppression that names the window.

Examples

Before — flagged A test waits a guessed interval before asserting
tests/test_monitor.py
import asyncio
async def test_reports_silence(monitor):
monitor.start()
await asyncio.sleep(0.5)
assert monitor.reason == "silence"
After — preferred A test awaits the signal with a deadline before asserting
tests/test_monitor.py
import asyncio
async def test_reports_silence(monitor):
monitor.start()
await asyncio.wait_for(monitor.fired.wait(), timeout=5)
assert monitor.reason == "silence"
Before — flagged A synchronous test blocks for a guessed interval before asserting
tests/test_worker.py
import time
def test_worker_drains_queue(worker, queue):
worker.start()
time.sleep(1)
assert queue.pending() == 0
After — preferred A synchronous test polls the condition with a deadline before asserting
tests/test_worker.py
import time
def test_worker_drains_queue(worker, queue):
worker.start()
deadline = time.monotonic() + 5
while queue.pending() and time.monotonic() < deadline:
time.sleep(0.01)
assert queue.pending() == 0