Skip to content
>_devvkit
$devvkit learn --librarie pytest-guide

pytest Guide

[python][testing]
Python
Install
pip install pytest
pip install pytest-cov

pytest requires zero boilerplate. Write test functions, use assert, run pytest.

Fixtures replace setUp/tearDown. Parametrize tests to run multiple cases.

Plugin ecosystem: pytest-cov, pytest-django, pytest-mock, pytest-asyncio.

Setup

Basic testWrite and run.
# test_math.py
def test_add():
    assert 1 + 1 == 2

# Run: pytest
Exception testAssert raises.
import pytest
def test_raises():
    with pytest.raises(ValueError):
        int('abc')

Fixtures

FixtureReusable setup.
@pytest.fixture
def user():
    return User(name='Alice', is_admin=True)

def test_admin(user):
    assert user.is_admin
Fixture with cleanupYield fixture.
@pytest.fixture
def db():
    conn = connect()
    yield conn
    conn.close()

Parametrization

ParametrizeMultiple cases.
@pytest.mark.parametrize('a,b,expected', [
    (1, 2, 3), (0, 0, 0), (-1, 1, 0),
])
def test_add(a, b, expected):
    assert a + b == expected

Mocking

MonkeypatchMock during test.
def test_env(monkeypatch):
    monkeypatch.setenv('API_KEY', 'test123')
    assert os.getenv('API_KEY') == 'test123'

Configuration

Skip testConditional skip.
@pytest.mark.skipif(sys.version_info < (3, 10), reason='needs py310+')
def test_new_feature():
    pass
CoverageRun with coverage.
pytest --cov=src --cov-report=term-missing