7.9. Assert Statements¶
Think of writing functions as creating a contract. When you write a function you are guaranteeing that the function’s output is correct for all valid input. But what happens when a functions receives invalid input?
Or worse, input that will cause will cause the function to break. For example:
If a function receieves invalid input it should inform the calling code that there is an error. If a function recieves invalid input, then the error is not in the function it is in the calling code. The function is making clear that it did not break its contract to always give correct output. In Python, this is done with an assert statement.
An assert statement stops running the function and produces an error that the calling code can respond to.
The assert statement has two parts, the condition and the message. The condition is what must be true for the function to work correctly. If the condition is false the function’s execution is terminated with an error that displays the assert’s message.
Conditionals and Equivalence Classes
The is_divisible
function can return either True
or
False
. These two different outputs give us two equivalence
classes. We then choose inputs that should give each of the different
results. It is important to have at least one test for each output
equivalence class.
Extend the program …
Write an additional unit test for when the output is False.