MCPInstall

python-testing-patterns

Python testing patterns and best practices using pytest, mocking, and property-based testing. Use when writing unit tests, integration tests, or implementing test-driven development in Python projects.

Installs
91
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/nickcrew/claude-cortex --skill python-testing-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads python-testing-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Python Testing Patterns

Comprehensive guide to implementing robust testing strategies in Python using pytest, fixtures, mocking, parameterization, and property-based testing.

When to Use This Skill

  • Writing unit tests for Python functions and classes
  • Setting up comprehensive test suites and infrastructure
  • Implementing test-driven development (TDD) workflows
  • Creating integration tests for APIs, databases, and services
  • Mocking external dependencies and third-party services
  • Testing async code and concurrent operations
  • Implementing property-based testing with Hypothesis
  • Setting up CI/CD test automation
  • Debugging failing tests and improving test coverage

Core Concepts

Test Discovery: Files matching test_*.py or *_test.py, functions starting with test_

Fixtures: Reusable test resources with setup and teardown

  • Scopes: function (default), class, module, session
  • Composition: Build complex fixtures from simple ones
  • Share via conftest.py for project-wide availability

Assertions: Use assert statements, pytest.raises() for exceptions

Organization: Separate unit/, integration/, e2e/ directories

Quick Reference

Load detailed references for specific topics:

TaskReference File
Pytest basics, test structure, AAA patternskills/python-testing-patterns/references/pytest-fundamentals.md
Fixtures, scopes, setup/teardown, conftest.pyskills/python-testing-patterns/references/fixtures.md
Parametrization, multiple test casesskills/python-testing-patterns/references/parametrized-tests.md
Mocking, patching, unittest.mock, pytest-mockskills/python-testing-patterns/references/mocking.md
Async tests, pytest-asyncio, event loopsskills/python-testing-patterns/references/async-testing.md
Property-based testing, Hypothesis, strategiesskills/python-testing-patterns/references/property-based-testing.md
Monkeypatch, environment variables, attributesskills/python-testing-patterns/references/monkeypatch.md
Test structure, markers, conftest.py patternsskills/python-testing-patterns/references/test-organization.md
Coverage measurement, reports, thresholdsskills/python-testing-patterns/references/coverage.md
Database, API, Redis, message queue testingskills/python-testing-patterns/references/integration-testing.md
Best practices, test quality, fixture designskills/python-testing-patterns/references/best-practices.md

Workflow

1. Basic Test Setup

# test_example.py
import pytest

def test_something():
    """Descriptive test name."""
    # Arrange
    expected = 5

    # Act
    result = 2 + 3

    # Assert
    assert result == expected

Run tests:

pytest                    # Run all tests
pytest -v                 # Verbose output
pytest tests/unit/        # Specific directory
pytest -k "test_user"     # Match pattern
pytest -m unit            # Run marked tests

2. Using Fixtures

@pytest.fixture
def sample_data():
    """Provide test data."""
    data = {"key": "value"}
    yield data
    # Cleanup if needed

def test_with_fixture(sample_data):
    assert sample_data["key"] == "value"

3. Parametrized Tests

@pytest.mark.parametrize("input,expected", [
    (2, 4),
    (3, 9),
    (4, 16),
])
def test_square(input, expected):
    assert input ** 2 == expected

4. Mocking External Dependencies

from unittest.mock import patch

@patch("module.external_api_call")
def test_with_mock(mock_api):
    mock_api.return_value = {"status": "ok"}

    result = my_function()

    assert result["status"] == "ok"
    mock_api.assert_called_once()

5. Coverage Measurement

pytest --cov=src --cov-report=term-missing
pytest --cov=src --cov-report=html
pytest --cov=src --cov-fail-under=80

6. Test Configuration

pytest.ini:

[pytest]
testpaths = tests
python_files = test_*.py
addopts = -v --strict-markers --cov=src
markers =
    unit: Unit tests
    integration: Integration tests
    slow: Slow tests

Common Patterns

Exception testing:

with pytest.raises(ValueError, match="error message"):
    function_that_raises()

Async testing:

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

Temporary files:

def test_file_operation(tmp_path):
    test_file = tmp_path / "test.txt"
    test_file.write_text("content")
    assert test_file.read_text() == "content"

Markers for test selection:

@pytest.mark.slow
@pytest.mark.integration
def test_database_operation():
    pass

Common Mistakes

  1. Not using fixtures: Repeating setup code across tests

    • Solution: Create fixtures in conftest.py
  2. Tests depending on order: Global state pollution

    • Solution: Ensure test independence with proper fixtures
  3. Over-mocking: Mocking internal implementation

    • Solution: Mock only external boundaries (APIs, databases)
  4. Missing edge cases: Only testing happy path

    • Solution: Test boundary conditions, errors, and invalid inputs
  5. Slow tests: Running full integration tests frequently

    • Solution: Separate unit/integration, use markers, optimize fixtures
  6. Ignoring coverage gaps: Not measuring test coverage

    • Solution: Use pytest-cov and track metrics
  7. Poor test names: Generic names like test_1()

    • Solution: Use descriptive names: test_<behavior>_<condition>_<expected>
  8. No cleanup: Resources not released

    • Solution: Use fixtures with proper teardown (yield pattern)

Resources

FAQ

What does the python-testing-patterns skill do?

Python testing patterns and best practices using pytest, mocking, and property-based testing. Use when writing unit tests, integration tests, or implementing test-driven development in Python projects.

How do I install python-testing-patterns?

Run npx skills add https://github.com/nickcrew/claude-cortex --skill python-testing-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/python-testing-patterns/ (personal) or .claude/skills/python-testing-patterns/ (project).

Which AI agents can use python-testing-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is python-testing-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains python-testing-patterns?

It is published by nickcrew in nickcrew/claude-cortex. It has 91 recorded installs.

More from nickcrew/claude-cortex

View all →

react-performance-optimization

nickcrew/claude-cortex

React performance optimization patterns using memoization, code splitting, and efficient rendering strategies. Use when optimizing slow React applications, reducing bundle size, or improving user experience with large datasets.

Frontend & Design1.9K installs

owasp-top-10

nickcrew/claude-cortex

OWASP Top 10 security vulnerabilities with detection and remediation patterns. Use when conducting security audits, implementing secure coding practices, or reviewing code for common security vulnerabilities.

Security758 installs

ui-design-aesthetics

nickcrew/claude-cortex

Open the skill to read its SKILL.md instructions.

Frontend & Design358 installs

threat-modeling-techniques

nickcrew/claude-cortex

Open the skill to read its SKILL.md instructions.

Security357 installs

token-efficiency

nickcrew/claude-cortex

Open the skill to read its SKILL.md instructions.

227 installs

helm-chart-patterns

nickcrew/claude-cortex

Open the skill to read its SKILL.md instructions.

DevOps & Cloud179 installs

Popular testing & qa skills

View category →

tdd

mattpocock/skills

Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.

Testing & QA1.2M installs

grilling

mattpocock/skills

Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.

Testing & QA996.2K installs

migrate-to-shoehorn

mattpocock/skills

Migrate test files from as type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace as in tests, or needs partial test data.

Testing & QA484.1K installs

run-train

lllllllama/rigorpilot-skills

Rigor Train skill for deep learning research repositories. Use when a documented or selected training command should be run conservatively for startup verification, short-run verification, full kickoff, or resume, with command, config, seed, log, checkpoint, status, and metric evidence written to standardized trainoutputs/. Do not use for environment setup, exploratory sweeps, speculative idea implementation, or end-to-end orchestration.

Testing & QA337.8K installs

test-driven-development

obra/superpowers

Use when implementing any feature or bugfix, before writing implementation code

Testing & QA261.8K installs

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

Testing & QA216.8K installs