Skip to main content
skill CX Codex

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

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-code
Open on GitHub

What 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-code

2Manually: put the files in place

~/.claude/skills/pytest/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/pytest/

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.

pytest Claude MPM Team A pytest skill for Claude Code, Codex, Cursor and other platforms. Adds fixtures, parametrization, markers, async support and integration with FastAPI, Django, Flask. CX Codex +1 1,300installs pytest Claude Support Team Teaches the agent to write tests for support APIs, databases, and background jobs using FastAPI and SQLAlchemy. Sets up pytest fixtures and async tests. CX Codex +1 458installs pytest-patterns manutej pytest-patterns is a Claude Code skill for structuring Python tests with pytest, including fixtures and parametrization. CX Codex +1 870installs pytest-advanced laurigates pytest-advanced is a Claude Code skill for building pytest infrastructure, writing fixtures, and running tests with coverage. It activates for fixture work, test setup, and coverage runs. CX Codex +1 388installs Pytest Testing pluginagentmarketplace Pytest Testing — a skill for writing pytest tests: fixtures, mocks, coverage and CI runs. Useful when a Python project's tests need structure. CX Codex +1 555installs pytest-skill TestMu AI An agent skill that writes pytest tests for Python: fixtures, parametrize, markers, mocking and conftest patterns. Useful when you need test coverage without writing boilerplate by hand. CX Codex +1 442installs python-testing-patterns Seth Hobson The python-testing-patterns skill guides Python testing with pytest, fixtures and mocks. Use it when building a test suite or tracking down failing checks. CX Codex +1 36,943installs python-testing affaan-m A pytest skill for Python testing with TDD, fixtures, mocks, parametrization, and coverage checks. Use it when building or reviewing test suites. CX Codex +1 6,800installs

From the same set20

The whole set →
typescript Enforces strict TypeScript rules: const types, flat interfaces, type guards. Kicks in when the agent writes types, interfaces, or generics. CX Codex +1 500installs angular-performance angular-performance — an Angular skill that tells the agent how to load images with NgOptimizedImage, defer heavy components with @defer, and set up SSR with hydration. CX Codex +1 353installs java-21 Brings Java 21 patterns — records, sealed types, and virtual threads — into code generation. CX Codex +1 330installs angular-architecture angular-architecture — a skill that decides where Angular components go, how files are named, and which style guide rules to follow. CX Codex +1 322installs react-native Patterns for React Native mobile development across iOS and Android. Covers typed components, navigation with Expo Router, NativeWind styling, and state management. CX Codex +1 263installs hexagonal-architecture-layers-java The hexagonal-architecture-layers-java skill structures Java services around Domain, Application, and Infrastructure layers. Use it for new services or Spring refactoring. CX Codex +1 250installs angular-core angular-core — a skill that teaches the agent modern Angular patterns: standalone components, signals instead of hooks, zoneless mode, and native control flow. CX Codex +1 230installs jira-task Generates structured Jira tasks following Prowler's format. Handles bug reports, feature requests, and refactoring work with proper titles, acceptance criteria, and component-based splitting. CX Codex +1 217installs

Project sponsors

Companies that keep this analytics open