| name | pytest-testing |
|---|---|
| description | Create and maintain tests with pytest: fixtures, parametrization, mocking (monkeypatch/pytest-mock), tmp_path, async, CLI/web apps, coverage and CI. Use this when adding tests to an existing project, refactoring a test suite, or debugging flaky/failing tests. |
Use this skill to quickly stand up a robust pytest setup and to write clear, maintainable tests. It includes a project initializer and copy‑paste recipes for common patterns.
- Initialize pytest in your project directory:
python3 skill-pytest/init_pytest.py --ci- Creates
tests/,pytest.ini,conftest.py,.coveragerc,requirements-dev.txt, and a GitHub Actions CI workflow (optional with--ci).
- Run tests:
python3 -m pip install -r requirements-dev.txtpytest -qorpytest -q --cov
project/
├─ src/yourpkg/ # or a flat module layout
├─ tests/
│ ├─ test_sample.py
│ └─ conftest.py # shared fixtures/config
├─ pytest.ini # pytest config
├─ .coveragerc # coverage config
└─ requirements-dev.txt # dev deps
- Fixtures: share setup/teardown logic; prefer function scope by default.
- Parametrization: compactly test multiple input/output cases.
- Isolation: use
tmp_pathandmonkeypatchto avoid side effects. - Async: use
pytest-asyncioand mark async tests with@pytest.mark.asyncio. - Marks: declare
unit,integration,slow,flakyto filter/select. - Coverage: measure with
pytest-cov, set afail_underthreshold.
Parametrized test:
import pytest @pytest.mark.parametrize( "a,b,expected", [ (2, 2, 4), (2, -2, 0), (0, 0, 0), ], ) def test_add(a, b, expected): assert a + b == expected
Using tmp_path and monkeypatch:
def test_writes_file(tmp_path, monkeypatch): out = tmp_path / "data.txt" monkeypatch.setenv("APP_MODE", "TEST") out.write_text("hello") assert out.read_text() == "hello"
Async test:
import asyncio import pytest @pytest.mark.asyncio async def test_async_step(): await asyncio.sleep(0) assert True
Mock with pytest-mock:
def test_external_call_is_mocked(mocker): mock = mocker.patch("yourpkg.api.fetch", return_value={"ok": True}) from yourpkg.service import run assert run() is True mock.assert_called_once()
-qquiet output;-vvmore detail-k exprselect by substring:-k "not slow and login"-m markselect by mark:-m integration--maxfail=1 -xfail fast--pdbdrop into debugger on failure--cov=yourpkg --cov-report=term-missingcoverage
The initializer can add .github/workflows/python-tests.yml that installs dev deps and runs pytest --cov on push/PR.
- Tests not discovered: ensure files match
test_*.pyand are undertests/(or settestpathsinpytest.ini). - Import errors: use
src/layout andpip install -e .or setPYTHONPATHin CI. - Flaky tests: use explicit timeouts, seed RNGs, and reduce implicit waits in async/HTTP tests.