Testing with pytest
Write small tests that prove your code works and keep working.
A test is code that checks that other code behaves as expected. Tests let you change a program with confidence, because a break shows up immediately.
pip install pytestimport pytest
from utils import slugify
def test_slugify_lowercases_and_joins_words():
assert slugify("Hello World") == "hello-world"
def test_slugify_empty_string():
assert slugify("") == ""
@pytest.mark.parametrize("raw, expected", [
("A B", "a-b"),
("Already-ok", "already-ok"),
])
def test_slugify_cases(raw, expected):
assert slugify(raw) == expectedpytest # run every test
pytest -k slugify # only tests whose name matches
pytest -x # stop at the first failureWhat makes a good test
- One behaviour per test, with a name that says what it checks.
- Edge cases: empty input, zero, negative numbers, very long text.
- Errors: use
with pytest.raises(ValueError):to check that bad input is rejected. - Tests must not depend on each other or on the order they run.
def test_deposit_rejects_negative():
acc = Account("Ana")
with pytest.raises(ValueError):
acc.deposit(-5)NoteWrite the failing test first when you fix a bug. Once it passes, that bug cannot return without you noticing.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.