python-testing-patterns
Skill8 starsChanged 9 months agoMITView on GitHub
Guide pytest patterns and testing strategies when the user asks about Python testing, fixtures, mocking, or test organization
38 other projects use a version of this.
Adopted by
Most recently taken up by
- gromov0737/skillstheir own version, first seen Nov 29, 2026
- alexj11324/Mikkatheir own version, first seen Nov 29, 2026
- fxckcode/ai-code-reviewtheir own version, first seen Nov 29, 2026
- theexperiencecompany/gaiatheir own version, first seen Nov 26, 2026
- rotnov/pycctheir own version, first seen Nov 22, 2026
- aspectly-labs/Mikkatheir own version, first seen Nov 22, 2026
Used with
Projects with it also use python-type-safety, python-observability and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
CodeWithBehnamSkillpython-type-safety
Python type safety with type hints, generics, protocols, and strict type checking. Use when adding type annotations, implementing generic classes, defining structural interfaces, or configuring mypy/pyright.
Also in 5 projects that use this
CodeWithBehnamSkillpython-observability
Python observability patterns including structured logging, metrics, and distributed tracing. Use when adding logging, implementing metrics collection, setting up tracing, or debugging production systems.
Also in 4 projects that use this
jh941213Skilldocs-ci
문서 CI(링크·OpenAPI lint·breaking 게이트·mermaid 검증)나 문서 드리프트 감지(docs.yaml 신선도 검사)를 설치하거나 돌릴 때 사용. 문서 내용 작성은 docs-architecture·docs-interfaces·docs-manuals.
Also in 3 projects that use this
jh941213Skilldocs-interfaces
API·이벤트 인터페이스 문서(OpenAPI·swagger·AsyncAPI 명세, 엔드포인트 레퍼런스, API 구성도·시퀀스, API CHANGELOG)를 만들거나 코드와 맞출 때 사용. 시스템 구성도는 docs-architecture, API 설계 원칙은 api-design-principles.
Also in 3 projects that use this
Aver005Skillpython-resource-management
Python resource management with context managers, cleanup patterns, and streaming. Use when managing connections, file handles, implementing cleanup logic, or building streaming responses with accumulated state.
Also in 4 projects that use this
Aver005Skillpython-code-style
Python code style, linting, formatting, naming conventions, and documentation standards. Use when writing new code, reviewing style, configuring linters, writing docstrings, or establishing project standards.
Also in 5 projects that use this
- +4 more from jh941213
- +1 more from Aver005
- +1 more from CodeWithBehnam
Other versions38 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 38
- theexperiencecompany/gaia★ 336same name
- jh941213/ADLC-harness★ 125same name
- jh941213/my-cc-harness★ 125same name
- jh941213/my-claude-code-asset★ 125same name
- alexj11324/Mikka★ 90same name
- aspectly-labs/Mikka★ 90same name
- kumaran-is/claude-code-onboarding★ 35same name
- elimydlarz/gralkor★ 9same name
- xfstudio/skills★ 9same name
- VoVuongThanhDat/agentflow★ 8same name
28 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository79 other files it gives its agents.
- AGENTS.mdAGENTS.md
- analyze-competitorsSkill
- analyze-dependenciesSkill
- analyze-metricsSkill
- audit-accessibilitySkill
- audit-api-consistencySkill
- audit-performanceSkill
- audit-securitySkill
- capture-pr-visualsSkill
- commitSkill
- create-adrSkill
- create-api-designSkill
- create-bug-reportSkill
- create-commit-messageSkill
- create-data-modelSkill
- create-decision-logSkill
- create-docSkill
- create-estimationSkill
- create-experiment-designSkill
- create-feature-flag-planSkill
- create-gtm-briefSkill
- create-handoffSkill
- create-incident-reportSkill
- create-interview-guideSkill
- create-jtbd-canvasSkill
- create-metrics-frameworkSkill
- create-onboarding-guideSkill
- create-ostSkill
- create-planSkill
- create-postmortemSkill
- create-pr-descriptionSkill
- create-prdSkill
- create-prSkill
- create-release-checklistSkill
- create-release-notesSkill
- create-retroSkill
- create-reviewSkill
- create-rfcSkill
- create-roadmapSkill
- create-rollback-planSkill
- create-runbookSkill
- create-shape-up-pitchSkill
- create-stakeholder-updateSkill
- create-test-planSkill
- create-threat-modelSkill
- create-user-storiesSkill
- debug-systematicSkill
- fastapi-endpoint-patternsSkill
- fix-findingsSkill
- fix-reviewSkill
- flutter-platform-patternsSkill
- flutter-state-managementSkill
- flutter-version-managementSkill
- flutter-widget-patternsSkill
- manage-tech-debtSkill
- nextjs-api-patternsSkill
- nextjs-app-router-patternsSkill
- nextjs-performanceSkill
- product-context-docsSkill
- project-skill-creatorSkill
- The first 60 shown.
The file
Files
Python Testing Patterns
Overview
Guide pytest-based testing for Python services. Covers fixture design, factory patterns, mocking strategies, async testing, and parametrize usage. Applies the testing pyramid: unit tests for services, integration tests for repos and DB, end-to-end tests for API endpoints. Stack-specific Tier 3 reference skill.
Workflow
- Read project setup — Check
.chalk/docs/engineering/for architecture docs. Determine the testing stack: pytest version, async framework (asyncio, trio), HTTP client (httpx, requests, aiohttp), ORM (SQLAlchemy, Django ORM, Tortoise), and any existing test conventions. Readconftest.pyfiles to understand current fixture organization. - Identify the scope — Parse
$ARGUMENTSfor the specific module, test file, or testing concern. Categories include: fixture design, factory patterns, mocking, async testing, parametrize, or test organization. - Audit fixture design — Check for:
- Fixture scope:
function(default, safest),class,module,session(fastest but risk shared state). Use the narrowest scope that avoids unacceptable slowness. conftest.pyorganization: fixtures in the rightconftest.pylevel (project root for shared, per-directory for scoped). Avoid importing fixtures across test directories.- Fixture dependencies: fixtures that depend on other fixtures should form a clean DAG, not a tangled web.
yieldfixtures for setup/teardown: prefer overaddfinalizerfor readability.
- Fixture scope:
- Audit factory patterns — Check for:
- Inline test data construction (repeated
User(name="test", email="test@test.com")across tests). Recommendfactory_boyor custom factory functions. - Factory classes that mirror models:
UserFactory,OrderFactorywith sensible defaults and traits for variations. - Factories that hit the database when they do not need to (
factory.build()vs.factory.create()).
- Inline test data construction (repeated
- Audit mocking strategy — Check for:
- Over-mocking: mocking the thing you are testing (tests pass but prove nothing).
- Under-mocking: tests that hit real external services (slow, flaky, costly).
- Mock placement: patch where the object is used, not where it is defined (
unittest.mock.patch("mymodule.requests.get")notpatch("requests.get")). - HTTP mocking:
respxforhttpx,responsesforrequests,aioresponsesforaiohttp. - Missing
spec=Trueon mocks (allows calling methods that do not exist on the real object).
- Audit async testing — If the project uses async code, check for:
pytest-asynciowithmode="auto"or explicit@pytest.mark.asynciodecorators.- Missing
asyncon test functions that test async code (test passes silently without actually awaiting). - Async fixtures using
@pytest_asyncio.fixtureinstead of@pytest.fixture. - Event loop scope mismatches between fixtures and tests.
- Audit parametrize usage — Check for:
- Duplicate test functions that differ only in input/output (should be
@pytest.mark.parametrize). - Missing edge case parameters: empty input, None, boundary values, unicode, very large inputs.
- Parametrize IDs for readable test output (
pytest.param(..., id="empty-list")).
- Duplicate test functions that differ only in input/output (should be
- Assess testing pyramid — Check the balance:
- Unit tests (services, pure functions): fast, isolated, high coverage. Should be the majority.
- Integration tests (repos + DB, external service wrappers): test real interactions, use test databases or containers.
- E2E tests (API endpoints): test the full stack via
TestClient/httpx.AsyncClient. Should be the fewest, covering critical paths.
- Report findings — Present findings with specific file references, current patterns, recommended improvements, and examples.
Output
- Format: Audit report delivered in the conversation
- Key sections: Fixture Organization, Factory Patterns, Mocking Strategy, Async Testing (if applicable), Parametrize Opportunities, Testing Pyramid Balance, Prioritized Recommendations with Code Examples
Anti-patterns
- Testing implementation, not behavior — Tests that assert on internal method calls or private attributes break when you refactor. Test the public interface and observable outcomes.
- Shared mutable state between tests — Session-scoped fixtures with mutable state cause tests to pass individually but fail together. Default to function scope; widen only with immutable data.
- Mock everything — If every dependency is mocked, the test proves the mock works, not the code. Integration tests exist for a reason. Mock external boundaries (APIs, databases in unit tests), not internal collaborators.
- No assertion messages — While
pytestprovides rich diffs for failures, complex assertions can benefit from a message explaining the intent of the check. For example,assert user.is_active, "New users should be active by default"is more informative than justassert user.is_active is True. - Ignoring test performance — A test suite that takes 10 minutes will not be run locally. Profile slow tests, use appropriate fixture scopes, and parallelize with
pytest-xdist. - Copy-paste test functions — Five test functions that differ by one line should be one parametrized test. Duplication in tests is just as harmful as duplication in production code.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

