pydantic-ai / tests
AGENTS.md20k starsChanged 2 months agoMITView on GitHub
Every async def test runs via the anyio pytest plugin automatically (anyio_mode = "auto" in pyproject.toml); don't add @pytest.mark.anyio. The async backend defaults to asyncio. Use uv run pytest <test-path> --anyio-backend=trio --record-mode=none to run selected portable tests on Trio without duplicating the default suite. During the Trio migration, run affected concurrency tests once per backend. Keep broad Trio runs manual or periodic; do not add a second backend to every ordinary CI matrix. The selector does not imply that every…
- Reads credentials
Trending
Less talk lately.about the whole repository
Who's talking about pydantic/pydantic-ai
- A Hacker News story“MCP Run Python”Hacker News · Apr 15, 2025 · 173 points
- @pythonhub.dev“PydanticAI PydanticAI is a Python Agent Framework designed to make it less painful to build production …”Bluesky · Dec 11, 2024 · 8 likes
- langfuse/langfuse“Add support for `gen_ai.system_instructions` gen-ai field”GitHub · Sep 19, 2025 · 7 reactions
- A Hacker News story“Agent Framework / shim to use Pydantic with LLMs”Hacker News · Dec 2, 2024 · 7 points
- pydantic/mcp-run-python“Dockerise the MCP Run Python server”GitHub · May 27, 2025 · 5 reactions
The biggest 5 of 64 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 64
Talked about on GitHub, Bluesky, Hacker News and the web (64 times).
On GitHub · 50
- Sep 19, 2025Add support for `gen_ai.system_instructions` gen-ai field — langfuse/langfuse7 reactions · 4 comments
- May 27, 2025Dockerise the MCP Run Python server — pydantic/mcp-run-python5 reactions · 6 comments
- Oct 16, 2025Inngest Durable execution with Pydantic-AI — inngest/inngest-py4 reactions · 9 comments
- May 23, 2025Handle `type[T]` for type variables — astral-sh/ty4 reactions · 3 comments
- Mar 12, 2026Impossible to run the app due to Mistral import error — Denario-AI/Denario3 reactions · 3 comments
45 more on GitHub
- Feb 27, 2026Anthropic cache tokens double-counted: usage.input already includes cache via OTel/genai-prices — langfuse/langfuse3 reactions · 6 comments
- May 25, 2025Misc. bug: Streaming with tools causes pydantic-ai to mess up tool name — ggml-org/llama.cpp3 reactions · 5 comments
- Jun 30, 2026chore(deps): bump pydantic-ai-slim from 1.63.0 to 1.102.0 in /python/examples/pydantic-ai-cdp-chatbot — Dustin4444/agentkit2 reactions · 5 comments
- Jun 30, 2026chore(deps): bump pydantic-ai from 1.63.0 to 1.102.0 in /python/examples/pydantic-ai-cdp-chatbot — Dustin4444/agentkit2 reactions · 6 comments
- May 21, 2026chore(deps): bump pydantic-ai from 1.66.0 to 1.99.0 in /python/framework-extensions/pydantic-ai — Dustin4444/agentkit2 reactions · 4 comments
- May 21, 2026chore(deps): bump pydantic-ai-slim from 1.66.0 to 1.99.0 in /python/framework-extensions/pydantic-ai — Dustin4444/agentkit2 reactions · 4 comments
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.2.15 to 1.56.0 in /backend — cicero-im/meeting-minutes2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 1.0.1 to 1.56.0 — cicero-im/codantic-aidisplayagent2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 1.0.1 to 1.56.0 — cicero-im/codantic-aidisplayagent2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai-slim from 0.0.46 to 1.56.0 in /pydantic-ai-langfuse — cicero-im/ottomator-agents2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 0.6.2 to 1.56.0 — cicero-im/paigeant2 reactions · 2 comments
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.2.6 to 1.56.0 — cicero-im/tunacode2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai-slim from 0.7.4 to 1.56.0 in /agent-backend — cicero-im/pydantic-ai-fastapi-react-vite-agent2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 1.0.10 to 1.56.0 in /examples/integrations/pydanticAI_researcher_example — cicero-im/memori2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 1.0.17 to 1.56.0 — cicero-im/github-issue-analysis2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.6.2 to 1.56.0 — cicero-im/paigeant2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.0.46 to 1.56.0 in /pydantic-ai-langfuse — cicero-im/ottomator-agents2 reactions · 1 comment
- Apr 1, 2026chore(deps): bump pydantic-ai-slim from 1.0.15 to 1.56.0 — cicero-im/pydantic_ai_claude_code2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.7.4 to 1.56.0 in /agent-backend — cicero-im/pydantic-ai-fastapi-react-vite-agent2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 0.0.30 to 1.56.0 — cicero-im/pydanticai_mcp_demo2 reactions · 1 comment
- Apr 1, 2026build(deps): bump pydantic-ai from 0.2.0 to 1.56.0 — cicero-im/lightblue-ai2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai from 0.3.1 to 1.56.0 — cicero-im/pydantic_ai_editor2 reactions · 2 comments
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.3.4 to 1.56.0 — cicero-im/mcp2 reactions · 2 comments
- Apr 1, 2026chore(deps): bump pydantic-ai-slim from 0.3.4 to 1.56.0 — cicero-im/mcp2 reactions · 3 comments
- Apr 1, 2026chore(deps): bump pydantic-ai-slim from 0.2.12 to 1.56.0 — cicero-im/pydantic-ai-mcp-experiment2 reactions · 1 comment
- Apr 1, 2026build(deps): bump pydantic-ai-slim from 0.2.18 to 1.56.0 — cicero-im/me-pydanticai-2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai from 0.0.30 to 1.56.0 — cicero-im/pydanticai_mcp_demo2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai-slim from 0.3.1 to 1.56.0 — cicero-im/pydantic_ai_editor2 reactions · 2 comments
- Apr 1, 2026build(deps): bump pydantic-ai from 0.2.18 to 1.56.0 — cicero-im/me-pydanticai-2 reactions · 2 comments
- Apr 1, 2026build(deps): bump pydantic-ai-slim from 0.0.52 to 1.56.0 — cicero-im/wa_llm2 reactions · 1 comment
- Apr 1, 2026build(deps): bump pydantic-ai-slim from 0.2.0 to 1.56.0 — cicero-im/lightblue-ai2 reactions · 1 comment
- Apr 1, 2026Bump pydantic-ai-slim from 0.0.43 to 1.56.0 — cicero-im/Ai_Tutor2 reactions · 1 comment
- Apr 1, 2026chore(deps): bump pydantic-ai from 0.0.42 to 1.56.0 — cicero-im/automagik-agents2 reactions · 2 comments
- Apr 1, 2026Bump pydantic-ai from 0.0.43 to 1.56.0 — cicero-im/Ai_Tutor2 reactions · 2 comments
- Apr 1, 2026build(deps): bump pydantic-ai from 0.0.52 to 1.56.0 — cicero-im/wa_llm2 reactions · 1 comment
- Mar 26, 2026build(deps): bump the pip group across 5 directories with 4 updates — GoldenEagle-23/oss-fuzz2 reactions · 1 comment
- Feb 28, 2026Error because `thoughtSignature` missing from Gemini 3 function call — Arjun-Vashistha/Test-Repo-22 reactions
- Nov 21, 2025Run generator.__anext__ in the same task to avoid anyio RuntimeError — langfuse/langfuse-python2 reactions · 1 comment
- Nov 14, 2025Dockerise MCP-run-python server + add git workflows to publish images — pydantic/mcp-run-python2 reactions · 5 comments
- Aug 4, 2025Tracking: Contribute FastMCP Toolset to Pydantic AI — PrefectHQ/fastmcp2 reactions · 1 comment
- Jul 12, 2025Tool context kwarg detection not compatible with string-valued/__future__ annotations — modelcontextprotocol/python-sdk2 reactions · 3 comments
- May 23, 2025Sequence of types — python/mypy2 reactions · 2 comments
- Aug 7, 2026Pydantic AI as an agentic engine — github/gh-aw1 reaction · 12 comments
- Jul 8, 2026chore: port pydantic-ai v2.6.0 changes — a7ul/vibes1 reaction
- Jul 7, 2026chore: port pydantic-ai v2.5.1 changes — a7ul/vibes1 reaction
On Bluesky · 7
- Dec 11, 2024PydanticAI PydanticAI is a Python Agent Framework designed to make it less painful to build production grade applications with Generative… — @pythonhub.dev8 likes and reposts
- Aug 9, 2025I use 'llm' now for my cli explorations with genai. Will i move to `clai` for that "FastAPI feeling" they promise? i do love pydantic! see:… — @paulkarayan.bsky.social2 likes and reposts
- Dec 4, 2024🚀 Skyrocketing! 🚀 (200+ new stars) 📦 pydantic / pydantic-ai ⭐ 1,319 (+429) 🗒 Python Agent Framework / shim to use Pydantic with LLMs — @github-trending.bsky.social2 likes and reposts · 1 reply
- Sep 3, 2025https://github.com/pydantic/pydantic-ai — @tom-doerr.bsky.social1 likes and repost
- Jul 18, 2025📦 pydantic / pydantic-ai ⭐ 10,912 (+49) 🗒 Python Agent Framework / shim to use Pydantic with LLMs — @github-trending.bsky.social1 likes and repost
2 more on Bluesky
- Dec 6, 2024PydanticAI: Build production-grade Agentic AI apps in pure Python! PydanticAI offers the same elegance and ease of use as FastAPI, now… — @akshay-pachaar.bsky.social1 likes and repost · 1 reply
- Dec 4, 2024github.com/pydantic/pyd... — @presidentlin.bsky.social0 likes and reposts · 1 reply
On Hacker News · 5
- Apr 15, 2025MCP Run Python173 points · 66 comments
- Dec 2, 2024Agent Framework / shim to use Pydantic with LLMs7 points · 3 comments
- Dec 3, 2024Pydantic AI3 points
- Dec 6, 2024PydanticAI using Ollama (llama3.2) running locally2 points · 3 comments
- Dec 5, 2024PydanticAI1 point
On the web · 2
- Oct 7, 2026Test Pydantic AI Agents – Scenario — langwatch.ai
- Jul 9, 2026Pydantic AI AI Agent Security Evaluation — trustvector.guard0.ai
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository56 other files it gives its agents.
- AGENTS.mdAGENTS.md
- docs/AGENTS.mdAGENTS.md
- docs/harness/AGENTS.mdAGENTS.md
- docs/realtime/AGENTS.mdAGENTS.md
- .github/workflows/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/capabilities/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/durable_exec/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/models/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/native_tools/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/profiles/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/providers/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/realtime/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/toolsets/AGENTS.mdAGENTS.md
- pydantic_ai_slim/pydantic_ai/ui/AGENTS.mdAGENTS.md
- src/pydantic_ai_harness/AGENTS.mdAGENTS.md
- src/pydantic_clai2/AGENTS.mdAGENTS.md
- tests/benchmarks/AGENTS.mdAGENTS.md
- tests/harness/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- docs/CLAUDE.mdCLAUDE.md
- docs/harness/CLAUDE.mdCLAUDE.md
- docs/realtime/CLAUDE.mdCLAUDE.md
- .github/workflows/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/models/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/native_tools/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/realtime/CLAUDE.mdCLAUDE.md
- pydantic_ai_slim/pydantic_ai/ui/CLAUDE.mdCLAUDE.md
- src/pydantic_ai_harness/CLAUDE.mdCLAUDE.md
- src/pydantic_clai2/CLAUDE.mdCLAUDE.md
- tests/benchmarks/CLAUDE.mdCLAUDE.md
- tests/CLAUDE.mdCLAUDE.md
- tests/harness/CLAUDE.mdCLAUDE.md
- adding-a-provider-api-featureSkill
- add-new-modelSkill
- complete-partial-prSkill
- docs-parity-reviewerSkill
- i-have-adhdSkill
- poweruser-feature-auditSkill
- pushing-commits-to-the-repoSkill
- address-feedbackSkill
- pre-push-reviewSkill
- testing-skillSkill
- building-pydantic-ai-agentsSkill
- migrating-agno-to-pydantic-aiSkill
- migrating-claude-agent-sdk-to-pydantic-aiSkill
- migrating-google-adk-to-pydantic-aiSkill
- migrating-langchain-to-pydantic-aiSkill
- migrating-mastra-to-pydantic-aiSkill
- migrating-openai-agents-sdk-to-pydantic-aiSkill
- migrating-pi-to-pydantic-aiSkill
- migrating-vercel-ai-sdk-and-eve-to-pydantic-aiSkill
- migrating-deep-agents-to-pydantic-ai-harnessSkill
- pydantic-ai-harnessSkill
- reviewerSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
15 rules. About 0 are common, 4 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 5
Every async def test runs via the anyio pytest plugin automatically (anyio_mode = "auto" in pyproject.toml).
- Very specific: line 92
Use the EXPECTATIONS dict only for a pure cartesian output lookup keyed by (model, stream).
- Distinctive: line 175
Test-only and third-party stacks are ignored.
- Very specific: line 177
Add legitimate blocking calls to BLOCKBUSTER_EXEMPTIONS in tests/conftest.py with a reason.
- Very specific: line 180
Use the narrowest module or test boundary.
- Very specific: line 260
Test through public APIs, not private methods (prefixed with _) or helpers — validates actual user-facing behavior and prevents brittle …
- Very specific: line 261
Prefer feature-centric parametrized test files (e.g.
- Very specific: line 262
Use snapshot() for complex structured outputs (objects, message sequences, API responses, nested dicts) — catches unexpected changes more …
- Distinctive: line 265
Test both positive and negative cases for optional capabilities (model features, server features, streaming) — ensures features work when …
- Distinctive: line 267
Ensure test assertions match test names and docstrings — tests without proper assertions or that verify opposite behavior create false …
- Very specific: line 268
Test MCP against real tests.mcp_server instance, not mocks — extend test server with helper tools to expose runtime context (instructions, …
- Distinctive: line 269
Remove stale test docstrings, comments, and historical provider bug notes when behavior changes
- Very specific: line 270
Prefer instructions= over system_prompt= when the test doesn't specifically need the system-prompt code path — instructions= is the …
- Very specific: line 271
Test async behavior directly, following Async & Concurrency — assert the cancellation, the ordering, or the cleanup itself rather than the …
- Very specific: line 272
Never reference line numbers in test docstrings or comments (lines 872-873, L42, line 100) — they go stale on the next edit to the …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Testing Guidelines
Testing philosophy
Every async def test runs via the anyio pytest plugin automatically (anyio_mode = "auto" in
pyproject.toml); don't add @pytest.mark.anyio. The async backend defaults to asyncio. Use
uv run pytest <test-path> --anyio-backend=trio --record-mode=none to run selected portable tests on Trio without duplicating the default suite. During the Trio migration,
run affected concurrency tests once per backend. Keep broad Trio runs manual or periodic; do not add a
second backend to every ordinary CI matrix. The selector does not imply that every test or integration
already supports Trio. tests/harness and tests/clai2 pin anyio_backend to asyncio in their conftest.py;
don't re-override it per file.
VCR + public-API tests are the default. We test through the public API the way a user would (Agent(...), agent.run(...)) against real provider responses recorded as cassettes — provider APIs are the ultimate judge of whether the code is correct when run as intended, and that user-facing correctness is what we care about, not behavior in isolated units.
Unit tests still earn their place — for internal behavior that is definitory and worth pinning against drift. That includes behavior you can't reach or reliably trigger through the public API (pre-request guards, defensive branches no real model produces), but also behavior a VCR test wouldn't actually protect: our cassette matchers aren't always sensitive to the request body, so a changed internal payload can still match an existing recording and pass green — a unit test asserting the internal shape directly is what catches that regression. Each unit test should still say why it isn't (or can't be) a VCR test.
Recording cassettes needs provider API keys and isn't trivial, so contributors routinely under-test the real behavior — writing the VCR test a contributor couldn't is core maintainer work.
Recorded cassettes also double as a suite-wide prompt-cache prefix regression net. The cache-prefix invariant checks that consecutive requests extend the same serialized provider-cache prefix; tests that deliberately move it through compaction, dynamic tool disclosure, or history rewriting must use @pytest.mark.moves_cache_prefix(reason=...) on the test.
Test File Structure
from __future__ import annotations
import pytest
from inline_snapshot import snapshot
from pydantic_ai import Agent
from pydantic_ai.models import Model
# ... other imports
pytestmark = pytest.mark.vcr
# fixtures/helpers immediately before their test
@pytest.fixture
def my_helper():
...
@pytest.mark.parametrize('model', ['openai', 'anthropic', 'google'], indirect=True)
@pytest.mark.parametrize('stream', [False, True])
async def test_feature(model: Model, stream: bool):
...Parametrization with Expectations
For cartesian product tests, use a dict to map parameter combinations to expected results:
from cassetter import Cassette
from pydantic_ai.models import Model
# expectation can be a dataclass, for more complex cases
EXPECTATIONS: dict[tuple[str, bool], str] = {
('openai', False): 'expected output for openai non-streaming',
('openai', True): 'expected output for openai streaming',
('anthropic', False): 'expected output for anthropic non-streaming',
('anthropic', True): 'expected output for anthropic streaming',
}
@pytest.mark.parametrize('model', ['openai', 'anthropic'], indirect=True)
@pytest.mark.parametrize('stream', [False, True])
async def test_feature(model: Model, stream: bool, request: pytest.FixtureRequest, vcr: Cassette):
"""What the test is asserting.
Use the `request` fixture to access test parameter values.
Use the `vcr` to make assertions about the HTTP requests if needed.
To assert what the code actually sent — headers included — take the `request_capture` fixture
instead. It reads the wire rather than the recording, so it is preferred whenever a transport
can be injected.
"""
model_name = request.node.callspec.params['model']
expected = EXPECTATIONS[(model_name, stream)]
agent = Agent(model)
if stream:
async with agent.run_stream('hello') as result:
output = await result.get_output()
else:
result = await agent.run('hello')
output = result.output
assert output == expectedUse the EXPECTATIONS dict only for a pure cartesian output lookup keyed by (model, stream). For feature-centric files where cases are heterogeneous — different inputs, expectations, and xfails per case, all run through one minimal comprehensive test — use a @dataclass Case with sensible defaults plus per-case overrides:
from dataclasses import dataclass, field
import pytest
from inline_snapshot import snapshot
from pydantic_ai import Agent
from pydantic_ai.messages import ModelMessage
@dataclass(frozen=True)
class Case:
id: str
model: str
prompt: str = 'hello'
instructions: str | None = None
expected_messages: list[ModelMessage] = field(default_factory=list[ModelMessage])
marks: tuple[pytest.MarkDecorator, ...] = ()
CASES = [
Case(
id='openai',
model='openai:gpt-5',
expected_messages=snapshot([...]),
),
Case(
id='anthropic',
model='anthropic:claude-sonnet-4-5',
instructions='be terse',
expected_messages=snapshot([...]),
marks=(pytest.mark.skipif(not anthropic_available(), reason='anthropic not installed'),),
),
]
@pytest.mark.parametrize('case', [pytest.param(c, id=c.id, marks=c.marks) for c in CASES])
async def test_feature(case: Case):
agent = Agent(case.model, instructions=case.instructions)
result = await agent.run(case.prompt)
assert result.all_messages() == case.expected_messagesEach case carries its own snapshot (not the central test body), so a reviewer can read the cases top to bottom and check that every expectation is realistic.
VCR Workflow
Record cassettes with --record-mode=rewrite, verify playback without the flag, and review diffs.
For detailed workflows see .claude/skills/testing-skill/SKILL.md.
Realtime WebSocket cassettes
Realtime cassettes live in tests/realtime/cassettes/<module>/<test>.yaml. Record them with
uv run --env-file .env pytest --record-mode=rewrite <test>; normal test runs replay them offline.
Unlike HTTP cassettes, they contain raw WebSocket frames, with secrets scrubbed and audio payloads
truncated. The testing skill's parse_cassette.py is HTTP-only and does not apply to these cassettes.
Asserting what goes out on the wire
Four mechanisms, and they are not interchangeable — pick by what the test's claim is about.
An httpx request hook — the boundary tap, and the first reach. Request the request_capture fixture from tests/conftest.py, route the provider through request_capture.client, and assert on request_capture.body(path_suffix); see test_anthropic_code_execution_tool_container_reuse in tests/models/test_anthropic.py. For an Anthropic model the anthropic_model factory does the routing, so anthropic_model('claude-sonnet-4-5', capture=True) is the whole setup. The fixture's client is an httpx2.AsyncClient carrying an event_hooks={'request': [...]} recorder, and event hooks run inside AsyncClient.send, above cassetter's transport patches, so the hook fires on replay too and observes the request the live code actually built — a field the code stops sending fails the assertion instead of hiding behind a frozen recording. It costs the cassette nothing: matching is untouched, so fields that legitimately vary stay free to vary, and it sees what a cassette will not, headers included (the recording hooks in tests/cassette_hooks.py strip anthropic-*, so the wire is the only place a test can assert beta gating). Snapshot a projection of the body rather than the body itself — content_blocks, message_shape and cache_breakpoints, in tests/models/conftest.py, pin the fields a claim rests on without churning on unrelated conversation-shape changes. The fixture is reachable from anywhere under tests/; those three projections are not. A test outside tests/models/ imports them explicitly (from tests.models.conftest import message_shape) rather than re-implementing the comprehension inline. The shared fixture works only when the provider accepts httpx2.AsyncClient as its injected client. Check the provider signature before using it. GroqProvider requires legacy httpx.AsyncClient, and HuggingFaceProvider rejects http_client in favor of hf_client; capture those SDK boundaries with provider-specific clients. A provider on another transport taps its own send-time event for the same reason — see _capture_bedrock_request_headers in tests/models/test_bedrock.py, a botocore before-send handler.
Snapshot the request body — the review surface. single_request_body in tests/cassette_utils.py decodes the request the cassette holds, so assert single_request_body(vcr) == snapshot({...}) puts the whole outbound payload in the test body instead of leaving it buried in a long YAML. What it does not do is catch drift: the recording is frozen, so it keeps passing after the live code stops sending a field, and a recording can already disagree with what the code sends today. Its second job is at re-record time, where a changed payload surfaces as a snapshot diff. Where a hook is attached, snapshot what the hook captured instead — same review surface, and it is the request that is actually going out.
A per-test matcher — the gate for when you cannot tap the boundary. Making a field part of the cassette match also fails when the live code drifts: a request that no longer carries the recorded value cannot match its recording, so replay errors instead of quietly passing. Reach for it when the test doesn't build its own model (a shared or indirect fixture supplies it), when one guard should cover a whole family of tests, or when the provider isn't on httpx. Opt the test in with @pytest.mark.vcr(additional_matchers=['body']), which adds to the default method + uri match rather than replacing it; cassetter's matchers are method, uri, headers, body and json_body, and a module vcr_config override can set match_on for a whole directory (see tests/harness/media/conftest.py) or ignore_json_paths for fields that legitimately vary. Match on the fields the test's claim rests on, not on every field you snapshot — matching a field that legitimately varies makes the cassette brittle and buys no information, which is the cost a hook doesn't have.
Capture the render — for claims no single exchange holds. When the SDK client is mocked outright so nothing goes over the wire, or the claim is that two renderings are byte-identical rather than that one recorded request looked a certain way, capture what the adapter produces and assert against that; see test_tool_availability_delta_and_the_tools_cache_section in tests/test_tool_availability_portability.py, and rendered_requests in tests/models/test_anthropic_mid_conversation_system.py for the per-request form. Where the requests do go out over httpx, the boundary tap gets the same evidence without reaching into adapter internals.
Default for a test that asserts an outbound field: take the capture fixture and assert on what it recorded, snapshotting a projection when the whole payload is worth reviewing. Fall back to snapshotting the cassette body and matching on the field where no hook can be attached. Don't add field-by-field asserts alongside a snapshot — the snapshot already pins them.
Key Fixtures
From conftest.py
Model requests
allow_model_requests- bypasses the defaultALLOW_MODEL_REQUESTS = False
Blocking-call detection
blockbuster(autouse) raisesBlockingErrorwhen a scanned library frame blocks inside the event loop.- Scanned packages are
pydantic_ai,pydantic_graph,pydantic_evals, andclai. - Test-only and third-party stacks are ignored. User callbacks remain covered while a scanned library frame is below them.
- Fix blocking calls by offloading with
anyio.to_thread.run_sync. - Add legitimate blocking calls to
BLOCKBUSTER_EXEMPTIONSintests/conftest.pywith a reason. - Override
blockbuster_excluded_moduleswhen one integration module intentionally provides synchronous APIs. - Override
blockbuster_enabledat the narrowest test or integration-module boundary that intentionally performs blocking work. - Use the narrowest module or test boundary. Do not replace the autouse
blockbusterfixture. - Each pytest worker configures one detector per exclusion set and activates it separately for each test.
- CI enables BlockBuster in Python 3.13 slim, evals, and standard jobs, plus unique compatibility or live-provider jobs.
- The all-extras job disables BlockBuster because its stack-inspection overhead exceeds the seven-minute CI budget. Rebenchmark after BlockBuster #61 is released in a compatible version, and re-enable it if the job stays within seven minutes.
- Other Python-version lanes disable BlockBuster because they repeat the same dependency set.
- Lowest-version lanes disable BlockBuster to keep jobs within the seven-minute CI budget. This leaves dependency-version-specific blocking behavior outside CI detection.
- Local targeted tests enable BlockBuster by default.
The model fixture (use with indirect=True)
The model fixture takes a string param (e.g. 'openai', 'anthropic', 'google') and returns a configured Model instance, using session-scoped API key fixtures that default to 'mock-api-key' (real keys loaded from env when recording).
See tests/conftest.py for the full list of supported param values.
@pytest.mark.parametrize('model', ['openai', 'anthropic'], indirect=True)
async def test_something(model: Model):
...Environment management
env-TestEnvinstance for temporary env var changesdef test_missing_key(env: TestEnv): env.remove('OPENAI_API_KEY') with pytest.raises(UserError): ...
Binary content (session-scoped)
assets_path-Pathtotests/assets/image_content-BinaryImage(kiwi.jpg)audio_content-BinaryContent(marcelo.mp3)video_content-BinaryContent(small_video.mp4)document_content-BinaryContent(dummy.pdf)text_document_content-BinaryContent(dummy.txt)
SSRF protection for URL downloads
disable_ssrf_protection_for_vcr- required for VCR tests that download URL content (ImageUrl,AudioUrl,DocumentUrl,VideoUrlwithforce_download=True)
Asserting the outbound request
request_capture- aRequestCapturewhoseclientrecords every outbound request; read bodies with.body(path_suffix)/.bodies(path_suffix)and headers off.headers. See "Asserting what goes out on the wire" for when to reach for it
From models/conftest.py
Available to every test under tests/models/. See "Asserting what goes out on the wire" for when to reach for them.
anthropic_model- factory forAnthropicModel;capture=Trueroutes it throughrequest_capture.clientasync def test_something( allow_model_requests: None, anthropic_model: AnthropicModelFactory, request_capture: RequestCapture ): agent = Agent(anthropic_model('claude-sonnet-4-5', capture=True)) await agent.run('hello') assert message_shape(request_capture.body('/v1/messages')) == snapshot([...])content_blocks(body, block_type),message_shape(body),cache_breakpoints(body)- plain functions, not fixtures; projections of a captured body to snapshot instead of the whole payload
Assertion Helpers
From conftest.py
IsNow(tz=timezone.utc)- datetime within 10 seconds of nowIsStr()- any string, supportsregex=r'...'IsDatetime()- any datetimeIsBytes()- any bytesIsInt()- any intIsFloat()- any floatIsList()- any listIsInstance(SomeClass)- instance of class
Additional helpers
IsSameStr()- asserts same string value across multiple uses in one assertionassert events == [ {'id': (msg_id := IsSameStr())}, {'id': msg_id}, # must match first ]
Best Practices
- Test through public APIs, not private methods (prefixed with
_) or helpers — validates actual user-facing behavior and prevents brittle tests tied to implementation details - Prefer feature-centric parametrized test files (e.g.
test_multimodal_tool_returns.py) over appending to monolithictest_<provider>.pyfiles — the legacy per-provider files are large and hard for agents to navigate; new features should get their own test file with aCaseclass and parametrized providers - Use
snapshot()for complex structured outputs (objects, message sequences, API responses, nested dicts) — catches unexpected changes more reliably than field-by-field assertions; useIsStrand similar matchers for variable values - Assert the core aspect of the change being introduced — use whatever means necessary: patching clients to inspect request payloads, tapping into pydantic-ai internals, snapshot comparisons. Snapshots are valuable for catching structural drift in objects and message arrays, but only use
result.all_messages()or output assertions when the structure demonstrates behavior you care about keeping consistent - Pin recorded facts in the test body, never in the cassette alone — cassettes are long and humans skim them, so a load-bearing fact that only lives in the recording is effectively unreviewed. If a recording demonstrates something worth keeping (a resolved model alias, the actual returned format, an echoed setting), assert it in the test and explain it in the docstring
- Test both positive and negative cases for optional capabilities (model features, server features, streaming) — ensures features work when supported AND fail gracefully when absent
- When a change branches on a model-profile flag (a
profile.get(...)read), at least one test must pin a model on each side of that flag so both the flag-on and flag-off paths run; if only one side is reachable, say why in the test. This is stricter than the capability bullet above and mechanical: it fires on any profile-flag branch, including a flag that is ambient to the feature under test, and one side alone does not satisfy it. Coverage cannot catch the gap, since the branch line reads at 100% while the on/off combination goes unvisited - Ensure test assertions match test names and docstrings — tests without proper assertions or that verify opposite behavior create false positives
- Test MCP against real
tests.mcp_serverinstance, not mocks — extend test server with helper tools to expose runtime context (instructions, client info, session state) - Remove stale test docstrings, comments, and historical provider bug notes when behavior changes
- Prefer
instructions=oversystem_prompt=when the test doesn't specifically need the system-prompt code path —instructions=is the canonical entry point for non-system-prompt-specific behavior (cacheable prefix, persona priming, format guidance), and reservingsystem_prompt=for tests that exercise the system-prompt machinery keeps intent legible - Test async behavior directly, following Async & Concurrency — assert the cancellation, the ordering, or the cleanup itself rather than the output it happens to produce, order steps with
Events instead of sleeps, and diffasyncio.all_tasks()to prove nothing leaked - Never reference line numbers in test docstrings or comments (
lines 872-873,L42,line 100) — they go stale on the next edit to the referenced file. Describe the condition or behavior instead - When testing prompt caching, assert prefix stability, not just a cache hit —
cache_read_tokens > 0only proves that some prefix was reused, not that the prefix you intended stayed stable as history grows; pin it by asserting the cacheable region (serialized leading blocks up to the breakpoint) is byte-identical across consecutive requests and/or that the cache read covers the full prior prefix, since a per-request injection or serialization that moves with history length silently busts the cache with no error - When you deprecate a public symbol (add
@deprecated), add a test asserting the warning fires — apytest.warns(PydanticAIDeprecationWarning, match=...)block whosematchpins both the symbol name and the migration guidance — so the deprecation is protected against accidental removal or a message rewrite, and any executable docstring/doc example that constructs the symbol is marked{test="skip"}(it would otherwise fail underfilterwarnings=["error"]) - Don't blanket-suppress
reportDeprecatedat file scope — no whole-file# pyright: ignore(or# pyright: basic) at the top of a file to kill every deprecation static-warning at once, since that also silences the next unintended use of a deprecated symbol in the file. Put# pyright: ignore[reportDeprecated]on each intentional call instead. (The runtime side is different and conventional: a module-levelwarnings.filterwarnings('ignore', message=...)scoped to one deprecation message, in a file that pervasively constructs the deprecated symbol it tests — seetests/durable_exec/temporal/test_agent.py/tests/durable_exec/test_prefect.py— is fine, as long as a dedicatedpytest.warnstest still proves the deprecation fires.) - Gate on a missing optional dependency with
try_import(), the default. It has two halves and they live in different files: each test module wraps its optional imports inwith try_import() as imports_successful:and appliespytestmark = pytest.mark.skipif(not imports_successful(), reason='<dep> not installed')(seetests/models/anthropic/test_native_tool_filtering.py); aconftest.pywraps its own optional imports the same way but carries no skip of its own (seetests/models/anthropic/conftest.py) — a conftest'spytestmarkis not inherited by the modules it serves, so the mark there would gate nothing whiletry_importstill keeps the file importable. Reach forpytest.skip(..., allow_module_level=True)only when the module cannot importtests/conftest.pyat all — the Temporal suite can't, because that would pullcassetterinto a module the workflow sandbox re-imports. In that case the gate goes in the test modules and any non-test helper they import (tests/durable_exec/temporal/_shared.py), never in theconftest.py, which instead stays importable without the dependency by deferring its fixtures' imports into the fixture bodies. Reason: pytest loads the conftest of every command-line argument's directory before collection, and_importconftestcatches onlyExceptionwhileSkippedis aBaseException, so a gate there escapes as a traceback with exit 1 the moment someone names that directory (or a node id inside it) instead of a parent. Seetests/durable_exec/temporal/conftest.pyand the guard intests/durable_exec/test_temporal_skip_gating.py - Do not use subprocesses to test logic that can run in-process. Starting another interpreter and importing the project again makes the full suite materially slower. Reserve subprocesses for behavior that depends on the process boundary, such as CLI invocation, interpreter startup, or import isolation. Scrub
COVERAGE_*from a required subprocess environment so[tool.coverage.run] patch = ["subprocess"]does not instrument the child.
Directory Structure
tests/
├── conftest.py # shared fixtures
├── cassette_hooks.py # scrubbing and header filtering applied while recording
├── assets/ # binary test files
├── cassettes/ # VCR recordings for root tests
├── models/
│ ├── conftest.py # model-specific fixtures (if needed)
│ ├── cassettes/ # VCR recordings per test file
│ │ ├── test_openai/
│ │ ├── test_anthropic/
│ │ └── ...
│ └── test_*.py
├── providers/
│ └── test_*.py # provider initialization tests (unit)
└── test_*.py # feature tests (prefer VCR + parametrize)Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

