Doctest#
Das Python-Modul doctest prüft, ob die in einem Docstring angegebenen Tests erfüllt sind.
In
arithmetic.py
könnt ihr folgenden Docstring hinzufügen: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 """
Anschließend könnt ihr ihn testen mit:
$ 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:> Scripts\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.
Damit die Doctests auch in andere Module importiert werden können, solltet ihr die folgenden Zeilen hinzufügen:
38if __name__ == "__main__": 39 import doctest 40 41 doctest.testmod(verbose=True)