sleep-in-test
A test sleeps.
- Group
- Tests
- Runs
- On by default
- Level
- note
- Reads
- Tests
- Fix
- None: what the test is waiting for is the author's to say
- Defends
- Resilience: the test fails only when the code is broken.
Why
The test, a closure it writes, or a helper of its file that only it calls waits for time to pass. A sleep long enough to be safe makes the test slow, and one short enough to be fast makes it fail on a loaded machine.
The fix, as Ur suggests it: wait for the condition, or advance a fake clock.
For agents
Never sleep in a test; wait for the condition the test is waiting for, with an event, a latch, or the framework's synchronization, or advance a fake clock.
Example
shop/restock.pyimport threading
class Restock:
def __init__(self, levels):
self.levels = levels
self.done = threading.Event()
def run(self, name, count):
self.levels[name] = self.levels.get(name, 0) + count
self.done.set()
def start_restock(levels, name, count):
restock = Restock(levels)
thread = threading.Thread(target=restock.run, args=(name, count))
thread.start()
return restock, thread
tests/test_restock.pyimport time
from shop.restock import start_restock
def test_restock_adds_to_the_level():
levels = {"kettle": 3}
start_restock(levels, "kettle", 2)
time.sleep(1)
assert levels["kettle"] == 5
$ ur lint --rule sleep-in-test
note[sleep-in-test]: test `test_restock_adds_to_the_level` sleeps with `time.sleep`; wait for the condition it is waiting for instead
--> ./tests/test_restock.py:9:5 test `test_restock_adds_to_the_level`
= hint: wait for the condition, or advance a fake clock
= see: TotT: Sleeping != Synchronization, Google Testing Blog (2008-08-21), https://testing.googleblog.com/2008/08/tott-sleeping-synchronization.html
0 clone classes and 1 test finding in 2 files
Source
TotT: Sleeping != Synchronization, Google Testing Blog (2008-08-21).