We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

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 test· Write and run.
# test_math.py
def test_add():
    assert 1 + 1 == 2

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

Fixtures

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

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

Parametrization

Parametrize· Multiple 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

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

Configuration

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