Run pytest from a program and read a failure
pytest is installed in the in-browser Python. The first lines (down to run_pytest) are plumbing that runs pytest inside this page and removes the timing text so the output stays the same each run: you do not need to study them. The test file is the text inside the triple quotes. Change the expected 7 to 6 and run again.
pytest finds functions named test_*, runs each one separately and reports the results. It rewrites your plain assert lines so a failure shows the actual values, which makes it the standard tool for Python tests.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write is_palindrome(text) and a test file (as a string you run with the pytest helper from the examples) with at least three tests: a palindrome, a non-palindrome and the empty string.
Write a test that checks int("abc") raises ValueError and that the message contains the word "invalid". Use pytest.raises with match.
Write a check comparing 0.1 + 0.2 to 0.3 that passes using pytest.approx, and explain why the plain == version fails.
Explain it without notes
How does pytest find tests, and what do you do if it reports "no tests ran"?
How does pytest show useful failure messages for plain assert statements?
How do you test that a function raises an exception, and how do you check the message?
Why not compare floats with == in a test, and what do you use instead?
What do -k, -x, -v, -s and --lf do?
Expected output
..F [100%]
=================================== FAILURES ===================================
____________________________ test_wrong_on_purpose _____________________________
def test_wrong_on_purpose():
prices = [1, 2, 3]
> assert total(prices) == 7
E assert 6 == 7
E + where 6 = total([1, 2, 3])
test_cart.py:16: AssertionError
=========================== short test summary info ============================
FAILED test_cart.py::test_wrong_on_purpose - assert 6 == 7
1 failed, 2 passed