pytest · gentleman-programming — скилл для Claude Code: паттерны тестов на Python
Скилл для Claude Code добавляет шаблоны тестов на pytest: фикстуры, моки, маркеры и параметризацию. Помогает агенту писать тесты для Python-кода.
Apache-2.0 291 установок ★ 678 обновлён 2026-03-28
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-codeЧто делает pytest
Скилл добавляет агенту набор паттернов для тестов на pytest. Внутри — структура тестовых классов, фикстуры с очисткой через yield, моки через unittest.mock, параметризация через @pytest.mark.parametrize и маркеры вроде slow или integration.
Есть готовые примеры: проверка исключений через pytest.raises, фикстуры с разными scope (module, class, session), общие фикстуры в conftest.py. Асинхронные тесты тоже покрыты — через @pytest.mark.asyncio.
Скилл срабатывает, когда агент видит задачу на написание тестов на Python. Ставить нужно через npx skills add, скилл подхватывается из общего репозитория Gentleman-Skills. Лицензия Apache-2.0.
Какие задачи решает
- написать тестовый класс с проверкой исключений
- поднять фикстуру с очисткой временного файла
- замокать внешний сервис в тесте оплаты
- прогнать один тест с разными входными данными
- разметить медленные тесты и запускать только быстрые
Примеры запросов агенту
- Напиши тест для create_user с проверкой исключения на невалидный email
- Сделай фикстуру для временного файла с очисткой после теста
- Замокай stripe_client в тесте process_payment и проверь вызов charge
Как установить pytest
1Через Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-code2Вручную: положить файлы
~/.claude/skills/pytest/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/pytest/
1Через Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a codex2Вручную: положить файлы
.agents/skills/pytest/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a cursor2Вручную: положить файлы
.cursor/skills/pytest/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install Gentleman-Programming/Gentleman-Skills curated/pytest/SKILL.md2Вручную: положить файлы
.github/skills/pytest/SKILL.md1Через Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a gemini-cli2Командой платформы
gemini skills install https://github.com/Gentleman-Programming/Gentleman-Skills --path curated/pytestВручную: положить файлы
.devin/skills/pytest/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о pytest
Как установить pytest в Claude Code?
Выполни npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-code. Скилл появится в ~/.claude/skills/pytest/SKILL.md.
Что делает скилл pytest?
Даёт агенту паттерны для тестов на Python: фикстуры, моки, маркеры, параметризацию и асинхронные тесты. Срабатывает при написании тестов.
Где хранятся фикстуры для нескольких тестов?
В conftest.py — скилл показывает, как вынести туда общие фикстуры вроде db_session или api_client.
Исходный текст
SKILL.md · Apache-2.0
---
name: pytest
description: >
Pytest testing patterns for Python.
Trigger: When writing Python tests - fixtures, mocking, markers.
license: Apache-2.0
metadata:
author: gentleman-programming
version: "1.0"
---
## Basic Test Structure
```python
import pytest
class TestUserService:
def test_create_user_success(self):
user = create_user(name="John", email="[email protected]")
assert user.name == "John"
assert user.email == "[email protected]"
def test_create_user_invalid_email_fails(self):
with pytest.raises(ValueError, match="Invalid email"):
create_user(name="John", email="invalid")
```
## Fixtures
```python
import pytest
@pytest.fixture
def user():
"""Create a test user."""
return User(name="Test User", email="[email protected]")
@pytest.fixture
def authenticated_client(client, user):
"""Client with authenticated user."""
client.force_login(user)
return client
# Fixture with teardown
@pytest.fixture
def temp_file():
path = Path("/tmp/test_file.txt")
path.write_text("test content")
yield path # Test runs here
path.unlink() # Cleanup after test
# Fixture scopes
@pytest.fixture(scope="module") # Once per module
@pytest.fixture(scope="class") # Once per class
@pytest.fixture(scope="session") # Once per test session
```
## conftest.py
```python
# tests/conftest.py - Shared fixtures
import pytest
@pytest.fixture
def db_session():
session = create_session()
yield session
session.rollback()
@pytest.fixture
def api_client():
return TestClient(app)
```
## Mocking
```python
from unittest.mock import patch, MagicMock
class TestPaymentService:
def test_process_payment_success(self):
with patch("services.payment.stripe_client") as mock_stripe:
mock_stripe.charge.return_value = {"id": "ch_123", "status": "succeeded"}
result = process_payment(amount=100)
assert result["status"] == "succeeded"
mock_stripe.charge.assert_called_once_with(amount=100)
def test_process_payment_failure(self):
with patch("services.payment.stripe_client") as mock_stripe:
mock_stripe.charge.side_effect = PaymentError("Card declined")
with pytest.raises(PaymentError):
process_payment(amount=100)
# MagicMock for complex objects
def test_with_mock_object():
mock_user = MagicMock()
mock_user.id = "user-123"
mock_user.name = "Test User"
mock_user.is_active = True
result = get_user_info(mock_user)
assert result["name"] == "Test User"
```
## Parametrize
```python
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("world", "WORLD"),
("pytest", "PYTEST"),
])
def test_uppercase(input, expected):
assert input.upper() == expected
@pytest.mark.parametrize("email,is_valid", [
("[email protected]", True),
("invalid-email", False),
("", False),
("[email protected]", False),
])
def test_email_validation(email, is_valid):
assert validate_email(email) == is_valid
```
## Markers
```python
# pytest.ini or pyproject.toml
[tool.pytest.ini_options]
markers = [
"slow: marks tests as slow",
"integration: marks integration tests",
]
# Usage
@pytest.mark.slow
def test_large_data_processing():
...
@pytest.mark.integration
def test_database_connection():
...
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
...
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_specific():
...
# Run specific markers
# pytest -m "not slow"
# pytest -m "integration"
```
## Async Tests
```python
import pytest
@pytest.mark.asyncio
async def test_async_function():
result = await async_fetch_data()
assert result is not None
```
## Commands
```bash
pytest # Run all tests
pytest -v # Verbose output
pytest -x # Stop on first failure
pytest -k "test_user" # Filter by name
pytest -m "not slow" # Filter by marker
pytest --cov=src # With coverage
pytest -n auto # Parallel (pytest-xdist)
pytest --tb=short # Short traceback
```
## Keywords
pytest, python, testing, fixtures, mocking, parametrize, markers
© gentleman-programming · Apache-2.0 · Gentleman-Programming/Gentleman-Skills
Похожие скиллы
Все скиллы по теме «Тесты и QA» →Сначала — pytest от других авторов.