New to Claude Skills? Learn how to install them →

prowler-cloud on GitHub

Pytest Patterns

Free

Streamline your Python testing with proven patterns.

Get this skill

Free · Opens the source repo

What Pytest Patterns does

Pytest Patterns is designed for developers working with Python who need to implement or refactor tests using the pytest framework. This skill provides a comprehensive set of testing patterns including basic test structures, fixtures, mocking, parameterization, and markers. It serves as a practical reference for both new and experienced developers looking to enhance their testing practices in Python applications.

The skill includes examples of how to structure tests effectively, utilize fixtures for setup and teardown, and apply mocking techniques to isolate code during testing. It also covers how to use parameterization to run the same test with multiple inputs, which can significantly reduce code duplication and improve test coverage. Additionally, users can learn how to categorize tests with markers, allowing for selective execution based on test characteristics.

For those working specifically with Prowler's API or SDK, this skill points to additional resources that align with Prowler's testing conventions. The skill is particularly useful for teams adopting pytest in their development workflow, as it encourages best practices and consistency across test cases. By following the provided patterns, developers can write more maintainable and robust tests, ultimately improving software quality.

Whether you're writing new tests or refactoring existing ones, Pytest Patterns offers the guidance needed to implement effective testing strategies. It is an essential resource for anyone involved in Python development who wants to leverage the full capabilities of pytest in their projects.

When to use it

Use this skill when you need to create or refactor tests in Python using pytest, especially in projects utilizing Prowler's API or SDK.

When not to use it

This skill may not be suitable for testing frameworks other than pytest or for projects that do not involve Python.

What you can build with it

Creating New Tests

Use this skill to quickly reference patterns for writing new tests in Python, ensuring best practices are followed.

Refactoring Existing Tests

When updating old tests, leverage the provided examples to enhance readability and maintainability.

Implementing Mocking Techniques

Utilize the mocking patterns to isolate components in your tests, making them more reliable and focused.

How to install Pytest Patterns

View source

1. Install with the skills CLI

npx skills add prowler-cloud/prowler/pytest --agent claude-code

2. Or install it manually

Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.

Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs

Inside SKILL.md

Written by prowler-cloud

Basic Test Structure

import pytest

class TestUserService:
    def test_create_user_success(self):
        user = create_user(name="John", email="john@test.com")
        assert user.name == "John"
        assert user.email == "john@test.com"

    def test_create_user_invalid_email_fails(self):
        with pytest.raises(ValueError, match="Invalid email"):
            create_user(name="John", email="invalid")

Fixtures

import pytest

@pytest.fixture
def user():
    """Create a test user."""
    return User(name="Test User", email="test@example.com")

@pytest.fixture
def authenticated_client(client, user):
    """Client with authenticated user."""
    client.force_login(user)
    return client

# Fixture with teardown
@pytest.fixture
def temp_file():
    path = Path("/tmp/test_file.txt")
    path.write_text("test content")
    yield path  # Test runs here
    path.unlink()  # Cleanup after test

# Fixture scopes
@pytest.fixture(scope="module")  # Once per module
@pytest.fixture(scope="class")   # Once per class
@pytest.fixture(scope="session") # Once per test session

conftest.py

# tests/conftest.py - Shared fixtures
import pytest

@pytest.fixture
def db_session():
    session = create_session()
    yield session
    session.rollback()

@pytest.fixture
def api_client():
    return TestClient(app)

Mocking

from unittest.mock import patch, MagicMock

class TestPaymentService:
    def test_process_payment_success(self):
        with patch("services.payment.stripe_client") as mock_stripe:
            mock_stripe.charge.return_value = {"id": "ch_123", "status": "succeeded"}

            result = process_payment(amount=100)

            assert result["status"] == "succeeded"
            mock_stripe.charge.assert_called_once_with(amount=100)

    def test_process_payment_failure(self):
        with patch("services.payment.stripe_client") as mock_stripe:
            mock_stripe.charge.side_effect = PaymentError("Card declined")

            with pytest.raises(PaymentError):
                process_payment(amount=100)

# MagicMock for complex objects
def test_with_mock_object():
    mock_user = MagicMock()
    mock_user.id = "user-123"
    mock_user.name = "Test User"
    mock_user.is_active = True

    result = get_user_info(mock_user)
    assert result["name"] == "Test User"

Parametrize

@pytest.mark.parametrize("input,expected", [
    ("hello", "HELLO"),
    ("world", "WORLD"),
    ("pytest", "PYTEST"),
])
def test_uppercase(input, expected):
    assert input.upper() == expected

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

Markers

# pytest.ini or pyproject.toml
[tool.pytest.ini_options]
markers = [
    "slow: marks tests as slow",
    "integration: marks integration tests",
]

# Usage
@pytest.mark.slow
def test_large_data_processing():
    ...

@pytest.mark.integration
def test_database_connection():
    ...

@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
    ...

@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_specific():
    ...

# Run specific markers
# pytest -m "not slow"
# pytest -m "integration"

Async Tests

import pytest

@pytest.mark.asyncio
async def test_async_function():
    result = await async_fetch_data()
    assert result is not None

Commands

pytest                          # Run all tests
pytest -v                       # Verbose output
pytest -x                       # Stop on first failure
pytest -k "test_user"           # Filter by name
pytest -m "not slow"            # Filter by marker
pytest --cov=src                # With coverage
pytest -n auto                  # Parallel (pytest-xdist)
pytest --tb=short               # Short traceback

References

For general pytest documentation, see:

For Prowler SDK testing with provider-specific patterns (moto, MagicMock), see:

Frequently asked questions about Pytest Patterns

Similar skills