Testing with pytest
Catch regressions with small tests for normal and edge cases.
What you will be able to do
- Write test functions pytest discovers
- Assert expected errors
- Cover empty and boundary inputs
Tests are executable documentation. They prove behavior still works after a change and make edge cases explicit.
import pytest
def safe_divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_safe_divide():
assert safe_divide(10, 2) == 5
def test_zero_division():
with pytest.raises(ValueError):
safe_divide(1, 0)- Files and functions start with test_ so pytest finds them.
- Follow arrange, act, assert in each test.
- Test the empty case, the boundary and the happy path.
- One behaviour per test keeps failures easy to read.
Your turn
MediumTest a word counter
Write two tests: one for an empty string, one for repeated words.
PYTHON · starter
def count_words(text):
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
return counts
# write two tests belowCheck your understanding before moving on.
Knowledge checkQuestion 1
Which function name does pytest discover by default?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.