C · TestingIntermediate45 min read
7. pytest fundamentals
Python · 52 pages source format
Arrange-act-assert. test_ prefix. assert directly. pytest discovers tests/ automatically.
What you'll learn
- pytest discovery
- assert style
- Running pytest
- Test naming
First tests
test_is_valid_email_true(), test_is_valid_email_false(). No unittest boilerplate.
# tests/test_helpers.py
from src.helpers import is_valid_email
def test_valid_email():
assert is_valid_email("a@b.com") is True
def test_invalid_email():
assert is_valid_email("nope") is FalseDo this now
5 pytest tests for helpers from earlier chapters. pytest -v.
Clear?
Arrange-act-assert
Setup data, call function, assert outcome. One logical assertion per test when possible.
Do this now
Refactor one vague test into three focused tests.
Clear?
Run and debug failures
pytest shows assertion diffs. pytest -k email runs subset. pytest --lf reruns last failures.
Do this now
Break a test on purpose. Read failure output. Fix it.
Pro tip. Keep tests fast — no network in unit tests. Mock or fixture files instead.
Clear?