pytest
pytest Python testing framework. Covers fixtures, parametrize, and mocking. Use for Python testing. USE WHEN: user mentions "pytest", "python test", "fixture", asks about "@pytest.fixture", "@pytest.mark.parametrize", "conftest.py", "pytest coverage", "python unit test" DO NOT USE FOR: JavaScript/TypeScript - use `vitest` or `jest`; Java - use `junit`; E2E web tests - use `playwright`; Load testing - use locust
What this skill does
# pytest Core Knowledge
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `pytest` for comprehensive documentation.
## When NOT to Use This Skill
- **JavaScript/TypeScript Testing** - Use `vitest` or `jest` for JS/TS projects
- **Java Testing** - Use `junit` for Java/Spring projects
- **E2E Web Testing** - Use `playwright` for browser automation
- **Load Testing** - Use locust or pytest-benchmark for performance
- **API Contract Testing** - Use dedicated tools like Pact
## Basic Tests
```python
def test_addition():
assert 1 + 1 == 2
def test_list_contains():
items = [1, 2, 3]
assert 2 in items
def test_raises_exception():
with pytest.raises(ValueError):
int("not a number")
class TestUserService:
def test_create_user(self):
user = create_user(name="John")
assert user.name == "John"
```
## Fixtures
```python
import pytest
@pytest.fixture
def user():
return User(name="John", email="[email protected]")
@pytest.fixture
def db():
connection = create_db_connection()
yield connection
connection.close()
def test_user_name(user):
assert user.name == "John"
def test_user_in_db(db, user):
db.save(user)
assert db.find(user.id) is not None
```
## Parametrize
```python
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_double(input, expected):
assert double(input) == expected
@pytest.mark.parametrize("email,valid", [
("[email protected]", True),
("invalid", False),
("", False),
])
def test_validate_email(email, valid):
assert validate_email(email) == valid
```
## Mocking
```python
from unittest.mock import Mock, patch
def test_with_mock():
mock_api = Mock()
mock_api.get_users.return_value = [{"name": "John"}]
result = process_users(mock_api)
mock_api.get_users.assert_called_once()
@patch('myapp.api.requests.get')
def test_api_call(mock_get):
mock_get.return_value.json.return_value = {"data": []}
result = fetch_data()
assert result == {"data": []}
```
## Async Tests
```python
import pytest
@pytest.mark.asyncio
async def test_async_function():
result = await async_fetch_data()
assert result is not None
# With pytest-asyncio 0.23+
@pytest.mark.asyncio(loop_scope="module")
async def test_shared_loop():
pass
```
## Property-Based Testing (Hypothesis)
```python
from hypothesis import given, strategies as st
@given(st.integers(), st.integers())
def test_addition_commutative(a: int, b: int):
assert a + b == b + a
@given(st.lists(st.integers()))
def test_sort_idempotent(items: list[int]):
assert sorted(sorted(items)) == sorted(items)
@given(st.text(min_size=1))
def test_string_nonempty(s: str):
assert len(s) >= 1
# Custom strategies
@given(st.builds(User, name=st.text(min_size=1), age=st.integers(0, 150)))
def test_user_creation(user: User):
assert user.name
assert 0 <= user.age <= 150
# Stateful testing
from hypothesis.stateful import RuleBasedStateMachine, rule
class SetMachine(RuleBasedStateMachine):
def __init__(self):
self.model = set()
self.impl = MySet()
@rule(value=st.integers())
def add(self, value):
self.model.add(value)
self.impl.add(value)
assert self.impl.contains(value)
```
## Configuration
```ini
# pytest.ini
[pytest]
testpaths = tests
python_files = test_*.py
python_functions = test_*
addopts = -v --cov=src --cov-report=html
```
## Production Readiness
### Test Organization
```python
# tests/conftest.py - Shared fixtures
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@pytest.fixture(scope="session")
def engine():
"""Database engine for all tests."""
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
yield engine
engine.dispose()
@pytest.fixture(scope="function")
def db_session(engine):
"""Fresh database session for each test."""
Session = sessionmaker(bind=engine)
session = Session()
yield session
session.rollback()
session.close()
@pytest.fixture
def client(db_session):
"""Test client with database session."""
app.dependency_overrides[get_db] = lambda: db_session
with TestClient(app) as client:
yield client
app.dependency_overrides.clear()
```
### Coverage Configuration
```ini
# pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
addopts = "-v --cov=src --cov-report=term-missing --cov-report=xml --cov-fail-under=80"
markers = [
"slow: marks tests as slow",
"integration: integration tests",
]
[tool.coverage.run]
source = ["src"]
omit = ["*/tests/*", "*/__init__.py"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"if TYPE_CHECKING:",
"raise NotImplementedError",
]
```
### CI Configuration
```yaml
# GitHub Actions
- name: Run tests
run: |
pytest --junitxml=test-results.xml --cov-report=xml
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage.xml
```
### Factory Pattern
```python
# tests/factories.py
import factory
from faker import Faker
fake = Faker()
class UserFactory(factory.Factory):
class Meta:
model = User
name = factory.LazyAttribute(lambda _: fake.name())
email = factory.LazyAttribute(lambda _: fake.email())
is_active = True
# Usage
def test_user_creation(db_session):
user = UserFactory()
db_session.add(user)
db_session.commit()
assert user.id is not None
```
### Monitoring Metrics
| Metric | Target |
|--------|--------|
| Line coverage | > 80% |
| Branch coverage | > 75% |
| Test execution time | < 60s |
| Flaky test rate | 0% |
### Checklist
- [ ] Fixtures in conftest.py
- [ ] Database isolation per test
- [ ] Coverage thresholds enforced
- [ ] CI/CD integration
- [ ] Factory pattern for test data
- [ ] Proper test markers
- [ ] Async tests with pytest-asyncio
- [ ] Mocking external services
- [ ] Parametrized edge cases
- [ ] Error paths tested
## Anti-Patterns
| Anti-Pattern | Why It's Bad | Solution |
|--------------|--------------|----------|
| Sharing mutable fixtures | Tests affect each other | Use function-scoped fixtures |
| Not using parametrize | Duplicate test code | Use @pytest.mark.parametrize |
| Testing implementation details | Brittle tests | Test public API behavior |
| Fixtures with side effects | Hard to debug | Keep fixtures pure, use yield for cleanup |
| No conftest.py organization | Scattered fixtures | Centralize in conftest.py |
| Ignoring warnings | Hidden issues | Treat warnings as errors in CI |
| Not mocking external services | Slow, flaky tests | Mock HTTP, database, file system |
## Quick Troubleshooting
| Problem | Likely Cause | Solution |
|---------|--------------|----------|
| "fixture not found" | Fixture not in scope | Move to conftest.py or same file |
| Test hangs | Missing await or infinite loop | Check async operations, add timeout |
| "Database is locked" | Shared DB connection | Use function-scoped DB fixtures |
| Flaky test | Shared state or timing | Isolate setup, check for race conditions |
| Import error | PYTHONPATH not set | Add src to path or use pytest.ini |
| Coverage not accurate | Missing source paths | Configure [tool.coverage.run] in pyproject.toml |
## Hypothesis Configuration
```toml
# pyproject.toml
[tool.hypothesis]
deadline = 500 # ms
max_examples = 100
database = ".hypothesis"
[tool.pytest.ini_options]
addopts = "--hypothesis-show-statistics"
```
## Reference Documentation
- [Fixtures](quick-ref/fixtures.md)
- [Mocking](quick-ref/mocking.md)
**Official docs:**
- pytest: https://docs.pytest.org/
- hypothesis: https://hypothesis.readthedocs.io/
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.