Framework Essentials: Asserts, Fixtures and Parametrized Cases (pytest or Vitest)
Cover a validation helper with pytest using arrange-act-assert, parametrized cases, error-path tests and shared fixtures in conftest.py, and map every pattern to Vitest.
Contentsand lesson path
On this page
- The task
- Step 1: one behaviour, arranged, acted, asserted
- Step 2: test the error path
- Step 3: many cases, one test function
- Step 4: share setup with a fixture
- Step 5: the same suite in Vitest
- What goes wrong in young suites
- Check your understanding
- Apply it
- Review prompt
Lessons of Software Testing Fundamentals
- Why Automated Tests, and What to Test First Concept · 15 min
- Framework Essentials: Asserts, Fixtures and Parametrized Cases (pytest or Vitest) Worked example · 25 min
- Fakes, Stubs and Mocks Without Over-Mocking Concept · 20 min
- Lab: Testing Endpoints with a Test Client Lab · 25 min
- Reading Coverage and Choosing Test Levels Worked example · 15 min
- Check: Find the Missing Test Knowledge check · 8 questions
What you will learn
- Write unit tests with a unit-test framework (pytest in the reference stack, Vitest for JavaScript/TypeScript) using arrange-act-assert, parametrized cases and shared fixtures, including tests for error paths.
Prerequisites: Python Foundations
01. The task
The reading-list service you will build across this skill accepts anything readers type: titles pasted from a shop page, ratings typed as 4/5 or 4 / 5. Before any endpoint exists, the rules for cleaning that input live in two small helpers, and this worked example gives them a unit suite.
You have already run pytest in the final python-foundations lesson: a test is a function named test_..., a plain assert decides pass or fail, and pytest.raises checks errors. This lesson adds the four patterns you will use on every service codebase: arrange-act-assert structure, parametrized cases for many inputs, error paths as first-class tests, and fixtures for setup several tests share. The same suite in Vitest closes the lesson, so the ideas transfer if your stack is JavaScript. Here is the code under test:
"""Input helpers for the reading-list API."""
import re
_RATING = re.compile(r"([1-5])\s*/\s*5")
class InvalidInput(ValueError):
"""Raised when reader-supplied text cannot be normalised."""
def normalise_title(raw: str) -> str:
"""Collapse runs of whitespace and trim a book title."""
if not raw.strip():
raise InvalidInput("title must not be blank")
return " ".join(raw.split())
def parse_rating(raw: str) -> int:
"""Turn a rating such as '4/5' into stars, 1 to 5."""
match = _RATING.fullmatch(raw.strip())
if match is None:
raise InvalidInput(f"rating must look like '4/5', got {raw!r}")
return int(match.group(1))Set up the project before step 1. Save the helper as app/validation.py and put the tests in a tests/ folder next to app/. The tests import app.validation, but pytest's default import mode puts the test folder on the import path, not the project root, so a plain pytest run would stop at collection with ModuleNotFoundError: No module named 'app'. Tell pytest where the code lives with a pyproject.toml in the project root (the pythonpath setting needs pytest 7 or later; this lesson was run with pytest 9.2). Then run pytest -q from the project root after each step and compare with the output shown.
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]02. Step 1: one behaviour, arranged, acted, asserted
Start with one behaviour of normalise_title. Most test frameworks encourage the same three-part shape, arrange-act-assert: set up the input, call the code under test, check the result. The blank lines between the parts are part of the style; a reader should find each part without reading a word. Create tests/test_validation.py:
from app.validation import normalise_title
def test_normalise_title_collapses_runs_of_whitespace() -> None:
title = normalise_title(" The Pragmatic \n Programmer ")
assert title == "The Pragmatic Programmer"1 passed in 0.31sThe test name states the behaviour, not the method: a failure report that reads test_normalise_title_collapses_runs_of_whitespace FAILED already tells you what broke. One behaviour per test keeps that promise. When a test walks through several actions with an assert after each, a failure in the second half hides behind the first, and the report cannot say which behaviour regressed.
03. Step 2: test the error path
Raising InvalidInput for a blank title is part of the helper's promise, so it gets its own test. pytest.raises passes only if the block raises that exception, and match checks the message against a regular expression so a future refactor cannot silently swap in a meaningless error. Put the two import lines at the top of the file, in place of the old import, and append the test:
import pytest
from app.validation import InvalidInput, normalise_title, parse_rating
def test_normalise_title_rejects_blank_titles() -> None:
with pytest.raises(InvalidInput, match="must not be blank"):
normalise_title(" ")2 passed in 0.22sError paths deserve the same attention as happy paths because they are the code nobody exercises by hand, and the messages are what a client reads once an endpoint maps them onto responses. The endpoint lab in this skill shows the other side: an InvalidInput that no handler maps surfaces as a 500, not a 422. Testing the message here, at unit level, is far cheaper than discovering a vague error through HTTP.
04. Step 3: many cases, one test function
parse_rating has many valid spellings and many wrong ones. Writing a function per case drowns the suite in copies; looping over pairs inside one test stops at the first failure and hides the rest. Parametrizing generates one reported test per case from one body. Add both cases to the file:
@pytest.mark.parametrize(
("raw", "expected"),
[
("4/5", 4),
("5 / 5", 5),
("1/5", 1),
("3/ 5", 3),
],
ids=["plain", "spaces around slash", "lowest", "space after slash"],
)
def test_parse_rating_accepts_valid_ratings(raw: str, expected: int) -> None:
stars = parse_rating(raw)
assert stars == expected
@pytest.mark.parametrize(
"raw",
["", " ", "0/5", "6/5", "4 out of 5", "half"],
)
def test_parse_rating_rejects_bad_ratings(raw: str) -> None:
with pytest.raises(InvalidInput, match="rating must look like"):
parse_rating(raw)12 passed in 0.47stests/test_validation.py::test_parse_rating_accepts_valid_ratings[plain] PASSED [ 25%]
tests/test_validation.py::test_parse_rating_accepts_valid_ratings[spaces
around slash] PASSED [ 33%]
tests/test_validation.py::test_parse_rating_accepts_valid_ratings[lowest] PASSED [ 41%]
tests/test_validation.py::test_parse_rating_accepts_valid_ratings[space after
slash] PASSED [ 50%]
tests/test_validation.py::test_parse_rating_rejects_bad_ratings[0/5] PASSED [ 75%]
tests/test_validation.py::test_parse_rating_rejects_bad_ratings[6/5] PASSED [ 83%]
tests/test_validation.py::test_parse_rating_rejects_bad_ratings[4 out
of 5] PASSED [ 91%]The ids list names the valid cases, so the report describes intent instead of echoing values; without it pytest builds ids from the arguments, which you can see on the bad-input cases. When 6/5 starts failing in eight months, the report will show exactly which spelling broke, alongside the five that still pass. Keeping the case list next to the body also makes it trivial to add 4/5 with a trailing space the day a reader sends one.
05. Step 4: share setup with a fixture
Several tests now want the same starting point: a set of real-world messy titles, normalised. Copying the list into every test works until the data changes. A fixture is a named function that prepares something and hands it to any test that asks for it by parameter name. Put it in tests/conftest.py and every test file in the folder can use it without an import:
import pytest
from app.validation import normalise_title
MESSY_TITLES = [
" The Pragmatic Programmer ",
"Refactoring\n(2nd edition)",
"\tWorking Effectively\twith Legacy Code\t",
]
@pytest.fixture
def tidy_titles() -> list[str]:
return [normalise_title(raw) for raw in MESSY_TITLES]def test_tidy_titles_have_no_runs_of_whitespace(
tidy_titles: list[str],
) -> None:
for title in tidy_titles:
assert title == " ".join(title.split())
def test_tidy_titles_keep_their_words(tidy_titles: list[str]) -> None:
assert tidy_titles[0] == "The Pragmatic Programmer"
assert tidy_titles[2] == "Working Effectively with Legacy Code"14 passed in 0.72sA fixture written this way has function scope: pytest calls it fresh for every test, so no test can see another's changes. That is the default you want. When setup is genuinely expensive and read-only, such as loading a large table from a file, @pytest.fixture(scope="session") builds it once for the whole run; treat that as an optimisation you earn, because shared state is the classic cause of tests that pass alone and fail together. pytest ships fixtures too: tmp_path gives each test a private temporary directory and capsys captures output, both used in the python-foundations lab.
06. Step 5: the same suite in Vitest
Every pattern above has a direct Vitest counterpart, which you met in the frontend testing skill; the mapping is worth having in one place. describe groups, it is one behaviour, it.each parametrizes, toThrow checks the error path, and a plain function or beforeEach hook plays the fixture's role:
export class InvalidInput extends Error {
constructor(message: string) {
super(message);
this.name = 'InvalidInput';
}
}
const RATING = /^([1-5])\s*\/\s*5$/;
export function parseRating(raw: string): number {
const match = RATING.exec(raw.trim());
if (match === null) {
throw new InvalidInput(`rating must look like '4/5', got ${JSON.stringify(raw)}`);
}
return Number(match[1]);
}Save it next to the test file and run npx vitest run (the output below is from Vitest 5.0.5; 5.1.2 is the newest release). Setting this.name gives readable failure messages; toThrow(InvalidInput) works because the class extends Error and modern TypeScript targets keep the subclass intact.
import { describe, expect, it } from 'vitest';
import { InvalidInput, parseRating } from './validation';
describe('parseRating', () => {
it.each([
['4/5', 4],
['5 / 5', 5],
['1/5', 1],
])('parses %s into %i stars', (raw, expected) => {
expect(parseRating(raw)).toBe(expected);
});
it.each(['', ' ', '0/5', '6/5', '4 out of 5', 'half'])('rejects %j', (raw) => {
expect(() => parseRating(raw)).toThrow(InvalidInput);
expect(() => parseRating(raw)).toThrow("rating must look like '4/5'");
});
}); Test Files 1 passed (1)
Tests 9 passed (9)The %s, %i and %j placeholders name each case in the report, exactly like ids in pytest; %j prints the value as JSON, so the empty string shows as "". The error-path cases use it.each as well, so each bad spelling is reported on its own line, just as the parametrized pytest test reports it.
07. What goes wrong in young suites
08. Check your understanding
09. Apply it
Continue the practice task for this skill: take a validation helper from your own project, or write parse_rating's sibling parse_pages("312 pp."), and give it the full treatment. Write the AAA happy path first, then the error path with match, then at least eight parametrized cases including two you expect to fail today. Finish by moving shared input data into a conftest.py fixture consumed by two tests. If your stack is JavaScript, write the same suite with Vitest and it.each instead.
10. Review prompt
Without looking back: name the three parts of a test and what each is for. Explain what pytest does with one test function decorated with parametrize and four cases, and what ids add. Say how you test that a function raises, and what match checks. Finally, describe what a conftest.py fixture is, its default scope, and when a wider scope is justified.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.