Testing with pytest
Why test?
Without tests, every change means clicking through the program by hand to check that nothing broke, so people stop checking. A test is a small function that runs your code and asserts the result is what you expect. pytest finds and runs all of them in a second.
Evals for LLM apps (Week 19) are tests too. The habit you build now is the one AI teams hire for.
Your first tests
Figure 2.3: Every test has three parts (arrange, act, assert). Work in a loop: write a failing test, make it pass, then clean up.
How it works:
- pytest collects files named
test_*.pyand functions namedtest_*. assert <condition>passes if the condition is true. If it's false, pytest shows both sides so you can see the difference.- A fixture is reusable setup. Naming
libas a parameter tells pytest to call the fixture and pass in the result, fresh for each test, so tests can't affect each other. pytest.raises(SomeError)checks that the code does fail the way it should. Testing the error paths matters as much as testing the happy path.
What to test
For each public method, test:
- The happy path: normal input gives the expected result.