0%

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 : a function that makes a fake session, whose inner functions record what they were called with and answer from a . This lesson does the same, with 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 , and each becomes an attribute, so types.SimpleNamespace(readline=readline) is an whose .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 , and the test passes it to 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 run: that is the whole point of Pulse. A fake that never awaits anything finishes inside one step of the , so code that would run other checks during the wait never gets the chance to. Chapter 8 showed that 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 that the test reads afterwards. Its open_connection is an async def that pauses once and returns reader, writer, like asyncio.open_connection:

  • the reader is a SimpleNamespace with an async def readline() that pauses once and returns reply;

  • the writer is a SimpleNamespace with a plain write(data) that appends data to a list in record, an async def drain(), a plain close() that adds one to a count in record, and an async 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 ; nothing connects to it.

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 needs: a client whose answers come from a function you write.

Task

Write four fakes in tests/fakes.py and three tests in tests/test_pulse.py.

Fakes, each built from nested and types.SimpleNamespace, each pausing once with await asyncio.sleep(0) where the real thing would wait:

  1. fake_streams(reply) returns (open_connection, record). Awaiting open_connection(host, port) gives (reader, writer): await reader.readline() returns reply; the writer has write(data), await drain(), close() and await wait_closed(), and record shows what was written and how many times close was called.

  2. refusing_open_connection() returns an open_connection that raises ConnectionRefusedError when awaited.

  3. closing_client() returns (client, record): await client.aclose() records that it was called.

  4. recording_append(seen) returns append(path, line), which appends "on the loop" to seen when asyncio.get_running_loop() works and "in a thread" when it raises RuntimeError.

Tests:

  1. test_check_tcp_sends_ping_and_closes: check_tcp with fake_streams(b"PONG\n") reports up PONG, wrote b"PING\n" once and closed once.

  2. test_a_refused_tcp_check_is_an_error: with refusing_open_connection(), the result is error with detail ConnectionRefusedError.

  3. test_watch_closes_the_client_and_writes_in_a_thread: a two-round watch of one tcp target with closing_client(), fake_streams, and recording_append closes the client once, appends every line in a thread, and ends with stopped 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 and one through 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 , a watch that never closes its client, and a history writer that appends on the loop instead of in a worker thread. At least one test must fail against each.