Python · testing
no-sleep-in-test-body
python:no-sleep-in-test-body Tests should synchronize on observable state instead of waiting a fixed duration.
- Code
- SARJ031
- Default
- error
- Fix
- none
- Languages
- python
Why
A fixed nonzero sleep makes test reliability and runtime depend on machine and CI timing.
Fix
Await the operation, wait on an event, or poll the expected condition with a bounded timeout.
Before / after
Executed by this rule’s unit tests.
Before
Test waits a fixed duration
import asyncio
async def test_worker_finishes():
start_worker()
await asyncio.sleep(0.1)
assert worker_finished()
After
Test waits for the completion signal
async def test_worker_finishes():
finished = start_worker()
await finished.wait()
assert worker_finished()
Limits
- Only test paths and calls resolved to imported `time.sleep` or `asyncio.sleep` are analyzed.
- Zero, computed, helper-owned, and bounded polling-loop sleeps are excluded.