python-testing
Skill0 starsChanged 7 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.).
53 other projects use a version of this.
Adopted by
Most recently taken up by
- Rojios/everything-claude-codetheir own version, first seen Nov 8, 2026
- dmoreq/agent-grimoiretheir own version, first seen Nov 8, 2026
- lhbsaa/apex-unifiedtheir own version, first seen Nov 8, 2026
- ahmadvahidi/skill-atlastheir own version, first seen Nov 8, 2026
- Ashfaqbs/ai-coding-agent-toolkittheir own version, first seen Nov 8, 2026
- pankaj-mahaur/Agent-Daemontheir own version, first seen Nov 6, 2026
Used with
Projects with it also use django-verification, python-patterns 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.
mstuder-slalomSkilldjango-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
xenitV1Skillpython-patterns
Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.
Also in 22 projects that use this
HABUBUSSSkillproject-guidelines-example
Also in 8 projects that use this
AshfaqbsSkillspringboot-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 7 projects that use this
mstuder-slalomSkillspringboot-security
Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.
Also in 8 projects that use this
nek1987Skillpostgres-patterns
PostgreSQL patterns for reviewing migrations and writing efficient queries. Use when reviewing Alembic migrations, optimizing queries, or debugging database issues.
Also in 15 projects that use this
- +2 more from mstuder-slalom
Other versions53 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 53
- ComposioHQ/composio★ 31ksame name
- microsoft/agent-framework★ 15ksame name
- openJiuwen-ai/agent-core★ 464same name
- Mindrally/skills★ 275same name
- loulanyue/awesome-claude-notes★ 272same name
- Fmarzochi/EGC★ 61same name
- Ashfaqbs/ai-coding-agent-toolkit★ 27same name
- FaisalAlqarni/sp-ecc★ 9same name
- DetectHensenberg/RAG4JZDQ★ 8same name
- gongyijie85/dsh-ecc★ 8same name
43 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 48 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 48 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.

