Python Foundations·Quality and delivery

Testing with pytest

Catch regressions with small tests for normal and edge cases.

Beginner 13 min read Lesson 14 of 480 Challenge included
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.

test_math.pyPython
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

Test a word counter

Medium

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 below
Check 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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 14 of 480 · 0% of course