blob: f9a97fa6193e20ffd120a196e34cd05cf3bb8300 [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
Edward Loperb3666a32004-09-21 03:00:51 +0000204For more information on \function{testmod()}, see
205section~\ref{doctest-basic-api}.
206
207\subsection{Simple Usage: Checking Examples in a Text
208 File\label{doctest-simple-testfile}}
209
210Another simple application of doctest is testing interactive examples
211in a text file. This can be done with the \function{testfile()}
212function:
213
214\begin{verbatim}
215import doctest
Tim Peters06cc8472004-09-25 00:49:53 +0000216doctest.testfile("example.txt")
Edward Loperb3666a32004-09-21 03:00:51 +0000217\end{verbatim}
218
Tim Peters06cc8472004-09-25 00:49:53 +0000219That short script executes and verifies any interactive Python
220examples contained in the file \file{example.txt}. The file content
221is treated as if it were a single giant docstring; the file doesn't
222need to contain a Python program! For example, perhaps \file{example.txt}
223contains this:
224
225\begin{verbatim}
226The ``example`` module
227======================
228
229Using ``factorial``
230-------------------
231
232This is an example text file in reStructuredText format. First import
233``factorial`` from the ``example`` module:
234
235 >>> from example import factorial
236
237Now use it:
238
239 >>> factorial(6)
240 120
241\end{verbatim}
242
243Running \code{doctest.testfile("example.txt")} then finds the error
244in this documentation:
245
246\begin{verbatim}
247File "./example.txt", line 14, in example.txt
248Failed example:
249 factorial(6)
250Expected:
251 120
252Got:
253 720
254\end{verbatim}
255
256As with \function{testmod()}, \function{testfile()} won't display anything
257unless an example fails. If an example does fail, then the failing
258example(s) and the cause(s) of the failure(s) are printed to stdout, using
259the same format as \function{testmod()}.
Edward Loperb3666a32004-09-21 03:00:51 +0000260
261By default, \function{testfile()} looks for files in the calling
262module's directory. See section~\ref{doctest-basic-api} for a
263description of the optional arguments that can be used to tell it to
264look for files in other locations.
265
266Like \function{testmod()}, \function{testfile()}'s verbosity can be
267set with the \programopt{-v} command-line switch or with the optional
Tim Peters06cc8472004-09-25 00:49:53 +0000268keyword argument \var{verbose}.
Edward Loperb3666a32004-09-21 03:00:51 +0000269
270For more information on \function{testfile()}, see
271section~\ref{doctest-basic-api}.
272
273\subsection{How It Works\label{doctest-how-it-works}}
274
275This section examines in detail how doctest works: which docstrings it
276looks at, how it finds interactive examples, what execution context it
277uses, how it handles exceptions, and how option flags can be used to
278control its behavior. This is the information that you need to know
279to write doctest examples; for information about actually running
280doctest on these examples, see the following sections.
281
282\subsubsection{Which Docstrings Are Examined?\label{doctest-which-docstrings}}
Tim Peters76882292001-02-17 05:58:44 +0000283
Tim Peters8a3b69c2004-08-12 22:31:25 +0000284The module docstring, and all function, class and method docstrings are
285searched. Objects imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000286
Fred Drake7eb14632001-02-17 17:32:41 +0000287In addition, if \code{M.__test__} exists and "is true", it must be a
288dict, and each entry maps a (string) name to a function object, class
289object, or string. Function and class object docstrings found from
Tim Peters8a3b69c2004-08-12 22:31:25 +0000290\code{M.__test__} are searched, and strings are treated as if they
291were docstrings. In output, a key \code{K} in \code{M.__test__} appears
292with name
Tim Peters76882292001-02-17 05:58:44 +0000293
294\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000295<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000296\end{verbatim}
297
298Any classes found are recursively searched similarly, to test docstrings in
Tim Peters8a3b69c2004-08-12 22:31:25 +0000299their contained methods and nested classes.
300
301\versionchanged[A "private name" concept is deprecated and no longer
Tim Peters26039602004-08-13 01:49:12 +0000302 documented]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000303
Edward Loperb3666a32004-09-21 03:00:51 +0000304\subsubsection{How are Docstring Examples
305 Recognized?\label{doctest-finding-examples}}
Tim Peters76882292001-02-17 05:58:44 +0000306
Edward Loperb3666a32004-09-21 03:00:51 +0000307In most cases a copy-and-paste of an interactive console session works
308fine, but doctest isn't trying to do an exact emulation of any specific
309Python shell. All hard tab characters are expanded to spaces, using
3108-column tab stops. If you don't believe tabs should mean that, too
311bad: don't use hard tabs, or write your own \class{DocTestParser}
312class.
Tim Peters76882292001-02-17 05:58:44 +0000313
Edward Loperb3666a32004-09-21 03:00:51 +0000314\versionchanged[Expanding tabs to spaces is new; previous versions
315 tried to preserve hard tabs, with confusing results]{2.4}
316
317\begin{verbatim}
318>>> # comments are ignored
319>>> x = 12
320>>> x
32112
322>>> if x == 13:
323... print "yes"
324... else:
325... print "no"
326... print "NO"
327... print "NO!!!"
328...
329no
330NO
331NO!!!
332>>>
333\end{verbatim}
334
335Any expected output must immediately follow the final
Thomas Wouters477c8d52006-05-27 19:21:47 +0000336\code{'>>>~'} or \code{'...~'} line containing the code, and
337the expected output (if any) extends to the next \code{'>>>~'}
Edward Loperb3666a32004-09-21 03:00:51 +0000338or all-whitespace line.
339
340The fine print:
341
342\begin{itemize}
343
344\item Expected output cannot contain an all-whitespace line, since such a
345 line is taken to signal the end of expected output. If expected
346 output does contain a blank line, put \code{<BLANKLINE>} in your
347 doctest example each place a blank line is expected.
348 \versionchanged[\code{<BLANKLINE>} was added; there was no way to
349 use expected output containing empty lines in
350 previous versions]{2.4}
351
352\item Output to stdout is captured, but not output to stderr (exception
353 tracebacks are captured via a different means).
354
355\item If you continue a line via backslashing in an interactive session,
356 or for any other reason use a backslash, you should use a raw
357 docstring, which will preserve your backslashes exactly as you type
358 them:
359
360\begin{verbatim}
361>>> def f(x):
362... r'''Backslashes in a raw docstring: m\n'''
363>>> print f.__doc__
364Backslashes in a raw docstring: m\n
365\end{verbatim}
366
367 Otherwise, the backslash will be interpreted as part of the string.
Tim Peters39c5de02004-09-25 01:22:29 +0000368 For example, the "{\textbackslash}" above would be interpreted as a
369 newline character. Alternatively, you can double each backslash in the
Edward Loperb3666a32004-09-21 03:00:51 +0000370 doctest version (and not use a raw string):
371
372\begin{verbatim}
373>>> def f(x):
374... '''Backslashes in a raw docstring: m\\n'''
375>>> print f.__doc__
376Backslashes in a raw docstring: m\n
377\end{verbatim}
378
379\item The starting column doesn't matter:
380
381\begin{verbatim}
382 >>> assert "Easy!"
383 >>> import math
384 >>> math.floor(1.9)
385 1.0
386\end{verbatim}
387
388and as many leading whitespace characters are stripped from the
Thomas Wouters477c8d52006-05-27 19:21:47 +0000389expected output as appeared in the initial \code{'>>>~'} line
Edward Loperb3666a32004-09-21 03:00:51 +0000390that started the example.
391\end{itemize}
392
393\subsubsection{What's the Execution Context?\label{doctest-execution-context}}
394
Tim Peters9463d872004-09-26 21:05:03 +0000395By default, each time \refmodule{doctest} finds a docstring to test, it
Tim Peters41a65ea2004-08-13 03:55:05 +0000396uses a \emph{shallow copy} of \module{M}'s globals, so that running tests
Tim Peters76882292001-02-17 05:58:44 +0000397doesn't change the module's real globals, and so that one test in
398\module{M} can't leave behind crumbs that accidentally allow another test
399to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000400in \module{M}, and names defined earlier in the docstring being run.
Tim Peters41a65ea2004-08-13 03:55:05 +0000401Examples cannot see names defined in other docstrings.
Tim Peters76882292001-02-17 05:58:44 +0000402
403You can force use of your own dict as the execution context by passing
Edward Loperb3666a32004-09-21 03:00:51 +0000404\code{globs=your_dict} to \function{testmod()} or
405\function{testfile()} instead.
Tim Peters76882292001-02-17 05:58:44 +0000406
Edward Loperb3666a32004-09-21 03:00:51 +0000407\subsubsection{What About Exceptions?\label{doctest-exceptions}}
Tim Peters76882292001-02-17 05:58:44 +0000408
Tim Petersa07bcd42004-08-26 04:47:31 +0000409No problem, provided that the traceback is the only output produced by
Thomas Wouters477c8d52006-05-27 19:21:47 +0000410the example: just paste in the traceback.\footnote{Examples containing
411 both expected output and an exception are not supported. Trying
412 to guess where one ends and the other begins is too error-prone,
413 and that also makes for a confusing test.}
414Since tracebacks contain details that are likely to change rapidly (for
415example, exact file paths and line numbers), this is one case where doctest
416works hard to be flexible in what it accepts.
Tim Petersa07bcd42004-08-26 04:47:31 +0000417
418Simple example:
Tim Peters76882292001-02-17 05:58:44 +0000419
420\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000421>>> [1, 2, 3].remove(42)
422Traceback (most recent call last):
423 File "<stdin>", line 1, in ?
424ValueError: list.remove(x): x not in list
Tim Peters76882292001-02-17 05:58:44 +0000425\end{verbatim}
426
Edward Loper19b19582004-08-25 23:07:03 +0000427That doctest succeeds if \exception{ValueError} is raised, with the
Tim Petersa07bcd42004-08-26 04:47:31 +0000428\samp{list.remove(x): x not in list} detail as shown.
Tim Peters41a65ea2004-08-13 03:55:05 +0000429
Edward Loper19b19582004-08-25 23:07:03 +0000430The expected output for an exception must start with a traceback
431header, which may be either of the following two lines, indented the
432same as the first line of the example:
Tim Peters41a65ea2004-08-13 03:55:05 +0000433
434\begin{verbatim}
435Traceback (most recent call last):
436Traceback (innermost last):
437\end{verbatim}
438
Edward Loper19b19582004-08-25 23:07:03 +0000439The traceback header is followed by an optional traceback stack, whose
Tim Petersa07bcd42004-08-26 04:47:31 +0000440contents are ignored by doctest. The traceback stack is typically
441omitted, or copied verbatim from an interactive session.
Edward Loper19b19582004-08-25 23:07:03 +0000442
Tim Petersa07bcd42004-08-26 04:47:31 +0000443The traceback stack is followed by the most interesting part: the
Edward Loper19b19582004-08-25 23:07:03 +0000444line(s) containing the exception type and detail. This is usually the
445last line of a traceback, but can extend across multiple lines if the
Tim Petersa07bcd42004-08-26 04:47:31 +0000446exception has a multi-line detail:
Tim Peters41a65ea2004-08-13 03:55:05 +0000447
448\begin{verbatim}
Edward Loper456ff912004-09-27 03:30:44 +0000449>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000450Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000451 File "<stdin>", line 1, in ?
452ValueError: multi
453 line
454detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000455\end{verbatim}
456
Edward Loper6cc13502004-09-19 01:16:44 +0000457The last three lines (starting with \exception{ValueError}) are
Edward Loper19b19582004-08-25 23:07:03 +0000458compared against the exception's type and detail, and the rest are
459ignored.
Tim Peters41a65ea2004-08-13 03:55:05 +0000460
Edward Loper19b19582004-08-25 23:07:03 +0000461Best practice is to omit the traceback stack, unless it adds
Tim Petersa07bcd42004-08-26 04:47:31 +0000462significant documentation value to the example. So the last example
Tim Peters41a65ea2004-08-13 03:55:05 +0000463is probably better as:
464
465\begin{verbatim}
Edward Loper456ff912004-09-27 03:30:44 +0000466>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000467Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000468 ...
469ValueError: multi
470 line
471detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000472\end{verbatim}
473
Tim Petersa07bcd42004-08-26 04:47:31 +0000474Note that tracebacks are treated very specially. In particular, in the
Tim Peters41a65ea2004-08-13 03:55:05 +0000475rewritten example, the use of \samp{...} is independent of doctest's
Tim Petersa07bcd42004-08-26 04:47:31 +0000476\constant{ELLIPSIS} option. The ellipsis in that example could be left
477out, or could just as well be three (or three hundred) commas or digits,
478or an indented transcript of a Monty Python skit.
479
480Some details you should read once, but won't need to remember:
481
482\begin{itemize}
483
484\item Doctest can't guess whether your expected output came from an
485 exception traceback or from ordinary printing. So, e.g., an example
486 that expects \samp{ValueError: 42 is prime} will pass whether
487 \exception{ValueError} is actually raised or if the example merely
488 prints that traceback text. In practice, ordinary output rarely begins
489 with a traceback header line, so this doesn't create real problems.
490
491\item Each line of the traceback stack (if present) must be indented
492 further than the first line of the example, \emph{or} start with a
493 non-alphanumeric character. The first line following the traceback
494 header indented the same and starting with an alphanumeric is taken
495 to be the start of the exception detail. Of course this does the
496 right thing for genuine tracebacks.
497
Tim Peters1fbf9c52004-09-04 17:21:02 +0000498\item When the \constant{IGNORE_EXCEPTION_DETAIL} doctest option is
499 is specified, everything following the leftmost colon is ignored.
500
Edward Loper0fe00aa2004-09-30 17:18:18 +0000501\item The interactive shell omits the traceback header line for some
502 \exception{SyntaxError}s. But doctest uses the traceback header
503 line to distinguish exceptions from non-exceptions. So in the rare
504 case where you need to test a \exception{SyntaxError} that omits the
505 traceback header, you will need to manually add the traceback header
506 line to your test example.
Tim Peters29978ae2004-10-04 03:34:32 +0000507
Edward Loper0fe00aa2004-09-30 17:18:18 +0000508\item For some \exception{SyntaxError}s, Python displays the character
509 position of the syntax error, using a \code{\^} marker:
510
511\begin{verbatim}
512>>> 1 1
513 File "<stdin>", line 1
514 1 1
515 ^
516SyntaxError: invalid syntax
517\end{verbatim}
518
519 Since the lines showing the position of the error come before the
520 exception type and detail, they are not checked by doctest. For
521 example, the following test would pass, even though it puts the
522 \code{\^} marker in the wrong location:
523
524\begin{verbatim}
525>>> 1 1
Tim Peters29978ae2004-10-04 03:34:32 +0000526Traceback (most recent call last):
Edward Loper0fe00aa2004-09-30 17:18:18 +0000527 File "<stdin>", line 1
528 1 1
529 ^
530SyntaxError: invalid syntax
531\end{verbatim}
532
Tim Petersa07bcd42004-08-26 04:47:31 +0000533\end{itemize}
Tim Peters41a65ea2004-08-13 03:55:05 +0000534
Tim Peters39c5de02004-09-25 01:22:29 +0000535\versionchanged[The ability to handle a multi-line exception detail,
536 and the \constant{IGNORE_EXCEPTION_DETAIL} doctest option,
537 were added]{2.4}
Tim Peters0e448072004-08-26 01:02:08 +0000538
Edward Loperb3666a32004-09-21 03:00:51 +0000539\subsubsection{Option Flags and Directives\label{doctest-options}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000540
Tim Peterscf533552004-08-26 04:50:38 +0000541A number of option flags control various aspects of doctest's
Tim Peters026f8dc2004-08-19 16:38:58 +0000542behavior. Symbolic names for the flags are supplied as module constants,
Tim Peters83e259a2004-08-13 21:55:21 +0000543which can be or'ed together and passed to various functions. The names
Tim Peters026f8dc2004-08-19 16:38:58 +0000544can also be used in doctest directives (see below).
Tim Peters8a3b69c2004-08-12 22:31:25 +0000545
Tim Petersa07bcd42004-08-26 04:47:31 +0000546The first group of options define test semantics, controlling
547aspects of how doctest decides whether actual output matches an
548example's expected output:
549
Tim Peters8a3b69c2004-08-12 22:31:25 +0000550\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
551 By default, if an expected output block contains just \code{1},
552 an actual output block containing just \code{1} or just
553 \code{True} is considered to be a match, and similarly for \code{0}
554 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
555 specified, neither substitution is allowed. The default behavior
556 caters to that Python changed the return type of many functions
557 from integer to boolean; doctests expecting "little integer"
558 output still work in these cases. This option will probably go
559 away, but not for several years.
560\end{datadesc}
561
562\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
563 By default, if an expected output block contains a line
564 containing only the string \code{<BLANKLINE>}, then that line
565 will match a blank line in the actual output. Because a
566 genuinely blank line delimits the expected output, this is
567 the only way to communicate that a blank line is expected. When
568 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
569 is not allowed.
570\end{datadesc}
571
572\begin{datadesc}{NORMALIZE_WHITESPACE}
573 When specified, all sequences of whitespace (blanks and newlines) are
574 treated as equal. Any sequence of whitespace within the expected
575 output will match any sequence of whitespace within the actual output.
576 By default, whitespace must match exactly.
577 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
578 of expected output is very long, and you want to wrap it across
579 multiple lines in your source.
580\end{datadesc}
581
582\begin{datadesc}{ELLIPSIS}
583 When specified, an ellipsis marker (\code{...}) in the expected output
584 can match any substring in the actual output. This includes
Tim Peters026f8dc2004-08-19 16:38:58 +0000585 substrings that span line boundaries, and empty substrings, so it's
586 best to keep usage of this simple. Complicated uses can lead to the
587 same kinds of "oops, it matched too much!" surprises that \regexp{.*}
588 is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000589\end{datadesc}
590
Tim Peters1fbf9c52004-09-04 17:21:02 +0000591\begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
592 When specified, an example that expects an exception passes if
593 an exception of the expected type is raised, even if the exception
594 detail does not match. For example, an example expecting
595 \samp{ValueError: 42} will pass if the actual exception raised is
596 \samp{ValueError: 3*14}, but will fail, e.g., if
597 \exception{TypeError} is raised.
598
599 Note that a similar effect can be obtained using \constant{ELLIPSIS},
600 and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
601 prior to 2.4 become uninteresting. Until then,
602 \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
603 doctest that doesn't care about the exception detail yet continues
604 to pass under Python releases prior to 2.4 (doctest directives
605 appear to be comments to them). For example,
606
607\begin{verbatim}
608>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
609Traceback (most recent call last):
610 File "<stdin>", line 1, in ?
611TypeError: object doesn't support item assignment
612\end{verbatim}
613
614 passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
615 to say "does not" instead of "doesn't".
616
617\end{datadesc}
618
Thomas Wouters477c8d52006-05-27 19:21:47 +0000619\begin{datadesc}{SKIP}
620
621 When specified, do not run the example at all. This can be useful
622 in contexts where doctest examples serve as both documentation and
623 test cases, and an example should be included for documentation
624 purposes, but should not be checked. E.g., the example's output
625 might be random; or the example might depend on resources which
626 would be unavailable to the test driver.
627
628 The SKIP flag can also be used for temporarily "commenting out"
629 examples.
630
631\end{datadesc}
632
Tim Peters38330fe2004-08-30 16:19:24 +0000633\begin{datadesc}{COMPARISON_FLAGS}
634 A bitmask or'ing together all the comparison flags above.
635\end{datadesc}
636
Tim Petersf33683f2004-08-26 04:52:46 +0000637The second group of options controls how test failures are reported:
Tim Petersa07bcd42004-08-26 04:47:31 +0000638
Edward Loper71f55af2004-08-26 01:41:51 +0000639\begin{datadesc}{REPORT_UDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000640 When specified, failures that involve multi-line expected and
641 actual outputs are displayed using a unified diff.
642\end{datadesc}
643
Edward Loper71f55af2004-08-26 01:41:51 +0000644\begin{datadesc}{REPORT_CDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000645 When specified, failures that involve multi-line expected and
646 actual outputs will be displayed using a context diff.
647\end{datadesc}
648
Edward Loper71f55af2004-08-26 01:41:51 +0000649\begin{datadesc}{REPORT_NDIFF}
Tim Petersc6cbab02004-08-22 19:43:28 +0000650 When specified, differences are computed by \code{difflib.Differ},
651 using the same algorithm as the popular \file{ndiff.py} utility.
652 This is the only method that marks differences within lines as
653 well as across lines. For example, if a line of expected output
654 contains digit \code{1} where actual output contains letter \code{l},
655 a line is inserted with a caret marking the mismatching column
656 positions.
657\end{datadesc}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000658
Edward Lopera89f88d2004-08-26 02:45:51 +0000659\begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
660 When specified, display the first failing example in each doctest,
661 but suppress output for all remaining examples. This will prevent
662 doctest from reporting correct examples that break because of
663 earlier failures; but it might also hide incorrect examples that
664 fail independently of the first failure. When
665 \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
666 examples are still run, and still count towards the total number of
667 failures reported; only the output is suppressed.
668\end{datadesc}
669
Tim Peters38330fe2004-08-30 16:19:24 +0000670\begin{datadesc}{REPORTING_FLAGS}
671 A bitmask or'ing together all the reporting flags above.
672\end{datadesc}
673
Edward Loperb3666a32004-09-21 03:00:51 +0000674"Doctest directives" may be used to modify the option flags for
675individual examples. Doctest directives are expressed as a special
676Python comment following an example's source code:
Tim Peters026f8dc2004-08-19 16:38:58 +0000677
678\begin{productionlist}[doctest]
679 \production{directive}
Edward Loper6cc13502004-09-19 01:16:44 +0000680 {"\#" "doctest:" \token{directive_options}}
681 \production{directive_options}
682 {\token{directive_option} ("," \token{directive_option})*}
683 \production{directive_option}
684 {\token{on_or_off} \token{directive_option_name}}
Tim Peters026f8dc2004-08-19 16:38:58 +0000685 \production{on_or_off}
686 {"+" | "-"}
Edward Loper6cc13502004-09-19 01:16:44 +0000687 \production{directive_option_name}
Tim Peters026f8dc2004-08-19 16:38:58 +0000688 {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
689\end{productionlist}
690
691Whitespace is not allowed between the \code{+} or \code{-} and the
Edward Loper6cc13502004-09-19 01:16:44 +0000692directive option name. The directive option name can be any of the
Edward Loperb3666a32004-09-21 03:00:51 +0000693option flag names explained above.
Tim Peters026f8dc2004-08-19 16:38:58 +0000694
Edward Loperb3666a32004-09-21 03:00:51 +0000695An example's doctest directives modify doctest's behavior for that
696single example. Use \code{+} to enable the named behavior, or
697\code{-} to disable it.
Tim Peters026f8dc2004-08-19 16:38:58 +0000698
699For example, this test passes:
700
701\begin{verbatim}
702>>> print range(20) #doctest: +NORMALIZE_WHITESPACE
703[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
70410, 11, 12, 13, 14, 15, 16, 17, 18, 19]
705\end{verbatim}
706
707Without the directive it would fail, both because the actual output
708doesn't have two blanks before the single-digit list elements, and
709because the actual output is on a single line. This test also passes,
Tim Petersa07bcd42004-08-26 04:47:31 +0000710and also requires a directive to do so:
Tim Peters026f8dc2004-08-19 16:38:58 +0000711
712\begin{verbatim}
713>>> print range(20) # doctest:+ELLIPSIS
714[0, 1, ..., 18, 19]
715\end{verbatim}
716
Edward Loper6cc13502004-09-19 01:16:44 +0000717Multiple directives can be used on a single physical line, separated
718by commas:
Tim Peters026f8dc2004-08-19 16:38:58 +0000719
720\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000721>>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +0000722[0, 1, ..., 18, 19]
723\end{verbatim}
724
Edward Loperb3666a32004-09-21 03:00:51 +0000725If multiple directive comments are used for a single example, then
726they are combined:
Edward Loper6cc13502004-09-19 01:16:44 +0000727
728\begin{verbatim}
729>>> print range(20) # doctest: +ELLIPSIS
730... # doctest: +NORMALIZE_WHITESPACE
731[0, 1, ..., 18, 19]
732\end{verbatim}
733
734As the previous example shows, you can add \samp{...} lines to your
Edward Loperb3666a32004-09-21 03:00:51 +0000735example containing only directives. This can be useful when an
Edward Loper6cc13502004-09-19 01:16:44 +0000736example is too long for a directive to comfortably fit on the same
737line:
738
739\begin{verbatim}
740>>> print range(5) + range(10,20) + range(30,40) + range(50,60)
741... # doctest: +ELLIPSIS
742[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
743\end{verbatim}
744
Tim Peters026f8dc2004-08-19 16:38:58 +0000745Note that since all options are disabled by default, and directives apply
746only to the example they appear in, enabling options (via \code{+} in a
747directive) is usually the only meaningful choice. However, option flags
748can also be passed to functions that run doctests, establishing different
749defaults. In such cases, disabling an option via \code{-} in a directive
750can be useful.
751
Tim Peters8a3b69c2004-08-12 22:31:25 +0000752\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
753 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
Edward Loper7d88a582004-09-28 05:50:57 +0000754 \constant{IGNORE_EXCEPTION_DETAIL},
Edward Lopera89f88d2004-08-26 02:45:51 +0000755 \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
Tim Peters38330fe2004-08-30 16:19:24 +0000756 \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
757 \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
Tim Peters026f8dc2004-08-19 16:38:58 +0000758 were added; by default \code{<BLANKLINE>} in expected output
759 matches an empty line in actual output; and doctest directives
760 were added]{2.4}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761\versionchanged[Constant \constant{SKIP} was added]{2.5}
Tim Peters026f8dc2004-08-19 16:38:58 +0000762
Tim Peters16be62f2004-09-26 02:38:41 +0000763There's also a way to register new option flag names, although this
Tim Peters9463d872004-09-26 21:05:03 +0000764isn't useful unless you intend to extend \refmodule{doctest} internals
Tim Peters16be62f2004-09-26 02:38:41 +0000765via subclassing:
766
767\begin{funcdesc}{register_optionflag}{name}
768 Create a new option flag with a given name, and return the new
769 flag's integer value. \function{register_optionflag()} can be
770 used when subclassing \class{OutputChecker} or
771 \class{DocTestRunner} to create new options that are supported by
772 your subclasses. \function{register_optionflag} should always be
773 called using the following idiom:
774
775\begin{verbatim}
776 MY_FLAG = register_optionflag('MY_FLAG')
777\end{verbatim}
778
779 \versionadded{2.4}
780\end{funcdesc}
781
Edward Loperb3666a32004-09-21 03:00:51 +0000782\subsubsection{Warnings\label{doctest-warnings}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000783
Tim Peters9463d872004-09-26 21:05:03 +0000784\refmodule{doctest} is serious about requiring exact matches in expected
Tim Peters2dc82052004-09-25 01:30:16 +0000785output. If even a single character doesn't match, the test fails. This
786will probably surprise you a few times, as you learn exactly what Python
787does and doesn't guarantee about output. For example, when printing a
788dict, Python doesn't guarantee that the key-value pairs will be printed
789in any particular order, so a test like
Tim Peters76882292001-02-17 05:58:44 +0000790
Edward Loperb3666a32004-09-21 03:00:51 +0000791% Hey! What happened to Monty Python examples?
792% Tim: ask Guido -- it's his example!
793\begin{verbatim}
794>>> foo()
795{"Hermione": "hippogryph", "Harry": "broomstick"}
796\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000797
Edward Loperb3666a32004-09-21 03:00:51 +0000798is vulnerable! One workaround is to do
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000799
Edward Loperb3666a32004-09-21 03:00:51 +0000800\begin{verbatim}
801>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
802True
803\end{verbatim}
804
805instead. Another is to do
806
807\begin{verbatim}
808>>> d = foo().items()
809>>> d.sort()
810>>> d
811[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
812\end{verbatim}
813
814There are others, but you get the idea.
815
816Another bad idea is to print things that embed an object address, like
817
818\begin{verbatim}
819>>> id(1.0) # certain to fail some of the time
8207948648
Tim Peters39c5de02004-09-25 01:22:29 +0000821>>> class C: pass
822>>> C() # the default repr() for instances embeds an address
823<__main__.C instance at 0x00AC18F0>
824\end{verbatim}
825
826The \constant{ELLIPSIS} directive gives a nice approach for the last
827example:
828
829\begin{verbatim}
830>>> C() #doctest: +ELLIPSIS
831<__main__.C instance at 0x...>
Edward Loperb3666a32004-09-21 03:00:51 +0000832\end{verbatim}
833
834Floating-point numbers are also subject to small output variations across
835platforms, because Python defers to the platform C library for float
836formatting, and C libraries vary widely in quality here.
837
838\begin{verbatim}
839>>> 1./7 # risky
8400.14285714285714285
841>>> print 1./7 # safer
8420.142857142857
843>>> print round(1./7, 6) # much safer
8440.142857
845\end{verbatim}
846
847Numbers of the form \code{I/2.**J} are safe across all platforms, and I
848often contrive doctest examples to produce numbers of that form:
849
850\begin{verbatim}
851>>> 3./4 # utterly safe
8520.75
853\end{verbatim}
854
855Simple fractions are also easier for people to understand, and that makes
856for better documentation.
857
Edward Loperb3666a32004-09-21 03:00:51 +0000858\subsection{Basic API\label{doctest-basic-api}}
859
860The functions \function{testmod()} and \function{testfile()} provide a
861simple interface to doctest that should be sufficient for most basic
Tim Petersb2b26ac2004-09-25 01:51:49 +0000862uses. For a less formal introduction to these two functions, see
Edward Loperb3666a32004-09-21 03:00:51 +0000863sections \ref{doctest-simple-testmod} and
864\ref{doctest-simple-testfile}.
865
866\begin{funcdesc}{testfile}{filename\optional{, module_relative}\optional{,
867 name}\optional{, package}\optional{,
868 globs}\optional{, verbose}\optional{,
869 report}\optional{, optionflags}\optional{,
Edward Lopera4c6a852004-09-27 04:08:20 +0000870 extraglobs}\optional{, raise_on_error}\optional{,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000871 parser}\optional{, encoding}}
Edward Loperb3666a32004-09-21 03:00:51 +0000872
873 All arguments except \var{filename} are optional, and should be
874 specified in keyword form.
875
876 Test examples in the file named \var{filename}. Return
877 \samp{(\var{failure_count}, \var{test_count})}.
878
879 Optional argument \var{module_relative} specifies how the filename
880 should be interpreted:
881
882 \begin{itemize}
883 \item If \var{module_relative} is \code{True} (the default), then
Tim Petersb2b26ac2004-09-25 01:51:49 +0000884 \var{filename} specifies an OS-independent module-relative
Edward Loperb3666a32004-09-21 03:00:51 +0000885 path. By default, this path is relative to the calling
886 module's directory; but if the \var{package} argument is
887 specified, then it is relative to that package. To ensure
Tim Petersb2b26ac2004-09-25 01:51:49 +0000888 OS-independence, \var{filename} should use \code{/} characters
Edward Loperb3666a32004-09-21 03:00:51 +0000889 to separate path segments, and may not be an absolute path
890 (i.e., it may not begin with \code{/}).
891 \item If \var{module_relative} is \code{False}, then \var{filename}
Tim Petersb2b26ac2004-09-25 01:51:49 +0000892 specifies an OS-specific path. The path may be absolute or
Edward Loperb3666a32004-09-21 03:00:51 +0000893 relative; relative paths are resolved with respect to the
894 current working directory.
895 \end{itemize}
896
897 Optional argument \var{name} gives the name of the test; by default,
898 or if \code{None}, \code{os.path.basename(\var{filename})} is used.
899
900 Optional argument \var{package} is a Python package or the name of a
901 Python package whose directory should be used as the base directory
902 for a module-relative filename. If no package is specified, then
903 the calling module's directory is used as the base directory for
904 module-relative filenames. It is an error to specify \var{package}
905 if \var{module_relative} is \code{False}.
906
907 Optional argument \var{globs} gives a dict to be used as the globals
Tim Petersb2b26ac2004-09-25 01:51:49 +0000908 when executing examples. A new shallow copy of this dict is
Edward Loperb3666a32004-09-21 03:00:51 +0000909 created for the doctest, so its examples start with a clean slate.
Tim Petersb2b26ac2004-09-25 01:51:49 +0000910 By default, or if \code{None}, a new empty dict is used.
Edward Loperb3666a32004-09-21 03:00:51 +0000911
912 Optional argument \var{extraglobs} gives a dict merged into the
913 globals used to execute examples. This works like
914 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
915 common key, the associated value in \var{extraglobs} appears in the
916 combined dict. By default, or if \code{None}, no extra globals are
917 used. This is an advanced feature that allows parameterization of
918 doctests. For example, a doctest can be written for a base class, using
919 a generic name for the class, then reused to test any number of
920 subclasses by passing an \var{extraglobs} dict mapping the generic
921 name to the subclass to be tested.
922
923 Optional argument \var{verbose} prints lots of stuff if true, and prints
924 only failures if false; by default, or if \code{None}, it's true
925 if and only if \code{'-v'} is in \code{sys.argv}.
926
927 Optional argument \var{report} prints a summary at the end when true,
928 else prints nothing at the end. In verbose mode, the summary is
929 detailed, else the summary is very brief (in fact, empty if all tests
930 passed).
931
932 Optional argument \var{optionflags} or's together option flags. See
Tim Peters8c0a2cf2004-09-25 03:02:23 +0000933 section~\ref{doctest-options}.
Edward Loperb3666a32004-09-21 03:00:51 +0000934
935 Optional argument \var{raise_on_error} defaults to false. If true,
936 an exception is raised upon the first failure or unexpected exception
937 in an example. This allows failures to be post-mortem debugged.
938 Default behavior is to continue running examples.
939
Edward Lopera4c6a852004-09-27 04:08:20 +0000940 Optional argument \var{parser} specifies a \class{DocTestParser} (or
941 subclass) that should be used to extract tests from the files. It
942 defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
943
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000944 Optional argument \var{encoding} specifies an encoding that should
945 be used to convert the file to unicode.
946
Edward Loperb3666a32004-09-21 03:00:51 +0000947 \versionadded{2.4}
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000948
949 \versionchanged[The parameter \var{encoding} was added]{2.5}
950
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000951\end{funcdesc}
952
Tim Peters83e259a2004-08-13 21:55:21 +0000953\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
954 globs}\optional{, verbose}\optional{,
955 isprivate}\optional{, report}\optional{,
956 optionflags}\optional{, extraglobs}\optional{,
Tim Peters82788602004-09-13 15:03:17 +0000957 raise_on_error}\optional{, exclude_empty}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000958
Tim Peters83e259a2004-08-13 21:55:21 +0000959 All arguments are optional, and all except for \var{m} should be
960 specified in keyword form.
961
962 Test examples in docstrings in functions and classes reachable
Tim Petersb2b26ac2004-09-25 01:51:49 +0000963 from module \var{m} (or module \module{__main__} if \var{m} is not
964 supplied or is \code{None}), starting with \code{\var{m}.__doc__}.
Tim Peters83e259a2004-08-13 21:55:21 +0000965
966 Also test examples reachable from dict \code{\var{m}.__test__}, if it
967 exists and is not \code{None}. \code{\var{m}.__test__} maps
968 names (strings) to functions, classes and strings; function and class
969 docstrings are searched for examples; strings are searched directly,
970 as if they were docstrings.
971
972 Only docstrings attached to objects belonging to module \var{m} are
973 searched.
974
975 Return \samp{(\var{failure_count}, \var{test_count})}.
976
977 Optional argument \var{name} gives the name of the module; by default,
978 or if \code{None}, \code{\var{m}.__name__} is used.
979
Tim Peters82788602004-09-13 15:03:17 +0000980 Optional argument \var{exclude_empty} defaults to false. If true,
981 objects for which no doctests are found are excluded from consideration.
982 The default is a backward compatibility hack, so that code still
983 using \method{doctest.master.summarize()} in conjunction with
984 \function{testmod()} continues to get output for objects with no tests.
985 The \var{exclude_empty} argument to the newer \class{DocTestFinder}
986 constructor defaults to true.
987
Tim Petersb2b26ac2004-09-25 01:51:49 +0000988 Optional arguments \var{extraglobs}, \var{verbose}, \var{report},
989 \var{optionflags}, \var{raise_on_error}, and \var{globs} are the same as
990 for function \function{testfile()} above, except that \var{globs}
991 defaults to \code{\var{m}.__dict__}.
992
Tim Peters83e259a2004-08-13 21:55:21 +0000993 Optional argument \var{isprivate} specifies a function used to
994 determine whether a name is private. The default function treats
995 all names as public. \var{isprivate} can be set to
996 \code{doctest.is_private} to skip over names that are
997 private according to Python's underscore naming convention.
998 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
999 If you need to skip tests based on name, filter the list returned by
1000 \code{DocTestFinder.find()} instead.}
1001
1002 \versionchanged[The parameter \var{optionflags} was added]{2.3}
1003
Tim Peters82788602004-09-13 15:03:17 +00001004 \versionchanged[The parameters \var{extraglobs}, \var{raise_on_error}
1005 and \var{exclude_empty} were added]{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001006\end{funcdesc}
1007
Tim Peters00411212004-09-26 20:45:04 +00001008There's also a function to run the doctests associated with a single object.
1009This function is provided for backward compatibility. There are no plans
1010to deprecate it, but it's rarely useful:
1011
1012\begin{funcdesc}{run_docstring_examples}{f, globs\optional{,
1013 verbose}\optional{, name}\optional{,
1014 compileflags}\optional{, optionflags}}
1015
1016 Test examples associated with object \var{f}; for example, \var{f} may
1017 be a module, function, or class object.
1018
1019 A shallow copy of dictionary argument \var{globs} is used for the
1020 execution context.
1021
1022 Optional argument \var{name} is used in failure messages, and defaults
1023 to \code{"NoName"}.
1024
1025 If optional argument \var{verbose} is true, output is generated even
1026 if there are no failures. By default, output is generated only in case
1027 of an example failure.
1028
1029 Optional argument \var{compileflags} gives the set of flags that should
1030 be used by the Python compiler when running the examples. By default, or
1031 if \code{None}, flags are deduced corresponding to the set of future
1032 features found in \var{globs}.
1033
1034 Optional argument \var{optionflags} works as for function
1035 \function{testfile()} above.
1036\end{funcdesc}
1037
Edward Loperb3666a32004-09-21 03:00:51 +00001038\subsection{Unittest API\label{doctest-unittest-api}}
1039
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001040As your collection of doctest'ed modules grows, you'll want a way to run
Tim Peters9463d872004-09-26 21:05:03 +00001041all their doctests systematically. Prior to Python 2.4, \refmodule{doctest}
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001042had a barely documented \class{Tester} class that supplied a rudimentary
1043way to combine doctests from multiple modules. \class{Tester} was feeble,
1044and in practice most serious Python testing frameworks build on the
Tim Peters9463d872004-09-26 21:05:03 +00001045\refmodule{unittest} module, which supplies many flexible ways to combine
1046tests from multiple sources. So, in Python 2.4, \refmodule{doctest}'s
1047\class{Tester} class is deprecated, and \refmodule{doctest} provides two
1048functions that can be used to create \refmodule{unittest} test suites from
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001049modules and text files containing doctests. These test suites can then be
Tim Peters9463d872004-09-26 21:05:03 +00001050run using \refmodule{unittest} test runners:
Edward Loperb3666a32004-09-21 03:00:51 +00001051
1052\begin{verbatim}
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001053import unittest
1054import doctest
1055import my_module_with_doctests, and_another
Edward Loperb3666a32004-09-21 03:00:51 +00001056
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001057suite = unittest.TestSuite()
1058for mod in my_module_with_doctests, and_another:
1059 suite.addTest(doctest.DocTestSuite(mod))
1060runner = unittest.TextTestRunner()
1061runner.run(suite)
Edward Loperb3666a32004-09-21 03:00:51 +00001062\end{verbatim}
1063
Tim Peters9463d872004-09-26 21:05:03 +00001064There are two main functions for creating \class{\refmodule{unittest}.TestSuite}
Tim Peters6a0a64b2004-09-26 02:12:40 +00001065instances from text files and modules with doctests:
1066
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067\begin{funcdesc}{DocFileSuite}{\optional{module_relative}\optional{,
1068 package}\optional{, setUp}\optional{,
1069 tearDown}\optional{, globs}\optional{,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001070 optionflags}\optional{, parser}\optional{,
1071 encoding}}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072
Edward Loperb3666a32004-09-21 03:00:51 +00001073 Convert doctest tests from one or more text files to a
1074 \class{\refmodule{unittest}.TestSuite}.
1075
Tim Peters9463d872004-09-26 21:05:03 +00001076 The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
1077 unittest framework and runs the interactive examples in each file. If an
1078 example in any file fails, then the synthesized unit test fails, and a
1079 \exception{failureException} exception is raised showing the name of the
1080 file containing the test and a (sometimes approximate) line number.
Edward Loperb3666a32004-09-21 03:00:51 +00001081
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001082 Pass one or more paths (as strings) to text files to be examined.
Edward Loperb3666a32004-09-21 03:00:51 +00001083
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001084 Options may be provided as keyword arguments:
1085
1086 Optional argument \var{module_relative} specifies how
Raymond Hettingerc90ea822004-09-25 08:09:23 +00001087 the filenames in \var{paths} should be interpreted:
Edward Loperb3666a32004-09-21 03:00:51 +00001088
1089 \begin{itemize}
1090 \item If \var{module_relative} is \code{True} (the default), then
Tim Petersb2b26ac2004-09-25 01:51:49 +00001091 each filename specifies an OS-independent module-relative
Edward Loperb3666a32004-09-21 03:00:51 +00001092 path. By default, this path is relative to the calling
1093 module's directory; but if the \var{package} argument is
1094 specified, then it is relative to that package. To ensure
Tim Petersb2b26ac2004-09-25 01:51:49 +00001095 OS-independence, each filename should use \code{/} characters
Edward Loperb3666a32004-09-21 03:00:51 +00001096 to separate path segments, and may not be an absolute path
1097 (i.e., it may not begin with \code{/}).
1098 \item If \var{module_relative} is \code{False}, then each filename
Tim Petersb2b26ac2004-09-25 01:51:49 +00001099 specifies an OS-specific path. The path may be absolute or
Edward Loperb3666a32004-09-21 03:00:51 +00001100 relative; relative paths are resolved with respect to the
1101 current working directory.
1102 \end{itemize}
1103
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001104 Optional argument \var{package} is a Python package or the name
Edward Loperb3666a32004-09-21 03:00:51 +00001105 of a Python package whose directory should be used as the base
1106 directory for module-relative filenames. If no package is
1107 specified, then the calling module's directory is used as the base
1108 directory for module-relative filenames. It is an error to specify
1109 \var{package} if \var{module_relative} is \code{False}.
1110
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001111 Optional argument \var{setUp} specifies a set-up function for
Edward Loperb3666a32004-09-21 03:00:51 +00001112 the test suite. This is called before running the tests in each
1113 file. The \var{setUp} function will be passed a \class{DocTest}
1114 object. The setUp function can access the test globals as the
1115 \var{globs} attribute of the test passed.
1116
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001117 Optional argument \var{tearDown} specifies a tear-down function
Edward Loperb3666a32004-09-21 03:00:51 +00001118 for the test suite. This is called after running the tests in each
1119 file. The \var{tearDown} function will be passed a \class{DocTest}
1120 object. The setUp function can access the test globals as the
1121 \var{globs} attribute of the test passed.
1122
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001123 Optional argument \var{globs} is a dictionary containing the
Edward Loperb3666a32004-09-21 03:00:51 +00001124 initial global variables for the tests. A new copy of this
1125 dictionary is created for each test. By default, \var{globs} is
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001126 a new empty dictionary.
Edward Loperb3666a32004-09-21 03:00:51 +00001127
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001128 Optional argument \var{optionflags} specifies the default
1129 doctest options for the tests, created by or-ing together
1130 individual option flags. See section~\ref{doctest-options}.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001131 See function \function{set_unittest_reportflags()} below for
1132 a better way to set reporting options.
Edward Loperb3666a32004-09-21 03:00:51 +00001133
Edward Lopera4c6a852004-09-27 04:08:20 +00001134 Optional argument \var{parser} specifies a \class{DocTestParser} (or
1135 subclass) that should be used to extract tests from the files. It
1136 defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
1137
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001138 Optional argument \var{encoding} specifies an encoding that should
1139 be used to convert the file to unicode.
1140
Edward Loperb3666a32004-09-21 03:00:51 +00001141 \versionadded{2.4}
Fred Drake7c404a42004-12-21 23:46:34 +00001142
Thomas Wouters477c8d52006-05-27 19:21:47 +00001143 \versionchanged[The global \code{__file__} was added to the
Fred Drake7c404a42004-12-21 23:46:34 +00001144 globals provided to doctests loaded from a text file using
Thomas Wouters477c8d52006-05-27 19:21:47 +00001145 \function{DocFileSuite()}]{2.5}
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001146
1147 \versionchanged[The parameter \var{encoding} was added]{2.5}
1148
Edward Loperb3666a32004-09-21 03:00:51 +00001149\end{funcdesc}
1150
1151\begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
1152 globs}\optional{, extraglobs}\optional{,
1153 test_finder}\optional{, setUp}\optional{,
1154 tearDown}\optional{, checker}}
1155 Convert doctest tests for a module to a
1156 \class{\refmodule{unittest}.TestSuite}.
1157
Tim Peters9463d872004-09-26 21:05:03 +00001158 The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
1159 unittest framework and runs each doctest in the module. If any of the
1160 doctests fail, then the synthesized unit test fails, and a
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001161 \exception{failureException} exception is raised showing the name of the
1162 file containing the test and a (sometimes approximate) line number.
Edward Loperb3666a32004-09-21 03:00:51 +00001163
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001164 Optional argument \var{module} provides the module to be tested. It
Edward Loperb3666a32004-09-21 03:00:51 +00001165 can be a module object or a (possibly dotted) module name. If not
1166 specified, the module calling this function is used.
1167
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001168 Optional argument \var{globs} is a dictionary containing the
Edward Loperb3666a32004-09-21 03:00:51 +00001169 initial global variables for the tests. A new copy of this
1170 dictionary is created for each test. By default, \var{globs} is
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001171 a new empty dictionary.
Edward Loperb3666a32004-09-21 03:00:51 +00001172
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001173 Optional argument \var{extraglobs} specifies an extra set of
Edward Loperb3666a32004-09-21 03:00:51 +00001174 global variables, which is merged into \var{globs}. By default, no
1175 extra globals are used.
1176
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001177 Optional argument \var{test_finder} is the \class{DocTestFinder}
Edward Loperb3666a32004-09-21 03:00:51 +00001178 object (or a drop-in replacement) that is used to extract doctests
1179 from the module.
1180
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001181 Optional arguments \var{setUp}, \var{tearDown}, and \var{optionflags}
1182 are the same as for function \function{DocFileSuite()} above.
Edward Loperb3666a32004-09-21 03:00:51 +00001183
1184 \versionadded{2.3}
Tim Peters6a0a64b2004-09-26 02:12:40 +00001185
Edward Loperb3666a32004-09-21 03:00:51 +00001186 \versionchanged[The parameters \var{globs}, \var{extraglobs},
1187 \var{test_finder}, \var{setUp}, \var{tearDown}, and
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001188 \var{optionflags} were added; this function now uses the same search
1189 technique as \function{testmod()}]{2.4}
Edward Loperb3666a32004-09-21 03:00:51 +00001190\end{funcdesc}
1191
Tim Peters6a0a64b2004-09-26 02:12:40 +00001192Under the covers, \function{DocTestSuite()} creates a
Tim Peters9463d872004-09-26 21:05:03 +00001193\class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocTestCase}
1194instances, and \class{DocTestCase} is a subclass of
1195\class{\refmodule{unittest}.TestCase}. \class{DocTestCase} isn't documented
1196here (it's an internal detail), but studying its code can answer questions
1197about the exact details of \refmodule{unittest} integration.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001198
Tim Peters9463d872004-09-26 21:05:03 +00001199Similarly, \function{DocFileSuite()} creates a
1200\class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocFileCase}
1201instances, and \class{DocFileCase} is a subclass of \class{DocTestCase}.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001202
Tim Peters9463d872004-09-26 21:05:03 +00001203So both ways of creating a \class{\refmodule{unittest}.TestSuite} run
1204instances of \class{DocTestCase}. This is important for a subtle reason:
1205when you run \refmodule{doctest} functions yourself, you can control the
1206\refmodule{doctest} options in use directly, by passing option flags to
1207\refmodule{doctest} functions. However, if you're writing a
1208\refmodule{unittest} framework, \refmodule{unittest} ultimately controls
1209when and how tests get run. The framework author typically wants to
1210control \refmodule{doctest} reporting options (perhaps, e.g., specified by
1211command line options), but there's no way to pass options through
1212\refmodule{unittest} to \refmodule{doctest} test runners.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001213
Tim Peters9463d872004-09-26 21:05:03 +00001214For this reason, \refmodule{doctest} also supports a notion of
1215\refmodule{doctest} reporting flags specific to \refmodule{unittest}
1216support, via this function:
Tim Peters6a0a64b2004-09-26 02:12:40 +00001217
1218\begin{funcdesc}{set_unittest_reportflags}{flags}
Tim Peters9463d872004-09-26 21:05:03 +00001219 Set the \refmodule{doctest} reporting flags to use.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001220
1221 Argument \var{flags} or's together option flags. See
1222 section~\ref{doctest-options}. Only "reporting flags" can be used.
1223
Tim Peters9463d872004-09-26 21:05:03 +00001224 This is a module-global setting, and affects all future doctests run by
1225 module \refmodule{unittest}: the \method{runTest()} method of
1226 \class{DocTestCase} looks at the option flags specified for the test case
1227 when the \class{DocTestCase} instance was constructed. If no reporting
1228 flags were specified (which is the typical and expected case),
1229 \refmodule{doctest}'s \refmodule{unittest} reporting flags are or'ed into
1230 the option flags, and the option flags so augmented are passed to the
Tim Peters6a0a64b2004-09-26 02:12:40 +00001231 \class{DocTestRunner} instance created to run the doctest. If any
Tim Peters9463d872004-09-26 21:05:03 +00001232 reporting flags were specified when the \class{DocTestCase} instance was
1233 constructed, \refmodule{doctest}'s \refmodule{unittest} reporting flags
Tim Peters6a0a64b2004-09-26 02:12:40 +00001234 are ignored.
1235
Tim Peters9463d872004-09-26 21:05:03 +00001236 The value of the \refmodule{unittest} reporting flags in effect before the
Tim Peters6a0a64b2004-09-26 02:12:40 +00001237 function was called is returned by the function.
1238
1239 \versionadded{2.4}
1240\end{funcdesc}
1241
1242
Edward Loperb3666a32004-09-21 03:00:51 +00001243\subsection{Advanced API\label{doctest-advanced-api}}
1244
1245The basic API is a simple wrapper that's intended to make doctest easy
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001246to use. It is fairly flexible, and should meet most users' needs;
1247however, if you require more fine-grained control over testing, or
Edward Loperb3666a32004-09-21 03:00:51 +00001248wish to extend doctest's capabilities, then you should use the
1249advanced API.
1250
1251The advanced API revolves around two container classes, which are used
1252to store the interactive examples extracted from doctest cases:
1253
1254\begin{itemize}
1255\item \class{Example}: A single python statement, paired with its
1256 expected output.
1257\item \class{DocTest}: A collection of \class{Example}s, typically
1258 extracted from a single docstring or text file.
1259\end{itemize}
1260
1261Additional processing classes are defined to find, parse, and run, and
1262check doctest examples:
1263
1264\begin{itemize}
1265\item \class{DocTestFinder}: Finds all docstrings in a given module,
1266 and uses a \class{DocTestParser} to create a \class{DocTest}
1267 from every docstring that contains interactive examples.
1268\item \class{DocTestParser}: Creates a \class{DocTest} object from
1269 a string (such as an object's docstring).
1270\item \class{DocTestRunner}: Executes the examples in a
1271 \class{DocTest}, and uses an \class{OutputChecker} to verify
1272 their output.
1273\item \class{OutputChecker}: Compares the actual output from a
1274 doctest example with the expected output, and decides whether
1275 they match.
1276\end{itemize}
1277
Tim Peters3f791252004-09-25 03:50:35 +00001278The relationships among these processing classes are summarized in the
Edward Loperb3666a32004-09-21 03:00:51 +00001279following diagram:
1280
1281\begin{verbatim}
1282 list of:
1283+------+ +---------+
1284|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1285+------+ | ^ +---------+ | ^ (printed)
1286 | | | Example | | |
Tim Peters3f791252004-09-25 03:50:35 +00001287 v | | ... | v |
Edward Loperb3666a32004-09-21 03:00:51 +00001288 DocTestParser | Example | OutputChecker
1289 +---------+
1290\end{verbatim}
1291
1292\subsubsection{DocTest Objects\label{doctest-DocTest}}
1293\begin{classdesc}{DocTest}{examples, globs, name, filename, lineno,
1294 docstring}
1295 A collection of doctest examples that should be run in a single
1296 namespace. The constructor arguments are used to initialize the
1297 member variables of the same names.
1298 \versionadded{2.4}
1299\end{classdesc}
1300
1301\class{DocTest} defines the following member variables. They are
1302initialized by the constructor, and should not be modified directly.
1303
1304\begin{memberdesc}{examples}
1305 A list of \class{Example} objects encoding the individual
1306 interactive Python examples that should be run by this test.
1307\end{memberdesc}
1308
1309\begin{memberdesc}{globs}
1310 The namespace (aka globals) that the examples should be run in.
1311 This is a dictionary mapping names to values. Any changes to the
1312 namespace made by the examples (such as binding new variables)
1313 will be reflected in \member{globs} after the test is run.
1314\end{memberdesc}
1315
1316\begin{memberdesc}{name}
1317 A string name identifying the \class{DocTest}. Typically, this is
1318 the name of the object or file that the test was extracted from.
1319\end{memberdesc}
1320
1321\begin{memberdesc}{filename}
1322 The name of the file that this \class{DocTest} was extracted from;
1323 or \code{None} if the filename is unknown, or if the
1324 \class{DocTest} was not extracted from a file.
1325\end{memberdesc}
1326
1327\begin{memberdesc}{lineno}
1328 The line number within \member{filename} where this
1329 \class{DocTest} begins, or \code{None} if the line number is
1330 unavailable. This line number is zero-based with respect to the
1331 beginning of the file.
1332\end{memberdesc}
1333
1334\begin{memberdesc}{docstring}
1335 The string that the test was extracted from, or `None` if the
1336 string is unavailable, or if the test was not extracted from a
1337 string.
1338\end{memberdesc}
1339
1340\subsubsection{Example Objects\label{doctest-Example}}
1341\begin{classdesc}{Example}{source, want\optional{,
1342 exc_msg}\optional{, lineno}\optional{,
1343 indent}\optional{, options}}
1344 A single interactive example, consisting of a Python statement and
1345 its expected output. The constructor arguments are used to
1346 initialize the member variables of the same names.
1347 \versionadded{2.4}
1348\end{classdesc}
1349
1350\class{Example} defines the following member variables. They are
1351initialized by the constructor, and should not be modified directly.
1352
1353\begin{memberdesc}{source}
1354 A string containing the example's source code. This source code
1355 consists of a single Python statement, and always ends with a
1356 newline; the constructor adds a newline when necessary.
1357\end{memberdesc}
1358
1359\begin{memberdesc}{want}
1360 The expected output from running the example's source code (either
1361 from stdout, or a traceback in case of exception). \member{want}
1362 ends with a newline unless no output is expected, in which case
1363 it's an empty string. The constructor adds a newline when
1364 necessary.
1365\end{memberdesc}
1366
1367\begin{memberdesc}{exc_msg}
1368 The exception message generated by the example, if the example is
1369 expected to generate an exception; or \code{None} if it is not
1370 expected to generate an exception. This exception message is
1371 compared against the return value of
1372 \function{traceback.format_exception_only()}. \member{exc_msg}
1373 ends with a newline unless it's \code{None}. The constructor adds
1374 a newline if needed.
1375\end{memberdesc}
1376
1377\begin{memberdesc}{lineno}
1378 The line number within the string containing this example where
1379 the example begins. This line number is zero-based with respect
1380 to the beginning of the containing string.
1381\end{memberdesc}
1382
1383\begin{memberdesc}{indent}
Tim Peters3f791252004-09-25 03:50:35 +00001384 The example's indentation in the containing string, i.e., the
Raymond Hettinger68804312005-01-01 00:28:46 +00001385 number of space characters that precede the example's first
Edward Loperb3666a32004-09-21 03:00:51 +00001386 prompt.
1387\end{memberdesc}
1388
1389\begin{memberdesc}{options}
1390 A dictionary mapping from option flags to \code{True} or
1391 \code{False}, which is used to override default options for this
1392 example. Any option flags not contained in this dictionary are
1393 left at their default value (as specified by the
Tim Peters3f791252004-09-25 03:50:35 +00001394 \class{DocTestRunner}'s \member{optionflags}).
1395 By default, no options are set.
Edward Loperb3666a32004-09-21 03:00:51 +00001396\end{memberdesc}
1397
1398\subsubsection{DocTestFinder objects\label{doctest-DocTestFinder}}
1399\begin{classdesc}{DocTestFinder}{\optional{verbose}\optional{,
1400 parser}\optional{, recurse}\optional{,
1401 exclude_empty}}
1402 A processing class used to extract the \class{DocTest}s that are
1403 relevant to a given object, from its docstring and the docstrings
1404 of its contained objects. \class{DocTest}s can currently be
1405 extracted from the following object types: modules, functions,
1406 classes, methods, staticmethods, classmethods, and properties.
1407
1408 The optional argument \var{verbose} can be used to display the
1409 objects searched by the finder. It defaults to \code{False} (no
1410 output).
1411
1412 The optional argument \var{parser} specifies the
1413 \class{DocTestParser} object (or a drop-in replacement) that is
1414 used to extract doctests from docstrings.
1415
1416 If the optional argument \var{recurse} is false, then
1417 \method{DocTestFinder.find()} will only examine the given object,
1418 and not any contained objects.
1419
1420 If the optional argument \var{exclude_empty} is false, then
1421 \method{DocTestFinder.find()} will include tests for objects with
1422 empty docstrings.
1423
1424 \versionadded{2.4}
1425\end{classdesc}
1426
1427\class{DocTestFinder} defines the following method:
1428
Tim Peters7a082142004-09-25 00:10:53 +00001429\begin{methoddesc}{find}{obj\optional{, name}\optional{,
Edward Loperb3666a32004-09-21 03:00:51 +00001430 module}\optional{, globs}\optional{, extraglobs}}
1431 Return a list of the \class{DocTest}s that are defined by
1432 \var{obj}'s docstring, or by any of its contained objects'
1433 docstrings.
1434
1435 The optional argument \var{name} specifies the object's name; this
1436 name will be used to construct names for the returned
1437 \class{DocTest}s. If \var{name} is not specified, then
Tim Peters3f791252004-09-25 03:50:35 +00001438 \code{\var{obj}.__name__} is used.
Edward Loperb3666a32004-09-21 03:00:51 +00001439
1440 The optional parameter \var{module} is the module that contains
1441 the given object. If the module is not specified or is None, then
1442 the test finder will attempt to automatically determine the
1443 correct module. The object's module is used:
1444
1445 \begin{itemize}
Tim Peters3f791252004-09-25 03:50:35 +00001446 \item As a default namespace, if \var{globs} is not specified.
Edward Loperb3666a32004-09-21 03:00:51 +00001447 \item To prevent the DocTestFinder from extracting DocTests
1448 from objects that are imported from other modules. (Contained
1449 objects with modules other than \var{module} are ignored.)
1450 \item To find the name of the file containing the object.
1451 \item To help find the line number of the object within its file.
1452 \end{itemize}
1453
1454 If \var{module} is \code{False}, no attempt to find the module
1455 will be made. This is obscure, of use mostly in testing doctest
1456 itself: if \var{module} is \code{False}, or is \code{None} but
1457 cannot be found automatically, then all objects are considered to
1458 belong to the (non-existent) module, so all contained objects will
1459 (recursively) be searched for doctests.
1460
1461 The globals for each \class{DocTest} is formed by combining
1462 \var{globs} and \var{extraglobs} (bindings in \var{extraglobs}
Tim Peters3f791252004-09-25 03:50:35 +00001463 override bindings in \var{globs}). A new shallow copy of the globals
Edward Loperb3666a32004-09-21 03:00:51 +00001464 dictionary is created for each \class{DocTest}. If \var{globs} is
1465 not specified, then it defaults to the module's \var{__dict__}, if
1466 specified, or \code{\{\}} otherwise. If \var{extraglobs} is not
1467 specified, then it defaults to \code{\{\}}.
1468\end{methoddesc}
1469
1470\subsubsection{DocTestParser objects\label{doctest-DocTestParser}}
1471\begin{classdesc}{DocTestParser}{}
1472 A processing class used to extract interactive examples from a
1473 string, and use them to create a \class{DocTest} object.
1474 \versionadded{2.4}
1475\end{classdesc}
1476
1477\class{DocTestParser} defines the following methods:
1478
1479\begin{methoddesc}{get_doctest}{string, globs, name, filename, lineno}
1480 Extract all doctest examples from the given string, and collect
1481 them into a \class{DocTest} object.
1482
1483 \var{globs}, \var{name}, \var{filename}, and \var{lineno} are
1484 attributes for the new \class{DocTest} object. See the
1485 documentation for \class{DocTest} for more information.
1486\end{methoddesc}
1487
1488\begin{methoddesc}{get_examples}{string\optional{, name}}
1489 Extract all doctest examples from the given string, and return
1490 them as a list of \class{Example} objects. Line numbers are
1491 0-based. The optional argument \var{name} is a name identifying
1492 this string, and is only used for error messages.
1493\end{methoddesc}
1494
1495\begin{methoddesc}{parse}{string\optional{, name}}
1496 Divide the given string into examples and intervening text, and
1497 return them as a list of alternating \class{Example}s and strings.
1498 Line numbers for the \class{Example}s are 0-based. The optional
1499 argument \var{name} is a name identifying this string, and is only
1500 used for error messages.
1501\end{methoddesc}
1502
1503\subsubsection{DocTestRunner objects\label{doctest-DocTestRunner}}
1504\begin{classdesc}{DocTestRunner}{\optional{checker}\optional{,
1505 verbose}\optional{, optionflags}}
1506 A processing class used to execute and verify the interactive
1507 examples in a \class{DocTest}.
1508
1509 The comparison between expected outputs and actual outputs is done
1510 by an \class{OutputChecker}. This comparison may be customized
1511 with a number of option flags; see section~\ref{doctest-options}
1512 for more information. If the option flags are insufficient, then
1513 the comparison may also be customized by passing a subclass of
1514 \class{OutputChecker} to the constructor.
1515
1516 The test runner's display output can be controlled in two ways.
1517 First, an output function can be passed to
1518 \method{TestRunner.run()}; this function will be called with
1519 strings that should be displayed. It defaults to
1520 \code{sys.stdout.write}. If capturing the output is not
1521 sufficient, then the display output can be also customized by
1522 subclassing DocTestRunner, and overriding the methods
1523 \method{report_start}, \method{report_success},
1524 \method{report_unexpected_exception}, and \method{report_failure}.
1525
1526 The optional keyword argument \var{checker} specifies the
1527 \class{OutputChecker} object (or drop-in replacement) that should
1528 be used to compare the expected outputs to the actual outputs of
1529 doctest examples.
1530
1531 The optional keyword argument \var{verbose} controls the
1532 \class{DocTestRunner}'s verbosity. If \var{verbose} is
1533 \code{True}, then information is printed about each example, as it
1534 is run. If \var{verbose} is \code{False}, then only failures are
1535 printed. If \var{verbose} is unspecified, or \code{None}, then
1536 verbose output is used iff the command-line switch \programopt{-v}
1537 is used.
1538
1539 The optional keyword argument \var{optionflags} can be used to
1540 control how the test runner compares expected output to actual
1541 output, and how it displays failures. For more information, see
1542 section~\ref{doctest-options}.
1543
1544 \versionadded{2.4}
1545\end{classdesc}
1546
1547\class{DocTestParser} defines the following methods:
1548
1549\begin{methoddesc}{report_start}{out, test, example}
1550 Report that the test runner is about to process the given example.
1551 This method is provided to allow subclasses of
1552 \class{DocTestRunner} to customize their output; it should not be
1553 called directly.
1554
1555 \var{example} is the example about to be processed. \var{test} is
1556 the test containing \var{example}. \var{out} is the output
1557 function that was passed to \method{DocTestRunner.run()}.
1558\end{methoddesc}
1559
1560\begin{methoddesc}{report_success}{out, test, example, got}
1561 Report that the given example ran successfully. This method is
1562 provided to allow subclasses of \class{DocTestRunner} to customize
1563 their output; it should not be called directly.
1564
1565 \var{example} is the example about to be processed. \var{got} is
1566 the actual output from the example. \var{test} is the test
1567 containing \var{example}. \var{out} is the output function that
1568 was passed to \method{DocTestRunner.run()}.
1569\end{methoddesc}
1570
1571\begin{methoddesc}{report_failure}{out, test, example, got}
1572 Report that the given example failed. This method is provided to
1573 allow subclasses of \class{DocTestRunner} to customize their
1574 output; it should not be called directly.
1575
1576 \var{example} is the example about to be processed. \var{got} is
1577 the actual output from the example. \var{test} is the test
1578 containing \var{example}. \var{out} is the output function that
1579 was passed to \method{DocTestRunner.run()}.
1580\end{methoddesc}
1581
1582\begin{methoddesc}{report_unexpected_exception}{out, test, example, exc_info}
1583 Report that the given example raised an unexpected exception.
1584 This method is provided to allow subclasses of
1585 \class{DocTestRunner} to customize their output; it should not be
1586 called directly.
1587
1588 \var{example} is the example about to be processed.
1589 \var{exc_info} is a tuple containing information about the
1590 unexpected exception (as returned by \function{sys.exc_info()}).
1591 \var{test} is the test containing \var{example}. \var{out} is the
1592 output function that was passed to \method{DocTestRunner.run()}.
1593\end{methoddesc}
1594
1595\begin{methoddesc}{run}{test\optional{, compileflags}\optional{,
1596 out}\optional{, clear_globs}}
1597 Run the examples in \var{test} (a \class{DocTest} object), and
1598 display the results using the writer function \var{out}.
1599
1600 The examples are run in the namespace \code{test.globs}. If
1601 \var{clear_globs} is true (the default), then this namespace will
1602 be cleared after the test runs, to help with garbage collection.
1603 If you would like to examine the namespace after the test
1604 completes, then use \var{clear_globs=False}.
1605
1606 \var{compileflags} gives the set of flags that should be used by
1607 the Python compiler when running the examples. If not specified,
1608 then it will default to the set of future-import flags that apply
1609 to \var{globs}.
1610
1611 The output of each example is checked using the
1612 \class{DocTestRunner}'s output checker, and the results are
1613 formatted by the \method{DocTestRunner.report_*} methods.
1614\end{methoddesc}
1615
1616\begin{methoddesc}{summarize}{\optional{verbose}}
1617 Print a summary of all the test cases that have been run by this
1618 DocTestRunner, and return a tuple \samp{(\var{failure_count},
1619 \var{test_count})}.
1620
1621 The optional \var{verbose} argument controls how detailed the
1622 summary is. If the verbosity is not specified, then the
1623 \class{DocTestRunner}'s verbosity is used.
1624\end{methoddesc}
1625
1626\subsubsection{OutputChecker objects\label{doctest-OutputChecker}}
1627
1628\begin{classdesc}{OutputChecker}{}
1629 A class used to check the whether the actual output from a doctest
1630 example matches the expected output. \class{OutputChecker}
1631 defines two methods: \method{check_output}, which compares a given
1632 pair of outputs, and returns true if they match; and
1633 \method{output_difference}, which returns a string describing the
1634 differences between two outputs.
1635 \versionadded{2.4}
1636\end{classdesc}
1637
1638\class{OutputChecker} defines the following methods:
1639
1640\begin{methoddesc}{check_output}{want, got, optionflags}
1641 Return \code{True} iff the actual output from an example
1642 (\var{got}) matches the expected output (\var{want}). These
1643 strings are always considered to match if they are identical; but
1644 depending on what option flags the test runner is using, several
1645 non-exact match types are also possible. See
1646 section~\ref{doctest-options} for more information about option
1647 flags.
1648\end{methoddesc}
1649
1650\begin{methoddesc}{output_difference}{example, got, optionflags}
1651 Return a string describing the differences between the expected
1652 output for a given example (\var{example}) and the actual output
1653 (\var{got}). \var{optionflags} is the set of option flags used to
1654 compare \var{want} and \var{got}.
1655\end{methoddesc}
1656
1657\subsection{Debugging\label{doctest-debugging}}
1658
Tim Peters05b05fe2004-09-26 05:09:59 +00001659Doctest provides several mechanisms for debugging doctest examples:
Edward Loperb3666a32004-09-21 03:00:51 +00001660
Tim Peters05b05fe2004-09-26 05:09:59 +00001661\begin{itemize}
1662\item Several functions convert doctests to executable Python
1663 programs, which can be run under the Python debugger, \refmodule{pdb}.
Edward Loperb3666a32004-09-21 03:00:51 +00001664\item The \class{DebugRunner} class is a subclass of
1665 \class{DocTestRunner} that raises an exception for the first
1666 failing example, containing information about that example.
1667 This information can be used to perform post-mortem debugging on
1668 the example.
Tim Peters9463d872004-09-26 21:05:03 +00001669\item The \refmodule{unittest} cases generated by \function{DocTestSuite()}
Tim Peters05b05fe2004-09-26 05:09:59 +00001670 support the \method{debug()} method defined by
Tim Peters9463d872004-09-26 21:05:03 +00001671 \class{\refmodule{unittest}.TestCase}.
1672\item You can add a call to \function{\refmodule{pdb}.set_trace()} in a
1673 doctest example, and you'll drop into the Python debugger when that
Tim Peters05b05fe2004-09-26 05:09:59 +00001674 line is executed. Then you can inspect current values of variables,
1675 and so on. For example, suppose \file{a.py} contains just this
1676 module docstring:
Edward Loperb3666a32004-09-21 03:00:51 +00001677
Tim Peters05b05fe2004-09-26 05:09:59 +00001678\begin{verbatim}
1679"""
1680>>> def f(x):
1681... g(x*2)
1682>>> def g(x):
1683... print x+3
1684... import pdb; pdb.set_trace()
1685>>> f(3)
16869
1687"""
1688\end{verbatim}
Edward Loperb3666a32004-09-21 03:00:51 +00001689
Tim Peters05b05fe2004-09-26 05:09:59 +00001690 Then an interactive Python session may look like this:
Edward Loperb3666a32004-09-21 03:00:51 +00001691
Tim Peters05b05fe2004-09-26 05:09:59 +00001692\begin{verbatim}
1693>>> import a, doctest
1694>>> doctest.testmod(a)
1695--Return--
1696> <doctest a[1]>(3)g()->None
1697-> import pdb; pdb.set_trace()
1698(Pdb) list
1699 1 def g(x):
1700 2 print x+3
1701 3 -> import pdb; pdb.set_trace()
1702[EOF]
1703(Pdb) print x
17046
1705(Pdb) step
1706--Return--
1707> <doctest a[0]>(2)f()->None
1708-> g(x*2)
1709(Pdb) list
1710 1 def f(x):
1711 2 -> g(x*2)
1712[EOF]
1713(Pdb) print x
17143
1715(Pdb) step
1716--Return--
1717> <doctest a[2]>(1)?()->None
1718-> f(3)
1719(Pdb) cont
1720(0, 3)
1721>>>
1722\end{verbatim}
1723
Tim Peters9463d872004-09-26 21:05:03 +00001724 \versionchanged[The ability to use \code{\refmodule{pdb}.set_trace()}
1725 usefully inside doctests was added]{2.4}
Tim Peters05b05fe2004-09-26 05:09:59 +00001726\end{itemize}
1727
1728Functions that convert doctests to Python code, and possibly run
1729the synthesized code under the debugger:
1730
1731\begin{funcdesc}{script_from_examples}{s}
1732 Convert text with examples to a script.
1733
1734 Argument \var{s} is a string containing doctest examples. The string
1735 is converted to a Python script, where doctest examples in \var{s}
1736 are converted to regular code, and everything else is converted to
1737 Python comments. The generated script is returned as a string.
Tim Peters36ee8ce2004-09-26 21:51:25 +00001738 For example,
Tim Peters05b05fe2004-09-26 05:09:59 +00001739
1740 \begin{verbatim}
Tim Peters36ee8ce2004-09-26 21:51:25 +00001741 import doctest
1742 print doctest.script_from_examples(r"""
1743 Set x and y to 1 and 2.
1744 >>> x, y = 1, 2
1745
1746 Print their sum:
1747 >>> print x+y
1748 3
1749 """)
Tim Peters05b05fe2004-09-26 05:09:59 +00001750 \end{verbatim}
1751
Tim Peters36ee8ce2004-09-26 21:51:25 +00001752 displays:
1753
1754 \begin{verbatim}
1755 # Set x and y to 1 and 2.
1756 x, y = 1, 2
1757 #
1758 # Print their sum:
1759 print x+y
1760 # Expected:
1761 ## 3
1762 \end{verbatim}
1763
1764 This function is used internally by other functions (see below), but
1765 can also be useful when you want to transform an interactive Python
1766 session into a Python script.
1767
Tim Peters05b05fe2004-09-26 05:09:59 +00001768 \versionadded{2.4}
1769\end{funcdesc}
1770
1771\begin{funcdesc}{testsource}{module, name}
1772 Convert the doctest for an object to a script.
1773
1774 Argument \var{module} is a module object, or dotted name of a module,
1775 containing the object whose doctests are of interest. Argument
1776 \var{name} is the name (within the module) of the object with the
1777 doctests of interest. The result is a string, containing the
1778 object's docstring converted to a Python script, as described for
1779 \function{script_from_examples()} above. For example, if module
1780 \file{a.py} contains a top-level function \function{f()}, then
1781
Edward Loper456ff912004-09-27 03:30:44 +00001782\begin{verbatim}
1783import a, doctest
1784print doctest.testsource(a, "a.f")
1785\end{verbatim}
Tim Peters05b05fe2004-09-26 05:09:59 +00001786
1787 prints a script version of function \function{f()}'s docstring,
1788 with doctests converted to code, and the rest placed in comments.
1789
Edward Loperb3666a32004-09-21 03:00:51 +00001790 \versionadded{2.3}
1791\end{funcdesc}
1792
Tim Peters05b05fe2004-09-26 05:09:59 +00001793\begin{funcdesc}{debug}{module, name\optional{, pm}}
1794 Debug the doctests for an object.
1795
1796 The \var{module} and \var{name} arguments are the same as for function
1797 \function{testsource()} above. The synthesized Python script for the
1798 named object's docstring is written to a temporary file, and then that
1799 file is run under the control of the Python debugger, \refmodule{pdb}.
1800
1801 A shallow copy of \code{\var{module}.__dict__} is used for both local
1802 and global execution context.
1803
1804 Optional argument \var{pm} controls whether post-mortem debugging is
Tim Peters9463d872004-09-26 21:05:03 +00001805 used. If \var{pm} has a true value, the script file is run directly, and
1806 the debugger gets involved only if the script terminates via raising an
1807 unhandled exception. If it does, then post-mortem debugging is invoked,
1808 via \code{\refmodule{pdb}.post_mortem()}, passing the traceback object
Tim Peters05b05fe2004-09-26 05:09:59 +00001809 from the unhandled exception. If \var{pm} is not specified, or is false,
1810 the script is run under the debugger from the start, via passing an
Tim Peters9463d872004-09-26 21:05:03 +00001811 appropriate \function{execfile()} call to \code{\refmodule{pdb}.run()}.
Tim Peters05b05fe2004-09-26 05:09:59 +00001812
1813 \versionadded{2.3}
1814
1815 \versionchanged[The \var{pm} argument was added]{2.4}
1816\end{funcdesc}
1817
1818\begin{funcdesc}{debug_src}{src\optional{, pm}\optional{, globs}}
1819 Debug the doctests in a string.
1820
1821 This is like function \function{debug()} above, except that
1822 a string containing doctest examples is specified directly, via
1823 the \var{src} argument.
1824
1825 Optional argument \var{pm} has the same meaning as in function
1826 \function{debug()} above.
1827
1828 Optional argument \var{globs} gives a dictionary to use as both
1829 local and global execution context. If not specified, or \code{None},
1830 an empty dictionary is used. If specified, a shallow copy of the
1831 dictionary is used.
1832
1833 \versionadded{2.4}
1834\end{funcdesc}
1835
1836The \class{DebugRunner} class, and the special exceptions it may raise,
1837are of most interest to testing framework authors, and will only be
1838sketched here. See the source code, and especially \class{DebugRunner}'s
1839docstring (which is a doctest!) for more details:
1840
Edward Loperb3666a32004-09-21 03:00:51 +00001841\begin{classdesc}{DebugRunner}{\optional{checker}\optional{,
1842 verbose}\optional{, optionflags}}
1843
1844 A subclass of \class{DocTestRunner} that raises an exception as
1845 soon as a failure is encountered. If an unexpected exception
1846 occurs, an \exception{UnexpectedException} exception is raised,
1847 containing the test, the example, and the original exception. If
1848 the output doesn't match, then a \exception{DocTestFailure}
1849 exception is raised, containing the test, the example, and the
1850 actual output.
1851
1852 For information about the constructor parameters and methods, see
1853 the documentation for \class{DocTestRunner} in
1854 section~\ref{doctest-advanced-api}.
1855\end{classdesc}
1856
Tim Peters05b05fe2004-09-26 05:09:59 +00001857There are two exceptions that may be raised by \class{DebugRunner}
1858instances:
1859
Edward Loperb3666a32004-09-21 03:00:51 +00001860\begin{excclassdesc}{DocTestFailure}{test, example, got}
1861 An exception thrown by \class{DocTestRunner} to signal that a
1862 doctest example's actual output did not match its expected output.
1863 The constructor arguments are used to initialize the member
1864 variables of the same names.
1865\end{excclassdesc}
1866\exception{DocTestFailure} defines the following member variables:
1867\begin{memberdesc}{test}
1868 The \class{DocTest} object that was being run when the example failed.
1869\end{memberdesc}
1870\begin{memberdesc}{example}
1871 The \class{Example} that failed.
1872\end{memberdesc}
1873\begin{memberdesc}{got}
1874 The example's actual output.
1875\end{memberdesc}
1876
Tim Peters05b05fe2004-09-26 05:09:59 +00001877\begin{excclassdesc}{UnexpectedException}{test, example, exc_info}
Edward Loperb3666a32004-09-21 03:00:51 +00001878 An exception thrown by \class{DocTestRunner} to signal that a
1879 doctest example raised an unexpected exception. The constructor
1880 arguments are used to initialize the member variables of the same
1881 names.
1882\end{excclassdesc}
1883\exception{UnexpectedException} defines the following member variables:
1884\begin{memberdesc}{test}
1885 The \class{DocTest} object that was being run when the example failed.
1886\end{memberdesc}
1887\begin{memberdesc}{example}
1888 The \class{Example} that failed.
1889\end{memberdesc}
1890\begin{memberdesc}{exc_info}
1891 A tuple containing information about the unexpected exception, as
1892 returned by \function{sys.exc_info()}.
1893\end{memberdesc}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001894
Edward Loperb3666a32004-09-21 03:00:51 +00001895\subsection{Soapbox\label{doctest-soapbox}}
Tim Peters76882292001-02-17 05:58:44 +00001896
Tim Peters9463d872004-09-26 21:05:03 +00001897As mentioned in the introduction, \refmodule{doctest} has grown to have
Tim Peters3f791252004-09-25 03:50:35 +00001898three primary uses:
Tim Peters76882292001-02-17 05:58:44 +00001899
1900\begin{enumerate}
Edward Loperb3666a32004-09-21 03:00:51 +00001901\item Checking examples in docstrings.
1902\item Regression testing.
Tim Peters3f791252004-09-25 03:50:35 +00001903\item Executable documentation / literate testing.
Fred Drakec1158352001-06-11 14:55:01 +00001904\end{enumerate}
1905
Tim Peters3f791252004-09-25 03:50:35 +00001906These uses have different requirements, and it is important to
Edward Loperb3666a32004-09-21 03:00:51 +00001907distinguish them. In particular, filling your docstrings with obscure
1908test cases makes for bad documentation.
Tim Peters76882292001-02-17 05:58:44 +00001909
Edward Loperb3666a32004-09-21 03:00:51 +00001910When writing a docstring, choose docstring examples with care.
1911There's an art to this that needs to be learned---it may not be
1912natural at first. Examples should add genuine value to the
1913documentation. A good example can often be worth many words.
Fred Drake7a6b4f02003-07-17 16:00:01 +00001914If done with care, the examples will be invaluable for your users, and
1915will pay back the time it takes to collect them many times over as the
1916years go by and things change. I'm still amazed at how often one of
Tim Peters3f791252004-09-25 03:50:35 +00001917my \refmodule{doctest} examples stops working after a "harmless"
Fred Drake7a6b4f02003-07-17 16:00:01 +00001918change.
Tim Peters76882292001-02-17 05:58:44 +00001919
Tim Peters3f791252004-09-25 03:50:35 +00001920Doctest also makes an excellent tool for regression testing, especially if
1921you don't skimp on explanatory text. By interleaving prose and examples,
1922it becomes much easier to keep track of what's actually being tested, and
1923why. When a test fails, good prose can make it much easier to figure out
1924what the problem is, and how it should be fixed. It's true that you could
1925write extensive comments in code-based testing, but few programmers do.
1926Many have found that using doctest approaches instead leads to much clearer
1927tests. Perhaps this is simply because doctest makes writing prose a little
1928easier than writing code, while writing comments in code is a little
1929harder. I think it goes deeper than just that: the natural attitude
1930when writing a doctest-based test is that you want to explain the fine
1931points of your software, and illustrate them with examples. This in
1932turn naturally leads to test files that start with the simplest features,
1933and logically progress to complications and edge cases. A coherent
1934narrative is the result, instead of a collection of isolated functions
1935that test isolated bits of functionality seemingly at random. It's
1936a different attitude, and produces different results, blurring the
1937distinction between testing and explaining.
1938
1939Regression testing is best confined to dedicated objects or files. There
1940are several options for organizing tests:
Edward Loperb3666a32004-09-21 03:00:51 +00001941
1942\begin{itemize}
Tim Peters3f791252004-09-25 03:50:35 +00001943\item Write text files containing test cases as interactive examples,
1944 and test the files using \function{testfile()} or
1945 \function{DocFileSuite()}. This is recommended, although is
1946 easiest to do for new projects, designed from the start to use
1947 doctest.
Edward Loperb3666a32004-09-21 03:00:51 +00001948\item Define functions named \code{_regrtest_\textit{topic}} that
1949 consist of single docstrings, containing test cases for the
1950 named topics. These functions can be included in the same file
1951 as the module, or separated out into a separate test file.
1952\item Define a \code{__test__} dictionary mapping from regression test
1953 topics to docstrings containing test cases.
Edward Loperb3666a32004-09-21 03:00:51 +00001954\end{itemize}