Doctest¶
The Python module doctest checks whether tests in a docstring or in another text file are fulfilled.
In
arithmetic.py
you can add the following docstring:9def divide(x, y): 10 """Divides the first parameter by the second 11 >>> x, y, z = 7, -6.0, 0 12 >>> divide(x, y) 13 -1.1666666666666667 14 >>> divide(x, z) 15 Traceback (most recent call last): 16 File "<stdin>", line 1, in <module> 17 ZeroDivisionError: division by zero 18 """
Then you can test it with:
$ python -m doctest test/arithmetic.py -v Trying: add(7,6) Expecting: 13 ok Trying: x, y, z = 7, -6.0, 0 Expecting nothing ok Trying: divide(x, y) Expecting: -1.1666666666666667 ok Trying: divide(x, z) Expecting: Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero ok Trying: multiply(7,6) Expecting: 42 ok Trying: subtract(7,6) Expecting: 1 ok 1 items had no tests: arithmetic 4 items passed all tests: 1 tests in arithmetic.add 3 tests in arithmetic.divide 1 tests in arithmetic.multiply 1 tests in arithmetic.subtract 6 tests in 5 items. 6 passed and 0 failed. Test passed.
C:> python -m doctest arithmetic.py -v Trying: add(7,6) Expecting: 13 ok Trying: x, y, z = 7, -6.0, 0 Expecting nothing ok Trying: divide(x, y) Expecting: -1.1666666666666667 ok Trying: divide(x, z) Expecting: Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero ok Trying: multiply(7,6) Expecting: 42 ok Trying: subtract(7,6) Expecting: 1 ok 1 items had no tests: arithmetic 4 items passed all tests: 1 tests in arithmetic.add 3 tests in arithmetic.divide 1 tests in arithmetic.multiply 1 tests in arithmetic.subtract 6 tests in 5 items. 6 passed and 0 failed. Test passed.
So that the doctests can also be imported into other modules, you should add the following lines:
38if __name__ == "__main__": 39 import doctest 40 41 doctest.testmod(verbose=True)
See also
doctest can also be used to continuous test the documentation: Continuous integration.