一键导入
python-testing
Python testing patterns with pytest including unit tests, integration tests, fixtures, mocking, and coverage. Use when writing Python tests.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Python testing patterns with pytest including unit tests, integration tests, fixtures, mocking, and coverage. Use when writing Python tests.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Drive a GitHub issue — bare or tracked on a Project board — from triage to a merge-ready PR through a gated pipeline (design hardening, tests green, code-review clean), scaling the machinery to the task's tier and asking at most one batched question. Auto-links the issue to close on merge, advances the board card, then merges and cleans up once you approve the PR in-session. Triggers: "take task N", "work on issue #N", "do the next task", "build/fix X" when no issue exists yet, and — for the merge gate later — "merge it", "approve the PR", "ship it", "lgtm merge".
Slim or restructure an oversized CLAUDE.md into path-scoped .claude/rules/ files, verifying nothing was lost. Use when it exceeds ~200 lines, when Claude ignores instructions in it, or when choosing between CLAUDE.md, rules, skills and @import.
Use when removing AI-generation patterns from text in English or Russian. Auto-detects language by Cyrillic ratio and applies the matching ruleset. Trigger phrases: "humanize this", "remove AI patterns", "make this sound human", "очеловечить текст", "убрать признаки нейросети", "сделай текст живым". Honors explicit overrides like "humanize as English" / "обработай как русский". For mixed-language text, asks which ruleset to apply.
Reads input artifact(s) — codebase, planning session, refactor plan, or generic doc — and writes a tour-spec.json describing sections, embedded sources, cross-refs, quizzes, and external link maps. Use when the user wants a fresh learning guide built from source material; auto-hands-off to learning-guide:render. Trigger phrases — "create a learning guide for X", "make an interactive tour", "generate onboarding doc", "build a learning module".
Use when the user asks to "create a learning guide", "make an interactive tour", "generate onboarding doc", "build a learning module", or any variant of turning an artifact (codebase, planning session, refactor plan, design doc) into an interactive HTML guide. Dispatches to learning-guide:analyze for new tours or learning-guide:render for re-renders after spec edits. Also use when the user is uncertain which step they need.
Renders an existing tour-spec.json to a self-contained interactive HTML guide via the bundled Node renderer. Use when the user has hand-edited a tour-spec.json, when learning-guide:analyze hands off after drafting, or when the user explicitly asks to "render the tour", "regenerate the HTML", or "update the embedded sources". Idempotent for generated artifacts; preserves user-edited README and tour-spec.json.
| name | python-testing |
| description | Python testing patterns with pytest including unit tests, integration tests, fixtures, mocking, and coverage. Use when writing Python tests. |
You are a testing specialist for Python projects.
conftest.py or pytest.ini → pytest[tool.pytest.ini_options] in pyproject.toml → pytestunittest imports → unittest (suggest migrating to pytest)tox.ini → tox runnernox → nox runnerimport pytest
from unittest.mock import Mock, AsyncMock, patch
class TestUserService:
@pytest.fixture
def mock_repository(self) -> Mock:
return Mock(spec=UserRepository)
@pytest.fixture
def service(self, mock_repository: Mock) -> UserService:
return UserService(mock_repository)
def test_get_user_returns_user_when_exists(
self, service: UserService, mock_repository: Mock
) -> None:
# Arrange
expected_user = User(id="1", name="Test", email="test@example.com")
mock_repository.find_by_id.return_value = expected_user
# Act
result = service.get_user("1")
# Assert
assert result == expected_user
mock_repository.find_by_id.assert_called_once_with("1")
def test_get_user_returns_none_when_not_exists(
self, service: UserService, mock_repository: Mock
) -> None:
# Arrange
mock_repository.find_by_id.return_value = None
# Act
result = service.get_user("unknown")
# Assert
assert result is None
@pytest.mark.parametrize("input_value,expected", [
("hello", "HELLO"),
("", ""),
("Hello World", "HELLO WORLD"),
])
def test_to_uppercase(input_value: str, expected: str) -> None:
assert to_uppercase(input_value) == expected
# Mock with spec for type safety
mock_repo = Mock(spec=UserRepository)
# Patch module-level dependencies
with patch("myapp.services.requests.get") as mock_get:
mock_get.return_value.json.return_value = {"id": "1"}
result = fetch_user("1")
# AsyncMock for async functions
mock_client = AsyncMock(spec=HttpClient)
mock_client.get.return_value = {"data": "value"}
Use the async plugin configured by the project (pytest-asyncio or pytest-anyio).
Note: Examples below use
@pytest.mark.asyncio(pytest-asyncio). If the project uses pytest-anyio, replace with@pytest.mark.anyio.
import pytest
from unittest.mock import AsyncMock
@pytest.mark.asyncio
async def test_async_fetch() -> None:
mock_session = AsyncMock()
mock_session.get.return_value.__aenter__.return_value.json = AsyncMock(
return_value={"id": "1"}
)
result = await fetch_data(mock_session, "http://example.com")
assert result == {"id": "1"}
@pytest.fixture
async def db_session():
"""Create a test database session."""
async with async_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async with AsyncSession(async_engine) as session:
yield session
async with async_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest.mark.asyncio
async def test_create_and_fetch_user(db_session: AsyncSession) -> None:
repo = SqlAlchemyUserRepository(db_session)
user = User(name="Test", email="test@example.com")
await repo.save(user)
fetched = await repo.find_by_id(user.id)
assert fetched is not None
assert fetched.name == "Test"
from fastapi.testclient import TestClient
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
def test_create_user(client: TestClient) -> None:
response = client.post("/users", json={"name": "Test", "email": "test@example.com"})
assert response.status_code == 201
assert response.json()["name"] == "Test"
# conftest.py - shared fixtures
import pytest
@pytest.fixture(scope="session")
def app_config() -> Config:
"""Application config for tests."""
return Config(api_url="http://test", timeout=5, debug=True)
@pytest.fixture
def temp_dir(tmp_path: "Path") -> "Path":
"""Temporary directory for file tests."""
return tmp_path
pytest-cov for coverage reports.env files or API keys in tests