agentleFS
LWaetzigLWaetzig/claude-code-skills/skills/python-testing/SKILL.md

python-testing

Skill0 starsChanged 7 months agoMITView on GitHub

Write and improve Python tests using pytest. Use when adding tests to a project, fixing broken tests, improving test coverage, setting up async tests, or asking how to test a specific pattern (HTTP endpoints, database, mocking, etc.).

53 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use django-verification, python-patterns and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • mstuder-slalomSkill

    django-verification

    Verification loop for Django projects: migrations, linting, tests with coverage, security scans, and deployment readiness checks before release or PR.

    Also in 9 projects that use this

  • xenitV1Skill

    python-patterns

    Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.

    Also in 22 projects that use this

  • HABUBUSSSkill

    project-guidelines-example

    Also in 8 projects that use this

  • AshfaqbsSkill

    springboot-tdd

    Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.

    Also in 7 projects that use this

  • mstuder-slalomSkill

    springboot-security

    Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.

    Also in 8 projects that use this

  • nek1987Skill

    postgres-patterns

    PostgreSQL patterns for reviewing migrations and writing efficient queries. Use when reviewing Alembic migrations, optimizing queries, or debugging database issues.

    Also in 15 projects that use this

  • +2 more from mstuder-slalom

The file

We split this skill into the rules it gives an agent

9 rules. 0 are common, 6 are distinctive, and 3 are very specific to this project.

  • 0

    Common

    Most of the 48 edited versions we read keep these.

  • 6

    Distinctive

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Write clear, fast, trustworthy tests.

    line 13
  2. Distinctive:

    Before writing any tests:

    line 19
  3. Distinctive:

    Read the function/module to understand its contract (inputs, outputs, side effects)

    line 20
  4. Distinctive:

    Check for existing tests — mimic the file structure and naming conventions in use

    line 21
  5. Very specific:

    Check pyproject.toml or setup.cfg for pytest config, markers, and plugins already installed

    line 22
  6. Distinctive:

    Default to the smallest test type that gives you confidence: Don't mock what you can test cheaply for real.

    line 36
  7. Distinctive:

    Use the Arrange / Act / Assert pattern.

    line 42
  8. Very specific:

    Keep names honest — test_returns_none should return None, not raise

    line 60
  9. Very specific:

    Run subsets: pytest -m "not slow", pytest -m integration

    line 230

“Common” is measured: kept by at least 6 in 10 of the 48 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python Testing Skill

Write clear, fast, trustworthy tests. Tests are code — they should be readable, maintainable, and test behaviour not implementation.


Step 1: Read the Code Under Test

Before writing any tests:

  1. Read the function/module to understand its contract (inputs, outputs, side effects)
  2. Check for existing tests — mimic the file structure and naming conventions in use
  3. Check pyproject.toml or setup.cfg for pytest config, markers, and plugins already installed

Step 2: Choose the Right Test Type

ScenarioApproach
Pure functionsUnit test with assert
Code with I/O / external dependenciesUnit test + mock the boundary
FastAPI / Flask / Django endpointsIntegration test with TestClient / AsyncClient
Database-backed codeIntegration test against real DB (use fixtures for setup/teardown)
Complex workflowsEnd-to-end test, sparingly

Default to the smallest test type that gives you confidence. Don't mock what you can test cheaply for real.


Step 3: Test Structure

Use the Arrange / Act / Assert pattern. One logical assertion per test.

def test_discount_applied_to_eligible_order():
    # Arrange
    order = Order(items=[Item(price=100)], customer_tier="gold")

    # Act
    total = calculate_total(order)

    # Assert
    assert total == 90  # 10% gold discount

File and function naming

  • Test files: test_<module>.py
  • Test functions: test_<what>_<when/condition>_<expected>
  • Keep names honest — test_returns_none should return None, not raise

Core Patterns

Fixtures

import pytest

@pytest.fixture
def user():
    return User(id=1, name="Ada", email="ada@example.com")

@pytest.fixture
def db(tmp_path):
    """Isolated SQLite DB per test."""
    engine = create_engine(f"sqlite:///{tmp_path}/test.db")
    Base.metadata.create_all(engine)
    with Session(engine) as session:
        yield session

# Reuse fixtures across files with conftest.py

Parametrize

@pytest.mark.parametrize("email,valid", [
    ("user@example.com", True),
    ("not-an-email", False),
    ("", False),
    ("user@", False),
])
def test_email_validation(email, valid):
    assert validate_email(email) == valid

Mocking

from unittest.mock import patch, MagicMock

def test_sends_welcome_email(mock_email_client):
    with patch("myapp.services.email_client") as mock_client:
        register_user("ada@example.com")
        mock_client.send.assert_called_once_with(
            to="ada@example.com",
            template="welcome",
        )

# Or use pytest-mock for cleaner syntax
def test_sends_welcome_email(mocker):
    mock_send = mocker.patch("myapp.services.email_client.send")
    register_user("ada@example.com")
    mock_send.assert_called_once()

Async tests

# Requires: pytest-asyncio
# pyproject.toml: [tool.pytest.ini_options] asyncio_mode = "auto"

import pytest

@pytest.mark.asyncio
async def test_fetch_user():
    async with AsyncClient(app=app, base_url="http://test") as client:
        response = await client.get("/users/1")
    assert response.status_code == 200

# With pytest-asyncio asyncio_mode="auto", mark is optional
async def test_fetch_user_auto():
    result = await fetch_user(user_id=1)
    assert result.name == "Ada"

Testing FastAPI endpoints

from fastapi.testclient import TestClient
from httpx import AsyncClient
import pytest

client = TestClient(app)  # sync — fine for most tests

def test_create_item_returns_201():
    response = client.post("/items/", json={"name": "Gadget", "price": 9.99})
    assert response.status_code == 201
    assert response.json()["name"] == "Gadget"

def test_get_item_not_found_returns_404():
    response = client.get("/items/99999")
    assert response.status_code == 404

# Override dependencies for isolation
def override_get_db():
    yield test_db_session

app.dependency_overrides[get_db] = override_get_db

Testing exceptions

import pytest

def test_raises_on_invalid_input():
    with pytest.raises(ValueError, match="must be positive"):
        compute_score(-1)

def test_raises_http_exception():
    response = client.get("/users/0")
    assert response.status_code == 422  # FastAPI validation error

Fixtures Best Practices

  • Keep fixtures focused — one fixture does one thing
  • Use yield fixtures for setup/teardown (replaces setup_method)
  • Scope appropriately: function (default), module, session
    • session-scoped DB migrations, function-scoped transactions (rollback after each test)
  • Put shared fixtures in conftest.py — pytest auto-discovers it
# conftest.py
@pytest.fixture(scope="session")
def engine():
    engine = create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
    yield engine
    engine.dispose()

@pytest.fixture
def db(engine):
    connection = engine.connect()
    transaction = connection.begin()
    session = Session(bind=connection)
    yield session
    session.close()
    transaction.rollback()
    connection.close()

Markers and Configuration

# pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
markers = [
    "slow: marks tests as slow (deselect with -m 'not slow')",
    "integration: marks integration tests",
]
@pytest.mark.slow
@pytest.mark.integration
def test_full_order_pipeline():
    ...

Run subsets: pytest -m "not slow", pytest -m integration


Coverage

pytest --cov=myapp --cov-report=term-missing
pytest --cov=myapp --cov-fail-under=80
# pyproject.toml
[tool.coverage.run]
omit = ["tests/*", "*/migrations/*"]

[tool.coverage.report]
exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:"]

Coverage is a floor, not a target. 80% with meaningful tests beats 100% with trivial ones.


What NOT to Test

  • Framework internals (don't test that FastAPI parses JSON — test your logic)
  • Implementation details (test behaviour, not which private method was called)
  • Trivial getters/setters
  • Code you don't own

Common Gotchas

  • Don't patch where it's defined — patch where it's used: patch("myapp.routes.send_email") not patch("myapp.email.send_email")
  • Async fixtures need pytest-asyncio and async def fixtures require the right scope
  • TestClient runs the app synchronously — use AsyncClient when you need true async behaviour
  • Avoid time.sleep in tests — mock datetime.now() or use freezegun

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.