ferroxlabs/wayland/python-testing-patterns
Claude Code and agent skill by ferroxlabs/wayland
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Guides expert-level Python testing with pytest: fixture design, parametrize patterns, mocking strategies with unittest.mock, async test patterns, and test organization. Covers the testing pyramid for Python projects with emphasis on fast, reliable, maintainable tests. Use when the user asks about Python testing, pytest fixtures, test mocking, parametrized tests, async testing in Python, or organizing Python test suites. Do NOT use when the user asks about project setup (use `python-project-setup`), language-agnostic testing concepts (use `unit-testing-patterns`), or Python performance profiling (use `python-performance`).
Install
npx vskill@latest install ferroxlabs/wayland/python-testing-patternsSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as ferroxlabs/wayland/python-testing-patterns.
Python Testing Patterns
When to Use
Use this skill when:
- User asks how to write tests in Python using pytest, including test discovery, fixture wiring, or assertion patterns
- User wants to design pytest fixtures for complex scenarios involving shared state, teardown, parameterization, or scoping
- User asks about
@pytest.mark.parametrizefor table-driven testing, including matrix combinations and conditional skipping - User needs to mock dependencies using
unittest.mock, includingpatch,MagicMock,AsyncMock,patch.dict, orpatch.object - User wants to test async Python code with
pytest-asyncio, including async fixtures, async generators, and timeout behavior - User asks about organizing test suites with
conftest.pyhierarchy, test markers, or coverage configuration - User wants to apply the testing pyramid to a Python project: balancing unit, integration, and contract tests by speed and scope
- User asks about test doubles -- stubs, spies, fakes, and mocks -- and when to use each in a Python context
- User needs guidance on testing patterns specific to Python frameworks such as FastAPI, SQLAlchemy, Celery, or Pydantic
Do NOT use this skill when:
- User wants to set up a new Python project from scratch -- use
python-project-setupinstead - User is asking about general testing philosophy or the testing pyramid as a concept -- use
unit-testing-patternsinstead - User wants structured TDD workflow coaching (red-green-refactor cycles) -- use
tdd-workflowinstead - User is asking about browser-based or end-to-end testing with Playwright or Selenium -- use
e2e-testing-patternsinstead - User wants performance benchmarking or profiling of Python code -- use
python-performanceinstead - User is making high-level decisions about what to test and at what layer -- use
test-strategy-designinstead - User is asking about CI/CD pipeline configuration for running tests -- use
ci-pipeline-designinstead
Process
1. Assess the Testing Context and Test Type
Before writing any code, classify what is being tested and choose the right test category. This determines every decision downstream.
- Pure functions with no I/O or side effects: Write direct unit tests with
assert. No mocking needed. These are the fastest, most reliable tests in the suite. Push as many behaviors as possible into pure functions specifically to make them this easy to test. - Classes with injected dependencies: Write unit tests using
MagicMockorAsyncMockfor collaborators. Verify behavior via return values and call assertions. Prefer constructor injection -- it makes the dependency boundary explicit and avoidspatchentirely. - Database interaction layers (repositories, DAOs): Write integration tests that talk to a real database (PostgreSQL in a Docker container or SQLite in-memory). Use transaction rollback per test to maintain isolation without schema recreation. These belong in a separate pytest mark (
@pytest.mark.integration) and run in CI, not in pre-commit hooks. - HTTP endpoints (FastAPI, Flask): Use framework-provided test clients (
httpx.AsyncClientfor FastAPI,flask.testing.FlaskClientfor Flask). These are integration tests that exercise routing, serialization, and middleware, but mock outbound external calls. - Async code: Check the event loop policy early. Confirm
pytest-asynciois installed andasyncio_mode = "auto"is set. All async test functions and async fixtures work without@pytest.mark.asynciodecoration in auto mode. - Determine test speed targets: Unit tests should run in under 1ms each. A suite of 1000 unit tests should finish in under 2 seconds. Any test taking longer than 100ms is a candidate for mock replacement or integration test reclassification.
2. Design the Fixture Hierarchy
Fixtures are the backbone of a pytest suite. Bad fixture design causes slow, brittle, or non-isolated tests. Apply this decision framework precisely:
- Use `scope="function"` (default) for: any fixture that mutates state, any fixture wrapping a mock, any database transaction that rolls back, or anything that has side effects. This is the safe default -- prefer it unless you have a measured performance reason not to.
- Use `scope="module"` for: expensive read-only setup that is identical for every test in the file, such as parsing a large static test data file or compiling a regex that is expensive to build.
- Use `scope="session"` for: database engine creation, HTTP test client initialization, external service connections, and other one-time-per-run operations. Never store mutable test state in session-scoped fixtures.
- Use `yield` fixtures for all teardown: put setup before the
yieldand teardown after it. This ensures cleanup runs even when a test fails. Never usepytest.fixturewith areturnif the fixture allocates resources that need cleanup. - Use `autouse=True` sparingly: Only for behavior that genuinely applies to every test in scope, such as resetting a global configuration registry or clearing a singleton cache. Always document why
autouseis justified. - Use `params` on fixtures to fan out test variants:
@pytest.fixture(params=["sqlite", "postgres"], ids=["sqlite", "postgres"])creates one test per parameter value for every test that uses that fixture. This is different fromparametrizeand is appropriate when the fixture itself is the variant (e.g., testing against multiple database backends). - Stack conftest.py files hierarchically:
tests/conftest.pyprovides project-wide fixtures.tests/unit/conftest.pyprovides unit-test-specific fixtures.tests/integration/conftest.pyprovides integration-test-specific fixtures. Never import fixtures across test files manually -- let pytest discover them. - Avoid fixture overuse: A fixture that sets up 15 attributes and is used by 3 tests is a smell. Extract targeted fixtures that set up only what each test needs. Over-specified fixtures make tests fragile to unrelated changes.
3. Choose the Right Test Double Strategy
Python's unittest.mock offers multiple double types. Choosing the wrong one causes brittle tests or misses real bugs.
- `MagicMock`: Use for synchronous dependencies where you want automatic attribute access and call tracking. By default, every attribute access returns another
MagicMock, which can mask typos -- always usespec=SomeClassto constrain the mock to the real interface:MagicMock(spec=UserRepository). - `AsyncMock`: Use for any dependency whose methods are
async def. Python 3.8+ provides this inunittest.mock. If you patch an async method with a regularMagicMock, the test will not await it correctly and will return a coroutine object instead of a value. - `patch` as a decorator vs. context manager: Use
@patch("myapp.services.user_service.EmailSender")when the mock scope is the entire test function. Usewith patch(...) as mock:when the mock applies to only part of the test. Always patch at the point of use (where the name is imported into the module under test), not at the point of definition. - `patch.object`: Use when you need to patch a method on an already-instantiated object or a class attribute without replacing the entire class. Prefer this over
patchwhen the dependency is accessed viaself.something. - `patch.dict`: Use for patching
os.environ,sys.modules, or any dictionary-like configuration store. Alwaysclear=False(the default) to avoid wiping unrelated keys that other code depends on. - Manual fakes: When a third-party interface is complex (e.g., S3 client with 40 methods), write a minimal in-memory fake class that implements only the methods your code uses. This is more maintainable than a
MagicMockwith 40return_valueassignments and is easier to reuse across tests. - Spy pattern with `wraps`: Use
MagicMock(wraps=real_function)to call through to the real implementation while still tracking calls. Useful for verifying that a real function is called with specific arguments without replacing its behavior. - Dependency injection over patching: If you find yourself patching the same thing in 10 tests, refactor the source code to accept the dependency as a constructor argument. The test suite cost of excessive patching reveals a design problem.
4. Write Parametrized Tests with Intention
@pytest.mark.parametrize is the most underused and most misused pytest feature. Apply it with discipline:
- Use `pytest.param(..., id="name")` for every parameter: Test IDs like
test_validate_email[email0]are useless in CI logs. Always name your cases:pytest.param("", id="empty-string"). This makes failure messages immediately diagnostic. - Separate happy-path, edge-case, and error-case parameter lists: Don't mix valid and invalid inputs into one parametrize block. The behavior being tested is different, and the assertion is different. Use three parametrize blocks with three test functions.
- Use indirect parametrize for fixture-based variants:
@pytest.mark.parametrize("user_fixture", ["admin_user", "guest_user"], indirect=True)passes the parameter to a fixture nameduser_fixturerather than directly to the test. This allows fixture setup logic to depend on the parameter. - Stack decorators for a cartesian product: Two
@pytest.mark.parametrizedecorators create a cartesian product of cases. Use this only when you genuinely need all combinations. If you have 3 email types and 4 locale settings and need all 12 combinations tested, stacking is correct. If you only need 4 specific combinations, write them explicitly to avoid testing meaningless combinations. - Use `pytest.mark.skip` and `pytest.mark.xfail` within parametrize:
pytest.param("edge-input", id="known-bug", marks=pytest.mark.xfail(reason="GH-1234"))marks a single parametrize case as expected-to-fail without skipping the rest of the cases. - Limit parametrize breadth to 10-15 cases per block: Beyond 15 cases, consider whether you are testing the same function boundary or whether you should add a fuzz testing tool like
hypothesisfor property-based testing of the same domain.
5. Configure and Write Async Tests Correctly
Async testing has specific pitfalls that cause tests to silently pass when they should fail, or to deadlock in CI.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingsrc/process/resources/skills-library/bodies/skills/software-engineering/python-testing-patterns/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/ferroxlabs/wayland/python-testing-patterns)