---
name: write-pytest
description: Write tests for x, Make a test suite, test it out. Use this skill when the user asks to write tests, create a test suite, or test existing code.
title: write-pytest
canonical_url: https://skilld.dev/gh/tytodd/skills
last_updated: 2026-10-01T04:25:34.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install tytodd/skills/write-pytest`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/write-pytest`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/tytodd/skills/write-pytest) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/write-pytest`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/write-pytest --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/write-pytest --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Write Tests

This skill guides writing a thorough, well-structured test suite for existing code using pytest.

## Workflow

### Step 1: Confirm Test Cases with the User

Before writing any code, identify the concrete examples you plan to use as test cases and **confirm them with the user**. List:

- The functions/classes/modules being tested
- The specific inputs and expected outputs for each test
- Edge cases and error conditions you intend to cover

Do not proceed to writing tests until the user approves the test cases.

### Step 2: Plan the Test Approach

Make a written plan before implementing. For each test, identify whether it requires a non-standard environment:

| Pattern | When to use |
|---|---|
| `unittest.mock.patch` / `MagicMock` | Isolating a unit from external calls (filesystem, network, other modules) |
| `monkeypatch` (pytest fixture) | Temporarily replacing env vars, attributes, or functions in-process |
| Docker / testcontainers | Tests that require a real running service (database, Redis, etc.) |
| Custom mock module | When a dependency is unavailable or would cause side effects in test |

**ALWAYS check with the user before using any non-standard pattern.** Explain:
1. Which pattern you plan to use
2. Why it is necessary for that specific test
3. Whether a simpler alternative exists

### Step 3: Write the Tests

Follow these pytest conventions:

- Place tests in a `tests/` directory mirroring the source layout
- One test file per source module (e.g., `src/foo.py` → `tests/test_foo.py`)
- Use fixtures for shared setup/teardown — prefer `conftest.py` for fixtures shared across files
- Name tests `test_<what_it_does>` — names should read like a sentence
- Group related tests in a class only when shared state or setup justifies it
- Use `pytest.mark` to annotate tests:
  - `@pytest.mark.slow` — tests that take more than a few seconds
  - `@pytest.mark.integration` — tests that touch external systems
  - `@pytest.mark.unit` — pure unit tests (optional but useful)

```python
# Example structure
import pytest

@pytest.fixture
def sample_data():
    return {"key": "value"}

@pytest.mark.slow
def test_heavy_operation(sample_data):
    ...

def test_expected_behavior(sample_data):
    result = my_function(sample_data)
    assert result == expected
```

### Step 4: Run the Tests and Interpret Failures

Always run tests with:

```bash
uv run pytest
```

To run a subset (e.g., skip slow tests):

```bash
uv run pytest -m "not slow"
```

Evaluate every failure carefully. For each failing test, reason through:

1. **Is the source code wrong?** — The implementation has a bug.
2. **Did I misunderstand the intended behavior?** — The test expectation is wrong.
3. **Is the test environment misconfigured?** — A fixture, mock, or dependency is broken.

If it is unclear whether the source code or the test expectation is wrong, **ask the user** to clarify how the code is supposed to behave before making any changes.

Do not blindly fix tests to pass — a green suite built on wrong assumptions is worse than a red one.

## Key Principles

- Keep tests fast by default; isolate slow/integration tests with markers
- Prefer explicit over implicit — assert specific values, not just truthiness
- One logical assertion per test where practical
- Never silence or skip failures without understanding them first
- Tests are documentation — readable test names and clear assertions matter
