Design an inventory management system
medium 80 minCount goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.
Watch lesson4:28
Testing
Make the bug happen on purpose
The point: write the four rules once and let random work, forced orders and many threads run against them.
Level 1
Random work against a simple model
import randomclass Simple: """So plain that it is obviously right: one entry for each jar.""" def __init__(self): self.jars = [] # each jar is None or the id of a promise def receive(self, n): self.jars += [None] * n def reserve(self, rid, n): free = [i for i, j in enumerate(self.jars) if j is None] if len(free) < n: return False for i in free[:n]: self.jars[i] = rid return True def release(self, rid): self.jars = [None if j == rid else j for j in self.jars] def ship(self, rid): self.jars = [j for j in self.jars if j != rid] def counts(self): return len(self.jars), sum(j is not None for j in self.jars)class Line: def __init__(self): self.on_hand = self.held = 0; self.open = {} def receive(self, n): self.on_hand += n def reserve(self, rid, n): if n > self.on_hand - self.held: return False self.held += n; self.open[rid] = n return True def release(self, rid): self.held -= self.open.pop(rid, 0) def ship(self, rid): n = self.open.pop(rid, 0) self.held -= n; self.on_hand -= n def counts(self): return self.on_hand, self.heldfor seed in range(300): rng, a, b = random.Random(seed), Simple(), Line() for step in range(60): op, rid, n = rng.choice(["receive", "reserve", "release", "ship"]), step, rng.randint(1, 4) if op == "receive": a.receive(n); b.receive(n) elif op == "reserve": assert a.reserve(rid, n) == b.reserve(rid, n), (seed, step) else: rid = rng.randint(0, step) # often closed already, or never opened getattr(a, op)(rid); getattr(b, op)(rid) assert a.counts() == b.counts(), (seed, step, op)print("300 runs agree")Level 2
The unlucky order, forced
from threading import Barrier, Threadclass Naive: def __init__(self): self.quantity, self.meet = 1, Barrier(2) def sell(self, out): if self.quantity >= 1: self.meet.wait() # both threads have checked before either changes self.quantity -= 1 out.append("sold")shop, out = Naive(), []threads = [Thread(target=shop.sell, args=(out,)) for _ in range(2)]for t in threads: t.start()for t in threads: t.join()assert out == ["sold", "sold"] and shop.quantity == -1print("the bug, every time")Level 3
Many threads, then the rules
- 1
Start together
All threads wait at a barrier, so they overlap.
- 2
Do different things
Reserve, ship, release, receive, and a sweeper with a clock that jumps.
- 3
Join
Then run the four rules. Not before: between two calls is allowed to look strange from outside the lock.
- 4
Account for each jar
Received minus shipped is on hand. Each thread counts what it got; the sum must match.
Level 4
The slow and the broken
| Fake | It does | The test asks |
|---|---|---|
| Slow listener | Waits on an event | Can another thread reserve meanwhile? |
| Broken listener | Raises | Does the promise stand? |
| Curious listener | Calls available | Does it come back, or hang? |
| Bad policy | Plans one more than there is | Does hold refuse, and is nothing half done? |
| Clock | Jumps to the very end | Is the end itself too late? |
The fourth row is a real gap: with a wrong policy the first holds have happened when a later one raises. If policies come from others, apply with a list of what was done and give it back on an exception.
What do you test first with ten minutes left?
BreaksGetters and setters
- How
- Set on hand, read on hand
- Limit
- Finds nothing.
- Choose when
- Never.
WorksEach verb once
- How
- One test for receive, reserve, ship, release
- Limit
- The bugs live in refusals and in repeats.
- Choose when
- As a start.
StrongThe four rules after each verb, also after refusals
- How
- One
checkfunction, called everywhere - Limit
- Needs a look inside.
- Choose when
- Always.