raises, approx, -k and -x
Four tests, one of them wrong on purpose (0.1 + 0.2 == 0.3 without approx). The run_pytest helper is the same plumbing as in the first example. Notice -x stops the run at the first failure.
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
--- --collect-only: list the tests ---
test_tools.py::test_divide_normal
test_tools.py::test_divide_by_zero_raises
test_tools.py::test_float_sum
test_tools.py::test_float_sum_exact_fails
4 tests collected
--- -k divide: only names that contain divide ---
.. [100%]
2 passed, 2 deselected
--- -x stops at the first failure ---
...F
=================================== FAILURES ===================================
__________________________ test_float_sum_exact_fails __________________________
def test_float_sum_exact_fails():
> assert 0.1 + 0.2 == 0.3
E assert (0.1 + 0.2) == 0.3
test_tools.py:25: AssertionError
=========================== short test summary info ============================
FAILED test_tools.py::test_float_sum_exact_fails - assert (0.1 + 0.2) == 0.3
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
1 failed, 3 passed