https://docs.python.org/3/library/doctest.html
https://www.python-course.eu/python3_tests.php
https://realpython.com/python-doctest/
Python's doctest: Document and Test Your Code at Once
The 'doctest' module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.
Note that comments are ignored by the interpreter but docstrings are not ignored and they are reachable at runtime (the __doc__ attribute of functions, methods, classes, modules). It is important to keep the documentation in sync with the current state of our code.
# Simple usage: checking examples in docstrings. # Content of the file fib4.py def fibonacci(n): """ Calculates the n-th Fibonacci number iteratively. >>> fibonacci(0) 0 >>> fibonacci(1) 1 >>> fibonacci(10) 55 >>> fibonacci(15) 610 >>> """ old, new = 0, 1 for _ in range(n): old, new = new, old + new return old if __name__ == "__main__": import doctest doctest.testmod()
# To execute tests: $ python fib4.py $ # no output = no errors $ python fib4.py -v # verbose mode Trying: fibonacci(0) Expecting: 0 ok Trying: fibonacci(1) Expecting: 1 ok Trying: fibonacci(10) Expecting: 55 ok Trying: fibonacci(15) Expecting: 610 ok 1 items had no tests: __main__ 1 items passed all tests: 4 tests in __main__.fibonacci 4 tests in 2 items. 4 passed and 0 failed. Test passed. $ python -m doctest fib5.py -v # without the 'if' part
# Simple usage: checking examples in a text file. import doctest doctest.testfile("example.txt") # The file content is treated as if it were a single giant docstring.
# In the case of exception tracebacks, doctest ignores the traceback body # because it can change unexpectedly. Only the first line: # Traceback (most recent call last): # and the last line are checked. """ ... inside a docstring ... >>> 2 / 0 Traceback (most recent call last): ... # the body is ignored by doctest ZeroDivisionError: division by zero """