python-testing
Skill0 starsChanged 8 months agoMITView on GitHub
Write and improve Python tests using pytest. Use when adding tests to a project, fixing broken tests, improving test coverage, setting up async tests, or asking how to test a specific pattern (HTTP endpoints, database, mocking, etc.).
33 other projects use a version of this.
Adopted by
Most recently taken up by
- fmind/dottheir own version, first seen Oct 5, 2026
- ComposioHQ/composiotheir own version, first seen Sep 29, 2026
- templetongroup/radianttheir own version, first seen Sep 17, 2026
- IAbuElRuzz/AgentSkillstheir own version, first seen Sep 16, 2026
- Paldom/python-skillstheir own version, first seen Sep 10, 2026
- konstruktoid/agent-instructions-skillstheir own version, first seen Aug 24, 2026
Used with
Projects with it also use swift-protocol-di-testing, springboot-tdd 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.
InfopibeSkillswift-protocol-di-testing
Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.
Also in 6 projects that use this
FaisalAlqarniSkillspringboot-tdd
Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.
Also in 9 projects that use this
FaisalAlqarniSkilldjango-verification
Verification loop for Django projects: migrations, linting, tests with coverage, security scans, and deployment readiness checks before release or PR.
Also in 9 projects that use this
InfopibeSkillswift-actor-persistence
Thread-safe data persistence in Swift using actors — in-memory cache with file-backed storage, eliminating data races by design.
Also in 6 projects that use this
johnrtiptonSkilldjango-security
This skill should be used when conducting security reviews, auditing Django applications, hardening security settings, implementing OWASP Top 10 protections, managing secrets, or ensuring multi-tenant security isolation. Provides automated security auditor that scans settings, code, dependencies, and multi-tenant configurations with auto-fix capabilities.
Also in 9 projects that use this
joneqianSkillpostgres-patterns
PostgreSQL database patterns for query optimization, schema design, indexing, and security. Based on Supabase best practices.
Also in 12 projects that use this
- +1 more from FaisalAlqarni
- +3 more from Infopibe
Other versions33 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 33
- ComposioHQ/composio★ 30ksame name
- microsoft/agent-framework★ 14ksame name
- xu-xiang/everything-claude-code-zh★ 2ksame name
- loulanyue/awesome-claude-notes★ 272same name
- Mindrally/skills★ 266same name
- tpavanipradeep/everything-claude-code★ 134same name
- templetongroup/radiant★ 113same name
- Jamkris/everything-gemini-code★ 87same name
- codelably/harmony-claude-code★ 43same name
- noah-sheldon/ai-dev-kit★ 13same name
23 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 repository8 other files it gives its agents.
- app-store-preflight-skillsSkill
- fastapi-patternsSkill
- frontend-designSkill
- mcp-builderSkill
- code-documentationSkill
- ui-patternsSkill
- view-refactorSkill
- theme-factorySkill
The file
We split this skill into the rules it gives an agent
9 rules. 0 are common, 6 are distinctive, and 3 are very specific to this project.
0
Common
Most of the 28 edited versions we read keep these.
6
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 13
Write clear, fast, trustworthy tests.
- Distinctive: line 19
Before writing any tests:
- Distinctive: line 20
Read the function/module to understand its contract (inputs, outputs, side effects)
- Distinctive: line 21
Check for existing tests — mimic the file structure and naming conventions in use
- Very specific: line 22
Check pyproject.toml or setup.cfg for pytest config, markers, and plugins already installed
- Distinctive: line 36
Default to the smallest test type that gives you confidence: Don't mock what you can test cheaply for real.
- Distinctive: line 42
Use the Arrange / Act / Assert pattern.
- Very specific: line 60
Keep names honest — test_returns_none should return None, not raise
- Very specific: line 230
Run subsets: pytest -m "not slow", pytest -m integration
“Common” is measured: kept by at least 6 in 10 of the 28 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Python Testing Skill
Write clear, fast, trustworthy tests. Tests are code — they should be readable, maintainable, and test behaviour not implementation.
Step 1: Read the Code Under Test
Before writing any tests:
- Read the function/module to understand its contract (inputs, outputs, side effects)
- Check for existing tests — mimic the file structure and naming conventions in use
- Check
pyproject.tomlorsetup.cfgfor pytest config, markers, and plugins already installed
Step 2: Choose the Right Test Type
| Scenario | Approach |
| Pure functions | Unit test with assert |
| Code with I/O / external dependencies | Unit test + mock the boundary |
| FastAPI / Flask / Django endpoints | Integration test with TestClient / AsyncClient |
| Database-backed code | Integration test against real DB (use fixtures for setup/teardown) |
| Complex workflows | End-to-end test, sparingly |
Default to the smallest test type that gives you confidence. Don't mock what you can test cheaply for real.
Step 3: Test Structure
Use the Arrange / Act / Assert pattern. One logical assertion per test.
def test_discount_applied_to_eligible_order():
# Arrange
order = Order(items=[Item(price=100)], customer_tier="gold")
# Act
total = calculate_total(order)
# Assert
assert total == 90 # 10% gold discountFile and function naming
- Test files:
test_<module>.py - Test functions:
test_<what>_<when/condition>_<expected> - Keep names honest —
test_returns_noneshould return None, not raise
Core Patterns
Fixtures
import pytest
@pytest.fixture
def user():
return User(id=1, name="Ada", email="ada@example.com")
@pytest.fixture
def db(tmp_path):
"""Isolated SQLite DB per test."""
engine = create_engine(f"sqlite:///{tmp_path}/test.db")
Base.metadata.create_all(engine)
with Session(engine) as session:
yield session
# Reuse fixtures across files with conftest.pyParametrize
@pytest.mark.parametrize("email,valid", [
("user@example.com", True),
("not-an-email", False),
("", False),
("user@", False),
])
def test_email_validation(email, valid):
assert validate_email(email) == validMocking
from unittest.mock import patch, MagicMock
def test_sends_welcome_email(mock_email_client):
with patch("myapp.services.email_client") as mock_client:
register_user("ada@example.com")
mock_client.send.assert_called_once_with(
to="ada@example.com",
template="welcome",
)
# Or use pytest-mock for cleaner syntax
def test_sends_welcome_email(mocker):
mock_send = mocker.patch("myapp.services.email_client.send")
register_user("ada@example.com")
mock_send.assert_called_once()Async tests
# Requires: pytest-asyncio
# pyproject.toml: [tool.pytest.ini_options] asyncio_mode = "auto"
import pytest
@pytest.mark.asyncio
async def test_fetch_user():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/users/1")
assert response.status_code == 200
# With pytest-asyncio asyncio_mode="auto", mark is optional
async def test_fetch_user_auto():
result = await fetch_user(user_id=1)
assert result.name == "Ada"Testing FastAPI endpoints
from fastapi.testclient import TestClient
from httpx import AsyncClient
import pytest
client = TestClient(app) # sync — fine for most tests
def test_create_item_returns_201():
response = client.post("/items/", json={"name": "Gadget", "price": 9.99})
assert response.status_code == 201
assert response.json()["name"] == "Gadget"
def test_get_item_not_found_returns_404():
response = client.get("/items/99999")
assert response.status_code == 404
# Override dependencies for isolation
def override_get_db():
yield test_db_session
app.dependency_overrides[get_db] = override_get_dbTesting exceptions
import pytest
def test_raises_on_invalid_input():
with pytest.raises(ValueError, match="must be positive"):
compute_score(-1)
def test_raises_http_exception():
response = client.get("/users/0")
assert response.status_code == 422 # FastAPI validation errorFixtures Best Practices
- Keep fixtures focused — one fixture does one thing
- Use
yieldfixtures for setup/teardown (replacessetup_method) - Scope appropriately:
function(default),module,sessionsession-scoped DB migrations,function-scoped transactions (rollback after each test)
- Put shared fixtures in
conftest.py— pytest auto-discovers it
# conftest.py
@pytest.fixture(scope="session")
def engine():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
yield engine
engine.dispose()
@pytest.fixture
def db(engine):
connection = engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
yield session
session.close()
transaction.rollback()
connection.close()Markers and Configuration
# pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
markers = [
"slow: marks tests as slow (deselect with -m 'not slow')",
"integration: marks integration tests",
]@pytest.mark.slow
@pytest.mark.integration
def test_full_order_pipeline():
...Run subsets: pytest -m "not slow", pytest -m integration
Coverage
pytest --cov=myapp --cov-report=term-missing
pytest --cov=myapp --cov-fail-under=80# pyproject.toml
[tool.coverage.run]
omit = ["tests/*", "*/migrations/*"]
[tool.coverage.report]
exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:"]Coverage is a floor, not a target. 80% with meaningful tests beats 100% with trivial ones.
What NOT to Test
- Framework internals (don't test that FastAPI parses JSON — test your logic)
- Implementation details (test behaviour, not which private method was called)
- Trivial getters/setters
- Code you don't own
Common Gotchas
- Don't patch where it's defined — patch where it's used:
patch("myapp.routes.send_email")notpatch("myapp.email.send_email") - Async fixtures need
pytest-asyncioandasync deffixtures require the right scope TestClientruns the app synchronously — useAsyncClientwhen you need true async behaviour- Avoid
time.sleepin tests — mockdatetime.now()or usefreezegun
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.

