Skip to content

Commit 6ccfb2f

Browse files
author
guibog
committed
Adding a sample and explanation for doctests
1 parent 877d878 commit 6ccfb2f

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

docs/writing/documentation.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ Inline comments are used for individual lines and should be used sparingly.: ::
3333
But sometimes, this is useful: ::
3434
x = x + 1 # Compensate for border
3535

36-
Doc Strings
36+
Docstrings
3737
-----------
3838

3939
PEP 257 is the primary reference for docstrings. (http://www.python.org/dev/peps/pep-0257/)

docs/writing/tests.rst

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,36 @@ Doctest
3737
-------
3838

3939
The doctest module searches for pieces of text that look like interactive Python
40-
sessions, and then executes those sessions to verify that they work exactly as
40+
sessions in docstrings, and then executes those sessions to verify that they work exactly as
4141
shown.
4242

43+
Doctests have a different use case than proper unit tests: they are usually less
44+
detailed and don't catch special cases or obscure regression bugs. They are
45+
useful as an expressive documentation of the main use cases of a module and
46+
its components. However, doctests should run automatically each time
47+
the full test suite runs.
48+
49+
A simple doctest in a function:
50+
51+
::
52+
53+
def square(x):
54+
"""Squares x.
55+
56+
>>> square(2)
57+
4
58+
>>> square(-2)
59+
4
60+
"""
61+
62+
return x * x
63+
64+
if __name__ == '__main__':
65+
import doctest
66+
doctest.testmod()
67+
68+
When running this module from the command line as in ``python module.py``, the doctests
69+
will run and complain if anything is not behaving as described in the docstrings.
4370

4471
Tools
4572
:::::

0 commit comments

Comments
 (0)