1. Concept library
  2. Python Foundations
  3. Module 11: Testing

Concept

Writing tests with pytest

pytest finds functions named test_* and runs them, reporting each failing assert with the values involved. A test is a plain function with an assert in it, which keeps the barrier to writing one low.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain how pytest finds tests and reports a failing assert
  2. Write a test function for one behaviour and name it after what it checks
  3. Split one test that checks everything into several focused tests

In practice

A few lines that show Writing tests with pytest doing its job.

Python
# test_slugify.py
from slugify import slugify
import pytest

def test_lowercases_and_joins_with_dashes():
    assert slugify("Hello World") == "hello-world"

@pytest.mark.parametrize("raw", ["", "   ", "!!!"])
def test_rejects_empty_input(raw):
    with pytest.raises(ValueError):
        slugify(raw)

The common mistake

Watch for

Writing one test that checks everything. When it fails you do not know which behaviour broke. One behaviour per test, named after what it checks.

What to know first

Your roadmap puts these before Writing tests with pytest, unless you already know them.

How it stays learned

Once a session shows you understand Writing tests with pytest, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Writing tests with pytest.

Previous in the module← Assertions
Next in the moduleTest fixtures →