blob: 5e28c2acc0c20bf82bb40eb37aadbcc3b9232d5a [file] [log] [blame]
Tim Peters76882292001-02-17 05:58:44 +00001\section{\module{doctest} ---
Edward Loperb3666a32004-09-21 03:00:51 +00002 Test interactive Python examples}
Tim Peters76882292001-02-17 05:58:44 +00003
4\declaremodule{standard}{doctest}
Tim Peters7a082142004-09-25 00:10:53 +00005\moduleauthor{Tim Peters}{tim@python.org}
6\sectionauthor{Tim Peters}{tim@python.org}
Tim Peters76882292001-02-17 05:58:44 +00007\sectionauthor{Moshe Zadka}{moshez@debian.org}
Edward Loperb3666a32004-09-21 03:00:51 +00008\sectionauthor{Edward Loper}{edloper@users.sourceforge.net}
Tim Peters76882292001-02-17 05:58:44 +00009
Edward Loperb3666a32004-09-21 03:00:51 +000010\modulesynopsis{A framework for verifying interactive Python examples.}
Tim Peters76882292001-02-17 05:58:44 +000011
Tim Peters9463d872004-09-26 21:05:03 +000012The \refmodule{doctest} module searches for pieces of text that look like
Edward Loperb3666a32004-09-21 03:00:51 +000013interactive Python sessions, and then executes those sessions to
Tim Peters7a082142004-09-25 00:10:53 +000014verify that they work exactly as shown. There are several common ways to
Edward Loperb3666a32004-09-21 03:00:51 +000015use doctest:
16
Tim Peters7a082142004-09-25 00:10:53 +000017\begin{itemize}
Edward Loperb3666a32004-09-21 03:00:51 +000018\item To check that a module's docstrings are up-to-date by verifying
19 that all interactive examples still work as documented.
20\item To perform regression testing by verifying that interactive
21 examples from a test file or a test object work as expected.
Tim Peters7a082142004-09-25 00:10:53 +000022\item To write tutorial documentation for a package, liberally
Tim Peterscac5e7b2004-09-25 00:11:43 +000023 illustrated with input-output examples. Depending on whether
Tim Peters7a082142004-09-25 00:10:53 +000024 the examples or the expository text are emphasized, this has
25 the flavor of "literate testing" or "executable documentation".
26\end{itemize}
Edward Loperb3666a32004-09-21 03:00:51 +000027
Tim Peters7a082142004-09-25 00:10:53 +000028Here's a complete but small example module:
Tim Peters76882292001-02-17 05:58:44 +000029
30\begin{verbatim}
31"""
Edward Loperb3666a32004-09-21 03:00:51 +000032This is the "example" module.
Tim Peters76882292001-02-17 05:58:44 +000033
Edward Loperb3666a32004-09-21 03:00:51 +000034The example module supplies one function, factorial(). For example,
Tim Peters76882292001-02-17 05:58:44 +000035
36>>> factorial(5)
37120
38"""
39
40def factorial(n):
41 """Return the factorial of n, an exact integer >= 0.
42
43 If the result is small enough to fit in an int, return an int.
44 Else return a long.
45
46 >>> [factorial(n) for n in range(6)]
47 [1, 1, 2, 6, 24, 120]
48 >>> [factorial(long(n)) for n in range(6)]
49 [1, 1, 2, 6, 24, 120]
50 >>> factorial(30)
51 265252859812191058636308480000000L
52 >>> factorial(30L)
53 265252859812191058636308480000000L
54 >>> factorial(-1)
55 Traceback (most recent call last):
56 ...
57 ValueError: n must be >= 0
58
59 Factorials of floats are OK, but the float must be an exact integer:
60 >>> factorial(30.1)
61 Traceback (most recent call last):
62 ...
63 ValueError: n must be exact integer
64 >>> factorial(30.0)
65 265252859812191058636308480000000L
66
67 It must also not be ridiculously large:
68 >>> factorial(1e100)
69 Traceback (most recent call last):
70 ...
71 OverflowError: n too large
72 """
73
74\end{verbatim}
75% allow LaTeX to break here.
76\begin{verbatim}
77
78 import math
79 if not n >= 0:
80 raise ValueError("n must be >= 0")
81 if math.floor(n) != n:
82 raise ValueError("n must be exact integer")
Raymond Hettinger92f21b12003-07-11 22:32:18 +000083 if n+1 == n: # catch a value like 1e300
Tim Peters76882292001-02-17 05:58:44 +000084 raise OverflowError("n too large")
85 result = 1
86 factor = 2
87 while factor <= n:
Tim Peters7a082142004-09-25 00:10:53 +000088 result *= factor
Tim Peters76882292001-02-17 05:58:44 +000089 factor += 1
90 return result
91
92def _test():
Tim Petersc2388a22004-08-10 01:41:28 +000093 import doctest
Tim Peters7a082142004-09-25 00:10:53 +000094 doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +000095
96if __name__ == "__main__":
97 _test()
98\end{verbatim}
99
Fred Drake7a6b4f02003-07-17 16:00:01 +0000100If you run \file{example.py} directly from the command line,
Tim Peters9463d872004-09-26 21:05:03 +0000101\refmodule{doctest} works its magic:
Tim Peters76882292001-02-17 05:58:44 +0000102
103\begin{verbatim}
104$ python example.py
105$
106\end{verbatim}
107
Fred Drake7a6b4f02003-07-17 16:00:01 +0000108There's no output! That's normal, and it means all the examples
Tim Peters9463d872004-09-26 21:05:03 +0000109worked. Pass \programopt{-v} to the script, and \refmodule{doctest}
Fred Drake7a6b4f02003-07-17 16:00:01 +0000110prints a detailed log of what it's trying, and prints a summary at the
111end:
Tim Peters76882292001-02-17 05:58:44 +0000112
113\begin{verbatim}
114$ python example.py -v
Edward Loper6cc13502004-09-19 01:16:44 +0000115Trying:
116 factorial(5)
117Expecting:
118 120
Tim Peters76882292001-02-17 05:58:44 +0000119ok
Edward Loper6cc13502004-09-19 01:16:44 +0000120Trying:
121 [factorial(n) for n in range(6)]
122Expecting:
123 [1, 1, 2, 6, 24, 120]
Tim Peters76882292001-02-17 05:58:44 +0000124ok
Edward Loper6cc13502004-09-19 01:16:44 +0000125Trying:
126 [factorial(long(n)) for n in range(6)]
127Expecting:
128 [1, 1, 2, 6, 24, 120]
Tim Peters41a65ea2004-08-13 03:55:05 +0000129ok
130\end{verbatim}
Tim Peters76882292001-02-17 05:58:44 +0000131
132And so on, eventually ending with:
133
134\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000135Trying:
136 factorial(1e100)
Tim Peters76882292001-02-17 05:58:44 +0000137Expecting:
Tim Petersc2388a22004-08-10 01:41:28 +0000138 Traceback (most recent call last):
139 ...
140 OverflowError: n too large
Tim Peters76882292001-02-17 05:58:44 +0000141ok
Tim Peters7a082142004-09-25 00:10:53 +00001421 items had no tests:
143 __main__._test
Tim Peters76882292001-02-17 05:58:44 +00001442 items passed all tests:
Tim Peters7a082142004-09-25 00:10:53 +0000145 1 tests in __main__
146 8 tests in __main__.factorial
1479 tests in 3 items.
Tim Peters76882292001-02-17 05:58:44 +00001489 passed and 0 failed.
149Test passed.
150$
151\end{verbatim}
152
Fred Drake7a6b4f02003-07-17 16:00:01 +0000153That's all you need to know to start making productive use of
Tim Peters9463d872004-09-26 21:05:03 +0000154\refmodule{doctest}! Jump in. The following sections provide full
Tim Peters41a65ea2004-08-13 03:55:05 +0000155details. Note that there are many examples of doctests in
Tim Peters7a082142004-09-25 00:10:53 +0000156the standard Python test suite and libraries. Especially useful examples
157can be found in the standard test file \file{Lib/test/test_doctest.py}.
Tim Peters76882292001-02-17 05:58:44 +0000158
Tim Peters7a082142004-09-25 00:10:53 +0000159\subsection{Simple Usage: Checking Examples in
Edward Loperb3666a32004-09-21 03:00:51 +0000160 Docstrings\label{doctest-simple-testmod}}
Tim Peters76882292001-02-17 05:58:44 +0000161
Tim Peters41a65ea2004-08-13 03:55:05 +0000162The simplest way to start using doctest (but not necessarily the way
163you'll continue to do it) is to end each module \module{M} with:
Tim Peters76882292001-02-17 05:58:44 +0000164
165\begin{verbatim}
166def _test():
Tim Petersc2388a22004-08-10 01:41:28 +0000167 import doctest
Tim Peters06cc8472004-09-25 00:49:53 +0000168 doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +0000169
170if __name__ == "__main__":
171 _test()
172\end{verbatim}
173
Tim Peters9463d872004-09-26 21:05:03 +0000174\refmodule{doctest} then examines docstrings in module \module{M}.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000175
Tim Petersc2388a22004-08-10 01:41:28 +0000176Running the module as a script causes the examples in the docstrings
Tim Peters76882292001-02-17 05:58:44 +0000177to get executed and verified:
178
179\begin{verbatim}
180python M.py
181\end{verbatim}
182
183This won't display anything unless an example fails, in which case the
184failing example(s) and the cause(s) of the failure(s) are printed to stdout,
Tim Petersc2388a22004-08-10 01:41:28 +0000185and the final line of output is
Tim Peters06cc8472004-09-25 00:49:53 +0000186\samp{***Test Failed*** \var{N} failures.}, where \var{N} is the
Tim Petersc2388a22004-08-10 01:41:28 +0000187number of examples that failed.
Tim Peters76882292001-02-17 05:58:44 +0000188
Fred Drake7eb14632001-02-17 17:32:41 +0000189Run it with the \programopt{-v} switch instead:
Tim Peters76882292001-02-17 05:58:44 +0000190
191\begin{verbatim}
192python M.py -v
193\end{verbatim}
194
Fred Drake8836e562003-07-17 15:22:47 +0000195and a detailed report of all examples tried is printed to standard
196output, along with assorted summaries at the end.
Tim Peters76882292001-02-17 05:58:44 +0000197
Tim Petersc2388a22004-08-10 01:41:28 +0000198You can force verbose mode by passing \code{verbose=True} to
Fred Drake5d2f5152003-06-28 03:09:06 +0000199\function{testmod()}, or
Tim Petersc2388a22004-08-10 01:41:28 +0000200prohibit it by passing \code{verbose=False}. In either of those cases,
Tim Peters06cc8472004-09-25 00:49:53 +0000201\code{sys.argv} is not examined by \function{testmod()} (so passing
202\programopt{-v} or not has no effect).
Tim Peters76882292001-02-17 05:58:44 +0000203
Guido van Rossumd8faa362007-04-27 19:54:29 +0000204Since Python 2.6, there is also a command line shortcut for running
205\function{testmod()}. You can instruct the Python interpreter to run
206the doctest module directly from the standard library and pass the module
207name(s) on the command line:
208
209\begin{verbatim}
210python -m doctest -v example.py
211\end{verbatim}
212
213This will import \file{example.py} as a standalone module and run
214\function{testmod()} on it. Note that this may not work correctly if the
215file is part of a package and imports other submodules from that package.
216
Edward Loperb3666a32004-09-21 03:00:51 +0000217For more information on \function{testmod()}, see
218section~\ref{doctest-basic-api}.
219
220\subsection{Simple Usage: Checking Examples in a Text
221 File\label{doctest-simple-testfile}}
222
223Another simple application of doctest is testing interactive examples
224in a text file. This can be done with the \function{testfile()}
225function:
226
227\begin{verbatim}
228import doctest
Tim Peters06cc8472004-09-25 00:49:53 +0000229doctest.testfile("example.txt")
Edward Loperb3666a32004-09-21 03:00:51 +0000230\end{verbatim}
231
Tim Peters06cc8472004-09-25 00:49:53 +0000232That short script executes and verifies any interactive Python
233examples contained in the file \file{example.txt}. The file content
234is treated as if it were a single giant docstring; the file doesn't
235need to contain a Python program! For example, perhaps \file{example.txt}
236contains this:
237
238\begin{verbatim}
239The ``example`` module
240======================
241
242Using ``factorial``
243-------------------
244
245This is an example text file in reStructuredText format. First import
246``factorial`` from the ``example`` module:
247
248 >>> from example import factorial
249
250Now use it:
251
252 >>> factorial(6)
253 120
254\end{verbatim}
255
256Running \code{doctest.testfile("example.txt")} then finds the error
257in this documentation:
258
259\begin{verbatim}
260File "./example.txt", line 14, in example.txt
261Failed example:
262 factorial(6)
263Expected:
264 120
265Got:
266 720
267\end{verbatim}
268
269As with \function{testmod()}, \function{testfile()} won't display anything
270unless an example fails. If an example does fail, then the failing
271example(s) and the cause(s) of the failure(s) are printed to stdout, using
272the same format as \function{testmod()}.
Edward Loperb3666a32004-09-21 03:00:51 +0000273
274By default, \function{testfile()} looks for files in the calling
275module's directory. See section~\ref{doctest-basic-api} for a
276description of the optional arguments that can be used to tell it to
277look for files in other locations.
278
279Like \function{testmod()}, \function{testfile()}'s verbosity can be
280set with the \programopt{-v} command-line switch or with the optional
Tim Peters06cc8472004-09-25 00:49:53 +0000281keyword argument \var{verbose}.
Edward Loperb3666a32004-09-21 03:00:51 +0000282
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283Since Python 2.6, there is also a command line shortcut for running
284\function{testfile()}. You can instruct the Python interpreter to run
285the doctest module directly from the standard library and pass the file
286name(s) on the command line:
287
288\begin{verbatim}
289python -m doctest -v example.txt
290\end{verbatim}
291
292Because the file name does not end with \file{.py}, \module{doctest} infers
293that it must be run with \function{testfile()}, not \function{testmod()}.
294
Edward Loperb3666a32004-09-21 03:00:51 +0000295For more information on \function{testfile()}, see
296section~\ref{doctest-basic-api}.
297
298\subsection{How It Works\label{doctest-how-it-works}}
299
300This section examines in detail how doctest works: which docstrings it
301looks at, how it finds interactive examples, what execution context it
302uses, how it handles exceptions, and how option flags can be used to
303control its behavior. This is the information that you need to know
304to write doctest examples; for information about actually running
305doctest on these examples, see the following sections.
306
307\subsubsection{Which Docstrings Are Examined?\label{doctest-which-docstrings}}
Tim Peters76882292001-02-17 05:58:44 +0000308
Tim Peters8a3b69c2004-08-12 22:31:25 +0000309The module docstring, and all function, class and method docstrings are
310searched. Objects imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000311
Fred Drake7eb14632001-02-17 17:32:41 +0000312In addition, if \code{M.__test__} exists and "is true", it must be a
313dict, and each entry maps a (string) name to a function object, class
314object, or string. Function and class object docstrings found from
Tim Peters8a3b69c2004-08-12 22:31:25 +0000315\code{M.__test__} are searched, and strings are treated as if they
316were docstrings. In output, a key \code{K} in \code{M.__test__} appears
317with name
Tim Peters76882292001-02-17 05:58:44 +0000318
319\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000320<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000321\end{verbatim}
322
323Any classes found are recursively searched similarly, to test docstrings in
Tim Peters8a3b69c2004-08-12 22:31:25 +0000324their contained methods and nested classes.
325
326\versionchanged[A "private name" concept is deprecated and no longer
Tim Peters26039602004-08-13 01:49:12 +0000327 documented]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000328
Edward Loperb3666a32004-09-21 03:00:51 +0000329\subsubsection{How are Docstring Examples
330 Recognized?\label{doctest-finding-examples}}
Tim Peters76882292001-02-17 05:58:44 +0000331
Edward Loperb3666a32004-09-21 03:00:51 +0000332In most cases a copy-and-paste of an interactive console session works
333fine, but doctest isn't trying to do an exact emulation of any specific
334Python shell. All hard tab characters are expanded to spaces, using
3358-column tab stops. If you don't believe tabs should mean that, too
336bad: don't use hard tabs, or write your own \class{DocTestParser}
337class.
Tim Peters76882292001-02-17 05:58:44 +0000338
Edward Loperb3666a32004-09-21 03:00:51 +0000339\versionchanged[Expanding tabs to spaces is new; previous versions
340 tried to preserve hard tabs, with confusing results]{2.4}
341
342\begin{verbatim}
343>>> # comments are ignored
344>>> x = 12
345>>> x
34612
347>>> if x == 13:
348... print "yes"
349... else:
350... print "no"
351... print "NO"
352... print "NO!!!"
353...
354no
355NO
356NO!!!
357>>>
358\end{verbatim}
359
360Any expected output must immediately follow the final
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361\code{'>>>~'} or \code{'...~'} line containing the code, and
362the expected output (if any) extends to the next \code{'>>>~'}
Edward Loperb3666a32004-09-21 03:00:51 +0000363or all-whitespace line.
364
365The fine print:
366
367\begin{itemize}
368
369\item Expected output cannot contain an all-whitespace line, since such a
370 line is taken to signal the end of expected output. If expected
371 output does contain a blank line, put \code{<BLANKLINE>} in your
372 doctest example each place a blank line is expected.
373 \versionchanged[\code{<BLANKLINE>} was added; there was no way to
374 use expected output containing empty lines in
375 previous versions]{2.4}
376
377\item Output to stdout is captured, but not output to stderr (exception
378 tracebacks are captured via a different means).
379
380\item If you continue a line via backslashing in an interactive session,
381 or for any other reason use a backslash, you should use a raw
382 docstring, which will preserve your backslashes exactly as you type
383 them:
384
385\begin{verbatim}
386>>> def f(x):
387... r'''Backslashes in a raw docstring: m\n'''
388>>> print f.__doc__
389Backslashes in a raw docstring: m\n
390\end{verbatim}
391
392 Otherwise, the backslash will be interpreted as part of the string.
Tim Peters39c5de02004-09-25 01:22:29 +0000393 For example, the "{\textbackslash}" above would be interpreted as a
394 newline character. Alternatively, you can double each backslash in the
Edward Loperb3666a32004-09-21 03:00:51 +0000395 doctest version (and not use a raw string):
396
397\begin{verbatim}
398>>> def f(x):
399... '''Backslashes in a raw docstring: m\\n'''
400>>> print f.__doc__
401Backslashes in a raw docstring: m\n
402\end{verbatim}
403
404\item The starting column doesn't matter:
405
406\begin{verbatim}
407 >>> assert "Easy!"
408 >>> import math
409 >>> math.floor(1.9)
410 1.0
411\end{verbatim}
412
413and as many leading whitespace characters are stripped from the
Thomas Wouters477c8d52006-05-27 19:21:47 +0000414expected output as appeared in the initial \code{'>>>~'} line
Edward Loperb3666a32004-09-21 03:00:51 +0000415that started the example.
416\end{itemize}
417
418\subsubsection{What's the Execution Context?\label{doctest-execution-context}}
419
Tim Peters9463d872004-09-26 21:05:03 +0000420By default, each time \refmodule{doctest} finds a docstring to test, it
Tim Peters41a65ea2004-08-13 03:55:05 +0000421uses a \emph{shallow copy} of \module{M}'s globals, so that running tests
Tim Peters76882292001-02-17 05:58:44 +0000422doesn't change the module's real globals, and so that one test in
423\module{M} can't leave behind crumbs that accidentally allow another test
424to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000425in \module{M}, and names defined earlier in the docstring being run.
Tim Peters41a65ea2004-08-13 03:55:05 +0000426Examples cannot see names defined in other docstrings.
Tim Peters76882292001-02-17 05:58:44 +0000427
428You can force use of your own dict as the execution context by passing
Edward Loperb3666a32004-09-21 03:00:51 +0000429\code{globs=your_dict} to \function{testmod()} or
430\function{testfile()} instead.
Tim Peters76882292001-02-17 05:58:44 +0000431
Edward Loperb3666a32004-09-21 03:00:51 +0000432\subsubsection{What About Exceptions?\label{doctest-exceptions}}
Tim Peters76882292001-02-17 05:58:44 +0000433
Tim Petersa07bcd42004-08-26 04:47:31 +0000434No problem, provided that the traceback is the only output produced by
Thomas Wouters477c8d52006-05-27 19:21:47 +0000435the example: just paste in the traceback.\footnote{Examples containing
436 both expected output and an exception are not supported. Trying
437 to guess where one ends and the other begins is too error-prone,
438 and that also makes for a confusing test.}
439Since tracebacks contain details that are likely to change rapidly (for
440example, exact file paths and line numbers), this is one case where doctest
441works hard to be flexible in what it accepts.
Tim Petersa07bcd42004-08-26 04:47:31 +0000442
443Simple example:
Tim Peters76882292001-02-17 05:58:44 +0000444
445\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000446>>> [1, 2, 3].remove(42)
447Traceback (most recent call last):
448 File "<stdin>", line 1, in ?
449ValueError: list.remove(x): x not in list
Tim Peters76882292001-02-17 05:58:44 +0000450\end{verbatim}
451
Edward Loper19b19582004-08-25 23:07:03 +0000452That doctest succeeds if \exception{ValueError} is raised, with the
Tim Petersa07bcd42004-08-26 04:47:31 +0000453\samp{list.remove(x): x not in list} detail as shown.
Tim Peters41a65ea2004-08-13 03:55:05 +0000454
Edward Loper19b19582004-08-25 23:07:03 +0000455The expected output for an exception must start with a traceback
456header, which may be either of the following two lines, indented the
457same as the first line of the example:
Tim Peters41a65ea2004-08-13 03:55:05 +0000458
459\begin{verbatim}
460Traceback (most recent call last):
461Traceback (innermost last):
462\end{verbatim}
463
Edward Loper19b19582004-08-25 23:07:03 +0000464The traceback header is followed by an optional traceback stack, whose
Tim Petersa07bcd42004-08-26 04:47:31 +0000465contents are ignored by doctest. The traceback stack is typically
466omitted, or copied verbatim from an interactive session.
Edward Loper19b19582004-08-25 23:07:03 +0000467
Tim Petersa07bcd42004-08-26 04:47:31 +0000468The traceback stack is followed by the most interesting part: the
Edward Loper19b19582004-08-25 23:07:03 +0000469line(s) containing the exception type and detail. This is usually the
470last line of a traceback, but can extend across multiple lines if the
Tim Petersa07bcd42004-08-26 04:47:31 +0000471exception has a multi-line detail:
Tim Peters41a65ea2004-08-13 03:55:05 +0000472
473\begin{verbatim}
Edward Loper456ff912004-09-27 03:30:44 +0000474>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000475Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000476 File "<stdin>", line 1, in ?
477ValueError: multi
478 line
479detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000480\end{verbatim}
481
Edward Loper6cc13502004-09-19 01:16:44 +0000482The last three lines (starting with \exception{ValueError}) are
Edward Loper19b19582004-08-25 23:07:03 +0000483compared against the exception's type and detail, and the rest are
484ignored.
Tim Peters41a65ea2004-08-13 03:55:05 +0000485
Edward Loper19b19582004-08-25 23:07:03 +0000486Best practice is to omit the traceback stack, unless it adds
Tim Petersa07bcd42004-08-26 04:47:31 +0000487significant documentation value to the example. So the last example
Tim Peters41a65ea2004-08-13 03:55:05 +0000488is probably better as:
489
490\begin{verbatim}
Edward Loper456ff912004-09-27 03:30:44 +0000491>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000492Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000493 ...
494ValueError: multi
495 line
496detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000497\end{verbatim}
498
Tim Petersa07bcd42004-08-26 04:47:31 +0000499Note that tracebacks are treated very specially. In particular, in the
Tim Peters41a65ea2004-08-13 03:55:05 +0000500rewritten example, the use of \samp{...} is independent of doctest's
Tim Petersa07bcd42004-08-26 04:47:31 +0000501\constant{ELLIPSIS} option. The ellipsis in that example could be left
502out, or could just as well be three (or three hundred) commas or digits,
503or an indented transcript of a Monty Python skit.
504
505Some details you should read once, but won't need to remember:
506
507\begin{itemize}
508
509\item Doctest can't guess whether your expected output came from an
510 exception traceback or from ordinary printing. So, e.g., an example
511 that expects \samp{ValueError: 42 is prime} will pass whether
512 \exception{ValueError} is actually raised or if the example merely
513 prints that traceback text. In practice, ordinary output rarely begins
514 with a traceback header line, so this doesn't create real problems.
515
516\item Each line of the traceback stack (if present) must be indented
517 further than the first line of the example, \emph{or} start with a
518 non-alphanumeric character. The first line following the traceback
519 header indented the same and starting with an alphanumeric is taken
520 to be the start of the exception detail. Of course this does the
521 right thing for genuine tracebacks.
522
Tim Peters1fbf9c52004-09-04 17:21:02 +0000523\item When the \constant{IGNORE_EXCEPTION_DETAIL} doctest option is
524 is specified, everything following the leftmost colon is ignored.
525
Edward Loper0fe00aa2004-09-30 17:18:18 +0000526\item The interactive shell omits the traceback header line for some
527 \exception{SyntaxError}s. But doctest uses the traceback header
528 line to distinguish exceptions from non-exceptions. So in the rare
529 case where you need to test a \exception{SyntaxError} that omits the
530 traceback header, you will need to manually add the traceback header
531 line to your test example.
Tim Peters29978ae2004-10-04 03:34:32 +0000532
Edward Loper0fe00aa2004-09-30 17:18:18 +0000533\item For some \exception{SyntaxError}s, Python displays the character
534 position of the syntax error, using a \code{\^} marker:
535
536\begin{verbatim}
537>>> 1 1
538 File "<stdin>", line 1
539 1 1
540 ^
541SyntaxError: invalid syntax
542\end{verbatim}
543
544 Since the lines showing the position of the error come before the
545 exception type and detail, they are not checked by doctest. For
546 example, the following test would pass, even though it puts the
547 \code{\^} marker in the wrong location:
548
549\begin{verbatim}
550>>> 1 1
Tim Peters29978ae2004-10-04 03:34:32 +0000551Traceback (most recent call last):
Edward Loper0fe00aa2004-09-30 17:18:18 +0000552 File "<stdin>", line 1
553 1 1
554 ^
555SyntaxError: invalid syntax
556\end{verbatim}
557
Tim Petersa07bcd42004-08-26 04:47:31 +0000558\end{itemize}
Tim Peters41a65ea2004-08-13 03:55:05 +0000559
Tim Peters39c5de02004-09-25 01:22:29 +0000560\versionchanged[The ability to handle a multi-line exception detail,
561 and the \constant{IGNORE_EXCEPTION_DETAIL} doctest option,
562 were added]{2.4}
Tim Peters0e448072004-08-26 01:02:08 +0000563
Edward Loperb3666a32004-09-21 03:00:51 +0000564\subsubsection{Option Flags and Directives\label{doctest-options}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000565
Tim Peterscf533552004-08-26 04:50:38 +0000566A number of option flags control various aspects of doctest's
Tim Peters026f8dc2004-08-19 16:38:58 +0000567behavior. Symbolic names for the flags are supplied as module constants,
Tim Peters83e259a2004-08-13 21:55:21 +0000568which can be or'ed together and passed to various functions. The names
Tim Peters026f8dc2004-08-19 16:38:58 +0000569can also be used in doctest directives (see below).
Tim Peters8a3b69c2004-08-12 22:31:25 +0000570
Tim Petersa07bcd42004-08-26 04:47:31 +0000571The first group of options define test semantics, controlling
572aspects of how doctest decides whether actual output matches an
573example's expected output:
574
Tim Peters8a3b69c2004-08-12 22:31:25 +0000575\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
576 By default, if an expected output block contains just \code{1},
577 an actual output block containing just \code{1} or just
578 \code{True} is considered to be a match, and similarly for \code{0}
579 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
580 specified, neither substitution is allowed. The default behavior
581 caters to that Python changed the return type of many functions
582 from integer to boolean; doctests expecting "little integer"
583 output still work in these cases. This option will probably go
584 away, but not for several years.
585\end{datadesc}
586
587\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
588 By default, if an expected output block contains a line
589 containing only the string \code{<BLANKLINE>}, then that line
590 will match a blank line in the actual output. Because a
591 genuinely blank line delimits the expected output, this is
592 the only way to communicate that a blank line is expected. When
593 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
594 is not allowed.
595\end{datadesc}
596
597\begin{datadesc}{NORMALIZE_WHITESPACE}
598 When specified, all sequences of whitespace (blanks and newlines) are
599 treated as equal. Any sequence of whitespace within the expected
600 output will match any sequence of whitespace within the actual output.
601 By default, whitespace must match exactly.
602 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
603 of expected output is very long, and you want to wrap it across
604 multiple lines in your source.
605\end{datadesc}
606
607\begin{datadesc}{ELLIPSIS}
608 When specified, an ellipsis marker (\code{...}) in the expected output
609 can match any substring in the actual output. This includes
Tim Peters026f8dc2004-08-19 16:38:58 +0000610 substrings that span line boundaries, and empty substrings, so it's
611 best to keep usage of this simple. Complicated uses can lead to the
612 same kinds of "oops, it matched too much!" surprises that \regexp{.*}
613 is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000614\end{datadesc}
615
Tim Peters1fbf9c52004-09-04 17:21:02 +0000616\begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
617 When specified, an example that expects an exception passes if
618 an exception of the expected type is raised, even if the exception
619 detail does not match. For example, an example expecting
620 \samp{ValueError: 42} will pass if the actual exception raised is
621 \samp{ValueError: 3*14}, but will fail, e.g., if
622 \exception{TypeError} is raised.
623
624 Note that a similar effect can be obtained using \constant{ELLIPSIS},
625 and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
626 prior to 2.4 become uninteresting. Until then,
627 \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
628 doctest that doesn't care about the exception detail yet continues
629 to pass under Python releases prior to 2.4 (doctest directives
630 appear to be comments to them). For example,
631
632\begin{verbatim}
633>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
634Traceback (most recent call last):
635 File "<stdin>", line 1, in ?
636TypeError: object doesn't support item assignment
637\end{verbatim}
638
639 passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
640 to say "does not" instead of "doesn't".
641
642\end{datadesc}
643
Thomas Wouters477c8d52006-05-27 19:21:47 +0000644\begin{datadesc}{SKIP}
645
646 When specified, do not run the example at all. This can be useful
647 in contexts where doctest examples serve as both documentation and
648 test cases, and an example should be included for documentation
649 purposes, but should not be checked. E.g., the example's output
650 might be random; or the example might depend on resources which
651 would be unavailable to the test driver.
652
653 The SKIP flag can also be used for temporarily "commenting out"
654 examples.
655
656\end{datadesc}
657
Tim Peters38330fe2004-08-30 16:19:24 +0000658\begin{datadesc}{COMPARISON_FLAGS}
659 A bitmask or'ing together all the comparison flags above.
660\end{datadesc}
661
Tim Petersf33683f2004-08-26 04:52:46 +0000662The second group of options controls how test failures are reported:
Tim Petersa07bcd42004-08-26 04:47:31 +0000663
Edward Loper71f55af2004-08-26 01:41:51 +0000664\begin{datadesc}{REPORT_UDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000665 When specified, failures that involve multi-line expected and
666 actual outputs are displayed using a unified diff.
667\end{datadesc}
668
Edward Loper71f55af2004-08-26 01:41:51 +0000669\begin{datadesc}{REPORT_CDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000670 When specified, failures that involve multi-line expected and
671 actual outputs will be displayed using a context diff.
672\end{datadesc}
673
Edward Loper71f55af2004-08-26 01:41:51 +0000674\begin{datadesc}{REPORT_NDIFF}
Tim Petersc6cbab02004-08-22 19:43:28 +0000675 When specified, differences are computed by \code{difflib.Differ},
676 using the same algorithm as the popular \file{ndiff.py} utility.
677 This is the only method that marks differences within lines as
678 well as across lines. For example, if a line of expected output
679 contains digit \code{1} where actual output contains letter \code{l},
680 a line is inserted with a caret marking the mismatching column
681 positions.
682\end{datadesc}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000683
Edward Lopera89f88d2004-08-26 02:45:51 +0000684\begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
685 When specified, display the first failing example in each doctest,
686 but suppress output for all remaining examples. This will prevent
687 doctest from reporting correct examples that break because of
688 earlier failures; but it might also hide incorrect examples that
689 fail independently of the first failure. When
690 \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
691 examples are still run, and still count towards the total number of
692 failures reported; only the output is suppressed.
693\end{datadesc}
694
Tim Peters38330fe2004-08-30 16:19:24 +0000695\begin{datadesc}{REPORTING_FLAGS}
696 A bitmask or'ing together all the reporting flags above.
697\end{datadesc}
698
Edward Loperb3666a32004-09-21 03:00:51 +0000699"Doctest directives" may be used to modify the option flags for
700individual examples. Doctest directives are expressed as a special
701Python comment following an example's source code:
Tim Peters026f8dc2004-08-19 16:38:58 +0000702
703\begin{productionlist}[doctest]
704 \production{directive}
Edward Loper6cc13502004-09-19 01:16:44 +0000705 {"\#" "doctest:" \token{directive_options}}
706 \production{directive_options}
707 {\token{directive_option} ("," \token{directive_option})*}
708 \production{directive_option}
709 {\token{on_or_off} \token{directive_option_name}}
Tim Peters026f8dc2004-08-19 16:38:58 +0000710 \production{on_or_off}
711 {"+" | "-"}
Edward Loper6cc13502004-09-19 01:16:44 +0000712 \production{directive_option_name}
Tim Peters026f8dc2004-08-19 16:38:58 +0000713 {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
714\end{productionlist}
715
716Whitespace is not allowed between the \code{+} or \code{-} and the
Edward Loper6cc13502004-09-19 01:16:44 +0000717directive option name. The directive option name can be any of the
Edward Loperb3666a32004-09-21 03:00:51 +0000718option flag names explained above.
Tim Peters026f8dc2004-08-19 16:38:58 +0000719
Edward Loperb3666a32004-09-21 03:00:51 +0000720An example's doctest directives modify doctest's behavior for that
721single example. Use \code{+} to enable the named behavior, or
722\code{-} to disable it.
Tim Peters026f8dc2004-08-19 16:38:58 +0000723
724For example, this test passes:
725
726\begin{verbatim}
727>>> print range(20) #doctest: +NORMALIZE_WHITESPACE
728[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
72910, 11, 12, 13, 14, 15, 16, 17, 18, 19]
730\end{verbatim}
731
732Without the directive it would fail, both because the actual output
733doesn't have two blanks before the single-digit list elements, and
734because the actual output is on a single line. This test also passes,
Tim Petersa07bcd42004-08-26 04:47:31 +0000735and also requires a directive to do so:
Tim Peters026f8dc2004-08-19 16:38:58 +0000736
737\begin{verbatim}
738>>> print range(20) # doctest:+ELLIPSIS
739[0, 1, ..., 18, 19]
740\end{verbatim}
741
Edward Loper6cc13502004-09-19 01:16:44 +0000742Multiple directives can be used on a single physical line, separated
743by commas:
Tim Peters026f8dc2004-08-19 16:38:58 +0000744
745\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000746>>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +0000747[0, 1, ..., 18, 19]
748\end{verbatim}
749
Edward Loperb3666a32004-09-21 03:00:51 +0000750If multiple directive comments are used for a single example, then
751they are combined:
Edward Loper6cc13502004-09-19 01:16:44 +0000752
753\begin{verbatim}
754>>> print range(20) # doctest: +ELLIPSIS
755... # doctest: +NORMALIZE_WHITESPACE
756[0, 1, ..., 18, 19]
757\end{verbatim}
758
759As the previous example shows, you can add \samp{...} lines to your
Edward Loperb3666a32004-09-21 03:00:51 +0000760example containing only directives. This can be useful when an
Edward Loper6cc13502004-09-19 01:16:44 +0000761example is too long for a directive to comfortably fit on the same
762line:
763
764\begin{verbatim}
765>>> print range(5) + range(10,20) + range(30,40) + range(50,60)
766... # doctest: +ELLIPSIS
767[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
768\end{verbatim}
769
Tim Peters026f8dc2004-08-19 16:38:58 +0000770Note that since all options are disabled by default, and directives apply
771only to the example they appear in, enabling options (via \code{+} in a
772directive) is usually the only meaningful choice. However, option flags
773can also be passed to functions that run doctests, establishing different
774defaults. In such cases, disabling an option via \code{-} in a directive
775can be useful.
776
Tim Peters8a3b69c2004-08-12 22:31:25 +0000777\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
778 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
Edward Loper7d88a582004-09-28 05:50:57 +0000779 \constant{IGNORE_EXCEPTION_DETAIL},
Edward Lopera89f88d2004-08-26 02:45:51 +0000780 \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
Tim Peters38330fe2004-08-30 16:19:24 +0000781 \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
782 \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
Tim Peters026f8dc2004-08-19 16:38:58 +0000783 were added; by default \code{<BLANKLINE>} in expected output
784 matches an empty line in actual output; and doctest directives
785 were added]{2.4}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000786\versionchanged[Constant \constant{SKIP} was added]{2.5}
Tim Peters026f8dc2004-08-19 16:38:58 +0000787
Tim Peters16be62f2004-09-26 02:38:41 +0000788There's also a way to register new option flag names, although this
Tim Peters9463d872004-09-26 21:05:03 +0000789isn't useful unless you intend to extend \refmodule{doctest} internals
Tim Peters16be62f2004-09-26 02:38:41 +0000790via subclassing:
791
792\begin{funcdesc}{register_optionflag}{name}
793 Create a new option flag with a given name, and return the new
794 flag's integer value. \function{register_optionflag()} can be
795 used when subclassing \class{OutputChecker} or
796 \class{DocTestRunner} to create new options that are supported by
797 your subclasses. \function{register_optionflag} should always be
798 called using the following idiom:
799
800\begin{verbatim}
801 MY_FLAG = register_optionflag('MY_FLAG')
802\end{verbatim}
803
804 \versionadded{2.4}
805\end{funcdesc}
806
Edward Loperb3666a32004-09-21 03:00:51 +0000807\subsubsection{Warnings\label{doctest-warnings}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000808
Tim Peters9463d872004-09-26 21:05:03 +0000809\refmodule{doctest} is serious about requiring exact matches in expected
Tim Peters2dc82052004-09-25 01:30:16 +0000810output. If even a single character doesn't match, the test fails. This
811will probably surprise you a few times, as you learn exactly what Python
812does and doesn't guarantee about output. For example, when printing a
813dict, Python doesn't guarantee that the key-value pairs will be printed
814in any particular order, so a test like
Tim Peters76882292001-02-17 05:58:44 +0000815
Edward Loperb3666a32004-09-21 03:00:51 +0000816% Hey! What happened to Monty Python examples?
817% Tim: ask Guido -- it's his example!
818\begin{verbatim}
819>>> foo()
820{"Hermione": "hippogryph", "Harry": "broomstick"}
821\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000822
Edward Loperb3666a32004-09-21 03:00:51 +0000823is vulnerable! One workaround is to do
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000824
Edward Loperb3666a32004-09-21 03:00:51 +0000825\begin{verbatim}
826>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
827True
828\end{verbatim}
829
830instead. Another is to do
831
832\begin{verbatim}
833>>> d = foo().items()
834>>> d.sort()
835>>> d
836[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
837\end{verbatim}
838
839There are others, but you get the idea.
840
841Another bad idea is to print things that embed an object address, like
842
843\begin{verbatim}
844>>> id(1.0) # certain to fail some of the time
8457948648
Tim Peters39c5de02004-09-25 01:22:29 +0000846>>> class C: pass
847>>> C() # the default repr() for instances embeds an address
848<__main__.C instance at 0x00AC18F0>
849\end{verbatim}
850
851The \constant{ELLIPSIS} directive gives a nice approach for the last
852example:
853
854\begin{verbatim}
855>>> C() #doctest: +ELLIPSIS
856<__main__.C instance at 0x...>
Edward Loperb3666a32004-09-21 03:00:51 +0000857\end{verbatim}
858
859Floating-point numbers are also subject to small output variations across
860platforms, because Python defers to the platform C library for float
861formatting, and C libraries vary widely in quality here.
862
863\begin{verbatim}
864>>> 1./7 # risky
8650.14285714285714285
866>>> print 1./7 # safer
8670.142857142857
868>>> print round(1./7, 6) # much safer
8690.142857
870\end{verbatim}
871
872Numbers of the form \code{I/2.**J} are safe across all platforms, and I
873often contrive doctest examples to produce numbers of that form:
874
875\begin{verbatim}
876>>> 3./4 # utterly safe
8770.75
878\end{verbatim}
879
880Simple fractions are also easier for people to understand, and that makes
881for better documentation.
882
Edward Loperb3666a32004-09-21 03:00:51 +0000883\subsection{Basic API\label{doctest-basic-api}}
884
885The functions \function{testmod()} and \function{testfile()} provide a
886simple interface to doctest that should be sufficient for most basic
Tim Petersb2b26ac2004-09-25 01:51:49 +0000887uses. For a less formal introduction to these two functions, see
Edward Loperb3666a32004-09-21 03:00:51 +0000888sections \ref{doctest-simple-testmod} and
889\ref{doctest-simple-testfile}.
890
891\begin{funcdesc}{testfile}{filename\optional{, module_relative}\optional{,
892 name}\optional{, package}\optional{,
893 globs}\optional{, verbose}\optional{,
894 report}\optional{, optionflags}\optional{,
Edward Lopera4c6a852004-09-27 04:08:20 +0000895 extraglobs}\optional{, raise_on_error}\optional{,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000896 parser}\optional{, encoding}}
Edward Loperb3666a32004-09-21 03:00:51 +0000897
898 All arguments except \var{filename} are optional, and should be
899 specified in keyword form.
900
901 Test examples in the file named \var{filename}. Return
902 \samp{(\var{failure_count}, \var{test_count})}.
903
904 Optional argument \var{module_relative} specifies how the filename
905 should be interpreted:
906
907 \begin{itemize}
908 \item If \var{module_relative} is \code{True} (the default), then
Tim Petersb2b26ac2004-09-25 01:51:49 +0000909 \var{filename} specifies an OS-independent module-relative
Edward Loperb3666a32004-09-21 03:00:51 +0000910 path. By default, this path is relative to the calling
911 module's directory; but if the \var{package} argument is
912 specified, then it is relative to that package. To ensure
Tim Petersb2b26ac2004-09-25 01:51:49 +0000913 OS-independence, \var{filename} should use \code{/} characters
Edward Loperb3666a32004-09-21 03:00:51 +0000914 to separate path segments, and may not be an absolute path
915 (i.e., it may not begin with \code{/}).
916 \item If \var{module_relative} is \code{False}, then \var{filename}
Tim Petersb2b26ac2004-09-25 01:51:49 +0000917 specifies an OS-specific path. The path may be absolute or
Edward Loperb3666a32004-09-21 03:00:51 +0000918 relative; relative paths are resolved with respect to the
919 current working directory.
920 \end{itemize}
921
922 Optional argument \var{name} gives the name of the test; by default,
923 or if \code{None}, \code{os.path.basename(\var{filename})} is used.
924
925 Optional argument \var{package} is a Python package or the name of a
926 Python package whose directory should be used as the base directory
927 for a module-relative filename. If no package is specified, then
928 the calling module's directory is used as the base directory for
929 module-relative filenames. It is an error to specify \var{package}
930 if \var{module_relative} is \code{False}.
931
932 Optional argument \var{globs} gives a dict to be used as the globals
Tim Petersb2b26ac2004-09-25 01:51:49 +0000933 when executing examples. A new shallow copy of this dict is
Edward Loperb3666a32004-09-21 03:00:51 +0000934 created for the doctest, so its examples start with a clean slate.
Tim Petersb2b26ac2004-09-25 01:51:49 +0000935 By default, or if \code{None}, a new empty dict is used.
Edward Loperb3666a32004-09-21 03:00:51 +0000936
937 Optional argument \var{extraglobs} gives a dict merged into the
938 globals used to execute examples. This works like
939 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
940 common key, the associated value in \var{extraglobs} appears in the
941 combined dict. By default, or if \code{None}, no extra globals are
942 used. This is an advanced feature that allows parameterization of
943 doctests. For example, a doctest can be written for a base class, using
944 a generic name for the class, then reused to test any number of
945 subclasses by passing an \var{extraglobs} dict mapping the generic
946 name to the subclass to be tested.
947
948 Optional argument \var{verbose} prints lots of stuff if true, and prints
949 only failures if false; by default, or if \code{None}, it's true
950 if and only if \code{'-v'} is in \code{sys.argv}.
951
952 Optional argument \var{report} prints a summary at the end when true,
953 else prints nothing at the end. In verbose mode, the summary is
954 detailed, else the summary is very brief (in fact, empty if all tests
955 passed).
956
957 Optional argument \var{optionflags} or's together option flags. See
Tim Peters8c0a2cf2004-09-25 03:02:23 +0000958 section~\ref{doctest-options}.
Edward Loperb3666a32004-09-21 03:00:51 +0000959
960 Optional argument \var{raise_on_error} defaults to false. If true,
961 an exception is raised upon the first failure or unexpected exception
962 in an example. This allows failures to be post-mortem debugged.
963 Default behavior is to continue running examples.
964
Edward Lopera4c6a852004-09-27 04:08:20 +0000965 Optional argument \var{parser} specifies a \class{DocTestParser} (or
966 subclass) that should be used to extract tests from the files. It
967 defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
968
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000969 Optional argument \var{encoding} specifies an encoding that should
970 be used to convert the file to unicode.
971
Edward Loperb3666a32004-09-21 03:00:51 +0000972 \versionadded{2.4}
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000973
974 \versionchanged[The parameter \var{encoding} was added]{2.5}
975
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000976\end{funcdesc}
977
Tim Peters83e259a2004-08-13 21:55:21 +0000978\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
979 globs}\optional{, verbose}\optional{,
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000980 report}\optional{,
Tim Peters83e259a2004-08-13 21:55:21 +0000981 optionflags}\optional{, extraglobs}\optional{,
Tim Peters82788602004-09-13 15:03:17 +0000982 raise_on_error}\optional{, exclude_empty}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000983
Tim Peters83e259a2004-08-13 21:55:21 +0000984 All arguments are optional, and all except for \var{m} should be
985 specified in keyword form.
986
987 Test examples in docstrings in functions and classes reachable
Tim Petersb2b26ac2004-09-25 01:51:49 +0000988 from module \var{m} (or module \module{__main__} if \var{m} is not
989 supplied or is \code{None}), starting with \code{\var{m}.__doc__}.
Tim Peters83e259a2004-08-13 21:55:21 +0000990
991 Also test examples reachable from dict \code{\var{m}.__test__}, if it
992 exists and is not \code{None}. \code{\var{m}.__test__} maps
993 names (strings) to functions, classes and strings; function and class
994 docstrings are searched for examples; strings are searched directly,
995 as if they were docstrings.
996
997 Only docstrings attached to objects belonging to module \var{m} are
998 searched.
999
1000 Return \samp{(\var{failure_count}, \var{test_count})}.
1001
1002 Optional argument \var{name} gives the name of the module; by default,
1003 or if \code{None}, \code{\var{m}.__name__} is used.
1004
Tim Peters82788602004-09-13 15:03:17 +00001005 Optional argument \var{exclude_empty} defaults to false. If true,
1006 objects for which no doctests are found are excluded from consideration.
1007 The default is a backward compatibility hack, so that code still
1008 using \method{doctest.master.summarize()} in conjunction with
1009 \function{testmod()} continues to get output for objects with no tests.
1010 The \var{exclude_empty} argument to the newer \class{DocTestFinder}
1011 constructor defaults to true.
1012
Tim Petersb2b26ac2004-09-25 01:51:49 +00001013 Optional arguments \var{extraglobs}, \var{verbose}, \var{report},
1014 \var{optionflags}, \var{raise_on_error}, and \var{globs} are the same as
1015 for function \function{testfile()} above, except that \var{globs}
1016 defaults to \code{\var{m}.__dict__}.
1017
Tim Peters83e259a2004-08-13 21:55:21 +00001018 \versionchanged[The parameter \var{optionflags} was added]{2.3}
1019
Tim Peters82788602004-09-13 15:03:17 +00001020 \versionchanged[The parameters \var{extraglobs}, \var{raise_on_error}
1021 and \var{exclude_empty} were added]{2.4}
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001022
1023 \versionchanged[The optional argument \var{isprivate}, deprecated
1024 in 2.4, was removed]{2.5}
1025
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001026\end{funcdesc}
1027
Tim Peters00411212004-09-26 20:45:04 +00001028There's also a function to run the doctests associated with a single object.
1029This function is provided for backward compatibility. There are no plans
1030to deprecate it, but it's rarely useful:
1031
1032\begin{funcdesc}{run_docstring_examples}{f, globs\optional{,
1033 verbose}\optional{, name}\optional{,
1034 compileflags}\optional{, optionflags}}
1035
1036 Test examples associated with object \var{f}; for example, \var{f} may
1037 be a module, function, or class object.
1038
1039 A shallow copy of dictionary argument \var{globs} is used for the
1040 execution context.
1041
1042 Optional argument \var{name} is used in failure messages, and defaults
1043 to \code{"NoName"}.
1044
1045 If optional argument \var{verbose} is true, output is generated even
1046 if there are no failures. By default, output is generated only in case
1047 of an example failure.
1048
1049 Optional argument \var{compileflags} gives the set of flags that should
1050 be used by the Python compiler when running the examples. By default, or
1051 if \code{None}, flags are deduced corresponding to the set of future
1052 features found in \var{globs}.
1053
1054 Optional argument \var{optionflags} works as for function
1055 \function{testfile()} above.
1056\end{funcdesc}
1057
Edward Loperb3666a32004-09-21 03:00:51 +00001058\subsection{Unittest API\label{doctest-unittest-api}}
1059
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001060As your collection of doctest'ed modules grows, you'll want a way to run
Tim Peters9463d872004-09-26 21:05:03 +00001061all their doctests systematically. Prior to Python 2.4, \refmodule{doctest}
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001062had a barely documented \class{Tester} class that supplied a rudimentary
1063way to combine doctests from multiple modules. \class{Tester} was feeble,
1064and in practice most serious Python testing frameworks build on the
Tim Peters9463d872004-09-26 21:05:03 +00001065\refmodule{unittest} module, which supplies many flexible ways to combine
1066tests from multiple sources. So, in Python 2.4, \refmodule{doctest}'s
1067\class{Tester} class is deprecated, and \refmodule{doctest} provides two
1068functions that can be used to create \refmodule{unittest} test suites from
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001069modules and text files containing doctests. These test suites can then be
Tim Peters9463d872004-09-26 21:05:03 +00001070run using \refmodule{unittest} test runners:
Edward Loperb3666a32004-09-21 03:00:51 +00001071
1072\begin{verbatim}
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001073import unittest
1074import doctest
1075import my_module_with_doctests, and_another
Edward Loperb3666a32004-09-21 03:00:51 +00001076
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001077suite = unittest.TestSuite()
1078for mod in my_module_with_doctests, and_another:
1079 suite.addTest(doctest.DocTestSuite(mod))
1080runner = unittest.TextTestRunner()
1081runner.run(suite)
Edward Loperb3666a32004-09-21 03:00:51 +00001082\end{verbatim}
1083
Tim Peters9463d872004-09-26 21:05:03 +00001084There are two main functions for creating \class{\refmodule{unittest}.TestSuite}
Tim Peters6a0a64b2004-09-26 02:12:40 +00001085instances from text files and modules with doctests:
1086
Thomas Wouters477c8d52006-05-27 19:21:47 +00001087\begin{funcdesc}{DocFileSuite}{\optional{module_relative}\optional{,
1088 package}\optional{, setUp}\optional{,
1089 tearDown}\optional{, globs}\optional{,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001090 optionflags}\optional{, parser}\optional{,
1091 encoding}}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092
Edward Loperb3666a32004-09-21 03:00:51 +00001093 Convert doctest tests from one or more text files to a
1094 \class{\refmodule{unittest}.TestSuite}.
1095
Tim Peters9463d872004-09-26 21:05:03 +00001096 The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
1097 unittest framework and runs the interactive examples in each file. If an
1098 example in any file fails, then the synthesized unit test fails, and a
1099 \exception{failureException} exception is raised showing the name of the
1100 file containing the test and a (sometimes approximate) line number.
Edward Loperb3666a32004-09-21 03:00:51 +00001101
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001102 Pass one or more paths (as strings) to text files to be examined.
Edward Loperb3666a32004-09-21 03:00:51 +00001103
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001104 Options may be provided as keyword arguments:
1105
1106 Optional argument \var{module_relative} specifies how
Raymond Hettingerc90ea822004-09-25 08:09:23 +00001107 the filenames in \var{paths} should be interpreted:
Edward Loperb3666a32004-09-21 03:00:51 +00001108
1109 \begin{itemize}
1110 \item If \var{module_relative} is \code{True} (the default), then
Tim Petersb2b26ac2004-09-25 01:51:49 +00001111 each filename specifies an OS-independent module-relative
Edward Loperb3666a32004-09-21 03:00:51 +00001112 path. By default, this path is relative to the calling
1113 module's directory; but if the \var{package} argument is
1114 specified, then it is relative to that package. To ensure
Tim Petersb2b26ac2004-09-25 01:51:49 +00001115 OS-independence, each filename should use \code{/} characters
Edward Loperb3666a32004-09-21 03:00:51 +00001116 to separate path segments, and may not be an absolute path
1117 (i.e., it may not begin with \code{/}).
1118 \item If \var{module_relative} is \code{False}, then each filename
Tim Petersb2b26ac2004-09-25 01:51:49 +00001119 specifies an OS-specific path. The path may be absolute or
Edward Loperb3666a32004-09-21 03:00:51 +00001120 relative; relative paths are resolved with respect to the
1121 current working directory.
1122 \end{itemize}
1123
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001124 Optional argument \var{package} is a Python package or the name
Edward Loperb3666a32004-09-21 03:00:51 +00001125 of a Python package whose directory should be used as the base
1126 directory for module-relative filenames. If no package is
1127 specified, then the calling module's directory is used as the base
1128 directory for module-relative filenames. It is an error to specify
1129 \var{package} if \var{module_relative} is \code{False}.
1130
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001131 Optional argument \var{setUp} specifies a set-up function for
Edward Loperb3666a32004-09-21 03:00:51 +00001132 the test suite. This is called before running the tests in each
1133 file. The \var{setUp} function will be passed a \class{DocTest}
1134 object. The setUp function can access the test globals as the
1135 \var{globs} attribute of the test passed.
1136
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001137 Optional argument \var{tearDown} specifies a tear-down function
Edward Loperb3666a32004-09-21 03:00:51 +00001138 for the test suite. This is called after running the tests in each
1139 file. The \var{tearDown} function will be passed a \class{DocTest}
1140 object. The setUp function can access the test globals as the
1141 \var{globs} attribute of the test passed.
1142
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001143 Optional argument \var{globs} is a dictionary containing the
Edward Loperb3666a32004-09-21 03:00:51 +00001144 initial global variables for the tests. A new copy of this
1145 dictionary is created for each test. By default, \var{globs} is
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001146 a new empty dictionary.
Edward Loperb3666a32004-09-21 03:00:51 +00001147
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001148 Optional argument \var{optionflags} specifies the default
1149 doctest options for the tests, created by or-ing together
1150 individual option flags. See section~\ref{doctest-options}.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001151 See function \function{set_unittest_reportflags()} below for
1152 a better way to set reporting options.
Edward Loperb3666a32004-09-21 03:00:51 +00001153
Edward Lopera4c6a852004-09-27 04:08:20 +00001154 Optional argument \var{parser} specifies a \class{DocTestParser} (or
1155 subclass) that should be used to extract tests from the files. It
1156 defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
1157
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001158 Optional argument \var{encoding} specifies an encoding that should
1159 be used to convert the file to unicode.
1160
Edward Loperb3666a32004-09-21 03:00:51 +00001161 \versionadded{2.4}
Fred Drake7c404a42004-12-21 23:46:34 +00001162
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163 \versionchanged[The global \code{__file__} was added to the
Fred Drake7c404a42004-12-21 23:46:34 +00001164 globals provided to doctests loaded from a text file using
Thomas Wouters477c8d52006-05-27 19:21:47 +00001165 \function{DocFileSuite()}]{2.5}
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001166
1167 \versionchanged[The parameter \var{encoding} was added]{2.5}
1168
Edward Loperb3666a32004-09-21 03:00:51 +00001169\end{funcdesc}
1170
1171\begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
1172 globs}\optional{, extraglobs}\optional{,
1173 test_finder}\optional{, setUp}\optional{,
1174 tearDown}\optional{, checker}}
1175 Convert doctest tests for a module to a
1176 \class{\refmodule{unittest}.TestSuite}.
1177
Tim Peters9463d872004-09-26 21:05:03 +00001178 The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
1179 unittest framework and runs each doctest in the module. If any of the
1180 doctests fail, then the synthesized unit test fails, and a
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001181 \exception{failureException} exception is raised showing the name of the
1182 file containing the test and a (sometimes approximate) line number.
Edward Loperb3666a32004-09-21 03:00:51 +00001183
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001184 Optional argument \var{module} provides the module to be tested. It
Edward Loperb3666a32004-09-21 03:00:51 +00001185 can be a module object or a (possibly dotted) module name. If not
1186 specified, the module calling this function is used.
1187
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001188 Optional argument \var{globs} is a dictionary containing the
Edward Loperb3666a32004-09-21 03:00:51 +00001189 initial global variables for the tests. A new copy of this
1190 dictionary is created for each test. By default, \var{globs} is
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001191 a new empty dictionary.
Edward Loperb3666a32004-09-21 03:00:51 +00001192
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001193 Optional argument \var{extraglobs} specifies an extra set of
Edward Loperb3666a32004-09-21 03:00:51 +00001194 global variables, which is merged into \var{globs}. By default, no
1195 extra globals are used.
1196
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001197 Optional argument \var{test_finder} is the \class{DocTestFinder}
Edward Loperb3666a32004-09-21 03:00:51 +00001198 object (or a drop-in replacement) that is used to extract doctests
1199 from the module.
1200
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001201 Optional arguments \var{setUp}, \var{tearDown}, and \var{optionflags}
1202 are the same as for function \function{DocFileSuite()} above.
Edward Loperb3666a32004-09-21 03:00:51 +00001203
1204 \versionadded{2.3}
Tim Peters6a0a64b2004-09-26 02:12:40 +00001205
Edward Loperb3666a32004-09-21 03:00:51 +00001206 \versionchanged[The parameters \var{globs}, \var{extraglobs},
1207 \var{test_finder}, \var{setUp}, \var{tearDown}, and
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001208 \var{optionflags} were added; this function now uses the same search
1209 technique as \function{testmod()}]{2.4}
Edward Loperb3666a32004-09-21 03:00:51 +00001210\end{funcdesc}
1211
Tim Peters6a0a64b2004-09-26 02:12:40 +00001212Under the covers, \function{DocTestSuite()} creates a
Tim Peters9463d872004-09-26 21:05:03 +00001213\class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocTestCase}
1214instances, and \class{DocTestCase} is a subclass of
1215\class{\refmodule{unittest}.TestCase}. \class{DocTestCase} isn't documented
1216here (it's an internal detail), but studying its code can answer questions
1217about the exact details of \refmodule{unittest} integration.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001218
Tim Peters9463d872004-09-26 21:05:03 +00001219Similarly, \function{DocFileSuite()} creates a
1220\class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocFileCase}
1221instances, and \class{DocFileCase} is a subclass of \class{DocTestCase}.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001222
Tim Peters9463d872004-09-26 21:05:03 +00001223So both ways of creating a \class{\refmodule{unittest}.TestSuite} run
1224instances of \class{DocTestCase}. This is important for a subtle reason:
1225when you run \refmodule{doctest} functions yourself, you can control the
1226\refmodule{doctest} options in use directly, by passing option flags to
1227\refmodule{doctest} functions. However, if you're writing a
1228\refmodule{unittest} framework, \refmodule{unittest} ultimately controls
1229when and how tests get run. The framework author typically wants to
1230control \refmodule{doctest} reporting options (perhaps, e.g., specified by
1231command line options), but there's no way to pass options through
1232\refmodule{unittest} to \refmodule{doctest} test runners.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001233
Tim Peters9463d872004-09-26 21:05:03 +00001234For this reason, \refmodule{doctest} also supports a notion of
1235\refmodule{doctest} reporting flags specific to \refmodule{unittest}
1236support, via this function:
Tim Peters6a0a64b2004-09-26 02:12:40 +00001237
1238\begin{funcdesc}{set_unittest_reportflags}{flags}
Tim Peters9463d872004-09-26 21:05:03 +00001239 Set the \refmodule{doctest} reporting flags to use.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001240
1241 Argument \var{flags} or's together option flags. See
1242 section~\ref{doctest-options}. Only "reporting flags" can be used.
1243
Tim Peters9463d872004-09-26 21:05:03 +00001244 This is a module-global setting, and affects all future doctests run by
1245 module \refmodule{unittest}: the \method{runTest()} method of
1246 \class{DocTestCase} looks at the option flags specified for the test case
1247 when the \class{DocTestCase} instance was constructed. If no reporting
1248 flags were specified (which is the typical and expected case),
1249 \refmodule{doctest}'s \refmodule{unittest} reporting flags are or'ed into
1250 the option flags, and the option flags so augmented are passed to the
Tim Peters6a0a64b2004-09-26 02:12:40 +00001251 \class{DocTestRunner} instance created to run the doctest. If any
Tim Peters9463d872004-09-26 21:05:03 +00001252 reporting flags were specified when the \class{DocTestCase} instance was
1253 constructed, \refmodule{doctest}'s \refmodule{unittest} reporting flags
Tim Peters6a0a64b2004-09-26 02:12:40 +00001254 are ignored.
1255
Tim Peters9463d872004-09-26 21:05:03 +00001256 The value of the \refmodule{unittest} reporting flags in effect before the
Tim Peters6a0a64b2004-09-26 02:12:40 +00001257 function was called is returned by the function.
1258
1259 \versionadded{2.4}
1260\end{funcdesc}
1261
1262
Edward Loperb3666a32004-09-21 03:00:51 +00001263\subsection{Advanced API\label{doctest-advanced-api}}
1264
1265The basic API is a simple wrapper that's intended to make doctest easy
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001266to use. It is fairly flexible, and should meet most users' needs;
1267however, if you require more fine-grained control over testing, or
Edward Loperb3666a32004-09-21 03:00:51 +00001268wish to extend doctest's capabilities, then you should use the
1269advanced API.
1270
1271The advanced API revolves around two container classes, which are used
1272to store the interactive examples extracted from doctest cases:
1273
1274\begin{itemize}
1275\item \class{Example}: A single python statement, paired with its
1276 expected output.
1277\item \class{DocTest}: A collection of \class{Example}s, typically
1278 extracted from a single docstring or text file.
1279\end{itemize}
1280
1281Additional processing classes are defined to find, parse, and run, and
1282check doctest examples:
1283
1284\begin{itemize}
1285\item \class{DocTestFinder}: Finds all docstrings in a given module,
1286 and uses a \class{DocTestParser} to create a \class{DocTest}
1287 from every docstring that contains interactive examples.
1288\item \class{DocTestParser}: Creates a \class{DocTest} object from
1289 a string (such as an object's docstring).
1290\item \class{DocTestRunner}: Executes the examples in a
1291 \class{DocTest}, and uses an \class{OutputChecker} to verify
1292 their output.
1293\item \class{OutputChecker}: Compares the actual output from a
1294 doctest example with the expected output, and decides whether
1295 they match.
1296\end{itemize}
1297
Tim Peters3f791252004-09-25 03:50:35 +00001298The relationships among these processing classes are summarized in the
Edward Loperb3666a32004-09-21 03:00:51 +00001299following diagram:
1300
1301\begin{verbatim}
1302 list of:
1303+------+ +---------+
1304|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1305+------+ | ^ +---------+ | ^ (printed)
1306 | | | Example | | |
Tim Peters3f791252004-09-25 03:50:35 +00001307 v | | ... | v |
Edward Loperb3666a32004-09-21 03:00:51 +00001308 DocTestParser | Example | OutputChecker
1309 +---------+
1310\end{verbatim}
1311
1312\subsubsection{DocTest Objects\label{doctest-DocTest}}
1313\begin{classdesc}{DocTest}{examples, globs, name, filename, lineno,
1314 docstring}
1315 A collection of doctest examples that should be run in a single
1316 namespace. The constructor arguments are used to initialize the
1317 member variables of the same names.
1318 \versionadded{2.4}
1319\end{classdesc}
1320
1321\class{DocTest} defines the following member variables. They are
1322initialized by the constructor, and should not be modified directly.
1323
1324\begin{memberdesc}{examples}
1325 A list of \class{Example} objects encoding the individual
1326 interactive Python examples that should be run by this test.
1327\end{memberdesc}
1328
1329\begin{memberdesc}{globs}
1330 The namespace (aka globals) that the examples should be run in.
1331 This is a dictionary mapping names to values. Any changes to the
1332 namespace made by the examples (such as binding new variables)
1333 will be reflected in \member{globs} after the test is run.
1334\end{memberdesc}
1335
1336\begin{memberdesc}{name}
1337 A string name identifying the \class{DocTest}. Typically, this is
1338 the name of the object or file that the test was extracted from.
1339\end{memberdesc}
1340
1341\begin{memberdesc}{filename}
1342 The name of the file that this \class{DocTest} was extracted from;
1343 or \code{None} if the filename is unknown, or if the
1344 \class{DocTest} was not extracted from a file.
1345\end{memberdesc}
1346
1347\begin{memberdesc}{lineno}
1348 The line number within \member{filename} where this
1349 \class{DocTest} begins, or \code{None} if the line number is
1350 unavailable. This line number is zero-based with respect to the
1351 beginning of the file.
1352\end{memberdesc}
1353
1354\begin{memberdesc}{docstring}
1355 The string that the test was extracted from, or `None` if the
1356 string is unavailable, or if the test was not extracted from a
1357 string.
1358\end{memberdesc}
1359
1360\subsubsection{Example Objects\label{doctest-Example}}
1361\begin{classdesc}{Example}{source, want\optional{,
1362 exc_msg}\optional{, lineno}\optional{,
1363 indent}\optional{, options}}
1364 A single interactive example, consisting of a Python statement and
1365 its expected output. The constructor arguments are used to
1366 initialize the member variables of the same names.
1367 \versionadded{2.4}
1368\end{classdesc}
1369
1370\class{Example} defines the following member variables. They are
1371initialized by the constructor, and should not be modified directly.
1372
1373\begin{memberdesc}{source}
1374 A string containing the example's source code. This source code
1375 consists of a single Python statement, and always ends with a
1376 newline; the constructor adds a newline when necessary.
1377\end{memberdesc}
1378
1379\begin{memberdesc}{want}
1380 The expected output from running the example's source code (either
1381 from stdout, or a traceback in case of exception). \member{want}
1382 ends with a newline unless no output is expected, in which case
1383 it's an empty string. The constructor adds a newline when
1384 necessary.
1385\end{memberdesc}
1386
1387\begin{memberdesc}{exc_msg}
1388 The exception message generated by the example, if the example is
1389 expected to generate an exception; or \code{None} if it is not
1390 expected to generate an exception. This exception message is
1391 compared against the return value of
1392 \function{traceback.format_exception_only()}. \member{exc_msg}
1393 ends with a newline unless it's \code{None}. The constructor adds
1394 a newline if needed.
1395\end{memberdesc}
1396
1397\begin{memberdesc}{lineno}
1398 The line number within the string containing this example where
1399 the example begins. This line number is zero-based with respect
1400 to the beginning of the containing string.
1401\end{memberdesc}
1402
1403\begin{memberdesc}{indent}
Tim Peters3f791252004-09-25 03:50:35 +00001404 The example's indentation in the containing string, i.e., the
Raymond Hettinger68804312005-01-01 00:28:46 +00001405 number of space characters that precede the example's first
Edward Loperb3666a32004-09-21 03:00:51 +00001406 prompt.
1407\end{memberdesc}
1408
1409\begin{memberdesc}{options}
1410 A dictionary mapping from option flags to \code{True} or
1411 \code{False}, which is used to override default options for this
1412 example. Any option flags not contained in this dictionary are
1413 left at their default value (as specified by the
Tim Peters3f791252004-09-25 03:50:35 +00001414 \class{DocTestRunner}'s \member{optionflags}).
1415 By default, no options are set.
Edward Loperb3666a32004-09-21 03:00:51 +00001416\end{memberdesc}
1417
1418\subsubsection{DocTestFinder objects\label{doctest-DocTestFinder}}
1419\begin{classdesc}{DocTestFinder}{\optional{verbose}\optional{,
1420 parser}\optional{, recurse}\optional{,
1421 exclude_empty}}
1422 A processing class used to extract the \class{DocTest}s that are
1423 relevant to a given object, from its docstring and the docstrings
1424 of its contained objects. \class{DocTest}s can currently be
1425 extracted from the following object types: modules, functions,
1426 classes, methods, staticmethods, classmethods, and properties.
1427
1428 The optional argument \var{verbose} can be used to display the
1429 objects searched by the finder. It defaults to \code{False} (no
1430 output).
1431
1432 The optional argument \var{parser} specifies the
1433 \class{DocTestParser} object (or a drop-in replacement) that is
1434 used to extract doctests from docstrings.
1435
1436 If the optional argument \var{recurse} is false, then
1437 \method{DocTestFinder.find()} will only examine the given object,
1438 and not any contained objects.
1439
1440 If the optional argument \var{exclude_empty} is false, then
1441 \method{DocTestFinder.find()} will include tests for objects with
1442 empty docstrings.
1443
1444 \versionadded{2.4}
1445\end{classdesc}
1446
1447\class{DocTestFinder} defines the following method:
1448
Tim Peters7a082142004-09-25 00:10:53 +00001449\begin{methoddesc}{find}{obj\optional{, name}\optional{,
Edward Loperb3666a32004-09-21 03:00:51 +00001450 module}\optional{, globs}\optional{, extraglobs}}
1451 Return a list of the \class{DocTest}s that are defined by
1452 \var{obj}'s docstring, or by any of its contained objects'
1453 docstrings.
1454
1455 The optional argument \var{name} specifies the object's name; this
1456 name will be used to construct names for the returned
1457 \class{DocTest}s. If \var{name} is not specified, then
Tim Peters3f791252004-09-25 03:50:35 +00001458 \code{\var{obj}.__name__} is used.
Edward Loperb3666a32004-09-21 03:00:51 +00001459
1460 The optional parameter \var{module} is the module that contains
1461 the given object. If the module is not specified or is None, then
1462 the test finder will attempt to automatically determine the
1463 correct module. The object's module is used:
1464
1465 \begin{itemize}
Tim Peters3f791252004-09-25 03:50:35 +00001466 \item As a default namespace, if \var{globs} is not specified.
Edward Loperb3666a32004-09-21 03:00:51 +00001467 \item To prevent the DocTestFinder from extracting DocTests
1468 from objects that are imported from other modules. (Contained
1469 objects with modules other than \var{module} are ignored.)
1470 \item To find the name of the file containing the object.
1471 \item To help find the line number of the object within its file.
1472 \end{itemize}
1473
1474 If \var{module} is \code{False}, no attempt to find the module
1475 will be made. This is obscure, of use mostly in testing doctest
1476 itself: if \var{module} is \code{False}, or is \code{None} but
1477 cannot be found automatically, then all objects are considered to
1478 belong to the (non-existent) module, so all contained objects will
1479 (recursively) be searched for doctests.
1480
1481 The globals for each \class{DocTest} is formed by combining
1482 \var{globs} and \var{extraglobs} (bindings in \var{extraglobs}
Tim Peters3f791252004-09-25 03:50:35 +00001483 override bindings in \var{globs}). A new shallow copy of the globals
Edward Loperb3666a32004-09-21 03:00:51 +00001484 dictionary is created for each \class{DocTest}. If \var{globs} is
1485 not specified, then it defaults to the module's \var{__dict__}, if
1486 specified, or \code{\{\}} otherwise. If \var{extraglobs} is not
1487 specified, then it defaults to \code{\{\}}.
1488\end{methoddesc}
1489
1490\subsubsection{DocTestParser objects\label{doctest-DocTestParser}}
1491\begin{classdesc}{DocTestParser}{}
1492 A processing class used to extract interactive examples from a
1493 string, and use them to create a \class{DocTest} object.
1494 \versionadded{2.4}
1495\end{classdesc}
1496
1497\class{DocTestParser} defines the following methods:
1498
1499\begin{methoddesc}{get_doctest}{string, globs, name, filename, lineno}
1500 Extract all doctest examples from the given string, and collect
1501 them into a \class{DocTest} object.
1502
1503 \var{globs}, \var{name}, \var{filename}, and \var{lineno} are
1504 attributes for the new \class{DocTest} object. See the
1505 documentation for \class{DocTest} for more information.
1506\end{methoddesc}
1507
1508\begin{methoddesc}{get_examples}{string\optional{, name}}
1509 Extract all doctest examples from the given string, and return
1510 them as a list of \class{Example} objects. Line numbers are
1511 0-based. The optional argument \var{name} is a name identifying
1512 this string, and is only used for error messages.
1513\end{methoddesc}
1514
1515\begin{methoddesc}{parse}{string\optional{, name}}
1516 Divide the given string into examples and intervening text, and
1517 return them as a list of alternating \class{Example}s and strings.
1518 Line numbers for the \class{Example}s are 0-based. The optional
1519 argument \var{name} is a name identifying this string, and is only
1520 used for error messages.
1521\end{methoddesc}
1522
1523\subsubsection{DocTestRunner objects\label{doctest-DocTestRunner}}
1524\begin{classdesc}{DocTestRunner}{\optional{checker}\optional{,
1525 verbose}\optional{, optionflags}}
1526 A processing class used to execute and verify the interactive
1527 examples in a \class{DocTest}.
1528
1529 The comparison between expected outputs and actual outputs is done
1530 by an \class{OutputChecker}. This comparison may be customized
1531 with a number of option flags; see section~\ref{doctest-options}
1532 for more information. If the option flags are insufficient, then
1533 the comparison may also be customized by passing a subclass of
1534 \class{OutputChecker} to the constructor.
1535
1536 The test runner's display output can be controlled in two ways.
1537 First, an output function can be passed to
1538 \method{TestRunner.run()}; this function will be called with
1539 strings that should be displayed. It defaults to
1540 \code{sys.stdout.write}. If capturing the output is not
1541 sufficient, then the display output can be also customized by
1542 subclassing DocTestRunner, and overriding the methods
1543 \method{report_start}, \method{report_success},
1544 \method{report_unexpected_exception}, and \method{report_failure}.
1545
1546 The optional keyword argument \var{checker} specifies the
1547 \class{OutputChecker} object (or drop-in replacement) that should
1548 be used to compare the expected outputs to the actual outputs of
1549 doctest examples.
1550
1551 The optional keyword argument \var{verbose} controls the
1552 \class{DocTestRunner}'s verbosity. If \var{verbose} is
1553 \code{True}, then information is printed about each example, as it
1554 is run. If \var{verbose} is \code{False}, then only failures are
1555 printed. If \var{verbose} is unspecified, or \code{None}, then
1556 verbose output is used iff the command-line switch \programopt{-v}
1557 is used.
1558
1559 The optional keyword argument \var{optionflags} can be used to
1560 control how the test runner compares expected output to actual
1561 output, and how it displays failures. For more information, see
1562 section~\ref{doctest-options}.
1563
1564 \versionadded{2.4}
1565\end{classdesc}
1566
1567\class{DocTestParser} defines the following methods:
1568
1569\begin{methoddesc}{report_start}{out, test, example}
1570 Report that the test runner is about to process the given example.
1571 This method is provided to allow subclasses of
1572 \class{DocTestRunner} to customize their output; it should not be
1573 called directly.
1574
1575 \var{example} is the example about to be processed. \var{test} is
1576 the test containing \var{example}. \var{out} is the output
1577 function that was passed to \method{DocTestRunner.run()}.
1578\end{methoddesc}
1579
1580\begin{methoddesc}{report_success}{out, test, example, got}
1581 Report that the given example ran successfully. This method is
1582 provided to allow subclasses of \class{DocTestRunner} to customize
1583 their output; it should not be called directly.
1584
1585 \var{example} is the example about to be processed. \var{got} is
1586 the actual output from the example. \var{test} is the test
1587 containing \var{example}. \var{out} is the output function that
1588 was passed to \method{DocTestRunner.run()}.
1589\end{methoddesc}
1590
1591\begin{methoddesc}{report_failure}{out, test, example, got}
1592 Report that the given example failed. This method is provided to
1593 allow subclasses of \class{DocTestRunner} to customize their
1594 output; it should not be called directly.
1595
1596 \var{example} is the example about to be processed. \var{got} is
1597 the actual output from the example. \var{test} is the test
1598 containing \var{example}. \var{out} is the output function that
1599 was passed to \method{DocTestRunner.run()}.
1600\end{methoddesc}
1601
1602\begin{methoddesc}{report_unexpected_exception}{out, test, example, exc_info}
1603 Report that the given example raised an unexpected exception.
1604 This method is provided to allow subclasses of
1605 \class{DocTestRunner} to customize their output; it should not be
1606 called directly.
1607
1608 \var{example} is the example about to be processed.
1609 \var{exc_info} is a tuple containing information about the
1610 unexpected exception (as returned by \function{sys.exc_info()}).
1611 \var{test} is the test containing \var{example}. \var{out} is the
1612 output function that was passed to \method{DocTestRunner.run()}.
1613\end{methoddesc}
1614
1615\begin{methoddesc}{run}{test\optional{, compileflags}\optional{,
1616 out}\optional{, clear_globs}}
1617 Run the examples in \var{test} (a \class{DocTest} object), and
1618 display the results using the writer function \var{out}.
1619
1620 The examples are run in the namespace \code{test.globs}. If
1621 \var{clear_globs} is true (the default), then this namespace will
1622 be cleared after the test runs, to help with garbage collection.
1623 If you would like to examine the namespace after the test
1624 completes, then use \var{clear_globs=False}.
1625
1626 \var{compileflags} gives the set of flags that should be used by
1627 the Python compiler when running the examples. If not specified,
1628 then it will default to the set of future-import flags that apply
1629 to \var{globs}.
1630
1631 The output of each example is checked using the
1632 \class{DocTestRunner}'s output checker, and the results are
1633 formatted by the \method{DocTestRunner.report_*} methods.
1634\end{methoddesc}
1635
1636\begin{methoddesc}{summarize}{\optional{verbose}}
1637 Print a summary of all the test cases that have been run by this
1638 DocTestRunner, and return a tuple \samp{(\var{failure_count},
1639 \var{test_count})}.
1640
1641 The optional \var{verbose} argument controls how detailed the
1642 summary is. If the verbosity is not specified, then the
1643 \class{DocTestRunner}'s verbosity is used.
1644\end{methoddesc}
1645
1646\subsubsection{OutputChecker objects\label{doctest-OutputChecker}}
1647
1648\begin{classdesc}{OutputChecker}{}
1649 A class used to check the whether the actual output from a doctest
1650 example matches the expected output. \class{OutputChecker}
1651 defines two methods: \method{check_output}, which compares a given
1652 pair of outputs, and returns true if they match; and
1653 \method{output_difference}, which returns a string describing the
1654 differences between two outputs.
1655 \versionadded{2.4}
1656\end{classdesc}
1657
1658\class{OutputChecker} defines the following methods:
1659
1660\begin{methoddesc}{check_output}{want, got, optionflags}
1661 Return \code{True} iff the actual output from an example
1662 (\var{got}) matches the expected output (\var{want}). These
1663 strings are always considered to match if they are identical; but
1664 depending on what option flags the test runner is using, several
1665 non-exact match types are also possible. See
1666 section~\ref{doctest-options} for more information about option
1667 flags.
1668\end{methoddesc}
1669
1670\begin{methoddesc}{output_difference}{example, got, optionflags}
1671 Return a string describing the differences between the expected
1672 output for a given example (\var{example}) and the actual output
1673 (\var{got}). \var{optionflags} is the set of option flags used to
1674 compare \var{want} and \var{got}.
1675\end{methoddesc}
1676
1677\subsection{Debugging\label{doctest-debugging}}
1678
Tim Peters05b05fe2004-09-26 05:09:59 +00001679Doctest provides several mechanisms for debugging doctest examples:
Edward Loperb3666a32004-09-21 03:00:51 +00001680
Tim Peters05b05fe2004-09-26 05:09:59 +00001681\begin{itemize}
1682\item Several functions convert doctests to executable Python
1683 programs, which can be run under the Python debugger, \refmodule{pdb}.
Edward Loperb3666a32004-09-21 03:00:51 +00001684\item The \class{DebugRunner} class is a subclass of
1685 \class{DocTestRunner} that raises an exception for the first
1686 failing example, containing information about that example.
1687 This information can be used to perform post-mortem debugging on
1688 the example.
Tim Peters9463d872004-09-26 21:05:03 +00001689\item The \refmodule{unittest} cases generated by \function{DocTestSuite()}
Tim Peters05b05fe2004-09-26 05:09:59 +00001690 support the \method{debug()} method defined by
Tim Peters9463d872004-09-26 21:05:03 +00001691 \class{\refmodule{unittest}.TestCase}.
1692\item You can add a call to \function{\refmodule{pdb}.set_trace()} in a
1693 doctest example, and you'll drop into the Python debugger when that
Tim Peters05b05fe2004-09-26 05:09:59 +00001694 line is executed. Then you can inspect current values of variables,
1695 and so on. For example, suppose \file{a.py} contains just this
1696 module docstring:
Edward Loperb3666a32004-09-21 03:00:51 +00001697
Tim Peters05b05fe2004-09-26 05:09:59 +00001698\begin{verbatim}
1699"""
1700>>> def f(x):
1701... g(x*2)
1702>>> def g(x):
1703... print x+3
1704... import pdb; pdb.set_trace()
1705>>> f(3)
17069
1707"""
1708\end{verbatim}
Edward Loperb3666a32004-09-21 03:00:51 +00001709
Tim Peters05b05fe2004-09-26 05:09:59 +00001710 Then an interactive Python session may look like this:
Edward Loperb3666a32004-09-21 03:00:51 +00001711
Tim Peters05b05fe2004-09-26 05:09:59 +00001712\begin{verbatim}
1713>>> import a, doctest
1714>>> doctest.testmod(a)
1715--Return--
1716> <doctest a[1]>(3)g()->None
1717-> import pdb; pdb.set_trace()
1718(Pdb) list
1719 1 def g(x):
1720 2 print x+3
1721 3 -> import pdb; pdb.set_trace()
1722[EOF]
1723(Pdb) print x
17246
1725(Pdb) step
1726--Return--
1727> <doctest a[0]>(2)f()->None
1728-> g(x*2)
1729(Pdb) list
1730 1 def f(x):
1731 2 -> g(x*2)
1732[EOF]
1733(Pdb) print x
17343
1735(Pdb) step
1736--Return--
1737> <doctest a[2]>(1)?()->None
1738-> f(3)
1739(Pdb) cont
1740(0, 3)
1741>>>
1742\end{verbatim}
1743
Guido van Rossumd8faa362007-04-27 19:54:29 +00001744 \versionchanged[The ability to use \function{\refmodule{pdb}.set_trace()}
Tim Peters9463d872004-09-26 21:05:03 +00001745 usefully inside doctests was added]{2.4}
Tim Peters05b05fe2004-09-26 05:09:59 +00001746\end{itemize}
1747
1748Functions that convert doctests to Python code, and possibly run
1749the synthesized code under the debugger:
1750
1751\begin{funcdesc}{script_from_examples}{s}
1752 Convert text with examples to a script.
1753
1754 Argument \var{s} is a string containing doctest examples. The string
1755 is converted to a Python script, where doctest examples in \var{s}
1756 are converted to regular code, and everything else is converted to
1757 Python comments. The generated script is returned as a string.
Tim Peters36ee8ce2004-09-26 21:51:25 +00001758 For example,
Tim Peters05b05fe2004-09-26 05:09:59 +00001759
1760 \begin{verbatim}
Tim Peters36ee8ce2004-09-26 21:51:25 +00001761 import doctest
1762 print doctest.script_from_examples(r"""
1763 Set x and y to 1 and 2.
1764 >>> x, y = 1, 2
1765
1766 Print their sum:
1767 >>> print x+y
1768 3
1769 """)
Tim Peters05b05fe2004-09-26 05:09:59 +00001770 \end{verbatim}
1771
Tim Peters36ee8ce2004-09-26 21:51:25 +00001772 displays:
1773
1774 \begin{verbatim}
1775 # Set x and y to 1 and 2.
1776 x, y = 1, 2
1777 #
1778 # Print their sum:
1779 print x+y
1780 # Expected:
1781 ## 3
1782 \end{verbatim}
1783
1784 This function is used internally by other functions (see below), but
1785 can also be useful when you want to transform an interactive Python
1786 session into a Python script.
1787
Tim Peters05b05fe2004-09-26 05:09:59 +00001788 \versionadded{2.4}
1789\end{funcdesc}
1790
1791\begin{funcdesc}{testsource}{module, name}
1792 Convert the doctest for an object to a script.
1793
1794 Argument \var{module} is a module object, or dotted name of a module,
1795 containing the object whose doctests are of interest. Argument
1796 \var{name} is the name (within the module) of the object with the
1797 doctests of interest. The result is a string, containing the
1798 object's docstring converted to a Python script, as described for
1799 \function{script_from_examples()} above. For example, if module
1800 \file{a.py} contains a top-level function \function{f()}, then
1801
Edward Loper456ff912004-09-27 03:30:44 +00001802\begin{verbatim}
1803import a, doctest
1804print doctest.testsource(a, "a.f")
1805\end{verbatim}
Tim Peters05b05fe2004-09-26 05:09:59 +00001806
1807 prints a script version of function \function{f()}'s docstring,
1808 with doctests converted to code, and the rest placed in comments.
1809
Edward Loperb3666a32004-09-21 03:00:51 +00001810 \versionadded{2.3}
1811\end{funcdesc}
1812
Tim Peters05b05fe2004-09-26 05:09:59 +00001813\begin{funcdesc}{debug}{module, name\optional{, pm}}
1814 Debug the doctests for an object.
1815
1816 The \var{module} and \var{name} arguments are the same as for function
1817 \function{testsource()} above. The synthesized Python script for the
1818 named object's docstring is written to a temporary file, and then that
1819 file is run under the control of the Python debugger, \refmodule{pdb}.
1820
1821 A shallow copy of \code{\var{module}.__dict__} is used for both local
1822 and global execution context.
1823
1824 Optional argument \var{pm} controls whether post-mortem debugging is
Tim Peters9463d872004-09-26 21:05:03 +00001825 used. If \var{pm} has a true value, the script file is run directly, and
1826 the debugger gets involved only if the script terminates via raising an
1827 unhandled exception. If it does, then post-mortem debugging is invoked,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001828 via \function{\refmodule{pdb}.post_mortem()}, passing the traceback object
Tim Peters05b05fe2004-09-26 05:09:59 +00001829 from the unhandled exception. If \var{pm} is not specified, or is false,
1830 the script is run under the debugger from the start, via passing an
Guido van Rossumd8faa362007-04-27 19:54:29 +00001831 appropriate \function{execfile()} call to \function{\refmodule{pdb}.run()}.
Tim Peters05b05fe2004-09-26 05:09:59 +00001832
1833 \versionadded{2.3}
1834
1835 \versionchanged[The \var{pm} argument was added]{2.4}
1836\end{funcdesc}
1837
1838\begin{funcdesc}{debug_src}{src\optional{, pm}\optional{, globs}}
1839 Debug the doctests in a string.
1840
1841 This is like function \function{debug()} above, except that
1842 a string containing doctest examples is specified directly, via
1843 the \var{src} argument.
1844
1845 Optional argument \var{pm} has the same meaning as in function
1846 \function{debug()} above.
1847
1848 Optional argument \var{globs} gives a dictionary to use as both
1849 local and global execution context. If not specified, or \code{None},
1850 an empty dictionary is used. If specified, a shallow copy of the
1851 dictionary is used.
1852
1853 \versionadded{2.4}
1854\end{funcdesc}
1855
1856The \class{DebugRunner} class, and the special exceptions it may raise,
1857are of most interest to testing framework authors, and will only be
1858sketched here. See the source code, and especially \class{DebugRunner}'s
1859docstring (which is a doctest!) for more details:
1860
Edward Loperb3666a32004-09-21 03:00:51 +00001861\begin{classdesc}{DebugRunner}{\optional{checker}\optional{,
1862 verbose}\optional{, optionflags}}
1863
1864 A subclass of \class{DocTestRunner} that raises an exception as
1865 soon as a failure is encountered. If an unexpected exception
1866 occurs, an \exception{UnexpectedException} exception is raised,
1867 containing the test, the example, and the original exception. If
1868 the output doesn't match, then a \exception{DocTestFailure}
1869 exception is raised, containing the test, the example, and the
1870 actual output.
1871
1872 For information about the constructor parameters and methods, see
1873 the documentation for \class{DocTestRunner} in
1874 section~\ref{doctest-advanced-api}.
1875\end{classdesc}
1876
Tim Peters05b05fe2004-09-26 05:09:59 +00001877There are two exceptions that may be raised by \class{DebugRunner}
1878instances:
1879
Edward Loperb3666a32004-09-21 03:00:51 +00001880\begin{excclassdesc}{DocTestFailure}{test, example, got}
1881 An exception thrown by \class{DocTestRunner} to signal that a
1882 doctest example's actual output did not match its expected output.
1883 The constructor arguments are used to initialize the member
1884 variables of the same names.
1885\end{excclassdesc}
1886\exception{DocTestFailure} defines the following member variables:
1887\begin{memberdesc}{test}
1888 The \class{DocTest} object that was being run when the example failed.
1889\end{memberdesc}
1890\begin{memberdesc}{example}
1891 The \class{Example} that failed.
1892\end{memberdesc}
1893\begin{memberdesc}{got}
1894 The example's actual output.
1895\end{memberdesc}
1896
Tim Peters05b05fe2004-09-26 05:09:59 +00001897\begin{excclassdesc}{UnexpectedException}{test, example, exc_info}
Edward Loperb3666a32004-09-21 03:00:51 +00001898 An exception thrown by \class{DocTestRunner} to signal that a
1899 doctest example raised an unexpected exception. The constructor
1900 arguments are used to initialize the member variables of the same
1901 names.
1902\end{excclassdesc}
1903\exception{UnexpectedException} defines the following member variables:
1904\begin{memberdesc}{test}
1905 The \class{DocTest} object that was being run when the example failed.
1906\end{memberdesc}
1907\begin{memberdesc}{example}
1908 The \class{Example} that failed.
1909\end{memberdesc}
1910\begin{memberdesc}{exc_info}
1911 A tuple containing information about the unexpected exception, as
1912 returned by \function{sys.exc_info()}.
1913\end{memberdesc}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001914
Edward Loperb3666a32004-09-21 03:00:51 +00001915\subsection{Soapbox\label{doctest-soapbox}}
Tim Peters76882292001-02-17 05:58:44 +00001916
Tim Peters9463d872004-09-26 21:05:03 +00001917As mentioned in the introduction, \refmodule{doctest} has grown to have
Tim Peters3f791252004-09-25 03:50:35 +00001918three primary uses:
Tim Peters76882292001-02-17 05:58:44 +00001919
1920\begin{enumerate}
Edward Loperb3666a32004-09-21 03:00:51 +00001921\item Checking examples in docstrings.
1922\item Regression testing.
Tim Peters3f791252004-09-25 03:50:35 +00001923\item Executable documentation / literate testing.
Fred Drakec1158352001-06-11 14:55:01 +00001924\end{enumerate}
1925
Tim Peters3f791252004-09-25 03:50:35 +00001926These uses have different requirements, and it is important to
Edward Loperb3666a32004-09-21 03:00:51 +00001927distinguish them. In particular, filling your docstrings with obscure
1928test cases makes for bad documentation.
Tim Peters76882292001-02-17 05:58:44 +00001929
Edward Loperb3666a32004-09-21 03:00:51 +00001930When writing a docstring, choose docstring examples with care.
1931There's an art to this that needs to be learned---it may not be
1932natural at first. Examples should add genuine value to the
1933documentation. A good example can often be worth many words.
Fred Drake7a6b4f02003-07-17 16:00:01 +00001934If done with care, the examples will be invaluable for your users, and
1935will pay back the time it takes to collect them many times over as the
1936years go by and things change. I'm still amazed at how often one of
Tim Peters3f791252004-09-25 03:50:35 +00001937my \refmodule{doctest} examples stops working after a "harmless"
Fred Drake7a6b4f02003-07-17 16:00:01 +00001938change.
Tim Peters76882292001-02-17 05:58:44 +00001939
Tim Peters3f791252004-09-25 03:50:35 +00001940Doctest also makes an excellent tool for regression testing, especially if
1941you don't skimp on explanatory text. By interleaving prose and examples,
1942it becomes much easier to keep track of what's actually being tested, and
1943why. When a test fails, good prose can make it much easier to figure out
1944what the problem is, and how it should be fixed. It's true that you could
1945write extensive comments in code-based testing, but few programmers do.
1946Many have found that using doctest approaches instead leads to much clearer
1947tests. Perhaps this is simply because doctest makes writing prose a little
1948easier than writing code, while writing comments in code is a little
1949harder. I think it goes deeper than just that: the natural attitude
1950when writing a doctest-based test is that you want to explain the fine
1951points of your software, and illustrate them with examples. This in
1952turn naturally leads to test files that start with the simplest features,
1953and logically progress to complications and edge cases. A coherent
1954narrative is the result, instead of a collection of isolated functions
1955that test isolated bits of functionality seemingly at random. It's
1956a different attitude, and produces different results, blurring the
1957distinction between testing and explaining.
1958
1959Regression testing is best confined to dedicated objects or files. There
1960are several options for organizing tests:
Edward Loperb3666a32004-09-21 03:00:51 +00001961
1962\begin{itemize}
Tim Peters3f791252004-09-25 03:50:35 +00001963\item Write text files containing test cases as interactive examples,
1964 and test the files using \function{testfile()} or
1965 \function{DocFileSuite()}. This is recommended, although is
1966 easiest to do for new projects, designed from the start to use
1967 doctest.
Edward Loperb3666a32004-09-21 03:00:51 +00001968\item Define functions named \code{_regrtest_\textit{topic}} that
1969 consist of single docstrings, containing test cases for the
1970 named topics. These functions can be included in the same file
1971 as the module, or separated out into a separate test file.
1972\item Define a \code{__test__} dictionary mapping from regression test
1973 topics to docstrings containing test cases.
Edward Loperb3666a32004-09-21 03:00:51 +00001974\end{itemize}