Testing Async Code · practice
Fakes That Await
Lesson 1’s tests needed only an event and a task. Most of Pulse talks to something: check_tcp opens a connection, check_http uses a client, and the watch closes its client and appends lines to a file. A test should touch none of them for real. Python in Practice faced the same problem with requests and solved it with stand-ins built from nested async def wherever Pulse awaits.
All the fakes live in tests/fakes.py, which already imports asyncio, types and httpx. types.SimpleNamespace(...) is the container you know from Python in Practice: give it keyword types.SimpleNamespace(readline=readline) is an .readline is your function.
A fake that pauses
Here is the shortest fake of the lesson, complete:
def refusing_open_connection():
"""Lesson 2: an open_connection that pauses once and raises ConnectionRefusedError."""
async def open_connection(host, port):
await asyncio.sleep(0)
raise ConnectionRefusedError("refused")
return open_connection
check_tcp awaits open_connection(host, port), so the fake is an async def with the same check_tcp as its open_connection argument, the seam Chapter 6 gave it.
Why the await asyncio.sleep(0)? A real connection takes time, and while it waits, other asyncio.sleep(0) is the smallest pause there is: it hands control back once and asks for no time at all. Every fake in this file pauses that way, once, where the real thing would wait. Lesson 4 depends on it.
Why does every fake await asyncio.sleep(0) once?
A reader, a writer, a record
fake_streams(reply) stands in for a connection that works. It returns two things, as a pair: the open_connection function, and a record open_connection is an async def that pauses once and returns reader, writer, like asyncio.open_connection:
the reader is a
SimpleNamespacewith anasync def readline()that pauses once and returnsreply;the writer is a
SimpleNamespacewith a plainwrite(data)that appendsdatato a list inrecord, anasync def drain(), a plainclose()that adds one to a count inrecord, and anasync def wait_closed().
Those are exactly the parts check_tcp calls, and their plain or async kind matches the real StreamWriter: write and close are plain drain and wait_closed are awaited. The record’s keys are yours to choose. {"written": [], "closed": 0} is enough for this lesson’s test, which arranges fake_streams(b"PONG\n"), acts with pulse.check_tcp(target, timeout=0.8, open_connection=open_connection) inside asyncio.run(bounded(...)), and asserts three things: the result is up with detail PONG, the writer was given b"PING\n" once, and it was closed once. The target is any tcp target dict, such as one with host 127.0.0.1 and a
closing_client() is smaller: a SimpleNamespace with an async def aclose() that records that it was called, returned with its record as a pair. The watch closes its client on every ending (Chapter 9), and this is how a test sees it.
Did the write happen in a thread?
Chapter 10’s writer appends each history line through asyncio.to_thread, so a slow disk never holds up the loop. A test can check that with an append stand-in that asks where it is running. asyncio.get_running_loop() returns the running loop when it is called from code the loop is running. In a worker thread there is no running loop, and it raises:
RuntimeError: no running event loop
That is the same message Chapter 8 got from stepping asyncio.sleep(0.1) by hand, for the same reason. So recording_append(seen) returns a plain function append(path, line) that calls asyncio.get_running_loop() inside try, appends "on the loop" to seen if that worked, and "in a thread" in the except RuntimeError:. Pulse itself never needs get_running_loop; here it is only a test’s way of asking where code ran.
In recording_append, asyncio.get_running_loop() raises RuntimeError. Where did the append run?
Test the watch
The third test runs a whole watch. Give pulse.watch one tcp target, the client from closing_client(), the open_connection from fake_streams(b"PONG\n"), append=fakes.recording_append(seen), a report that appends each line to a list of your own, rounds=2, every=0.01, workers=1, limit=1, timeout=0.8, and any history name, such as "unused.log": your append never opens it. The watch writes five lines (two round headers, two results, and the stopped line), so afterwards seen holds "in a thread" five times, the client’s record shows one aclose, and the last reported line starts with stopped after 2 of 2 rounds. The every=0.01 is a real wait the test lets finish, inside the 0.05 second rule.
Your task
In tests/fakes.py, write fake_streams, refusing_open_connection, closing_client and recording_append. In tests/test_pulse.py, replace the three Lesson 2 placeholders: test_check_tcp_sends_ping_and_closes, test_a_refused_tcp_check_is_an_error (its result is error with detail ConnectionRefusedError), and test_watch_closes_the_client_and_writes_in_a_thread. Then run them:
python -m pytest -q -k "tcp or watch_closes"
It should report 3 passed, 11 deselected. Then press Check my work. The next lesson writes the fake
Task
Write four fakes in tests/fakes.py and three tests in tests/test_pulse.py.
Fakes, each built from nested types.SimpleNamespace, each pausing once with await asyncio.sleep(0) where the real thing would wait:
fake_streams(reply)returns(open_connection, record). Awaitingopen_connection(host, port)gives(reader, writer):await reader.readline()returnsreply; the writer haswrite(data),await drain(),close()andawait wait_closed(), andrecordshows what was written and how many timesclosewas called.refusing_open_connection()returns anopen_connectionthat raisesConnectionRefusedErrorwhen awaited.closing_client()returns(client, record):await client.aclose()records that it was called.recording_append(seen)returnsappend(path, line), which appends"on the loop"toseenwhenasyncio.get_running_loop()works and"in a thread"when it raisesRuntimeError.
Tests:
test_check_tcp_sends_ping_and_closes:check_tcpwithfake_streams(b"PONG\n")reportsupPONG, wroteb"PING\n"once and closed once.test_a_refused_tcp_check_is_an_error: withrefusing_open_connection(), the result iserrorwith detailConnectionRefusedError.test_watch_closes_the_client_and_writes_in_a_thread: a two-round watch of onetcptarget withclosing_client(),fake_streams, andrecording_appendcloses the client once, appends every line in a thread, and ends withstopped after 2 of 2 rounds.
The Lesson 1 rules still hold: plain def tests, asyncio.run(bounded(...)), calls through pulse., no clock, real waits of 0.05 seconds at most. Neither file imports socket, threading or requests.
python -m pytest -q -k "tcp or watch_closes" should report 3 passed, 11 deselected.
Then press Check my work. It calls your four fakes directly with values of its own: a reply other than PONG, a refusal, a close, and one append on the asyncio.to_thread. Then it runs your Lesson 1 and Lesson 2 tests against a working copy of Pulse, where they must all pass within 1 second, and once against each of four versions with one mistake: a check_tcp that never closes its connection, a check_tcp that lets a refusal escape as an