ferroxlabs/wayland/python-testing-patterns

Claude Code and agent skill by ferroxlabs/wayland

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Source check pending

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-patterns

Semi-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.parametrize for table-driven testing, including matrix combinations and conditional skipping
  • User needs to mock dependencies using unittest.mock, including patch, MagicMock, AsyncMock, patch.dict, or patch.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.py hierarchy, 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-setup instead
  • User is asking about general testing philosophy or the testing pyramid as a concept -- use unit-testing-patterns instead
  • User wants structured TDD workflow coaching (red-green-refactor cycles) -- use tdd-workflow instead
  • User is asking about browser-based or end-to-end testing with Playwright or Selenium -- use e2e-testing-patterns instead
  • User wants performance benchmarking or profiling of Python code -- use python-performance instead
  • User is making high-level decisions about what to test and at what layer -- use test-strategy-design instead
  • User is asking about CI/CD pipeline configuration for running tests -- use ci-pipeline-design instead

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 MagicMock or AsyncMock for collaborators. Verify behavior via return values and call assertions. Prefer constructor injection -- it makes the dependency boundary explicit and avoids patch entirely.
  • 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.AsyncClient for FastAPI, flask.testing.FlaskClient for 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-asyncio is installed and asyncio_mode = "auto" is set. All async test functions and async fixtures work without @pytest.mark.asyncio decoration 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 yield and teardown after it. This ensures cleanup runs even when a test fails. Never use pytest.fixture with a return if 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 autouse is 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 from parametrize and is appropriate when the fixture itself is the variant (e.g., testing against multiple database backends).
  • Stack conftest.py files hierarchically: tests/conftest.py provides project-wide fixtures. tests/unit/conftest.py provides unit-test-specific fixtures. tests/integration/conftest.py provides 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 use spec=SomeClass to 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 in unittest.mock. If you patch an async method with a regular MagicMock, 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. Use with 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 patch when the dependency is accessed via self.something.
  • `patch.dict`: Use for patching os.environ, sys.modules, or any dictionary-like configuration store. Always clear=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 MagicMock with 40 return_value assignments 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 named user_fixture rather than directly to the test. This allows fixture setup logic to depend on the parameter.
  • Stack decorators for a cartesian product: Two @pytest.mark.parametrize decorators 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 hypothesis for 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

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
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ferroxlabs/wayland/python-testing-patterns/badge)](https://verified-skill.com/skills/ferroxlabs/wayland/python-testing-patterns)

Something wrong with this skill or its page? Tell us.