real-clock

A test reads the clock.

Group
Tests
Runs
On by default
Level
note
Reads
Tests
Fix
None: how the code takes its time 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 reads the current time, so what it checks depends on when it runs.

The fix, as Ur suggests it: pass the code under test a fixed time.

For agents

Never read the current time in a test; give the code under test a fixed time, as a parameter or through a fake clock.

Example

shop/hours.py
def is_open(hour):
    return 9 <= hour < 17
tests/test_hours.py
import datetime

from shop.hours import is_open


def test_shop_is_open_in_the_morning():
    hour = datetime.datetime.now().hour
    assert is_open(hour) == (9 <= hour < 17)
What Ur prints
$ ur lint --rule real-clock
note[real-clock]: test `test_shop_is_open_in_the_morning` reads the clock with `datetime.datetime.now`, so what it checks depends on when it runs
  --> ./tests/test_hours.py:7:12 test `test_shop_is_open_in_the_morning`
  = hint: pass the code under test a fixed time
  = see: TotT: Time is Random, Google Testing Blog (2008-04-03), https://testing.googleblog.com/2008/04/tott-time-is-random.html
0 clone classes and 1 test finding in 2 files

Try it in the playground →

Source

TotT: Time is Random, Google Testing Blog (2008-04-03).