In this lesson, you’ll learn about the doctest
module and assert
statements.
The doctest
module is very useful to test code in a quick and easy manner by specifying an input and the correct output in the docstring and running python3 -m doctest file.py
. You can check out the Python documentation on the doctest
module.
assert
statements are useful to write tests and check conditions in real time. The syntax looks like this:
assert <cond>, ([error_msg])
The error message is optional. Here’s an example:
>>> x = 5
>>> assert x > 0, "x is not positive"
>>> x = -1
>>> assert x > 0, "x is not positive"
AssertionError: x is not positive
To learn more about assert
statements and Python exceptions, check out Assertions and Try/Except.
James Uejio RP Team on April 27, 2020
Here is a Real Python walkthrough on
assert
statements and Python Exceptions: Assertions and Try/Except