Pydantic AI mocking for tests
Quick answer
Use Python's unittest.mock or pytest-mock to patch pydantic_ai.Agent.run_sync or run methods, returning predefined results for test isolation. This enables testing your code without calling the actual AI API.
PREREQUISITES
Python 3.8+pip install pydantic-aipip install pytest (optional for pytest-mock)
Setup
Install pydantic-ai via pip. Optionally install pytest and pytest-mock for easier mocking in tests.
pip install pydantic-aipip install pytest pytest-mock(optional)
Ensure your AI agent is created with pydantic_ai.Agent and configured with your model and system prompt.
pip install pydantic-ai
pip install pytest pytest-mock output
Collecting pydantic-ai Downloading pydantic_ai-0.1.0-py3-none-any.whl Collecting pytest Downloading pytest-7.4.0-py3-none-any.whl Collecting pytest-mock Downloading pytest_mock-3.11.1-py3-none-any.whl Successfully installed pydantic-ai pytest pytest-mock
Step by step
Mock Agent.run_sync in your test to return a fake response object with the expected attributes. This avoids real API calls and allows asserting your code's behavior.
from pydantic_ai import Agent
from pydantic import BaseModel
import os
from unittest.mock import patch
class Result(BaseModel):
answer: str
confidence: float
# Create the agent
agent = Agent(
"openai:gpt-4o-mini",
result_type=Result,
system_prompt="You are a helpful assistant."
)
# Function to test
def ask_question(question: str) -> str:
result = agent.run_sync(question)
return result.data.answer
# Test with mocking
def test_ask_question():
fake_result = Result(answer="Mocked answer", confidence=0.99)
class FakeResponse:
data = fake_result
with patch.object(agent, "run_sync", return_value=FakeResponse()):
answer = ask_question("What is RAG?")
assert answer == "Mocked answer"
if __name__ == "__main__":
test_ask_question()
print("Test passed: Mocked response returned correctly.") output
Test passed: Mocked response returned correctly.
Common variations
- Use
pytest-mockfixturemockerto patchrun_syncin pytest tests. - Mock async
Agent.runwithAsyncMockfor async code. - Mock different models by creating agents with other model strings.
import pytest
from pydantic_ai import Agent
from pydantic import BaseModel
class Result(BaseModel):
answer: str
confidence: float
@pytest.fixture
def agent():
return Agent("openai:gpt-4o-mini", result_type=Result)
# Using pytest-mock
def test_mock_with_pytest_mocker(agent, mocker):
fake_result = Result(answer="Pytest mock answer", confidence=0.95)
class FakeResponse:
data = fake_result
mocker.patch.object(agent, "run_sync", return_value=FakeResponse())
result = agent.run_sync("Hello")
assert result.data.answer == "Pytest mock answer"
# Async mocking example
import asyncio
from unittest.mock import AsyncMock
async def test_async_mock():
agent = Agent("openai:gpt-4o-mini", result_type=Result)
fake_result = Result(answer="Async mock answer", confidence=0.9)
class FakeResponse:
data = fake_result
agent.run = AsyncMock(return_value=FakeResponse())
response = await agent.run("Hello async")
assert response.data.answer == "Async mock answer" output
============================= test session starts ============================== collected 2 items test_example.py .. [100%] ============================== 2 passed in 0.12s ===============================
Troubleshooting
- If your mock returns
AttributeError, ensure your fake response has thedataattribute with the expected fields. - For async tests, use
pytest-asyncioandAsyncMockto properly mockAgent.run. - Verify your agent is created with the correct
result_typeto match the mocked response.
Key Takeaways
- Mock Agent.run_sync or run to isolate tests from real AI calls.
- Use unittest.mock.patch.object or pytest-mock for clean mocking.
- Ensure your fake response matches the result_type model structure.
- For async code, use AsyncMock and async test frameworks.
- Mocking improves test speed, reliability, and repeatability.