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?

 
1
def rect_area(width: int, height: int) -> int:
2
    return width * height
3
4
def main() -> None:
5
    print(str(rect_area(-1, 2)))       # This doesn't make sense a rectangle can't have a negative width
6
    return None
7
8
main()
9

(ch06_fun_w_bad_input)

Or worse, input that will cause will cause the function to break. For example:

9
 
1
def is_divisible(x: int, y: int) -> bool:
2
    return x % y == 0
3
4
def main() -> None:
5
    print(str(is_divisible(1, 0)))   # This will cause a division by zero error
6
    return None
7
8
main()
9

(ch06_fun_w_runtime_error)

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.

10
 
1
def rect_area(width: int, height: int) -> int:
2
    assert width >= 0 and height >= 0, "width and height must not be negative"
3
    return width * height
4
5
def main() -> None:
6
    print(str(rect_area(-1, 2)))
7
    return None
8
9
main()
10

(ch06_fun_assert)

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.

12
 
1
import test
2
3
def is_divisible(x: int, y: int) -> bool:
4
    assert y != 0, "can not test if a number is divisible by 0"
5
    return x % y == 0
6
7
def main() -> None:
8
    test.equal(is_divisible(15, 3), True)
9
    return None
10
11
main()
12

(ch06_boolfun3)

Extend the program …

Write an additional unit test for when the output is False.

You have attempted 1 of 5 activities on this page
Next Section - 7.10. Glossary