python-testing
Skill2 starsChanged 10 months agoMITView on GitHub
Modern Python testing with pytest. Use this skill when writing tests, setting up test infrastructure, or debugging test failures. Covers pytest fixtures, parametrization, mocking with unittest.mock, property-based testing with hypothesis, and test organization.
We split this skill into the rules it gives an agent
2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 44 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 116
When to mock vs use real objects
- Distinctive: line 143
When to use property-based tests
“Common” is measured: kept by at least 6 in 10 of the 44 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
Modern testing patterns with pytest for reliable, maintainable test suites.
Core Principles
- Use pytest over unittest - Better fixtures, assertions, parametrization
- Arrange-Act-Assert pattern - Clear test structure
- Test behavior, not implementation - Focus on public APIs
- Fixtures for setup - Reusable, composable test state
Basic Test Structure
def test_process_data_filters_correctly():
# Arrange
data = pd.DataFrame({"score": [1, 5, 10]})
# Act
result = process_data(data, threshold=5)
# Assert
assert len(result) == 1
assert result["score"].iloc[0] == 10Fixtures
Use fixtures for reusable test setup
import pytest
@pytest.fixture
def sample_data():
"""Provide sample DataFrame for tests."""
return pd.DataFrame({
"id": [1, 2, 3],
"value": [10, 20, 30]
})
def test_with_fixture(sample_data):
result = process_data(sample_data)
assert len(result) == 3Fixture scopes:
scope="function"(default) - Per testscope="class"- Per test classscope="module"- Per filescope="session"- Once per test run
See fixture-patterns.md for:
- Fixture composition
- Parametrized fixtures
- Fixture cleanup (yield pattern)
- conftest.py organization
Parametrization
Test multiple inputs efficiently
@pytest.mark.parametrize("input,expected", [
(5, 25),
(0, 0),
(-3, 9),
])
def test_square(input, expected):
assert square(input) == expected
# Multiple parameters
@pytest.mark.parametrize("threshold", [0.5, 0.8])
@pytest.mark.parametrize("method", ["linear", "cubic"])
def test_interpolation(threshold, method):
result = interpolate(data, threshold, method)
assert result is not NoneSee parametrization-examples.md for:
- Complex parameter combinations
- Parametrizing fixtures
- Using pytest.param for IDs
- Indirect parametrization
Mocking
Use unittest.mock for external dependencies
from unittest.mock import Mock, patch, MagicMock
def test_api_call():
# Mock the requests library
with patch('mymodule.requests.get') as mock_get:
mock_get.return_value.json.return_value = {"status": "ok"}
result = fetch_data()
assert result["status"] == "ok"
mock_get.assert_called_once()
# Mock as fixture
@pytest.fixture
def mock_database():
with patch('mymodule.Database') as mock_db:
mock_db.return_value.query.return_value = [{"id": 1}]
yield mock_dbSee mocking-patterns.md for:
- When to mock vs use real objects
- Mock vs MagicMock
- Side effects and exceptions
- Patching strategies
Property-Based Testing
Use hypothesis for generative testing
from hypothesis import given, strategies as st
@given(st.lists(st.integers()))
def test_sort_is_idempotent(items):
"""Sorting twice should equal sorting once."""
assert sorted(sorted(items)) == sorted(items)
@given(st.text(), st.text())
def test_string_concatenation(s1, s2):
"""Concatenation should preserve length."""
result = s1 + s2
assert len(result) == len(s1) + len(s2)See property-based-testing.md for:
- Strategy composition
- Custom strategies
- Stateful testing
- When to use property-based tests
Test Organization
tests/
├── conftest.py # Shared fixtures
├── unit/
│ ├── test_processing.py # Unit tests
│ └── test_validation.py
├── integration/
│ └── test_pipeline.py # Integration tests
└── fixtures/
└── sample_data.json # Test dataconftest.py for shared fixtures:
import pytest
@pytest.fixture(scope="session")
def test_config():
return {"api_key": "test", "debug": True}Assertions
# Basic assertions
assert value == expected
assert value > threshold
assert item in collection
# Approximate comparisons
assert value == pytest.approx(3.14, rel=0.01)
# Exception testing
with pytest.raises(ValueError, match="Invalid input"):
process_invalid_data()
# Warnings testing
with pytest.warns(DeprecationWarning):
legacy_function()Test Markers
@pytest.mark.slow
def test_long_running():
pass
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
pass
@pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires 3.10+")
def test_pattern_matching():
pass
# Run with: pytest -m "not slow"Coverage
# Run with coverage
pytest --cov=mymodule --cov-report=html
# Enforce coverage threshold
pytest --cov=mymodule --cov-fail-under=80Anti-Patterns to Avoid
| Avoid | Use Instead |
self.assertEqual() | assert x == y |
| Large test classes | Grouped by fixtures |
| Testing implementation details | Test public API behavior |
| No parametrization | @pytest.mark.parametrize |
| Manual setup/teardown | Fixtures with yield |
source: pytest documentation, Testing Best Practices
Other versions48 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 48
- ComposioHQ/composio★ 31ksame name
- microsoft/agent-framework★ 14ksame name
- openJiuwen-ai/agent-core★ 451same name
- Mindrally/skills★ 275same name
- loulanyue/awesome-claude-notes★ 272same name
- Fmarzochi/EGC★ 61same name
- fmind/dot★ 11same name
- fmind/dotfiles★ 11same name
- FaisalAlqarni/sp-ecc★ 9same name
- DetectHensenberg/RAG4JZDQ★ 8same name
38 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.
Used alongsideProjects 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 8 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 17 projects that use this
HABUBUSSSkillproject-guidelines-example
Also in 7 projects that use this
mstuder-slalomSkilldjango-security
Django security best practices, authentication, authorization, CSRF protection, SQL injection prevention, XSS prevention, and secure deployment configurations.
Also in 8 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 5 projects that use this
yanhaoluo0Skilljava-coding-standards
阿里巴巴Java开发手册编程规约,包含命名风格、常量定义、代码格式、OOP规约、日期时间、集合处理、并发处理、控制语句、注释规约等。Use when writing Java code, reviewing code, or following Alibaba Java coding standards.
Also in 5 projects that use this
- +4 more from mstuder-slalom
In this repository38 other files it gives its agents.
- Data Engineering Cloud InfrastructureSkill
- data-eng-data-qualitySkill
- data-eng-streaming-patternsSkill
- data-eng-testing-patternsSkill
- data-eng-warehouse-patternsSkill
- DevOps CI/CD PatternsSkill
- devops-docker-patternsSkill
- devops-monitoring-observabilitySkill
- devops-terraform-patternsSkill
- git-advanced-operationsSkill
- git-workflow-patternsSkill
- modern-python-patternsSkill
- python-api-developmentSkill
- python-async-patternsSkill
- python-data-pipelinesSkill
- python-data-wranglingSkill
- python-devops-automationSkill
- python-error-handlingSkill
- python-package-developmentSkill
- python-performanceSkill
- customizing-vectors-rSkill
- designing-oop-rSkill
- developing-packages-rSkill
- metaprogramming-rlangSkill
- optimizing-rSkill
- writing-tidyverse-rSkill
- sql-advanced-featuresSkill
- sql-analytics-patternsSkill
- sql-data-modelingSkill
- SQL Integration PatternsSkill
- sql-query-fundamentalsSkill
- sql-query-optimizationSkill
- sql-transformationsSkill
- API DesignSkill
- webdev-html-css-patternsSkill
- webdev-javascript-fundamentalsSkill
- webdev-react-patternsSkill
- webdev-typescript-patternsSkill
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.

