agentleFS
G1JoshiG1Joshi/Agent-Skills/skills/testing/pytest/SKILL.md

pytest

Skill15 starsChanged 2 months agoMITView on GitHub

Expert Pytest testing assistance covering fixtures, parametrization, marks, and test plugins. Use when writing Python tests, building test suites, or running `pytest` in CI/CD pipelines.

8 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

6 rules. 0 are common, 1 is distinctive, and 5 are very specific to this project.

  • 0

    Common

    Most of the 7 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 5

    Very specific

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

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

    Use @pytest.fixture with the yield statement:

    line 100
  2. Very specific:

    Use Plain assert Statements: Pytest provides detailed assertion introspection without requiring special assertion methods.

    line 123
  3. Very specific:

    Use conftest.py for Shared Fixtures: Place global fixtures and configuration hooks in conftest.py files.

    line 124
  4. Very specific:

    Run Parallel Tests with pytest-xdist: Accelerate test runs across all CPU cores with pytest -n auto.

    line 125
  5. Very specific:

    Use assert with parentheses: Writing assert(a == b, "msg") evaluates a non-empty tuple which is always truthy.

    line 130
  6. Distinctive:

    Create deep nested class hierarchies: Pytest favors simple standalone test functions over unittest-style classes.

    line 132

“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

Pytest is the dominant testing framework for Python. It is loved for its no-boilerplate syntax (assert x == y), powerful fixture system, and rich plugin ecosystem.

When to Use

  • Python Standard Testing Framework: The most widely adopted, powerful testing framework for Python web backends, data science, and ML.
  • Clean Fixture Dependency Injection: Managing test setup, database connections, and teardown cleanly with @pytest.fixture.
  • Parameterized Testing: Running test functions across multi-dimensional input sets with @pytest.mark.parametrize.
  • Rich Plugin Ecosystem: Extending capabilities via pytest-asyncio, pytest-cov, pytest-xdist, and pytest-mock.

Quick Start

# content of test_sample.py
def inc(x):
    return x + 1

def test_answer():
    assert inc(3) == 5

Running it:

pytest

Core Concepts

Dependency Injection with Fixtures

Fixtures provide modular, reusable dependencies with explicit lifecycle scopes:

# conftest.py
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

@pytest.fixture(scope="session")
def db_engine():
    engine = create_engine("sqlite:///:memory:")
    yield engine
    engine.dispose()

@pytest.fixture
def db_session(db_engine):
    Session = sessionmaker(bind=db_engine)
    session = Session()
    yield session
    session.rollback()
    session.close()

Parameterized Tests (@pytest.mark.parametrize)

Tests multiple input/output scenarios cleanly without loop boilerplate:

import pytest

@pytest.mark.parametrize("email,expected_valid", [
    ("user@example.com", True),
    ("invalid-email", False),
    ("@missinguser.com", False),
    ("user.name+tag@sub.domain.co", True),
])
def test_email_validation(email, expected_valid):
    assert validate_email(email) == expected_valid

Async Testing with pytest-asyncio

Tests async coroutines seamlessly:

import pytest
import httpx

@pytest.mark.asyncio
async def test_async_fetch():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://httpbin.org/get")
        assert response.status_code == 200

Common Patterns

Scoped Fixtures with Teardown / Cleanup

Problem: Database or mock setup code repeated across dozens of test functions creates duplication and leftover state.

Solution: Use @pytest.fixture with the yield statement:

import pytest

@pytest.fixture(scope="function")
def db_session():
    # Setup test database session
    session = create_test_session()
    yield session
    # Cleanup and rollback after test completes
    session.rollback()
    session.close()

def test_user_creation(db_session):
    user = db_session.create_user("alice@example.com")
    assert user.id is not None

Best Practices

Do:

  • Use Plain assert Statements: Pytest provides detailed assertion introspection without requiring special assertion methods.
  • Use conftest.py for Shared Fixtures: Place global fixtures and configuration hooks in conftest.py files.
  • Run Parallel Tests with pytest-xdist: Accelerate test runs across all CPU cores with pytest -n auto.
  • Mark Tests by Category: Use custom marks (@pytest.mark.slow, @pytest.mark.integration) and filter runs with -m "not slow".

Don't:

  • Use assert with parentheses: Writing assert(a == b, "msg") evaluates a non-empty tuple which is always truthy.
  • Mutate shared session-scoped fixtures: Keep session fixtures read-only; use function-scoped fixtures for test-isolated mutations.
  • Create deep nested class hierarchies: Pytest favors simple standalone test functions over unittest-style classes.

Troubleshooting

ErrorCauseSolution
ModuleNotFoundError: No module named 'src'Current directory not in sys.path when running pytest.Run pytest as a module: python -m pytest, or configure pythonpath = ["src"] in pyproject.toml.
FixtureNotFound: fixture '...' not foundTypo in fixture argument name or fixture defined outside conftest.py.Move shared fixtures to root conftest.py file.
Failed: DID NOT RAISE <class '...'>Code did not raise the exception expected by pytest.raises.Inspect inputs to verify failure condition is actually triggered.

References

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.