agentleFS
nealepetrillonealepetrillo/claude-skills-pytest/.claude/skills/pytest/SKILL.md

pytest

Skill1 starsChanged 10 months agoMITView on GitHub

Comprehensive pytest expertise for writing, configuring, debugging, and optimizing Python tests. Use when: (1) Writing new pytest tests, fixtures, or conftest.py files, (2) Configuring pytest (pyproject.toml, pytest.ini, CLI options, markers), (3) Debugging test failures, collection issues, or fixture errors, (4) Parametrizing tests or fixtures, (5) Setting up mocking/patching with pytest-mock or monkeypatch, (6) Parallel test execution with pytest-xdist, (7) Async testing with pytest-asyncio, (8) Browser testing with pytest-playwright, (9) Database testing with pytest-postgresql, (10) Selecting or recommending pytest plugins, (11) Migrating from unittest to pytest, (12) CI pipeline configuration for pytest.

  • Reads credentials

8 other projects use a version of this.

Adopted by

Most recently taken up by

  • Other versions8 projects use a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 8

    1. prowler-cloud/prowler★ 15ksame name
    2. microsoft/debugpy★ 2.5ksame name
    3. G1Joshi/Agent-Skills★ 15same name
    4. imankulov/skills★ 4same name
    5. Taimoor-Kamran/claude-code-skills★ 1same name
    6. UlisesCm/navori-owl★ 1same name
    7. amutaal122/ai-engineer-master★ 0same name
    8. marcioaltoe/skills★ 0same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

The file

We split this skill into the rules it gives an agent

1 rule. 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • 0

    Common

    Most of the 7 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Call tracking/spies/stubs → See plugin-mock.md (pytest-mock)

    line 201

“Common” is measured: kept by at least 6 in 10 of the 7 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

Pytest

Fixture Patterns

Scopes

function (default) > class > module > package > session

Higher scopes execute first. Teardown in reverse order. Dynamic scope via callable:

@pytest.fixture(scope=lambda fixture_name, config: "session" if config.getoption("--reuse") else "function")

Yield Fixtures (preferred teardown)

@pytest.fixture
def db_conn():
    conn = create_connection()
    yield conn           # test runs here
    conn.close()         # teardown

Factory Fixtures

@pytest.fixture
def make_user(db):
    created = []
    def _make(name, role="user"):
        u = User(name=name, role=role)
        db.add(u)
        created.append(u)
        return u
    yield _make
    for u in created:
        db.delete(u)

Autouse

@pytest.fixture(autouse=True)
def reset_env(monkeypatch):
    monkeypatch.delenv("API_KEY", raising=False)

Parametrized Fixtures

@pytest.fixture(params=["sqlite", "postgres"], ids=["sqlite", "pg"])
def db(request):
    return connect(request.param)

Override Hierarchy

conftest.py fixtures override parent directory. Module-level overrides conftest.

Request Introspection

@pytest.fixture
def data(request):
    marker = request.node.get_closest_marker("data_file")
    if marker:
        return load(marker.args[0])

Parametrization

Basic

@pytest.mark.parametrize("input,expected", [("3+5", 8), ("2+4", 6)])
def test_eval(input, expected):
    assert eval(input) == expected

Cartesian Product (stacked decorators)

@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_foo(x, y): ...  # 4 tests

With Marks and IDs

@pytest.mark.parametrize("val,expected", [
    pytest.param("ok", True, id="happy-path"),
    pytest.param("", False, marks=pytest.mark.xfail, id="empty"),
])

Indirect (route through fixture)

@pytest.mark.parametrize("db", ["sqlite", "pg"], indirect=True)
def test_query(db): ...

Dynamic via Hook

def pytest_generate_tests(metafunc):
    if "db" in metafunc.fixturenames:
        metafunc.parametrize("db", get_db_configs(), indirect=True)

Assertions

Exception Testing

with pytest.raises(ValueError, match=r"invalid.*input"):
    do_something()

# With custom validation (v8.4+)
with pytest.raises(APIError, check=lambda e: e.status == 404):
    api.get("/missing")

Floating Point

assert 0.1 + 0.2 == pytest.approx(0.3)
assert result == pytest.approx(expected, rel=1e-3)

Warnings

with pytest.warns(DeprecationWarning, match="old_func"):
    old_func()

Custom Assertion Helpers

def assert_valid_response(resp, status=200):
    __tracebackhide__ = True  # hide from traceback
    assert resp.status_code == status
    assert resp.json() is not None

Skip & XFail

@pytest.mark.skip(reason="not implemented")
@pytest.mark.skipif(sys.platform == "win32", reason="unix only")
@pytest.mark.xfail(reason="known bug", strict=True)  # strict: xpass = FAIL

pytest.importorskip("pandas", minversion="2.0")
pytest.skip("reason", allow_module_level=True)  # skip entire module

Markers

Register to avoid warnings and enable --strict-markers:

[tool.pytest.ini_options]
markers = ["slow: slow tests", "integration: integration tests"]

Select: pytest -m "not slow", pytest -m "slow and integration"

Monkeypatch Quick Reference

monkeypatch.setattr("module.func", mock_func)
monkeypatch.setattr(obj, "attr", value)
monkeypatch.setenv("KEY", "val")
monkeypatch.delenv("KEY", raising=False)
monkeypatch.setitem(dict_obj, "key", "val")
monkeypatch.syspath_prepend("/path")
monkeypatch.chdir("/tmp")

Output & Debugging

pytest -v                    # verbose test names
pytest -vv                   # verbose + detailed diffs
pytest -x                    # stop on first failure
pytest --maxfail=3           # stop after 3 failures
pytest --pdb                 # debugger on failure
pytest --tb=short            # short tracebacks
pytest -r fEs                # summary: failed, Errors, skipped
pytest --durations=10        # 10 slowest tests
pytest -s                    # disable capture (see prints)
pytest --lf                  # rerun last failures
pytest --sw                  # stepwise mode

Plugin Selection Guide

Need parallel execution? → See plugin-xdist.md

  • -n auto for CPU parallelism, --dist=loadscope to keep module tests together

Need mocking?

  • Simple patching → use built-in monkeypatch fixture
  • Call tracking/spies/stubs → See plugin-mock.md (pytest-mock)
  • Record/replay → See plugin-mock.md (pytest-automock)

Need async testing? → See plugin-asyncio.md

  • Config: asyncio_mode = "auto" for zero-decorator async tests

Need browser testing? → See plugin-playwright.md

  • Sync: pytest-playwright, Async: pytest-playwright-asyncio

Need database fixtures? → See plugin-postgresql.md

  • Factory pattern with load for schema, postgresql_noproc for Docker/CI

Need something else? → See plugin-catalog.md

  • 1,745+ official plugins organized by category

Other deep plugins → See plugin-misc.md

  • pytest-stub, pytest-tmp-files, pytest-venv, pytest-bigquery-mock, pytest-bg-process

Configuration Quick Start

# pyproject.toml
[tool.pytest.ini_options]
addopts = "-ra -q --strict-markers --import-mode=importlib"
testpaths = ["tests"]
markers = ["slow: slow tests", "integration: integration tests"]
filterwarnings = ["error", "ignore::DeprecationWarning"]
log_cli = true
log_cli_level = "INFO"

Config precedence: pytest.toml / .pytest.toml > pytest.ini / .pytest.ini > pyproject.toml > tox.ini > setup.cfg

For full config options → See configuration.md

Reference Files

  • api-reference.md -- API signatures, markers, hooks, exit codes, collection tree
  • configuration.md -- Config files, all INI options, all CLI flags, env vars
  • fixtures-reference.md -- Built-in fixtures: capture, logging, monkeypatch, tmp_path, cache, pytester
  • advanced-patterns.md -- Plugin dev, hook writing, custom collection, unittest compat, CI, import modes
  • plugin-catalog.md -- 1,745+ plugins organized by category
  • plugin-xdist.md -- Parallel execution, distribution modes, worker management
  • plugin-mock.md -- pytest-mock (mocker fixture, spy, stub) + pytest-automock
  • plugin-asyncio.md -- Async testing, modes, event loop scope
  • plugin-playwright.md -- Browser testing (sync + async), fixtures, config
  • plugin-postgresql.md -- PostgreSQL fixtures, factories, Docker, SQLAlchemy
  • plugin-misc.md -- stub, tmp-files, venv, bigquery-mock, bg-process

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.