pytest-patterns

Python testing with pytest covering fixtures, parametrization, mocking, and test organization for reliable test suites

By manutej · 784 installs

npx skills add manutej/luxor-claude-marketplace --skill pytest-patterns

Source repository · Upstream listing

Pytest Patterns Comprehensive Testing Guide A comprehensive skill for mastering Python testing with pytest. This skill covers everything from basic test structure to advanced patterns including fixtures, parametrization, mocking, test organization, coverage analysis, and CI/CD integration. When to Use This Skill Use this skill when: Writing tests for Python applications (web apps, APIs, CLI tools, libraries) Setting up test infrastructure for a new Python project Refactoring existing tests to be more maintainable and efficient Implementing test driven development (TDD) workflows Creating fixture patterns for database, API, or external service testing Organizing large test suites with hundreds or thousands of tests Debugging failing tests or improving test reliability Setting up continuous integration testing pipelines Measuring and improving code coverage Writing integration, unit, or end to end tests Testing async Python code Mocking external dependencies and services Core Concepts What is pytest? pytest is a mature, full featured Python testing framework that makes it easy to write simple tests, yet scales to support complex functional testing. It provides: Simple syntax : Use plain assert statements instead of special assertion methods Powerful fixtures : Modular, composable test setup and teardown Parametrization : Run the same test with different inputs Plugin ecosystem : Hundreds of plugins for extended functionality Detailed reporting : Clear failure messages and debugging information Test discovery : Automatic test collection following naming conventions pytest vs unittest Test Discovery Rules pytest automatically discovers tests by following these conventions: 1. Test files : test .py or test.py 2. Test functions : Functions prefixed with test 3. Test classes : Classes prefixed with Test (no init method) 4. Test methods : Methods prefixed with test inside Test classes Fixtures The Heart of pytest What are Fixtures? Fixtures provide a fixed baseline for tests to run reliably and repeatably. They handle setup, provide test data, and perform cleanup. Basic Fixture Pattern Fixture Scopes Fixtures can have different scopes controlling how often they're created: function (default): Created for each test function class : Created once per test class module : Created once per test module package : Created once per test package session : Created once per test session Fixture Dependencies Fixtures can depend on other fixtures, creating a dependency graph: Autouse Fixtures Fixtures that run automatically without being explicitly requested: Fixture Factories Fixtures that return functions for creating test data: Parametrization Testing Multiple Cases Basic Parametrization Run the same test with different inputs: Multiple Parameters Parametrizing with IDs Make test output more readable: Parametrizing Fixtures Create fixture instances with different values: Combining Parametrization and Marks Indirect Parametrization Pass parameters through fixtures: Mocking and Monkeypatching Using pytest's monkeypatch The monkeypatch fixture provides safe patching that's automatically undone: Mocking Functions and Methods Using unittest.mock Mock Return Values and Side Effects Spy Pattern Partial Mocking Test Organization Directory Structure conftest.py Sharing Fixtures The conftest.py file makes fixtures available to all tests in its directory and subdirectories: Using Markers Markers allow categorizing and selecting tests: Running tests with markers: Test Classes for Organization Coverage Analysis Installing Coverage Tools Running Coverage Coverage Configuration Coverage in Code pytest Configuration pytest.ini pyproject.toml Configuration CI/CD Integration GitHub Actions GitLab CI Jenkins Pipeline Advanced Patterns Testing Async Code Testing Database Operations Testing with Temporary Files Caplog Capturing Log Output Capsys Capturing stdout/stderr Test Examples Example 1: Basic Unit Test Example 2: Parametrized String Validation Example 3: API Testing with Fixtures Example 4: Database Testing Example 5: Mocking External Services Example 6: Testing File Operations Example 7: Testing Classes and Methods Example 8: Testing Command Line Interface Example 9: Testing Async Functions Example 10: Fixture Parametrization Example 11: Testing Exceptions Example 12: Testing with Fixtures and Mocks Example 13: Integration Test Example Example 14: Property Based Testing Example 15: Performance Testing Best Practices Test Organization 1. One test file per source file : mymodule.py → test mymodule.py 2. Group related tests in classes : Use Test classes for logical grouping 3. Use descriptive test names : test user login with invalid credentials 4. Keep tests independent : Each test should work in isolation 5. Use fixtures for setup : Avoid duplicate setup code Writing Effective Tests 1. Follow AAA pattern : Arrange, Act, Assert 2. Test one thing per test : Each test should verify a single behavior 3. Use descriptive assertions : Make failures easy to understand 4. Avoid test interdependencies : Tests should not depend on execution order 5. Test edge cases : Empty lists, None values, boundary conditions Fixture Best Practices 1. Use appropriate scope : Minimize fixture creation cost 2. Keep fixtures small : Each fixture should have a single responsibility 3. Use fixture factories : For creating multiple test objects 4. Clean up resources : Use yield for teardown 5. Share fixtures via conftest.py : Make common fixtures available Coverage Guidelines 1. Aim for high coverage : 80%+ is a good target 2. Focus on critical paths : Prioritize important business logic 3. Don't chase 100% : Some code doesn't need tests (getters, setters) 4. Use coverage to find gaps : Not as a quality metric 5. Exclude generated code : Mark with pragma: no cover CI/CD Integration 1. Run tests on every commit : Catch issues early 2. Test on multiple Python versions : Ensure compatibility 3. Generate coverage reports : Track coverage trends 4. Fail on low coverage : Maintain coverage standards 5. Run tests in parallel : Speed up CI pipeline Useful Plugins pytest cov : Coverage reporting pytest xdist : Parallel test execution pytest asyncio : Async/await support pytest mock : Enhanced mocking pytest timeout : Test timeouts pytest randomly : Randomize test order pytest html : HTML test reports pytest benchmark : Performance benchmarking hypothesis : Property based testing pytest django : Django testing support pytest flask : Flask testing support Troubleshooting Tests Not Discovered Check file naming: test .py or test.py Check function naming: test Verify init .py files exist in test directories Run with v flag to see discovery process Fixtures Not Found Check fixture is in conftest.py or same file Verify fixture scope is appropriate Check for typos in fixture name Use fixtures flag to list available fixtures Test Failures Use v for verbose output Use tb=long for detailed tracebacks Use pdb to drop into debugger on failure Use x to stop on first failure Use lf to rerun last failed tests Import Errors Ensure package is installed: pip install e . Check PYTHONPATH is set correctly Verify init .py files exist Use sys.path manipulation if needed Resources pytest Documentation: https://docs.pytest.org/ pytest GitHub: https://github.com/pytest dev/pytest pytest Plugins: https://docs.pytest.org/en/latest/reference/plugin list.html Real Python pytest Guide: https://realpython.com/pytest python testing/ Test Driven Development with Python: https://www.obeythetestinggoat.com/ Skill Version : 1.0.0 Last Updated : October 2025 Skill Category : Testing, Python, Quality Assurance, Test Automation Compatible With : pytest 7.0+, Python 3.8+