From 6ccfb2fff52173bbe0babd5e5ecb0e60b388c8d0 Mon Sep 17 00:00:00 2001 From: guibog Date: Sat, 21 Apr 2012 19:42:37 +0800 Subject: [PATCH] Adding a sample and explanation for doctests --- docs/writing/documentation.rst | 2 +- docs/writing/tests.rst | 29 ++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/writing/documentation.rst b/docs/writing/documentation.rst index 60be079..28edaf4 100644 --- a/docs/writing/documentation.rst +++ b/docs/writing/documentation.rst @@ -33,7 +33,7 @@ Inline comments are used for individual lines and should be used sparingly.: :: But sometimes, this is useful: :: x = x + 1 # Compensate for border -Doc Strings +Docstrings ----------- PEP 257 is the primary reference for docstrings. (http://www.python.org/dev/peps/pep-0257/) diff --git a/docs/writing/tests.rst b/docs/writing/tests.rst index 90a63df..306c25d 100644 --- a/docs/writing/tests.rst +++ b/docs/writing/tests.rst @@ -37,9 +37,36 @@ Doctest ------- 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 +sessions in docstrings, and then executes those sessions to verify that they work exactly as shown. +Doctests have a different use case than proper unit tests: they are usually less +detailed and don't catch special cases or obscure regression bugs. They are +useful as an expressive documentation of the main use cases of a module and +its components. However, doctests should run automatically each time +the full test suite runs. + +A simple doctest in a function: + +:: + + def square(x): + """Squares x. + + >>> square(2) + 4 + >>> square(-2) + 4 + """ + + return x * x + + if __name__ == '__main__': + import doctest + doctest.testmod() + +When running this module from the command line as in ``python module.py``, the doctests +will run and complain if anything is not behaving as described in the docstrings. Tools :::::