К основному содержанию
скилл CX Codex

pydantic-ai-testing — скилл для Claude Code: тесты PydanticAI

Скилл pydantic-ai-testing помогает писать тесты для агентов PydanticAI: подменять ответы модели, проверять вызовы инструментов и воспроизводить записанные API-запросы.

Apache-2.0 146 установок ★ 89 обновлён 2026-09-15

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add existential-birds/beagle --skill pydantic-ai-testing -a claude-code
Открыть на GitHub

Что делает pydantic-ai-testing

Для тестов без API-вызовов скилл предлагает TestModel: можно задать текстовый или структурированный ответ, закрепить seed либо заставить модель вызвать нужный инструмент. FunctionModel позволяет описать собственную логику ответа. Через agent.override тесты подменяют модель и зависимости, а capture_run_messages помогает изучить сообщения прогона.

Для проверок с реальными ответами используются VCR-кассеты в tests/cassettes/, для сравнения результатов — inline-снимки. Обновление кассет и снимков меняет файлы на диске: после записи или исправления нужно повторно запустить тесты без флагов обновления и проверить git diff. В примерах используются pytest и команды uv run pytest; примеры кода написаны на Python.

Какие задачи решает

  • проверить ответ агента без API-вызова
  • задать модели тестовый структурированный ответ
  • проверить, что агент вызвал нужный инструмент
  • подменить зависимости агента в тесте
  • записать и воспроизвести ответы API через VCR-кассеты

Примеры запросов агенту

  • Напиши тест агента PydanticAI без API-вызова с помощью TestModel.
  • Проверь, что агент вызывает fetch_data, и подмени его зависимости в тесте.
  • Добавь тест с VCR-кассетой и обнови её для выбранного тестового файла.

Как установить pydantic-ai-testing

1Через Skills CLI (Vercel)

npx skills add existential-birds/beagle --skill pydantic-ai-testing -a claude-code

2Вручную: положить файлы

~/.claude/skills/pydantic-ai-testing/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/pydantic-ai-testing/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о pydantic-ai-testing

Как установить pydantic-ai-testing в Claude Code?

Выполните npx skills add existential-birds/beagle --skill pydantic-ai-testing -a claude-code. Файл скилла находится по пути ~/.claude/skills/pydantic-ai-testing/SKILL.md.

Что делает pydantic-ai-testing?

Помогает тестировать агентов PydanticAI с подменными моделями, VCR-кассетами и inline-снимками. Включает приёмы для проверки вызовов инструментов и подмены зависимостей.

Как безопасно обновить VCR-кассету или inline-снимок?

Сначала запустите целевые тесты без флагов записи и исправления. Затем обновите только нужные файлы и снова запустите тесты без этих флагов; проверьте изменения через git diff.

Исходный текст

SKILL.md · Apache-2.0
---
name: pydantic-ai-testing
description: Test PydanticAI agents using TestModel, FunctionModel, VCR cassettes, and inline snapshots. Use when writing unit tests, mocking LLM responses, or recording API interactions.
---

# Testing PydanticAI Agents

## TestModel (Deterministic Testing)

Use `TestModel` for tests without API calls:

```python
import pytest
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel

def test_agent_basic():
    agent = Agent('openai:gpt-4o')

    # Override with TestModel for testing
    result = agent.run_sync('Hello', model=TestModel())

    # TestModel generates deterministic output based on output_type
    assert isinstance(result.output, str)
```

## TestModel Configuration

```python
from pydantic_ai.models.test import TestModel

# Custom text output
model = TestModel(custom_output_text='Custom response')
result = agent.run_sync('Hello', model=model)
assert result.output == 'Custom response'

# Custom structured output (for output_type agents)
from pydantic import BaseModel

class Response(BaseModel):
    message: str
    score: int

agent = Agent('openai:gpt-4o', output_type=Response)
model = TestModel(custom_output_args={'message': 'Test', 'score': 42})
result = agent.run_sync('Hello', model=model)
assert result.output.message == 'Test'

# Seed for reproducible random output
model = TestModel(seed=42)

# Force tool calls
model = TestModel(call_tools=['my_tool', 'another_tool'])
```

## Override Context Manager

```python
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel

agent = Agent('openai:gpt-4o', deps_type=MyDeps)

def test_with_override():
    mock_deps = MyDeps(db=MockDB())

    with agent.override(model=TestModel(), deps=mock_deps):
        # All runs use TestModel and mock_deps
        result = agent.run_sync('Hello')
        assert result.output
```

## FunctionModel (Custom Logic)

For complete control over model responses:

```python
from pydantic_ai import Agent, ModelMessage, ModelResponse, TextPart
from pydantic_ai.models.function import AgentInfo, FunctionModel

def custom_model(
    messages: list[ModelMessage],
    info: AgentInfo
) -> ModelResponse:
    """Custom model that inspects messages and returns response."""
    # Access the last user message
    last_msg = messages[-1]

    # Return custom response
    return ModelResponse(parts=[TextPart('Custom response')])

agent = Agent(FunctionModel(custom_model))
result = agent.run_sync('Hello')
```

### FunctionModel with Tool Calls

```python
from pydantic_ai import ToolCallPart, ModelResponse
from pydantic_ai.models.function import AgentInfo, FunctionModel

def model_with_tools(
    messages: list[ModelMessage],
    info: AgentInfo
) -> ModelResponse:
    # First request: call a tool
    if len(messages) == 1:
        return ModelResponse(parts=[
            ToolCallPart(
                tool_name='get_data',
                args='{"id": 123}'
            )
        ])

    # After tool response: return final result
    return ModelResponse(parts=[TextPart('Done with tool result')])

agent = Agent(FunctionModel(model_with_tools))

@agent.tool_plain
def get_data(id: int) -> str:
    return f"Data for {id}"

result = agent.run_sync('Get data')
```

## VCR Cassettes (Recorded API Calls)

Record and replay real LLM API interactions:

```python
import pytest

@pytest.mark.vcr
def test_with_recorded_response():
    """Uses recorded cassette from tests/cassettes/"""
    agent = Agent('openai:gpt-4o')
    result = agent.run_sync('Hello')
    assert 'hello' in result.output.lower()

# To record/update cassettes:
# uv run pytest --record-mode=rewrite tests/test_file.py
```

Cassette files are stored in `tests/cassettes/` as YAML.

## Inline Snapshots

Assert expected outputs with auto-updating snapshots:

```python
from inline_snapshot import snapshot

def test_agent_output():
    result = agent.run_sync('Hello', model=TestModel())

    # First run: creates snapshot
    # Subsequent runs: asserts against it
    assert result.output == snapshot('expected output here')

# Update snapshots:
# uv run pytest --inline-snapshot=fix
```

## Gates: VCR cassettes and inline snapshots

Recording or fixing rewrites files on disk. Follow this sequence; do not skip steps.

1. **Replay pass (no record/fix flags):** Run `uv run pytest` on the target path; **all green** (or failures are understood and unrelated to the artifact you will refresh).
2. **Scope locked:** Identify the cassette under `tests/cassettes/` or the `snapshot(...)` assertion to update; confirm **only** those files should change.
3. **Record or fix:** Run **one** scoped command: `uv run pytest --record-mode=rewrite …` **or** `uv run pytest --inline-snapshot=fix …` for that path only.
4. **Post-condition:** Run the same tests again **without** record/fix flags; **all green**. Inspect `git diff` — only expected `.yaml` / snapshot changes.

If step 4 fails, revert unintended diffs and fix the test or model before re-recording.

## Testing Tools

```python
from pydantic_ai import Agent, RunContext
from pydantic_ai.models.test import TestModel

def test_tool_is_called():
    agent = Agent('openai:gpt-4o')
    tool_called = False

    @agent.tool_plain
    def my_tool(x: int) -> str:
        nonlocal tool_called
        tool_called = True
        return f"Result: {x}"

    # Force TestModel to call the tool
    result = agent.run_sync(
        'Use my_tool',
        model=TestModel(call_tools=['my_tool'])
    )

    assert tool_called
```

## Testing with Dependencies

```python
from dataclasses import dataclass
from unittest.mock import AsyncMock

@dataclass
class Deps:
    api: ApiClient

def test_tool_with_deps():
    # Create mock dependency
    mock_api = AsyncMock()
    mock_api.fetch.return_value = {'data': 'test'}

    agent = Agent('openai:gpt-4o', deps_type=Deps)

    @agent.tool
    async def fetch_data(ctx: RunContext[Deps]) -> dict:
        return await ctx.deps.api.fetch()

    with agent.override(
        model=TestModel(call_tools=['fetch_data']),
        deps=Deps(api=mock_api)
    ):
        result = agent.run_sync('Fetch data')

    mock_api.fetch.assert_called_once()
```

## Capture Messages

Inspect all messages in a run:

```python
from pydantic_ai import Agent, capture_run_messages

agent = Agent('openai:gpt-4o')

with capture_run_messages() as messages:
    result = agent.run_sync('Hello', model=TestModel())

# Inspect captured messages
for msg in messages:
    print(msg)
```

## Testing Patterns Summary

| Scenario | Approach |
|----------|----------|
| Unit tests without API | `TestModel()` |
| Custom model logic | `FunctionModel(func)` |
| Recorded real responses | `@pytest.mark.vcr` |
| Assert output structure | `inline_snapshot` |
| Test tools are called | `TestModel(call_tools=[...])` |
| Mock dependencies | `agent.override(deps=...)` |

## pytest Configuration

Typical `pyproject.toml`:

```toml
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"  # For async tests
```

Run tests:
```bash
uv run pytest tests/test_agent.py -v
uv run pytest --inline-snapshot=fix  # Update snapshots
```

© existential-birds · Apache-2.0 · existential-birds/beagle

Похожие скиллы

Все скиллы по теме «Тесты и QA» →
building-pydantic-ai-agents pydantic Скилл building-pydantic-ai-agents учит помощника проектировать приложения на Pydantic AI с инструментами и валидацией ответов. Пригодится при сборке типизированных агентных систем. CX Codex +1 6 600установок migrating-deep-agents-to-pydantic-ai-harness pydantic Скилл migrating-deep-agents-to-pydantic-ai-harness для Claude Code переносит Python-приложения LangChain Deep Agents на Pydantic AI и Pydantic AI Harness. Работает с контрактами middleware, памяти, субагентов и sandbox. CX Codex +1 234установок testing-livekit-agents livekit Скилл testing-livekit-agents генерирует пошаговые тесты для агентов LiveKit в pytest или Vitest. Помогает проверить вызовы тулов, передачи диалога и регрессии прямо в коде. CX Codex +1 516установок python-testing-patterns Seth Hobson Скилл python-testing-patterns помогает писать тесты Python с pytest, фикстурами и моками. Подходит для настройки тестового набора и отладки падающих проверок. CX Codex +1 36 943установок temporal-python-testing Seth Hobson Скилл temporal-python-testing помогает писать тесты для Temporal workflow на pytest: с пропуском времени, моками активностей и проверкой воспроизведения истории. Пригодится при разработке workflow и разборе падений тестов. CX Codex +1 10 900установок python-testing affaan-m Скилл python-testing задаёт подход к тестам Python на pytest: TDD, фикстуры, моки, параметризацию и проверку покрытия. Пригодится при создании и ревью тестов. CX Codex +1 6 800установок

Из того же набора68

Весь набор →
postgres-code-review Скилл postgres-code-review проверяет SQL, схемы и код работы с PostgreSQL: ищет проблемы с индексами, JSONB, соединениями и транзакциями. Подключайте его при ревью изменений в базе. CX Codex +1 158установок explanation-docs Скилл explanation-docs для Claude Code помогает писать документы о том, как и почему устроена система. Документирует архитектурные решения и материалы для онбординга. CX Codex +1 152установок llm-artifacts-detection Скилл llm-artifacts-detection находит типичный мусор после ИИ-кодеров: лишние слои абстракций, тесты стандартных библиотек, мёртвый код и очевидные комментарии. CX Codex +1 151установок go-testing-code-review Скилл go-testing-code-review ревьюит тесты Go: табличные кейсы, сообщения об ошибках, параллельность и покрытие. Замечания отдаёт с файлом, строкой и важностью. CX Codex +1 148установок adr-decision-extraction Скилл adr-decision-extraction извлекает архитектурные решения из чатов и расшифровок, чтобы подготовить материал для ADR. Он распознаёт выбор технологий, компромиссы и явные метки. CX Codex +1 144установок deepagents-implementation Скилл deepagents-implementation для Claude Code даёт рецепты сборки агентов на Deep Agents: фабрика create_deep_agent, файловые бэкенды, субагенты и стриминг LangGraph. CX Codex +1 142установок llm-judge Скилл llm-judge сравнивает две и более реализации одной задачи по файлу спецификации: собирает факты, ставит оценки по пяти измерениям и выдаёт отчёт с победителем. CX Codex +1 141установок pydantic-ai-dependency-injection Скилл pydantic-ai-dependency-injection показывает, как передавать базы данных, API-клиенты и контекст пользователя в PydanticAI через RunContext и deps_type. CX Codex +1 141установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой