PY-101 ยท Testing and debugging
pytest basics
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
pytest is Python's most popular testing tool: you write functions whose names start with test_, put plain asserts inside, and run pytest to execute them all and report which pass. pytest.raises checks that code raises the right error. Tests let you change code with confidence, because they tell you at once if something broke.
- Write test_ functions with asserts
- Check errors with pytest.raises
- Run a suite and read the result
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
def add_tax(amount, rate=18):if amount < 0:raise ValueError("amount must not be negative")return round(amount * (1 + rate / 100), 2)def test_default_rate():assert add_tax(100) == 118def test_custom_rate():assert add_tax(200, rate=5) == 210def test_negative_amount():try:add_tax(-1)except ValueError:returnraise AssertionError("expected ValueError")tests = [test_default_rate, test_custom_rate, test_negative_amount]for t in tests:t()print("PASSED", t.__name__)print(len(tests), "passed")
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
PASSED test_default_rate
PASSED test_custom_rate
PASSED test_negative_amount
3 passed ๐ฏ Write two tests for is_even: test_even_number (is_even(4) is True) and test_odd_number (is_even(7) is False). The runner below calls them and prints 2 passed.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
def test_even_number(): assert is_even(4) is True
- The problemYou fix a bug in the tax calculator and accidentally break discounts. Without tests, a customer finds it. With tests, pytest goes red in two seconds, before you even commit.
- The Python idea
# test_prices.pypytest is Python's most popular testing tool: you write functions whose names start with test_, put plain asserts inside, and run pytest to execute them all and report which pass. - In real lifeGitHub Actions runs pytest on every pull request, and the merge button stays disabled until every test passes.
Start with a question
You fix a bug in the tax calculator and accidentally break discounts. Without tests, a customer finds it. With tests, pytest goes red in two seconds, before you even commit.
Professional codebases have tests for everything. Writing them is expected in every Python job.
Explain it like I'm 10
Tests are a checklist robot: every time you change something, it re-checks every item on the list and tells you if anything is now wrong.
The technical explanation
Put tests in files named test_*.py. pytest finds and runs every function starting with test_.
Use plain assert; pytest shows the actual values when one fails.
with pytest.raises(ValueError): passes only if the block raises ValueError. Run everything with pytest in a terminal.
Syntax
# test_prices.py
def test_adds_tax():
assert add_tax(100) == 118
# terminal
pytest Real-world scenario
GitHub Actions runs pytest on every pull request, and the merge button stays disabled until every test passes.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Take the PY-101 practice exam โQuestions people ask
What is the difference between unittest and pytest?
unittest ships with Python and uses test classes and assertEqual methods. pytest is installed with pip, uses plain functions and asserts, and gives clearer failure messages. Most new projects use pytest.
How many tests should I write?
Start with one test per important behaviour, plus one for each bug you fix so it never comes back.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between unittest and pytest?
unittest ships with Python and uses test classes and assertEqual methods. pytest is installed with pip, uses plain functions and asserts, and gives clearer failure messages. Most new projects use pytest.
beginner How many tests should I write?
Start with one test per important behaviour, plus one for each bug you fix so it never comes back.
intermediate Which function does pytest run automatically?
test_total. Names starting with test_.
intermediate What do you write inside a pytest test?
Plain assert statements. pytest uses plain asserts.
Quick revision
Remember
- Write test_ functions with asserts
- Check errors with pytest.raises
- Run a suite and read the result
- Test one behaviour per test, and name it after the behaviour: test_discount_never_goes_below_zero says what failed without reading the code.
Syntax
# test_prices.py
def test_adds_tax():
assert add_tax(100) == 118
# terminal
pytest Official documentation
- pytest: get started (docs.python.org)