Lesson 60 of 60

PY-101 ยท Testing and debugging

pytest basics

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

60of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    pytest basics, running
    1. def add_tax(amount, rate=18):
    2. if amount < 0:
    3. raise ValueError("amount must not be negative")
    4. return round(amount * (1 + rate / 100), 2)
    5. def test_default_rate():
    6. assert add_tax(100) == 118
    7. def test_custom_rate():
    8. assert add_tax(200, rate=5) == 210
    9. def test_negative_amount():
    10. try:
    11. add_tax(-1)
    12. except ValueError:
    13. return
    14. raise AssertionError("expected ValueError")
    15. tests = [test_default_rate, test_custom_rate, test_negative_amount]
    16. for t in tests:
    17. t()
    18. print("PASSED", t.__name__)
    19. print(len(tests), "passed")
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. 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.
    3. 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

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    GitHub Actions runs pytest on every pull request, and the merge button stays disabled until every test passes.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Which function does pytest run automatically?
    2. 2. What do you write inside a pytest test?
    3. 3. How do you check that code raises ValueError?
    4. 4. How do you run the tests?
    5. 5. Main benefit of tests?

    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