Skip to content

Testing

Guardrails are capabilities, so you test them the way you test any Pydantic AI agent: with TestModel, which returns canned output without calling a real model.

Terminal window
pip install pytest pytest-asyncio

pydantic_ai_guardrails.testing wraps the common cases. All helpers are async and build an agent on TestModel for you.

Helper Asserts
assert_input_blocked(guardrail, prompt) The input guardrail raises InputBlocked for prompt. Returns the exception
assert_output_blocked(guardrail, output_text, *, prompt='Hello') The output guardrail raises OutputBlocked when the model returns output_text. Use on_fail='raise' on the guardrail; with 'retry' the canned reply never changes. Returns the exception
assert_guardrail_passes(guardrail, prompt='Hello', *, output_text=None) The run completes. Returns the run result
run_with_input_guardrail(guardrail, prompt) Runs an agent with only this guardrail and returns the result

Every helper also accepts deps= for guardrails that read ctx.deps.

import pytest
from pydantic_ai_guardrails import DetectPII
from pydantic_ai_guardrails.testing import assert_input_blocked
@pytest.mark.anyio
async def test_reason(anyio_backend='asyncio'):
error = await assert_input_blocked(DetectPII(), 'mail me: jane@corp.com')
assert error.reason == 'detected PII: email'
import pytest
from pydantic_ai_guardrails import BlockRefusals, DetectPII, DetectPromptInjection, LimitOutputLength
from pydantic_ai_guardrails.testing import (
assert_guardrail_passes,
assert_input_blocked,
assert_output_blocked,
)
pytestmark = pytest.mark.anyio
@pytest.fixture
def anyio_backend():
return 'asyncio'
async def test_pii_blocked():
await assert_input_blocked(DetectPII(types=['ssn']), 'my SSN is 123-45-6789')
async def test_clean_prompt_passes():
await assert_guardrail_passes(DetectPromptInjection(), prompt='What is the weather?')
async def test_refusal_blocked():
await assert_output_blocked(BlockRefusals(on_fail='raise'), "I'm sorry, but I can't help with that.")
async def test_good_output_passes():
await assert_guardrail_passes(
LimitOutputLength(min_chars=10, on_fail='raise'),
output_text='A perfectly reasonable answer.',
)

The example uses the anyio pytest plugin, which is installed with this package. With pytest-asyncio, use @pytest.mark.asyncio instead.

For anything the helpers do not cover, such as several guardrails together, deps, or inspecting the error, build the agent yourself:

import pytest
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel
from pydantic_ai_guardrails import InputBlocked, OutputBlocked, RedactSecrets, DetectPII, MatchRegex
def test_reason_names_detected_type():
agent = Agent(TestModel(), capabilities=[DetectPII()])
with pytest.raises(InputBlocked) as exc_info:
agent.run_sync('email me at jane@example.com')
assert exc_info.value.guardrail == 'DetectPII'
assert 'email' in exc_info.value.reason
def test_secrets_are_redacted():
model = TestModel(custom_output_text='key: AKIAABCDEFGHIJKLMNOP')
agent = Agent(model, capabilities=[RedactSecrets()])
assert agent.run_sync('show config').output == 'key: [REDACTED]'
def test_output_must_contain_ticket_id():
model = TestModel(custom_output_text='No ticket here')
agent = Agent(model, capabilities=[MatchRegex(r'TICKET-\d+', on_fail='raise')])
with pytest.raises(OutputBlocked):
agent.run_sync('summarise')

Keep your real agent and swap the model in tests with agent.override:

from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel
from pydantic_ai_guardrails import LimitOutputLength
agent = Agent('openai:gpt-4o', capabilities=[LimitOutputLength(min_chars=5, on_fail='raise')])
def test_production_agent_guardrails():
with agent.override(model=TestModel(custom_output_text='Long enough')):
assert agent.run_sync('hi').output == 'Long enough'

With the default on_fail='retry', TestModel returns the same text every time, so the guardrail keeps failing until the retry budget is used up:

import pytest
from pydantic_ai import Agent
from pydantic_ai.exceptions import UnexpectedModelBehavior
from pydantic_ai.models.test import TestModel
from pydantic_ai_guardrails import LimitOutputLength
def test_retries_exhausted():
agent = Agent(
TestModel(custom_output_text='short'),
retries={'output': 2},
capabilities=[LimitOutputLength(min_chars=100)],
)
with pytest.raises(UnexpectedModelBehavior):
agent.run_sync('write an essay')

To test that the model recovers, use Pydantic AI’s FunctionModel and return different output on each call.

To run a table of prompts against a guardrail, see dataset_as_test_suite in the pydantic-evals integration.