pytest-mastery
Python testing with pytest using uv package manager. Use when: (1) Running Python tests, (2) Writing test files or test functions, (3) Setting up fixtures, (4) Parametrizing tests, (5) Generating coverage reports, (6) Testing FastAPI applications, (7) Debugging test failures, (8) Configuring pytest options. Triggers: "run tests", "write tests", "test coverage", "pytest", "unit test", "integration test", "test FastAPI".
What this skill does
# pytest Testing with uv
## Quick Reference
```bash
# Run all tests
uv run pytest
# Run with verbose output
uv run pytest -v
# Run specific file
uv run pytest tests/test_example.py
# Run specific test function
uv run pytest tests/test_example.py::test_function_name
# Run tests matching pattern
uv run pytest -k "pattern"
# Run with coverage
uv run pytest --cov=src --cov-report=html
```
## Installation
```bash
# Add pytest as dev dependency
uv add --dev pytest
# Add coverage support
uv add --dev pytest-cov
# Add async support (for FastAPI)
uv add --dev pytest-asyncio httpx
```
## Test Discovery
pytest automatically discovers tests following these conventions:
- Files: `test_*.py` or `*_test.py`
- Functions: `test_*`
- Classes: `Test*` (no `__init__` method)
- Methods: `test_*` inside `Test*` classes
Standard project structure:
```
project/
├── src/
│ └── myapp/
├── tests/
│ ├── __init__.py
│ ├── conftest.py # Shared fixtures
│ ├── test_unit.py
│ └── integration/
│ └── test_api.py
└── pyproject.toml
```
## Fixtures
Fixtures provide reusable test setup/teardown:
```python
import pytest
@pytest.fixture
def sample_user():
return {"id": 1, "name": "Test User"}
@pytest.fixture
def db_connection():
conn = create_connection()
yield conn # Test runs here
conn.close() # Teardown
def test_user_name(sample_user):
assert sample_user["name"] == "Test User"
```
### Fixture Scopes
```python
@pytest.fixture(scope="function") # Default: new instance per test
@pytest.fixture(scope="class") # Once per test class
@pytest.fixture(scope="module") # Once per module
@pytest.fixture(scope="session") # Once per test session
```
### Shared Fixtures (conftest.py)
Place in `tests/conftest.py` for automatic availability:
```python
# tests/conftest.py
import pytest
@pytest.fixture
def api_client():
return TestClient(app)
```
## Parametrization
Run same test with multiple inputs:
```python
import pytest
@pytest.mark.parametrize("input,expected", [
(1, 2),
(2, 4),
(3, 6),
])
def test_double(input, expected):
assert input * 2 == expected
@pytest.mark.parametrize("value", [None, "", [], {}])
def test_falsy_values(value):
assert not value
```
## Common Options
| Option | Description |
|--------|-------------|
| `-v` | Verbose output |
| `-vv` | More verbose |
| `-q` | Quiet mode |
| `-x` | Stop on first failure |
| `--lf` | Run last failed tests only |
| `--ff` | Run failures first |
| `-k "expr"` | Filter by name expression |
| `-m "mark"` | Run marked tests only |
| `--tb=short` | Shorter traceback |
| `--tb=no` | No traceback |
| `-s` | Show print statements |
| `--durations=10` | Show 10 slowest tests |
| `-n auto` | Parallel execution (pytest-xdist) |
## Coverage Reports
```bash
# Terminal report
uv run pytest --cov=src
# HTML report (creates htmlcov/)
uv run pytest --cov=src --cov-report=html
# With minimum threshold (fails if below)
uv run pytest --cov=src --cov-fail-under=80
# Multiple report formats
uv run pytest --cov=src --cov-report=term --cov-report=xml
```
## Markers
```python
import pytest
@pytest.mark.slow
def test_slow_operation():
...
@pytest.mark.skip(reason="Not implemented")
def test_future_feature():
...
@pytest.mark.skipif(condition, reason="...")
def test_conditional():
...
@pytest.mark.xfail(reason="Known bug")
def test_known_failure():
...
```
Run by marker:
```bash
uv run pytest -m "not slow"
uv run pytest -m "integration"
```
## pyproject.toml Configuration
```toml
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_functions = ["test_*"]
addopts = "-v --tb=short"
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:",
]
```
## FastAPI Testing
See [references/fastapi-testing.md](references/fastapi-testing.md) for comprehensive FastAPI testing patterns including:
- TestClient setup
- Async testing with httpx
- Database fixture patterns
- Dependency overrides
- Authentication testing
## Debugging Failed Tests
```bash
# Run with full traceback
uv run pytest --tb=long
# Drop into debugger on failure
uv run pytest --pdb
# Show local variables in traceback
uv run pytest -l
# Run only previously failed
uv run pytest --lf
```
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.