Execute Python tests with pytest, supporting fixtures, markers, coverage, and parallel execution. Use for Python test automation.
Single responsibility: Execute and manage pytest test suites with proper configuration, coverage reporting, and failure analysis. (BP-4)
Before executing, VERIFY:
pip show pytest)DO NOT run tests without verifying environment.
ASK USER instead of guessing when:
NEVER modify test configurations without user approval.
| Context Type | Included | Excluded |
|---|---|---|
| RELEVANT | Test files, pytest config, fixtures | Application code details |
| PERIPHERAL | Coverage reports, test markers | CI/CD pipelines |
| DISTRACTOR | Other language tests | Deployment configs |
# Verify virtual environment
if [ -z "$VIRTUAL_ENV" ]; then
# Activate if exists
if [ -f "venv/bin/activate" ]; then
source venv/bin/activate
elif [ -f ".venv/bin/activate" ]; then
source .venv/bin/activate
else
echo "WARNING: No virtual environment active"
fi
fi
# Verify pytest installed
python -m pytest --version || pip install pytest
# List all test files
find . -name "test_*.py" -o -name "*_test.py" | head -20
# Show pytest collection
python -m pytest --collect-only -q
Basic execution:
python -m pytest tests/ -v
With coverage:
python -m pytest tests/ -v --cov=src --cov-report=term-missing --cov-report=html
Parallel execution:
python -m pytest tests/ -v -n auto # requires pytest-xdist
With markers:
python -m pytest tests/ -v -m "unit"
python -m pytest tests/ -v -m "not slow"
# Parse test results
python -m pytest tests/ -v --tb=short 2>&1 | tee test_results.txt
# Extract failures
grep -E "^FAILED|^ERROR" test_results.txt
# Coverage summary
python -m pytest --cov=src --cov-report=term | grep -E "^TOTAL|^Name"
On error:
ImportError โ Check dependencies, PYTHONPATHFixtureError โ Check conftest.pyCollectionError โ Check test file syntaxTimeout โ Reduce test scope or add markersState saved to: .aiwg/working/checkpoints/pytest-runner/
checkpoints/pytest-runner/
โโโ test_collection.json # Discovered tests
โโโ test_results.json # Last run results
โโโ coverage_report.json # Coverage data
โโโ failure_analysis.md # Failure diagnostics
| Option | Purpose |
|---|---|
-v |
Verbose output |
-x |
Stop on first failure |
-s |
Show print statements |
--lf |
Run last failed tests |
--ff |
Run failed tests first |
-k "pattern" |
Filter by name pattern |
-m "marker" |
Filter by marker |
--tb=short |
Shorter tracebacks |
pytest.ini:
[pytest]
testpaths = tests
python_files = test_*.py *_test.py
python_functions = test_*
addopts = -v --tb=short
markers =
unit: Unit tests
integration: Integration tests
slow: Slow tests
pyproject.toml:
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
addopts = "-v --tb=short"