Doctest¶
Das Python-Modul doctest prüft, ob Tests in einem Docstring oder in einer anderen Textdatei 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 >>> round(divide(x, y), 8) 13 -1.16666667 14 >>> divide(x, z) 15 Traceback (most recent call last): 16 File "<stdin>", line 1, in <module> 17 ZeroDivisionError: division by zero 18 """ 19 return x / y
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: round(divide(x, y), 8) Expecting: -1.16666667 ok Trying: divide(x, y) 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: round(divide(x, y), 8) Expecting: -1.16666667 ok Trying: divide(x, y) 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)
Siehe auch
doctest kann auch zum kontinuierlichen Testen der Dokumentation verwendet werden: Kontinuierliche Integration.