Async Testing Expert
БесплатноБез исполняемых скриптовНе проверенComprehensive pytest skill for async Python testing with proper mocking, fixtures, and patterns from production-ready test suites. Use when writing or…
от diegosouzapw★ 68 звёзд на GitHubОб этом скилле
Async Testing Expert
Expert guidance for writing comprehensive async Python tests using pytest, based on production patterns from a 387-test FastAPI backend test suite.
When to Use This Skill
Activate this skill when:
- Writing async tests for FastAPI applications
- Testing async database operations (PostgreSQL, MySQL, etc.)
- Setting up pytest fixtures for async applications
- Creating mock objects for database connections
- Testing services with dependency injection
- Writing DAO (Data Access Object) layer tests
- Testing async API endpoints
Core Principles
1. Test Organization
tests/
├── conftest.py # Shared fixtures (app, client, event_loop, faker)
├── fakes.py # Reusable mock objects (FakeConnection, FakeRecord)
├── test_<module>_dao.py # DAO layer tests
├── test_<module>_service.py # Service layer tests
├── test_<module>_router.py # API endpoint tests
└── test_<module>_dto.py # DTO validation tests
2. Naming Conventions
- Test files:
test_<module>_<layer>.py - Test functions:
test_<what>_<scenario>(e.g.,test_create_calls_execute,test_fetch_by_id_error_maps_to_500) - Be descriptive: readers should understand what's being tested without reading the code
3. Always Use Type Hints
async def test_fetch_user_success(faker: Faker) -> None:
user_id: int = faker.random_int(1, 100)
conn: FakeConnection = FakeConnection()
# ...
Essential Fixtures (conftest.py)
FastAPI Application Fixtures
import asyncio
import pytest
from fastapi.testclient import TestClient
from httpx import AsyncClient, ASGITransport
from faker import Faker
@pytest.fixture(scope='session')
def app():
"""Create a FastAPI app instance for testing."""
from src.config.factory import create_app
return create_app()
@pytest.fixture(scope='session')
def client(app):
"""Provides a synchronous TestClient for FastAPI."""
with TestClient(app) as c:
yield c
@pytest.fixture
async def async_client(app):
"""Provides an asynchronous AsyncClient for FastAPI using ASGI transport."""
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url='http://test') as ac:
yield ac
@pytest.fixture
def event_loop():
"""Create a new event loop for each test."""
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest.fixture
def faker():
"""Provide a Faker instance configured for Brazilian Portuguese."""
return Faker('pt_BR') # Adjust locale as needed
Mock Objects for Database Testing (fakes.py)
FakeRecord - Simulate Query Results
class FakeRecord:
"""Simulate a database record with a .result() method and optional rowcount."""
def __init__(self, data, rowcount=None):
self._data = data
self.rowcount = rowcount if rowcount is not None else (
data if isinstance(data, int) else 1
)
def result(self):
return self._data
FakeConnection - Full Database Mock
class FakeConnection:
"""Simulate a psqlpy/asyncpg Connection with execute, fetch, fetch_val, and fetch_row."""
def __init__(self):
self.execute_return = None
self.fetch_return = None
self.fetch_row_return = None
self.fetch_val_return = None
self.execute_calls = []
self.fetch_calls = []
self.fetch_val_calls = []
def transaction(self):
return FakeTransactionContext(self)
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
return False
async def execute(self, stmt, parameters=None):
self.execute_calls.append((stmt, parameters))
if isinstance(self.execute_return, Exception):
raise self.execute_return
# Support list of return values for multiple execute calls
if (isinstance(self.execute_return, list) and
len(self.execute_return) > 0 and
all(isinstance(item, list) for item in self.execute_return)):
return FakeRecord(self.execute_return.pop(0))
return FakeRecord(self.execute_return)
async def execute_many(self, stmt, parameters_list=None):
"""Simulate execute_many for bulk operations."""
if parameters_list is None:
parameters_list = []
self.execute_calls.append((stmt, parameters_list))
if isinstance(self.execute_return, Exception):
raise self.execute_return
total_rows = len(parameters_list) if parameters_list else 0
return FakeRecord(data=total_rows, rowcount=total_rows)
async def fetch(self, stmt, parameters=None):
self.fetch_calls.append((stmt, parameters))
return FakeRecord(self.fetch_return)
async def fetch_val(self, stmt, parameters=None):
self.fetch_val_calls.append((stmt, parameters))
if isinstance(self.fetch_val_return, Exception):
raise sel
Установить Async Testing Expert в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл Async Testing Expert?
Comprehensive pytest skill for async Python testing with proper mocking, fixtures, and patterns from production-ready test suites. Use when writing or improving async tests for Python applications, especially FastAPI backends with database interactions.
Как установить скилл Async Testing Expert?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Async Testing Expert запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic