pytest · gentleman-programming — Claude Code skill: Python test patterns
A skill with pytest patterns: fixtures, mocking, markers, parametrization. Kicks in when the agent writes Python tests.
Apache-2.0 291 installs ★ 678 updated 2026-03-28
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-codeWhat pytest does
The skill gives the agent a set of pytest patterns. It covers test class structure, fixtures with yield-based cleanup, mocking via unittest.mock, parametrized tests, and markers like slow or integration.
Examples include checking exceptions with pytest.raises, fixture scopes (module, class, session), and shared fixtures in conftest.py. Async tests are handled with @pytest.mark.asyncio.
The skill activates when the agent is asked to write Python tests. It installs through npx skills add from the Gentleman-Skills repo. Apache-2.0 license.
What it helps with
- write a test class with exception checks
- set up a fixture that cleans up a temp file
- mock a payment service in a test
- run one test with many input values
- mark slow tests and skip them in a run
Example prompts for the agent
- Write a test for create_user that checks the invalid email exception
- Create a fixture for a temp file with cleanup after the test
- Mock stripe_client in process_payment and assert charge was called
How to install pytest
1Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-code2Manually: put the files in place
~/.claude/skills/pytest/SKILL.mdCopy the whole skill folder; for one project use .claude/skills/pytest/
1Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a codex2Manually: put the files in place
.agents/skills/pytest/SKILL.mdFor all projects use ~/.agents/skills/
1Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a cursor2Manually: put the files in place
.cursor/skills/pytest/SKILL.mdCursor also reads .agents/skills/ and .claude/skills/
1GitHub CLI
gh skill install Gentleman-Programming/Gentleman-Skills curated/pytest/SKILL.md2Manually: put the files in place
.github/skills/pytest/SKILL.md1Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a gemini-cli2Platform CLI
gemini skills install https://github.com/Gentleman-Programming/Gentleman-Skills --path curated/pytestManually: put the files in place
.devin/skills/pytest/SKILL.mdThe legacy .windsurf/skills/ path still works
Skills CLI (Vercel)
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a opencodeClaude.ai
Zip the folder and upload it in Settings → Capabilities → Skills
Step by step, with commands for each platform: How to install skills in Claude Code: five ways
Questions about pytest
How do I install pytest in Claude Code?
Run npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-code. The skill lands in ~/.claude/skills/pytest/SKILL.md.
What does the pytest skill do?
It gives the agent patterns for Python tests: fixtures, mocking, markers, parametrization, async tests. It triggers when tests are being written.
Where do shared fixtures live?
In conftest.py. The skill shows how to place fixtures like db_session or api_client there.
Source text
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
Similar skills
All skills for Testing and QA →pytest by other authors comes first.