Pass the clock in, so a test can move time
Part 3 brings time into the queue. Before you write any of it, decide where the time comes from.
If the class calls time.monotonic() itself, a test of a 30-second timeout has to sleep for 30 seconds. Tests get slow, and a busy machine makes them flaky. So pass a clock in: a function that returns the current time. Production passes time.monotonic. A test passes a fake clock and sets the time by hand.
class FakeClock:
def __init__(self):
self.now = 0
def __call__(self):
return self.now
clock = FakeClock()
print(clock())
clock.now = 12
print(clock())
0
12
The practice problem's WorkQueue(..., clock=time.monotonic) works this way, and every test in it moves the clock by hand. Use time.monotonic, not time.time, for the real clock: the wall clock can jump backward when the machine syncs its time, and a lease must never get longer by accident.
Now the first rule with time in it. A reservation made at time t, with a timeout of 10, is held while t <= now < t + 10. The start is in and the end is out. So at exactly t + 10 it's over.
Slide now. At 9 w1 still holds a. At 10 it doesn't. A timeout of None never ends, which is the queue of part 1.
The function lease_live in the editor answers whether a reservation is still held at now. Write it with the half-open rule, and let a timeout of None mean forever.