Quiz
Warm-up. In lesson 1-2 you refactored count_vowels from a loop into a one-line generator expression. What proved the refactor was safe?
The three-part shape of every test
Almost every good test has the same skeleton, called arrange, act, assert (AAA):
- Arrange: set up the input data and any objects you need
- Act: call the one function or method under test, once
- Assert: check the result against what you expected
Why enforce a shape? Because tests are documentation. A teammate (or you, in six months) should be able to open any test and answer three questions instantly: what was the situation, what did we do, what should have happened. When those three phases blur together, a failing test becomes a puzzle instead of a message.
Code exercise · python
Run this AAA-shaped test of cart_total. The comments mark the three phases, and there is exactly one act line.
Code exercise · python
Your turn. Write an AAA test for apply_discount named test_apply_discount_takes_percent_off: arrange a price of 80.0 and a percent of 25, act by calling apply_discount, assert the result is 60.0. Then call the test and print: PASS test_apply_discount_takes_percent_off
Code exercise · python
One more AAA rep. Write test_word_count_ignores_extra_spaces: arrange the text "hello world" (three spaces), act by calling word_count once, assert the count is 2. Then call the test and print: PASS test_word_count_ignores_extra_spaces