Pytest best practices

From cfircoo/claude-code-toolkit · View interactive version

Pytest best practices is an AI agent skill from the GitHub repository cfircoo/claude-code-toolkit. Expert guidance for writing high-quality pytest tests. Use when writing tests, setting up fixtures, parametrizing, mocking, or reviewing test code.

How to use this skill

Skill file

<objective>

Provide pytest best practices and patterns for writing maintainable, efficient tests.

</objective>

<essential_principles>

Test Independence

Naming Conventions

Directory Structure

tests/
├── conftest.py          # Shared fixtures
├── unit/
│   └── test_module.py
├── integration/
│   └── test_api.py
└── fixtures/            # Test data files

Core Testing Rules

</essential_principles>

<quick_reference>

| Pattern | Use Case |

|---------|----------|

| @pytest.fixture | Setup/teardown, dependency injection |

| @pytest.mark.parametrize | Run test with multiple inputs |

| @pytest.mark.skip | Skip test temporarily |

| @pytest.mark.xfail | Expected failure (known bug) |

| pytest.raises(Exception) | Test exception raising |

| pytest.approx(value) | Float comparison |

| mocker.patch() | Mock dependencies |

| conftest.py | Share fixtures across modules |

Common Commands

pytest -v                    # Verbose
pytest -x                    # Stop on first failure
pytest --lf                  # Run last failed
pytest -k "pattern"          # Match test names
pytest -m "marker"           # Run marked tests
pytest --cov=src             # Coverage report

</quick_reference>

<routing>

Based on what you're doing, read the relevant reference:

| Task | Reference |

|------|-----------|

| Setting up fixtures, scopes, factories | references/fixtures.md |

| Parametrizing tests, multiple inputs | references/parametrization.md |

| Mocking, patching, faking dependencies | references/mocking.md |

| Markers, exceptions, assertions, async | references/patterns.md |

</routing>

<dependencies>

pip install pytest pytest-asyncio pytest-mock pytest-cov pytest-xdist

</dependencies>

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.