mirror of
https://github.com/kennethreitz/python-guide.git
synced 2026-06-05 23:00:18 +00:00
Adding a sample and explanation for doctests
This commit is contained in:
@@ -33,7 +33,7 @@ Inline comments are used for individual lines and should be used sparingly.: ::
|
|||||||
But sometimes, this is useful: ::
|
But sometimes, this is useful: ::
|
||||||
x = x + 1 # Compensate for border
|
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/)
|
PEP 257 is the primary reference for docstrings. (http://www.python.org/dev/peps/pep-0257/)
|
||||||
|
|||||||
+28
-1
@@ -37,9 +37,36 @@ Doctest
|
|||||||
-------
|
-------
|
||||||
|
|
||||||
The doctest module searches for pieces of text that look like interactive Python
|
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.
|
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
|
Tools
|
||||||
:::::
|
:::::
|
||||||
|
|||||||
Reference in New Issue
Block a user