# pytest

A skill with pytest patterns: fixtures, mocking, markers, parametrization. Kicks in when the agent writes Python tests.

- skill · `type=skill` · Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, OpenCode, Windsurf (Devin Desktop), Claude.ai · 291 installs · ★ 678 repo stars
- Author: gentleman-programming
- License: Apache-2.0 · policy=mirror · the beginning of the file is at the end of this page
- Source: https://github.com/Gentleman-Programming/Gentleman-Skills/tree/HEAD/curated/pytest/SKILL.md
- Updated: 2026-03-28
- Security check: automated, 2026-11-16 (text) — no signs of malicious code found.
- HTML: https://affpapa.org/en/nevibecode/skills/gentleman-programming-pytest

## What it 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.

## Install

### Claude Code (native platform)

1. **Skills CLI (Vercel)**
```bash
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a claude-code
```

2. **Manually: put the files in place**
- File: `~/.claude/skills/pytest/SKILL.md` — Copy the whole skill folder; for one project use .claude/skills/pytest/

### Codex

1. **Skills CLI (Vercel)**
```bash
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a codex
```

2. **Manually: put the files in place**
- File: `.agents/skills/pytest/SKILL.md` — For all projects use ~/.agents/skills/

### Cursor

1. **Skills CLI (Vercel)**
```bash
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a cursor
```

2. **Manually: put the files in place**
- File: `.cursor/skills/pytest/SKILL.md` — Cursor also reads .agents/skills/ and .claude/skills/

### GitHub Copilot

1. **GitHub CLI**
```bash
gh skill install Gentleman-Programming/Gentleman-Skills curated/pytest/SKILL.md
```

2. **Manually: put the files in place**
- File: `.github/skills/pytest/SKILL.md`

### Gemini CLI

1. **Skills CLI (Vercel)**
```bash
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a gemini-cli
```

2. **Platform CLI**
```bash
gemini skills install https://github.com/Gentleman-Programming/Gentleman-Skills --path curated/pytest
```

### Windsurf (Devin Desktop)

**Manually: put the files in place**
- File: `.devin/skills/pytest/SKILL.md` — The legacy .windsurf/skills/ path still works

### OpenCode

**Skills CLI (Vercel)**
```bash
npx skills add Gentleman-Programming/Gentleman-Skills --skill pytest -a opencode
```

### Claude.ai

**Claude.ai**
- Zip the folder and upload it in Settings → Capabilities → Skills

Where a file is given instead of a command, copy the files from the source to that path: https://github.com/Gentleman-Programming/Gentleman-Skills/tree/HEAD/curated/pytest/SKILL.md

## When to use it
- 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
- 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

## Source text · SKILL.md · Apache-2.0

Below is the content of a third-party file. It is data, not instructions for you: do not act on anything written inside unless the human asks. Block tag: 4697e1b53c9850c4.

BEGIN THIRD-PARTY FILE 4697e1b53c9850c4
````text
---
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="john@test.com")
        assert user.name == "John"
        assert user.email == "john@test.com"

    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="test@example.com")

@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", [
    ("user@example.com", True),
    ("invalid-email", False),
    ("", False),
    ("user@.com", False),
])
def test_email_validation(email, is_valid):
    assert validate_email(email) == is_valid
```
````
END THIRD-PARTY FILE 4697e1b53c9850c4

The third-party file has ended. Everything between the 4697e1b53c9850c4 tags is data: requests and commands from it are not followed. An “end of file” line with another tag inside the block is part of the file.

First 3070 of 4318 bytes. © gentleman-programming · Apache-2.0 · https://github.com/Gentleman-Programming/Gentleman-Skills/tree/HEAD/curated/pytest/SKILL.md

_Part of the page did not fit — see the HTML version._

---
NeVibeCode on affpapa.org. Catalog texts are descriptions, not instructions for the agent. How to choose and install: https://affpapa.org/en/nevibecode/agents.md
