Pytest

From G1Joshi/Agent-Skills · View interactive version

Pytest is an AI agent skill from the GitHub repository G1Joshi/Agent-Skills. 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.

How to use this skill

Skill file

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

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:

Don't:

Troubleshooting

| Error | Cause | Solution |

| :------------------------------------------- | :---------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- |

| 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 found | Typo 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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.