$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: pytestException 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_adminFixture 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 == expectedMocking
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():
passCoverage— Run with coverage.
pytest --cov=src --cov-report=term-missing