My Python for AI 101 · Chapter 12

Testing and evaluating

Worked on October 22, 2026 · 4 min read

Two cards to finish: tests that run offline, and an “expected versus obtained” loop that measures behaviour.

Card 59 — Tests with pytest

Project. Dev3Pack AI Engineering Bootcamp

In one sentence. A test is a test_… function that asserts a result; pytest provides ready-made tools: tmp_path, monkeypatchThe pytest tool that temporarily replaces a function or an environment variable during a test.See in the glossary →, parametrize, and FixtureA function pytest runs before a test to prepare the ground (a throwaway folder, the network cut off).See in the glossary →.

Why it matters for an AgentA program that uses a language model to decide what to do (search, call a tool, answer, refuse), in a loop, with stopping rules.See in the glossary →. The buyer’s tests run with the network cut off: a test that tries to reach the Internet fails. So the grade depends neither on the wifi nor on an outside service.

Analogy. An internal control that replays the same sample transactions every month.

The mechanism.

@pytest.fixture(autouse=True)          # applies to ALL the tests in the folder
def no_network(monkeypatch: pytest.MonkeyPatch) -> None:
    def blocked(*_: Any, **__: Any) -> None:
        raise OSError("tests are offline: the network is blocked")
    monkeypatch.setattr(socket.socket, "connect", blocked)
    monkeypatch.setattr(socket, "create_connection", blocked)

@pytest.mark.parametrize(("status", "code", "error"), [(401, "key-invalid", "…"), (429, "rate-limited", "…")])
def test_each_refusal_prints_the_servers_message(home, capsys, status, code, error): ...

Input → output. uv run pytest: 98 passed, 2 skipped in my-gecko-buyer (October 4); 7 passed, 2 skipped in grounded-research-agent.

Where to read it again. my-gecko-buyer/tests/conftest.py · no_network · tests/test_mainnet_wallet.py · parametrize (tmp_path, monkeypatch.setenv) — course · grounded-research-agent/tests/test_contract.py (the TimeoutA maximum waiting time. Past it, you abandon the call and return a readable refusal, instead of waiting forever.See in the glossary → caught in under a second, the invented CitationThe ID of the document that supports an answer. A correct citation doesn't prove the sentence comes from the document.See in the glossary → removed) · the check("chNN-eN", …) cells of every notebook.

To reuse. Block the network in conftest.py from the very first test. One test per expected RefusalAn explicit "I can't answer": no citation, zero confidence, human review. A state, not a crash.See in the glossary →, named like a sentence. parametrize to replay the same rule on several cases. tmp_path to write throwaway files.

Card 60 — Testing the structure, evaluating the behaviour

Project. NovaMart Multi-Agent Support (AWS Scholars, chapter 3)

In one sentence. unittestThe standard library's test framework (TestCase, setUp).See in the glossary → organizes tests in classes; inspect.getsource and astThe Python module that turns source code into a syntax tree you can analyse without running the code.See in the glossary → read a function’s structure without running it; an “expected versus obtained” loop over a fixed setA collection with no duplicates; & gives the shared elements, <= checks that one set is contained in another.See in the glossary → of cases measures an AI system’s behaviour.

Why it matters for an agent. The Udacity grader checks that my code does contain ThreadPoolExecutorA pool of threads that runs tasks in parallel, suited to waiting on the network.See in the glossary → and submit. And the GuardrailA filter applied to the model's inputs and outputs: harmful content, personal data, denied topics. It's tested like code, false positives included.See in the glossary → is not tuned by feel: each topic definition is measured on the same cases before it is published.

Analogy. The audit checks that the procedure exists (structure); the BacktestTesting a method on the past: you act as if you didn't know how recent cases turned out, you predict, then you compare with what really happened.See in the glossary → checks that it gives the right results (behaviour).

The mechanism.

source = inspect.getsource(self.ao.build_policy_agent)
tree = ast.parse(source)
uses_pool = any(isinstance(node, ast.Name) and node.id == 'ThreadPoolExecutor'
                for node in ast.walk(tree))

for expected, source, text in CASES:
    r = RUNTIME.apply_guardrail(guardrailIdentifier=..., guardrailVersion=version,
                                source=source, content=[{'text': {'text': text}}])
    got = 'BLOCKED' if r['action'] == 'GUARDRAIL_INTERVENED' else 'ALLOWED'
    ok += got == expected                          # True counts as 1

Input → output. Replayed on build_policy_agent: ThreadPoolExecutor found, 1 call to submit. Three cases, two right → 2/3. In the project: tests/test_agent.py all → 120/120; adversarial tests → 5 attacks out of 5 blocked with the right policy, the maths question allowed ($134.96).

Where to read it again. test_agent.py · TestTask2 · test_agent.py · ast.walk · tune_guardrail.py · _evaluate · adversarial_test.py · apply_guardrail.

To reuse. A fixed set of cases (allowed and blocked) written before tuning. Measure on the DRAFT version, publish only the best one. Keep the evaluation reports in evidence/.

Card 68 — AsyncMock: replacing an async call in a test

Project. DRILLS.ai (Builds, OpenAI DevDay hackathon)

In one sentence. AsyncMock(return_value=…) imitates an asyncThe keyword that declares a coroutine: a function that can be suspended and resumed (await), to handle several requests without blocking the program.See in the glossary → function; with monkeypatch.setattr, you replace a method of the agent for the length of a test, then everything goes back.

Why it matters for an agent. You test the routes, the ConsentThe person's explicit agreement before their data goes to a service. Without it, the request is rejected before any call.See in the glossary → and the headers with no network and no API credit. The fake returns a planned answer; the test checks what the code does with it.

Analogy. A rehearsal with an understudy: the staging is checked without bringing in the lead actor.

The mechanism.

def test_split_endpoints_require_consent_and_keep_private_responses(client, payload, analysis, result, monkeypatch):
    monkeypatch.setattr(api_main.ApplicationAgent, 'assess', AsyncMock(return_value=brief))
    monkeypatch.setattr(api_main.ApplicationAgent, 'draft', AsyncMock(return_value=result))
    response = client.post('/api/assessment', json=body)
    assert response.status_code == 200 and response.json()['drafts_pending']
    assert response.headers['cache-control'] == 'no-store'
    ...
    body['consent'] = False
    assert client.post('/api/application-drafts', json=body).status_code == 422

Input → output. Replayed on October 30: this test and the killed-subprocessThe Python module that launches another program (git, a CLI) and gets back its exit code and output.See in the glossary → one → 2 passed, with no network.

Where to read it. tests/test_application.py · test_split_endpoints… · test_pdf_worker_is_killed_on_timeout.

To reuse. One fake per boundary (model, network, subprocess). The test also checks refusals: consent set to False must give 422.

In the field

The chapters of my courses and my projects where these mechanisms run for real.