Testing with pytest #5.3
Fixtures give each test its own data. A fake client lets a test check how the application handles a model reply, even offline.
From a sample reply to a test
Orbit asks a large language model (LLM) which queue should receive a support ticket. If the reply is " Billing ", the ticket should go to billing. A sample string is enough to check that step.
def queue_name(reply):
return reply.strip().lower()
print(queue_name(" Billing "))
# prints: billing
| Section | Example | Result |
|---|---|---|
| Fixtures | yield stream | The test gets an open stream |
| Test cases | (" Billing ", "billing") | A separate case for surrounding spaces |
| Fake LLM client | route("refund?", client) | billing |
| Mock and monkeypatch | client.assert_not_called() | The test catches an unnecessary call |
| Async tests | await route(client) | billing |
How some other languages compare
| Task | JS (Jest) | Java (JUnit) | Go |
|---|---|---|---|
| Define a test | test(...) | @Test | A TestXxx function |
| Compare values | expect(x).toBe(y) | assertEquals(y, x) | if x != y and t.Errorf |
Fixtures and resource lifetime
Save this example as test_stream.py and run python -m pytest -q test_stream.py. pytest looks for functions with names starting with test_. When it sees the parameter stream, it looks for a fixture of that name to supply the value.
| Syntax | Meaning |
|---|---|
@pytest.fixture | Register the function below as a fixture |
yield stream | Hand the resource to the test and pause here |
assert a == b | Fail the test if the values differ |
from io import StringIO
import pytest
@pytest.fixture
def stream():
stream = StringIO("billing")
yield stream
stream.close()
def test_read(stream):
assert stream.read() == "billing"
def test_cursor(stream):
assert stream.tell() == 0
The result is 2 passed. A StringIO is an in-memory text stream. The first test reads to the end. The second still finds the cursor at position 0 because the default scope is function: each test gets a fresh stream. Once the test finishes, even if an assertion fails, pytest resumes the fixture after yield from part 2.2 and closes the stream.
With @pytest.fixture(scope="module"), both tests in this file share one stream. In the order shown, the second test would find the cursor at position 7. A session fixture can be shared across the test run. Put a fixture in conftest.py if test files in the same directory or its subdirectories need it.
One case per set of arguments
@pytest.mark.parametrize matches parameter names to values in order. The names in "reply, expected" match the test function's two parameters. Each pair below becomes a case with its own result.
import pytest
def queue_name(reply):
return reply.strip().lower() or "triage"
@pytest.mark.parametrize("reply, expected", [
(" Billing ", "billing"),
("TECH", "tech"),
(" ", "triage"),
])
def test_queue_name(reply, expected):
assert queue_name(reply) == expected
The result is 3 passed. For the spaces-only reply, strip() returns an empty string, so or selects the fallback queue, "triage". Remove the fallback and only the third case fails.
Passing a fake client to the router
To test the call to the LLM as well, give route a client parameter. The fake client below looks up the prompt in a small dictionary. The router still has to send the right prompt and normalize the reply.
import pytest
class FakeClient:
def complete(self, prompt):
return {"refund?": " Billing "}[prompt]
def route(prompt, client):
return client.complete(prompt).strip().lower()
@pytest.fixture
def client():
return FakeClient()
def test_refund(client):
assert route("refund?", client) == "billing"
The result is 1 passed, even offline. Sending the wrong prompt triggers a KeyError on lookup. Dropping strip() leaves spaces in the queue name and fails the assertion. To evaluate the real model's routing decisions, use a separate set of labeled tickets.
Checking calls and changing settings
For a blank ticket, Orbit should use the default queue and skip the model call. Mock() creates an object that records calls. The built-in monkeypatch fixture lets the test temporarily change an environment variable that the application reads.
import os
from unittest.mock import Mock
def route(prompt, client):
if not prompt.strip():
return os.environ["DEFAULT_QUEUE"]
return client(prompt)
def test_blank_ticket(monkeypatch):
monkeypatch.setenv("DEFAULT_QUEUE", "triage")
client = Mock()
assert route(" ", client) == "triage"
client.assert_not_called()
The result is 1 passed. A test that only checks for "triage" would still pass if the router called the model and discarded the reply. The extra call would fail assert_not_called(). After the test, pytest restores the environment variable's previous value or removes the variable if it was absent.
Checking an async result
With an asynchronous client, await retrieves the reply before the call to strip(). In a project that uses the pytest-asyncio plugin, mark the test with @pytest.mark.asyncio so the plugin runs it in an event loop. This test file is for an environment with the plugin available.
import pytest
class FakeClient:
async def complete(self):
return " Billing "
async def route(client):
reply = await client.complete()
return reply.strip().lower()
@pytest.mark.asyncio
async def test_async_route():
client = FakeClient()
assert await route(client) == "billing"
The expected value is "billing". Dropping await before route(client) would compare a pending coroutine with that string.
Key takeaways
- Choose a scope that fits the resource's lifetime. Give each test a fresh resource when it holds state such as a read cursor.
- Use
parametrizeto see which input breaks a rule shared by several cases. - Pass a fake client to the application to check its output against a known reply. Use a mock when the test needs to tell whether a call happened.
