Why tests exist: fearless change
Two more definitions, then we practice.
Refactoring means changing how code is written without changing what it does, for example rewriting a loop as a comprehension (you met comprehensions in Advanced Python). A regression is when a change accidentally breaks something that used to work.
Here is the problem tests solve. Without tests, every refactor is a leap of faith: you think the new version behaves the same, but the only way to know is to try every input by hand. With tests, you refactor, hit run, and get an instant verdict. The tests are a safety net stretched under every change you will ever make.
Code exercise · python
Run this. count_vowels is written with a plain loop, and three tests pin down its behavior. All green.
Code exercise · python
Your turn: refactor count_vowels into a single line using sum and a generator expression, exactly like the ones you wrote in Advanced Python. Do not touch the three asserts. If they still pass, your refactor is proven safe.
Code exercise · python
Again, solo this time: refactor total_price into a single line using the built-in sum(). The three asserts are your net — leave them untouched, and green means the refactor is proven safe.
Quiz
You refactor a function and one of its tests turns red. What does that most likely mean?