Unit Testing with pytest
Prove your code works -- automatically, every time you change it
pytest collects all your tests, runs them in a second, and tells you exactly which ones failed -- so a bug you introduce today cannot quietly ship tomorrow.
- explain why automated tests matter,
- write test functions and
assertwhat you expect, - run the suite with the
pytestcommand and read its report, - share setup with fixtures,
- check that errors are raised with
pytest.raises, and cover many cases withparametrize.
1. Why testing matters
You already test your code -- by running it and looking at the output. The problem is that manual checking does not scale. A real program has dozens of functions, and every change can quietly break something you fixed last week. Automated tests turn "let me eyeball it" into a button you press: the machine re-checks every rule in under a second.
Think of tests as a safety net for a trapeze artist. The net does not do the tricks for you, but it lets you attempt bold changes -- refactor a function, rename a variable, speed something up -- knowing that if you fall, the net catches you immediately instead of a user discovering the bug in production.
Good tests give you three concrete wins:
- Confidence to change code. Green tests mean your edit did not break the parts you already trusted.
- Living documentation. A test named
test_withdraw_too_muchshows exactly how a function is meant to behave. - Faster debugging. A failing test points at one function, not the whole program.