python-testing · laurigates — скилл для Claude Code: что делает и как установить
Помогает писать тесты на pytest, настраивать фикстуры, моки и проверку покрытия кода. Пригодится при разработке на Python по методологии TDD.
npx skills add laurigates/claude-plugins --skill python-testing -a claude-codeЧто делает python-testing
Скилл подключает правила и шпаргалки по тестированию на Python через pytest. Он подсказывает агенту, как запускать тесты через менеджер uv, собирать отчёты покрытия с помощью pytest-cov, а также изолировать внешние вызовы через unittest.mock или плагин pytest-mock. Для анализа файлов и запуска команд скилл задействует инструменты Bash, Read, Grep и Glob.
Внутри собраны паттерны для параметризации тестов @pytest.mark.parametrize, асинхронных проверок с @pytest.mark.asyncio, создания временных файлов через tmp_path и типовой конфигурации в pyproject.toml. Скилл не вызывается отдельной командой. Он включается автоматически, когда в диалоге заходит речь о тестах или TDD.
Для сложных иерархий conftest.py или параллельного запуска тестов через pytest-xdist возможностей скилла не хватит: автор советует переходить на pytest-advanced.
Какие задачи решает
- написать базовые юнит-тесты и параметризованные проверки на pytest
- настроить запуск тестов и сбор отчётов покрытия через uv
- изолировать внешние API с помощью unittest.mock и фикстур
- проверить асинхронный код и перехват исключений
Примеры запросов агенту
- Напиши юнит-тесты на pytest для модуля auth.py с проверкой исключений
- Сделай фикстуру базы данных в conftest.py и добавь мок для внешнего API
- Запусти тесты через uv с генерацией отчёта покрытия в терминале
Как установить python-testing
1Через Skills CLI (Vercel)
npx skills add laurigates/claude-plugins --skill python-testing -a claude-code2Вручную: положить файлы
~/.claude/skills/python-testing/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/python-testing/
1Через Skills CLI (Vercel)
npx skills add laurigates/claude-plugins --skill python-testing -a codex2Вручную: положить файлы
.agents/skills/python-testing/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add laurigates/claude-plugins --skill python-testing -a cursor2Вручную: положить файлы
.cursor/skills/python-testing/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install laurigates/claude-plugins python-testing2Вручную: положить файлы
.github/skills/python-testing/SKILL.md1Через Skills CLI (Vercel)
npx skills add laurigates/claude-plugins --skill python-testing -a gemini-cli2Командой платформы
gemini skills install https://github.com/laurigates/claude-plugins --path python-plugin/skills/python-testingВручную: положить файлы
.devin/skills/python-testing/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add laurigates/claude-plugins --skill python-testing -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о python-testing
Как установить python-testing в Claude Code?
Выполните в терминале команду npx skills add laurigates/claude-plugins --skill python-testing -a claude-code. Навык сохранится в каталог ~/.claude/skills/python-testing/SKILL.md.
Что делает этот скилл?
Он предоставляет ИИ-ассистенту готовые шаблоны и правила для работы с pytest: фикстуры, мокирование, асинхронные тесты и шаги цикла TDD.
Когда стоит выбрать pytest-advanced вместо python-testing?
Автор рекомендует pytest-advanced, если вам нужна настройка pytest-xdist, собственные хуки или общие библиотеки фикстур для нескольких пакетов.
Исходный текст
SKILL.md · MIT
---
created: 2025-12-16
modified: 2026-05-09
reviewed: 2026-04-25
name: python-testing
description: Python testing with pytest, coverage, fixtures, and mocking. Use when the user mentions pytest, unit tests, coverage, fixtures, mocking, or writing Python tests.
user-invocable: false
allowed-tools: Bash, Read, Grep, Glob
---
# Python Testing
Quick reference for Python testing with pytest, coverage, fixtures, and best practices.
## When to Use This Skill
| Use this skill when... | Use pytest-advanced instead when... |
|---|---|
| Writing first pytest tests, learning fixtures and parametrization basics | Designing reusable conftest.py fixture hierarchies or parallel-execution markers |
| Setting up coverage reporting and basic mocking with `unittest.mock` | Tuning pytest-xdist, custom markers, or hookimpl plugins |
| Following TDD red-green-refactor cycles on a single module | Building shared fixture libraries across a multi-package test suite |
## When This Skill Applies
- Writing unit tests and integration tests
- Test-driven development (TDD)
- Test fixtures and parametrization
- Coverage analysis
- Mocking and patching
- Async testing
## Quick Reference
### Running Tests
```bash
# Basic test run
uv run pytest
# Verbose output
uv run pytest -v
# Show print statements
uv run pytest -s
# Stop at first failure
uv run pytest -x
# Run specific test
uv run pytest tests/test_module.py::test_function
# Run by keyword
uv run pytest -k "test_user"
```
### Test Coverage
```bash
# Run with coverage
uv run pytest --cov
# HTML report
uv run pytest --cov --cov-report=html
# Show missing lines
uv run pytest --cov --cov-report=term-missing
# Coverage for specific module
uv run pytest --cov=mymodule tests/
```
### Fixtures
```python
import pytest
@pytest.fixture
def sample_data():
return {"key": "value"}
@pytest.fixture(scope="module")
def db_connection():
conn = create_connection()
yield conn
conn.close()
def test_with_fixture(sample_data):
assert sample_data["key"] == "value"
```
### Parametrize Tests
```python
import pytest
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("world", "WORLD"),
("test", "TEST"),
])
def test_uppercase(input: str, expected: str):
assert input.upper() == expected
@pytest.mark.parametrize("value,is_valid", [
(1, True),
(0, False),
(-1, False),
])
def test_validation(value, is_valid):
assert validate(value) == is_valid
```
### Markers
```python
import pytest
@pytest.mark.slow
def test_slow_operation():
# Long-running test
pass
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
pass
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_specific():
pass
@pytest.mark.xfail
def test_known_issue():
# Expected to fail
pass
```
```bash
# Run only marked tests
uv run pytest -m slow
uv run pytest -m "not slow"
```
### Async Testing
```python
import pytest
@pytest.mark.asyncio
async def test_async_function():
result = await async_operation()
assert result == expected_value
@pytest.fixture
async def async_client():
client = AsyncClient()
await client.connect()
yield client
await client.disconnect()
```
### Mocking
```python
from unittest.mock import Mock, patch, MagicMock
def test_with_mock():
mock_obj = Mock()
mock_obj.method.return_value = "mocked"
assert mock_obj.method() == "mocked"
@patch('module.external_api')
def test_with_patch(mock_api):
mock_api.return_value = {"status": "success"}
result = call_external_api()
assert result["status"] == "success"
# pytest-mock (cleaner)
def test_with_mocker(mocker):
mock = mocker.patch('module.function')
mock.return_value = 42
assert function() == 42
```
## Test Organization
```
project/
├── src/
│ └── myproject/
│ ├── __init__.py
│ └── module.py
└── tests/
├── __init__.py
├── conftest.py # Shared fixtures
├── test_module.py
└── integration/
└── test_api.py
```
## conftest.py
```python
# tests/conftest.py
import pytest
@pytest.fixture(scope="session")
def app_config():
return {"debug": True, "testing": True}
@pytest.fixture(autouse=True)
def reset_db():
setup_database()
yield
teardown_database()
```
## pyproject.toml Configuration
```toml
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
addopts = [
"-v",
"--strict-markers",
"--cov=src",
"--cov-report=term-missing",
]
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration tests",
]
[tool.coverage.run]
source = ["src"]
omit = ["*/tests/*", "*/test_*.py"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"def __repr__",
"raise AssertionError",
"raise NotImplementedError",
"if __name__ == .__main__.:",
]
```
## Common Testing Patterns
### Test Exceptions
```python
import pytest
def test_raises_exception():
with pytest.raises(ValueError):
function_that_raises()
def test_raises_with_message():
with pytest.raises(ValueError, match="Invalid input"):
function_that_raises()
```
### Test Warnings
```python
import pytest
def test_deprecation_warning():
with pytest.warns(DeprecationWarning):
deprecated_function()
```
### Temporary Files
```python
def test_with_tmp_path(tmp_path):
file_path = tmp_path / "test.txt"
file_path.write_text("content")
assert file_path.read_text() == "content"
```
## TDD Workflow
```bash
# 1. RED: Write failing test
uv run pytest tests/test_new_feature.py
# FAILED
# 2. GREEN: Implement minimal code
uv run pytest tests/test_new_feature.py
# PASSED
# 3. REFACTOR: Improve code
uv run pytest # All tests pass
```
## See Also
- `uv-project-management` - Adding pytest to projects
- `python-code-quality` - Combining tests with linting
- `python-development` - Core Python development patterns
## References
- Official docs: https://docs.pytest.org/
- Detailed guide: See REFERENCE.md in this skill directory
© laurigates · MIT · laurigates/claude-plugins
Похожие скиллы
Все скиллы по теме «Тесты и QA» →Сначала — python-testing от других авторов.