pytest
БесплатноБез исполняемых скриптовНе проверенpytest is the standard Python test framework: plain assert statements, fixtures for setup and teardown, parametrized tests and a large plugin ecosystem. Use…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
pytest
Overview
pytest collects functions named test_* in files named test_*.py (or *_test.py), runs them, and rewrites plain assert statements so a failure shows both sides of the comparison. Fixtures provide setup and teardown, parametrize runs one test over many inputs, and plugins add async support, coverage, mocking and parallel runs. This skill targets pytest 9.x (checked against 9.1) with pytest-asyncio 1.x.
Instructions
Step 1: Install and configure
python -m venv .venv && source .venv/bin/activate
pip install pytest pytest-asyncio pytest-cov pytest-mock pytest-xdist
Put configuration in pyproject.toml ([tool.pytest.ini_options]) or, since pytest 9, in a native pytest.toml:
# pytest.toml
[pytest]
pythonpath = ["."] # lets tests import top-level modules such as `app`
testpaths = ["tests"]
asyncio_mode = "auto" # pytest-asyncio: no @pytest.mark.asyncio on every test
markers = ["slow: tests that take more than a second"]
strict = true # unknown markers and options become errors
Without pythonpath (or an installed package), from app import ... fails with ModuleNotFoundError when pytest is run from the project root.
Step 2: Basic tests
# tests/test_users.py
import pytest
from app.services.users import create_user, validate_email
def test_create_user_returns_user_object():
user = create_user(name="Priya Nair", email="[email protected]")
assert user.name == "Priya Nair"
assert user.id is not None
def test_validate_email_rejects_invalid():
assert validate_email("not-an-email") is False
assert validate_email("user@") is False
class TestUserService:
"""A class only groups tests; no base class or self.assert* methods needed."""
def test_duplicate_email_raises(self):
create_user(name="Priya Nair", email="[email protected]")
with pytest.raises(ValueError, match="Email already exists"):
create_user(name="Tom Berg", email="[email protected]")
Step 3: Fixtures
# tests/conftest.py — shared by every test in this directory and below
import pytest
import pytest_asyncio
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from app.models import Base, User
@pytest_asyncio.fixture # async fixtures need this decorator in strict mode
async def db():
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async with async_sessionmaker(engine, expire_on_commit=False)() as session:
yield session # code after yield is the teardown
await engine.dispose()
@pytest_asyncio.fixture
async def sample_user(db):
user = User(name="Priya Nair", email="[email protected]", role="member")
db.add(user)
await db.commit()
return user
@pytest.fixture
def api_client(db):
from fastapi.testclient import TestClient
from app.main import app
from app.dependencies import get_db
app.dependency_overrides[get_db] = lambda: db
yield TestClient(app)
app.dependency_overrides.clear()
That example needs pip install "sqlalchemy[asyncio]" aiosqlite. Built-in fixtures worth knowing: tmp_path (a fresh directory per test), monkeypatch (set env vars and attributes, undone automatically), capsys and caplog (captured output and log records). A fixture's scope can be function (default), class, module, package or session; widen it only for expensive, read-only resources.
Step 4: Parametrize
@pytest.mark.parametrize(
"plan,expected_price",
[("free", 0), ("starter", 29), ("pro", 79), pytest.param("enterprise", 199, id="enterprise-list-price")],
)
def test_calculate_price(plan, expected_price):
assert calculate_price(plan) == expected_price
pytest 9 also ships subtests (a subtests fixture) for looping over cases inside one test without stopping at the first failure:
def test_slugify_variants(subtests):
for raw, slug in [("Hello World", "hello-world"), (" Spaces ", "spaces")]:
with subtests.test(raw=raw):
assert slugify(raw) == slug
Step 5: Mocking
# tests/test_notifications.py — pytest-mock provides the `mocker` fixture
from unittest.mock import AsyncMock
async def test_send_welcome_email(mocker, sample_user):
send = mocker.patch("app.services.email.send_email", new_callable=AsyncMock,
return_value={"id": "msg_8841"})
result = await send_welcome_email(sample_user.id)
send.assert_awaited_once_with(to="[email protected]", subject="Welcome!", template="welcome")
assert result["id"] == "msg_8841"
Patch the name where it is looked up (app.services.notifications.send_email, if that module did from ... import send_email), not where it is defined.
Step 6: Run
pytest # everything under testpath
Установить pytest в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл pytest?
pytest is the standard Python test framework: plain assert statements, fixtures for setup and teardown, parametrized tests and a large plugin ecosystem. Use when a user asks to write unit tests, set up test fixtures, mock dependencies, run async tests, measure coverage, run tests in parallel, or practice test-driven development in Python.
Как установить скилл pytest?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл pytest запускает скрипты?
Нет, скилл состоит только из инструкций (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