Testing Async Code · practice
Prove Overlap Without a Clock
The claim this whole course rests on is that Pulse’s checks run at the same time. How would a test show it? The tempting answer is a stopwatch: time five checks that each wait 0.1 seconds, and if the total is near 0.1 rather than 0.5, they overlapped. That is a measurement of one computer on one day. On a busy machine the same correct code can take longer, and a test that sometimes fails on correct code teaches you to ignore it. Every Submit and Check my work in this course proved overlap another way, without reading a clock. This lesson you prove it the same way.
Count what is in flight
Put a counter inside the fake that every check goes through. Each request adds one on the way in, notes the largest number it has seen, pauses once, and takes one away on the way out:
async def handler(request):
record["now"] += 1
if record["now"] > record["most"]:
record["most"] = record["now"]
await asyncio.sleep(0)
record["now"] -= 1
return httpx.Response(200)
record["now"] += 1 is the short form of record["now"] = record["now"] + 1; either works.
record["most"] is then the largest number of requests that were inside the handler at once. Follow it with Chapter 8’s rule, that other await. If run_checks starts five checks at once, each one enters the handler and reaches the sleep(0) before any of them resumes, so all five are inside together: most is 5. If it awaited each check before starting the next, every request would leave the handler before the next one entered: most is 1. Neither number depends on how fast the computer is, and both are the same on every run.
Five checks each pause once inside a counting fake. run_checks awaits them one by one. What is the most in flight?
The same handler can count per host, for the watch’s per-host limit from Chapter 11. Keep a second pair of request.url.host: record["host_now"] and record["host_most"]. Add one to the host’s count on entry with record["host_now"].get(host, 0) + 1, keep the largest in record["host_most"][host], and take one away on the way out. This lesson’s tests read record["most"] and record["host_most"], so use those two keys.
The counter sits in the transport, below everything Pulse does, so it counts requests that actually reached the point where a real client would be waiting on the network. Nothing in pulse.py changes for the test, and the same fake serves run_checks and the watch alike.
Assert the exact number
For run_checks, give it five http targets and assert record["most"] == 5. Then assert the order of the names in its results: the checks overlap, but the results still come back in target order (Chapter 3). Two assertions, two promises.
For the limit, run one round of a watch over six targets on one host, with workers=6 and limit=2. Six workers could all reach that host at once; the record["host_most"]["alpha.test"] == 2, with the host your targets use, exactly two and not “at most two”. A watch that checked one target at a time would also stay at or below two, and it would be wrong in a different way. A test of a limit has to show both halves: that the limit held, and that two really did run together.
A test runs one round of a watch over six targets on the host alpha.test, with workers=6 and limit=2. A counting fake transport stores the most requests in flight to that host at once in record["host_most"]["alpha.test"]. Why assert that it == 2 and not <= 2?
These exact numbers hold because every fake pauses exactly once, on one sleep(0). A fake that waited real time, such as asyncio.sleep(0.01), would let timing decide who is inside the handler together, and the maximum could change from run to run. Count with pauses that take no time.
Never a stopwatch
So there is no clock anywhere in this suite. Check my work refuses a test file that imports time or datetime, or uses perf_counter or monotonic. It is not only a rule for its own sake: the sandbox that runs your tests shares its processor with other work, and how much of it your tests get changes from one run to the next. A counter gives the same answer either way.
Your task
In tests/fakes.py, write counting_client(): it returns (client, record), an httpx.AsyncClient on a MockTransport whose handler answers 200 after one pause and keeps record["most"] and record["host_most"] as above. In tests/test_pulse.py, replace the two Lesson 4 placeholders:
test_run_checks_overlaps_and_keeps_order: fivehttptargets, each with a name and aof its own; pulse.run_checks(targets, client=client, timeout=0.8); assert the most in flight is 5 and the names come back in target order.test_watch_limits_each_host: six targets on one host, one round ofpulse.watchwithworkers=6,limit=2, and theappendstand-in from Lesson 2; assert that host’s most in flight is 2.
Run them:
python -m pytest -q -k "overlaps or limits_each_host"
It should report 2 passed, 12 deselected. Then press Check my work. In the project that follows, your suite meets five versions of Pulse at once, and you add the test none of these lessons has written: one for a watch that is cancelled.
Task
Write counting_client in tests/fakes.py and the two Lesson 4 tests in tests/test_pulse.py.
counting_client()returns(client, record). The client ishttpx.AsyncClient(transport=httpx.MockTransport(handler)), and every request answers 200 after oneawait asyncio.sleep(0).record["most"]holds the most requests ever in flight at once, andrecord["host_most"]aof the most in flight per request.url.host.test_run_checks_overlaps_and_keeps_order: fivehttptargets throughpulse.run_checks; assert the most in flight is exactly 5 and the result names are in target order.test_watch_limits_each_host: one round ofpulse.watchover six targets on one host withworkers=6andlimit=2; assert that host’s most in flight is exactly 2.
The earlier rules still hold: plain def tests, asyncio.run(bounded(...)), calls through pulse., no socket, threading or requests, and no clock at all: no time, datetime, perf_counter or monotonic in either file.
python -m pytest -q -k "overlaps or limits_each_host" should report 2 passed, 12 deselected.
Then press Check my work. It reads both files for the rules first. It calls your counting_client directly: five requests at once, three to one host and two to another, must leave most at 5 and host_most at 3 and 2, and two requests awaited in turn must leave most at 1. It runs your Lessons 1 to 4 tests against a working copy of Pulse, where they must all pass within 1 second, and once against each of two versions with one mistake: a run_checks that awaits each check before starting the next, and a watch with no per-host limit. At least one test must fail against each.