blob: 92aa039a11649d9db0093c89f157d753e901b7a5 [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
336\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
337the expected output (if any) extends to the next \code{'>\code{>}>~'}
338or 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
389expected output as appeared in the initial \code{'>\code{>}>~'} line
390that 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
410the example: just paste in the traceback. Since tracebacks contain
411details that are likely to change rapidly (for example, exact file paths
412and line numbers), this is one case where doctest works hard to be
413flexible in what it accepts.
414
415Simple example:
Tim Peters76882292001-02-17 05:58:44 +0000416
417\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000418>>> [1, 2, 3].remove(42)
419Traceback (most recent call last):
420 File "<stdin>", line 1, in ?
421ValueError: list.remove(x): x not in list
Tim Peters76882292001-02-17 05:58:44 +0000422\end{verbatim}
423
Edward Loper19b19582004-08-25 23:07:03 +0000424That doctest succeeds if \exception{ValueError} is raised, with the
Tim Petersa07bcd42004-08-26 04:47:31 +0000425\samp{list.remove(x): x not in list} detail as shown.
Tim Peters41a65ea2004-08-13 03:55:05 +0000426
Edward Loper19b19582004-08-25 23:07:03 +0000427The expected output for an exception must start with a traceback
428header, which may be either of the following two lines, indented the
429same as the first line of the example:
Tim Peters41a65ea2004-08-13 03:55:05 +0000430
431\begin{verbatim}
432Traceback (most recent call last):
433Traceback (innermost last):
434\end{verbatim}
435
Edward Loper19b19582004-08-25 23:07:03 +0000436The traceback header is followed by an optional traceback stack, whose
Tim Petersa07bcd42004-08-26 04:47:31 +0000437contents are ignored by doctest. The traceback stack is typically
438omitted, or copied verbatim from an interactive session.
Edward Loper19b19582004-08-25 23:07:03 +0000439
Tim Petersa07bcd42004-08-26 04:47:31 +0000440The traceback stack is followed by the most interesting part: the
Edward Loper19b19582004-08-25 23:07:03 +0000441line(s) containing the exception type and detail. This is usually the
442last line of a traceback, but can extend across multiple lines if the
Tim Petersa07bcd42004-08-26 04:47:31 +0000443exception has a multi-line detail:
Tim Peters41a65ea2004-08-13 03:55:05 +0000444
445\begin{verbatim}
Edward Loper456ff912004-09-27 03:30:44 +0000446>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000447Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000448 File "<stdin>", line 1, in ?
449ValueError: multi
450 line
451detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000452\end{verbatim}
453
Edward Loper6cc13502004-09-19 01:16:44 +0000454The last three lines (starting with \exception{ValueError}) are
Edward Loper19b19582004-08-25 23:07:03 +0000455compared against the exception's type and detail, and the rest are
456ignored.
Tim Peters41a65ea2004-08-13 03:55:05 +0000457
Edward Loper19b19582004-08-25 23:07:03 +0000458Best practice is to omit the traceback stack, unless it adds
Tim Petersa07bcd42004-08-26 04:47:31 +0000459significant documentation value to the example. So the last example
Tim Peters41a65ea2004-08-13 03:55:05 +0000460is probably better as:
461
462\begin{verbatim}
Edward Loper456ff912004-09-27 03:30:44 +0000463>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000464Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000465 ...
466ValueError: multi
467 line
468detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000469\end{verbatim}
470
Tim Petersa07bcd42004-08-26 04:47:31 +0000471Note that tracebacks are treated very specially. In particular, in the
Tim Peters41a65ea2004-08-13 03:55:05 +0000472rewritten example, the use of \samp{...} is independent of doctest's
Tim Petersa07bcd42004-08-26 04:47:31 +0000473\constant{ELLIPSIS} option. The ellipsis in that example could be left
474out, or could just as well be three (or three hundred) commas or digits,
475or an indented transcript of a Monty Python skit.
476
477Some details you should read once, but won't need to remember:
478
479\begin{itemize}
480
481\item Doctest can't guess whether your expected output came from an
482 exception traceback or from ordinary printing. So, e.g., an example
483 that expects \samp{ValueError: 42 is prime} will pass whether
484 \exception{ValueError} is actually raised or if the example merely
485 prints that traceback text. In practice, ordinary output rarely begins
486 with a traceback header line, so this doesn't create real problems.
487
488\item Each line of the traceback stack (if present) must be indented
489 further than the first line of the example, \emph{or} start with a
490 non-alphanumeric character. The first line following the traceback
491 header indented the same and starting with an alphanumeric is taken
492 to be the start of the exception detail. Of course this does the
493 right thing for genuine tracebacks.
494
Tim Peters1fbf9c52004-09-04 17:21:02 +0000495\item When the \constant{IGNORE_EXCEPTION_DETAIL} doctest option is
496 is specified, everything following the leftmost colon is ignored.
497
Edward Loper0fe00aa2004-09-30 17:18:18 +0000498\item The interactive shell omits the traceback header line for some
499 \exception{SyntaxError}s. But doctest uses the traceback header
500 line to distinguish exceptions from non-exceptions. So in the rare
501 case where you need to test a \exception{SyntaxError} that omits the
502 traceback header, you will need to manually add the traceback header
503 line to your test example.
504
505\item For some \exception{SyntaxError}s, Python displays the character
506 position of the syntax error, using a \code{\^} marker:
507
508\begin{verbatim}
509>>> 1 1
510 File "<stdin>", line 1
511 1 1
512 ^
513SyntaxError: invalid syntax
514\end{verbatim}
515
516 Since the lines showing the position of the error come before the
517 exception type and detail, they are not checked by doctest. For
518 example, the following test would pass, even though it puts the
519 \code{\^} marker in the wrong location:
520
521\begin{verbatim}
522>>> 1 1
523 File "<stdin>", line 1
524 1 1
525 ^
526SyntaxError: invalid syntax
527\end{verbatim}
528
Tim Petersa07bcd42004-08-26 04:47:31 +0000529\end{itemize}
Tim Peters41a65ea2004-08-13 03:55:05 +0000530
Tim Peters39c5de02004-09-25 01:22:29 +0000531\versionchanged[The ability to handle a multi-line exception detail,
532 and the \constant{IGNORE_EXCEPTION_DETAIL} doctest option,
533 were added]{2.4}
Tim Peters0e448072004-08-26 01:02:08 +0000534
Edward Loperb3666a32004-09-21 03:00:51 +0000535\subsubsection{Option Flags and Directives\label{doctest-options}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000536
Tim Peterscf533552004-08-26 04:50:38 +0000537A number of option flags control various aspects of doctest's
Tim Peters026f8dc2004-08-19 16:38:58 +0000538behavior. Symbolic names for the flags are supplied as module constants,
Tim Peters83e259a2004-08-13 21:55:21 +0000539which can be or'ed together and passed to various functions. The names
Tim Peters026f8dc2004-08-19 16:38:58 +0000540can also be used in doctest directives (see below).
Tim Peters8a3b69c2004-08-12 22:31:25 +0000541
Tim Petersa07bcd42004-08-26 04:47:31 +0000542The first group of options define test semantics, controlling
543aspects of how doctest decides whether actual output matches an
544example's expected output:
545
Tim Peters8a3b69c2004-08-12 22:31:25 +0000546\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
547 By default, if an expected output block contains just \code{1},
548 an actual output block containing just \code{1} or just
549 \code{True} is considered to be a match, and similarly for \code{0}
550 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
551 specified, neither substitution is allowed. The default behavior
552 caters to that Python changed the return type of many functions
553 from integer to boolean; doctests expecting "little integer"
554 output still work in these cases. This option will probably go
555 away, but not for several years.
556\end{datadesc}
557
558\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
559 By default, if an expected output block contains a line
560 containing only the string \code{<BLANKLINE>}, then that line
561 will match a blank line in the actual output. Because a
562 genuinely blank line delimits the expected output, this is
563 the only way to communicate that a blank line is expected. When
564 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
565 is not allowed.
566\end{datadesc}
567
568\begin{datadesc}{NORMALIZE_WHITESPACE}
569 When specified, all sequences of whitespace (blanks and newlines) are
570 treated as equal. Any sequence of whitespace within the expected
571 output will match any sequence of whitespace within the actual output.
572 By default, whitespace must match exactly.
573 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
574 of expected output is very long, and you want to wrap it across
575 multiple lines in your source.
576\end{datadesc}
577
578\begin{datadesc}{ELLIPSIS}
579 When specified, an ellipsis marker (\code{...}) in the expected output
580 can match any substring in the actual output. This includes
Tim Peters026f8dc2004-08-19 16:38:58 +0000581 substrings that span line boundaries, and empty substrings, so it's
582 best to keep usage of this simple. Complicated uses can lead to the
583 same kinds of "oops, it matched too much!" surprises that \regexp{.*}
584 is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000585\end{datadesc}
586
Tim Peters1fbf9c52004-09-04 17:21:02 +0000587\begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
588 When specified, an example that expects an exception passes if
589 an exception of the expected type is raised, even if the exception
590 detail does not match. For example, an example expecting
591 \samp{ValueError: 42} will pass if the actual exception raised is
592 \samp{ValueError: 3*14}, but will fail, e.g., if
593 \exception{TypeError} is raised.
594
595 Note that a similar effect can be obtained using \constant{ELLIPSIS},
596 and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
597 prior to 2.4 become uninteresting. Until then,
598 \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
599 doctest that doesn't care about the exception detail yet continues
600 to pass under Python releases prior to 2.4 (doctest directives
601 appear to be comments to them). For example,
602
603\begin{verbatim}
604>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
605Traceback (most recent call last):
606 File "<stdin>", line 1, in ?
607TypeError: object doesn't support item assignment
608\end{verbatim}
609
610 passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
611 to say "does not" instead of "doesn't".
612
613\end{datadesc}
614
Tim Peters38330fe2004-08-30 16:19:24 +0000615\begin{datadesc}{COMPARISON_FLAGS}
616 A bitmask or'ing together all the comparison flags above.
617\end{datadesc}
618
Tim Petersf33683f2004-08-26 04:52:46 +0000619The second group of options controls how test failures are reported:
Tim Petersa07bcd42004-08-26 04:47:31 +0000620
Edward Loper71f55af2004-08-26 01:41:51 +0000621\begin{datadesc}{REPORT_UDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000622 When specified, failures that involve multi-line expected and
623 actual outputs are displayed using a unified diff.
624\end{datadesc}
625
Edward Loper71f55af2004-08-26 01:41:51 +0000626\begin{datadesc}{REPORT_CDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000627 When specified, failures that involve multi-line expected and
628 actual outputs will be displayed using a context diff.
629\end{datadesc}
630
Edward Loper71f55af2004-08-26 01:41:51 +0000631\begin{datadesc}{REPORT_NDIFF}
Tim Petersc6cbab02004-08-22 19:43:28 +0000632 When specified, differences are computed by \code{difflib.Differ},
633 using the same algorithm as the popular \file{ndiff.py} utility.
634 This is the only method that marks differences within lines as
635 well as across lines. For example, if a line of expected output
636 contains digit \code{1} where actual output contains letter \code{l},
637 a line is inserted with a caret marking the mismatching column
638 positions.
639\end{datadesc}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000640
Edward Lopera89f88d2004-08-26 02:45:51 +0000641\begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
642 When specified, display the first failing example in each doctest,
643 but suppress output for all remaining examples. This will prevent
644 doctest from reporting correct examples that break because of
645 earlier failures; but it might also hide incorrect examples that
646 fail independently of the first failure. When
647 \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
648 examples are still run, and still count towards the total number of
649 failures reported; only the output is suppressed.
650\end{datadesc}
651
Tim Peters38330fe2004-08-30 16:19:24 +0000652\begin{datadesc}{REPORTING_FLAGS}
653 A bitmask or'ing together all the reporting flags above.
654\end{datadesc}
655
Edward Loperb3666a32004-09-21 03:00:51 +0000656"Doctest directives" may be used to modify the option flags for
657individual examples. Doctest directives are expressed as a special
658Python comment following an example's source code:
Tim Peters026f8dc2004-08-19 16:38:58 +0000659
660\begin{productionlist}[doctest]
661 \production{directive}
Edward Loper6cc13502004-09-19 01:16:44 +0000662 {"\#" "doctest:" \token{directive_options}}
663 \production{directive_options}
664 {\token{directive_option} ("," \token{directive_option})*}
665 \production{directive_option}
666 {\token{on_or_off} \token{directive_option_name}}
Tim Peters026f8dc2004-08-19 16:38:58 +0000667 \production{on_or_off}
668 {"+" | "-"}
Edward Loper6cc13502004-09-19 01:16:44 +0000669 \production{directive_option_name}
Tim Peters026f8dc2004-08-19 16:38:58 +0000670 {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
671\end{productionlist}
672
673Whitespace is not allowed between the \code{+} or \code{-} and the
Edward Loper6cc13502004-09-19 01:16:44 +0000674directive option name. The directive option name can be any of the
Edward Loperb3666a32004-09-21 03:00:51 +0000675option flag names explained above.
Tim Peters026f8dc2004-08-19 16:38:58 +0000676
Edward Loperb3666a32004-09-21 03:00:51 +0000677An example's doctest directives modify doctest's behavior for that
678single example. Use \code{+} to enable the named behavior, or
679\code{-} to disable it.
Tim Peters026f8dc2004-08-19 16:38:58 +0000680
681For example, this test passes:
682
683\begin{verbatim}
684>>> print range(20) #doctest: +NORMALIZE_WHITESPACE
685[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
68610, 11, 12, 13, 14, 15, 16, 17, 18, 19]
687\end{verbatim}
688
689Without the directive it would fail, both because the actual output
690doesn't have two blanks before the single-digit list elements, and
691because the actual output is on a single line. This test also passes,
Tim Petersa07bcd42004-08-26 04:47:31 +0000692and also requires a directive to do so:
Tim Peters026f8dc2004-08-19 16:38:58 +0000693
694\begin{verbatim}
695>>> print range(20) # doctest:+ELLIPSIS
696[0, 1, ..., 18, 19]
697\end{verbatim}
698
Edward Loper6cc13502004-09-19 01:16:44 +0000699Multiple directives can be used on a single physical line, separated
700by commas:
Tim Peters026f8dc2004-08-19 16:38:58 +0000701
702\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000703>>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +0000704[0, 1, ..., 18, 19]
705\end{verbatim}
706
Edward Loperb3666a32004-09-21 03:00:51 +0000707If multiple directive comments are used for a single example, then
708they are combined:
Edward Loper6cc13502004-09-19 01:16:44 +0000709
710\begin{verbatim}
711>>> print range(20) # doctest: +ELLIPSIS
712... # doctest: +NORMALIZE_WHITESPACE
713[0, 1, ..., 18, 19]
714\end{verbatim}
715
716As the previous example shows, you can add \samp{...} lines to your
Edward Loperb3666a32004-09-21 03:00:51 +0000717example containing only directives. This can be useful when an
Edward Loper6cc13502004-09-19 01:16:44 +0000718example is too long for a directive to comfortably fit on the same
719line:
720
721\begin{verbatim}
722>>> print range(5) + range(10,20) + range(30,40) + range(50,60)
723... # doctest: +ELLIPSIS
724[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
725\end{verbatim}
726
Tim Peters026f8dc2004-08-19 16:38:58 +0000727Note that since all options are disabled by default, and directives apply
728only to the example they appear in, enabling options (via \code{+} in a
729directive) is usually the only meaningful choice. However, option flags
730can also be passed to functions that run doctests, establishing different
731defaults. In such cases, disabling an option via \code{-} in a directive
732can be useful.
733
Tim Peters8a3b69c2004-08-12 22:31:25 +0000734\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
735 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
Edward Loper7d88a582004-09-28 05:50:57 +0000736 \constant{IGNORE_EXCEPTION_DETAIL},
Edward Lopera89f88d2004-08-26 02:45:51 +0000737 \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
Tim Peters38330fe2004-08-30 16:19:24 +0000738 \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
739 \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
Tim Peters026f8dc2004-08-19 16:38:58 +0000740 were added; by default \code{<BLANKLINE>} in expected output
741 matches an empty line in actual output; and doctest directives
742 were added]{2.4}
743
Tim Peters16be62f2004-09-26 02:38:41 +0000744There's also a way to register new option flag names, although this
Tim Peters9463d872004-09-26 21:05:03 +0000745isn't useful unless you intend to extend \refmodule{doctest} internals
Tim Peters16be62f2004-09-26 02:38:41 +0000746via subclassing:
747
748\begin{funcdesc}{register_optionflag}{name}
749 Create a new option flag with a given name, and return the new
750 flag's integer value. \function{register_optionflag()} can be
751 used when subclassing \class{OutputChecker} or
752 \class{DocTestRunner} to create new options that are supported by
753 your subclasses. \function{register_optionflag} should always be
754 called using the following idiom:
755
756\begin{verbatim}
757 MY_FLAG = register_optionflag('MY_FLAG')
758\end{verbatim}
759
760 \versionadded{2.4}
761\end{funcdesc}
762
Edward Loperb3666a32004-09-21 03:00:51 +0000763\subsubsection{Warnings\label{doctest-warnings}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000764
Tim Peters9463d872004-09-26 21:05:03 +0000765\refmodule{doctest} is serious about requiring exact matches in expected
Tim Peters2dc82052004-09-25 01:30:16 +0000766output. If even a single character doesn't match, the test fails. This
767will probably surprise you a few times, as you learn exactly what Python
768does and doesn't guarantee about output. For example, when printing a
769dict, Python doesn't guarantee that the key-value pairs will be printed
770in any particular order, so a test like
Tim Peters76882292001-02-17 05:58:44 +0000771
Edward Loperb3666a32004-09-21 03:00:51 +0000772% Hey! What happened to Monty Python examples?
773% Tim: ask Guido -- it's his example!
774\begin{verbatim}
775>>> foo()
776{"Hermione": "hippogryph", "Harry": "broomstick"}
777\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000778
Edward Loperb3666a32004-09-21 03:00:51 +0000779is vulnerable! One workaround is to do
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000780
Edward Loperb3666a32004-09-21 03:00:51 +0000781\begin{verbatim}
782>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
783True
784\end{verbatim}
785
786instead. Another is to do
787
788\begin{verbatim}
789>>> d = foo().items()
790>>> d.sort()
791>>> d
792[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
793\end{verbatim}
794
795There are others, but you get the idea.
796
797Another bad idea is to print things that embed an object address, like
798
799\begin{verbatim}
800>>> id(1.0) # certain to fail some of the time
8017948648
Tim Peters39c5de02004-09-25 01:22:29 +0000802>>> class C: pass
803>>> C() # the default repr() for instances embeds an address
804<__main__.C instance at 0x00AC18F0>
805\end{verbatim}
806
807The \constant{ELLIPSIS} directive gives a nice approach for the last
808example:
809
810\begin{verbatim}
811>>> C() #doctest: +ELLIPSIS
812<__main__.C instance at 0x...>
Edward Loperb3666a32004-09-21 03:00:51 +0000813\end{verbatim}
814
815Floating-point numbers are also subject to small output variations across
816platforms, because Python defers to the platform C library for float
817formatting, and C libraries vary widely in quality here.
818
819\begin{verbatim}
820>>> 1./7 # risky
8210.14285714285714285
822>>> print 1./7 # safer
8230.142857142857
824>>> print round(1./7, 6) # much safer
8250.142857
826\end{verbatim}
827
828Numbers of the form \code{I/2.**J} are safe across all platforms, and I
829often contrive doctest examples to produce numbers of that form:
830
831\begin{verbatim}
832>>> 3./4 # utterly safe
8330.75
834\end{verbatim}
835
836Simple fractions are also easier for people to understand, and that makes
837for better documentation.
838
Edward Loperb3666a32004-09-21 03:00:51 +0000839\subsection{Basic API\label{doctest-basic-api}}
840
841The functions \function{testmod()} and \function{testfile()} provide a
842simple interface to doctest that should be sufficient for most basic
Tim Petersb2b26ac2004-09-25 01:51:49 +0000843uses. For a less formal introduction to these two functions, see
Edward Loperb3666a32004-09-21 03:00:51 +0000844sections \ref{doctest-simple-testmod} and
845\ref{doctest-simple-testfile}.
846
847\begin{funcdesc}{testfile}{filename\optional{, module_relative}\optional{,
848 name}\optional{, package}\optional{,
849 globs}\optional{, verbose}\optional{,
850 report}\optional{, optionflags}\optional{,
Edward Lopera4c6a852004-09-27 04:08:20 +0000851 extraglobs}\optional{, raise_on_error}\optional{,
852 parser}}
Edward Loperb3666a32004-09-21 03:00:51 +0000853
854 All arguments except \var{filename} are optional, and should be
855 specified in keyword form.
856
857 Test examples in the file named \var{filename}. Return
858 \samp{(\var{failure_count}, \var{test_count})}.
859
860 Optional argument \var{module_relative} specifies how the filename
861 should be interpreted:
862
863 \begin{itemize}
864 \item If \var{module_relative} is \code{True} (the default), then
Tim Petersb2b26ac2004-09-25 01:51:49 +0000865 \var{filename} specifies an OS-independent module-relative
Edward Loperb3666a32004-09-21 03:00:51 +0000866 path. By default, this path is relative to the calling
867 module's directory; but if the \var{package} argument is
868 specified, then it is relative to that package. To ensure
Tim Petersb2b26ac2004-09-25 01:51:49 +0000869 OS-independence, \var{filename} should use \code{/} characters
Edward Loperb3666a32004-09-21 03:00:51 +0000870 to separate path segments, and may not be an absolute path
871 (i.e., it may not begin with \code{/}).
872 \item If \var{module_relative} is \code{False}, then \var{filename}
Tim Petersb2b26ac2004-09-25 01:51:49 +0000873 specifies an OS-specific path. The path may be absolute or
Edward Loperb3666a32004-09-21 03:00:51 +0000874 relative; relative paths are resolved with respect to the
875 current working directory.
876 \end{itemize}
877
878 Optional argument \var{name} gives the name of the test; by default,
879 or if \code{None}, \code{os.path.basename(\var{filename})} is used.
880
881 Optional argument \var{package} is a Python package or the name of a
882 Python package whose directory should be used as the base directory
883 for a module-relative filename. If no package is specified, then
884 the calling module's directory is used as the base directory for
885 module-relative filenames. It is an error to specify \var{package}
886 if \var{module_relative} is \code{False}.
887
888 Optional argument \var{globs} gives a dict to be used as the globals
Tim Petersb2b26ac2004-09-25 01:51:49 +0000889 when executing examples. A new shallow copy of this dict is
Edward Loperb3666a32004-09-21 03:00:51 +0000890 created for the doctest, so its examples start with a clean slate.
Tim Petersb2b26ac2004-09-25 01:51:49 +0000891 By default, or if \code{None}, a new empty dict is used.
Edward Loperb3666a32004-09-21 03:00:51 +0000892
893 Optional argument \var{extraglobs} gives a dict merged into the
894 globals used to execute examples. This works like
895 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
896 common key, the associated value in \var{extraglobs} appears in the
897 combined dict. By default, or if \code{None}, no extra globals are
898 used. This is an advanced feature that allows parameterization of
899 doctests. For example, a doctest can be written for a base class, using
900 a generic name for the class, then reused to test any number of
901 subclasses by passing an \var{extraglobs} dict mapping the generic
902 name to the subclass to be tested.
903
904 Optional argument \var{verbose} prints lots of stuff if true, and prints
905 only failures if false; by default, or if \code{None}, it's true
906 if and only if \code{'-v'} is in \code{sys.argv}.
907
908 Optional argument \var{report} prints a summary at the end when true,
909 else prints nothing at the end. In verbose mode, the summary is
910 detailed, else the summary is very brief (in fact, empty if all tests
911 passed).
912
913 Optional argument \var{optionflags} or's together option flags. See
Tim Peters8c0a2cf2004-09-25 03:02:23 +0000914 section~\ref{doctest-options}.
Edward Loperb3666a32004-09-21 03:00:51 +0000915
916 Optional argument \var{raise_on_error} defaults to false. If true,
917 an exception is raised upon the first failure or unexpected exception
918 in an example. This allows failures to be post-mortem debugged.
919 Default behavior is to continue running examples.
920
Edward Lopera4c6a852004-09-27 04:08:20 +0000921 Optional argument \var{parser} specifies a \class{DocTestParser} (or
922 subclass) that should be used to extract tests from the files. It
923 defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
924
Edward Loperb3666a32004-09-21 03:00:51 +0000925 \versionadded{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000926\end{funcdesc}
927
Tim Peters83e259a2004-08-13 21:55:21 +0000928\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
929 globs}\optional{, verbose}\optional{,
930 isprivate}\optional{, report}\optional{,
931 optionflags}\optional{, extraglobs}\optional{,
Tim Peters82788602004-09-13 15:03:17 +0000932 raise_on_error}\optional{, exclude_empty}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000933
Tim Peters83e259a2004-08-13 21:55:21 +0000934 All arguments are optional, and all except for \var{m} should be
935 specified in keyword form.
936
937 Test examples in docstrings in functions and classes reachable
Tim Petersb2b26ac2004-09-25 01:51:49 +0000938 from module \var{m} (or module \module{__main__} if \var{m} is not
939 supplied or is \code{None}), starting with \code{\var{m}.__doc__}.
Tim Peters83e259a2004-08-13 21:55:21 +0000940
941 Also test examples reachable from dict \code{\var{m}.__test__}, if it
942 exists and is not \code{None}. \code{\var{m}.__test__} maps
943 names (strings) to functions, classes and strings; function and class
944 docstrings are searched for examples; strings are searched directly,
945 as if they were docstrings.
946
947 Only docstrings attached to objects belonging to module \var{m} are
948 searched.
949
950 Return \samp{(\var{failure_count}, \var{test_count})}.
951
952 Optional argument \var{name} gives the name of the module; by default,
953 or if \code{None}, \code{\var{m}.__name__} is used.
954
Tim Peters82788602004-09-13 15:03:17 +0000955 Optional argument \var{exclude_empty} defaults to false. If true,
956 objects for which no doctests are found are excluded from consideration.
957 The default is a backward compatibility hack, so that code still
958 using \method{doctest.master.summarize()} in conjunction with
959 \function{testmod()} continues to get output for objects with no tests.
960 The \var{exclude_empty} argument to the newer \class{DocTestFinder}
961 constructor defaults to true.
962
Tim Petersb2b26ac2004-09-25 01:51:49 +0000963 Optional arguments \var{extraglobs}, \var{verbose}, \var{report},
964 \var{optionflags}, \var{raise_on_error}, and \var{globs} are the same as
965 for function \function{testfile()} above, except that \var{globs}
966 defaults to \code{\var{m}.__dict__}.
967
Tim Peters83e259a2004-08-13 21:55:21 +0000968 Optional argument \var{isprivate} specifies a function used to
969 determine whether a name is private. The default function treats
970 all names as public. \var{isprivate} can be set to
971 \code{doctest.is_private} to skip over names that are
972 private according to Python's underscore naming convention.
973 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
974 If you need to skip tests based on name, filter the list returned by
975 \code{DocTestFinder.find()} instead.}
976
977 \versionchanged[The parameter \var{optionflags} was added]{2.3}
978
Tim Peters82788602004-09-13 15:03:17 +0000979 \versionchanged[The parameters \var{extraglobs}, \var{raise_on_error}
980 and \var{exclude_empty} were added]{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000981\end{funcdesc}
982
Tim Peters00411212004-09-26 20:45:04 +0000983There's also a function to run the doctests associated with a single object.
984This function is provided for backward compatibility. There are no plans
985to deprecate it, but it's rarely useful:
986
987\begin{funcdesc}{run_docstring_examples}{f, globs\optional{,
988 verbose}\optional{, name}\optional{,
989 compileflags}\optional{, optionflags}}
990
991 Test examples associated with object \var{f}; for example, \var{f} may
992 be a module, function, or class object.
993
994 A shallow copy of dictionary argument \var{globs} is used for the
995 execution context.
996
997 Optional argument \var{name} is used in failure messages, and defaults
998 to \code{"NoName"}.
999
1000 If optional argument \var{verbose} is true, output is generated even
1001 if there are no failures. By default, output is generated only in case
1002 of an example failure.
1003
1004 Optional argument \var{compileflags} gives the set of flags that should
1005 be used by the Python compiler when running the examples. By default, or
1006 if \code{None}, flags are deduced corresponding to the set of future
1007 features found in \var{globs}.
1008
1009 Optional argument \var{optionflags} works as for function
1010 \function{testfile()} above.
1011\end{funcdesc}
1012
Edward Loperb3666a32004-09-21 03:00:51 +00001013\subsection{Unittest API\label{doctest-unittest-api}}
1014
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001015As your collection of doctest'ed modules grows, you'll want a way to run
Tim Peters9463d872004-09-26 21:05:03 +00001016all their doctests systematically. Prior to Python 2.4, \refmodule{doctest}
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001017had a barely documented \class{Tester} class that supplied a rudimentary
1018way to combine doctests from multiple modules. \class{Tester} was feeble,
1019and in practice most serious Python testing frameworks build on the
Tim Peters9463d872004-09-26 21:05:03 +00001020\refmodule{unittest} module, which supplies many flexible ways to combine
1021tests from multiple sources. So, in Python 2.4, \refmodule{doctest}'s
1022\class{Tester} class is deprecated, and \refmodule{doctest} provides two
1023functions that can be used to create \refmodule{unittest} test suites from
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001024modules and text files containing doctests. These test suites can then be
Tim Peters9463d872004-09-26 21:05:03 +00001025run using \refmodule{unittest} test runners:
Edward Loperb3666a32004-09-21 03:00:51 +00001026
1027\begin{verbatim}
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001028import unittest
1029import doctest
1030import my_module_with_doctests, and_another
Edward Loperb3666a32004-09-21 03:00:51 +00001031
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001032suite = unittest.TestSuite()
1033for mod in my_module_with_doctests, and_another:
1034 suite.addTest(doctest.DocTestSuite(mod))
1035runner = unittest.TextTestRunner()
1036runner.run(suite)
Edward Loperb3666a32004-09-21 03:00:51 +00001037\end{verbatim}
1038
Tim Peters9463d872004-09-26 21:05:03 +00001039There are two main functions for creating \class{\refmodule{unittest}.TestSuite}
Tim Peters6a0a64b2004-09-26 02:12:40 +00001040instances from text files and modules with doctests:
1041
Edward Loperb3666a32004-09-21 03:00:51 +00001042\begin{funcdesc}{DocFileSuite}{*paths, **kw}
1043 Convert doctest tests from one or more text files to a
1044 \class{\refmodule{unittest}.TestSuite}.
1045
Tim Peters9463d872004-09-26 21:05:03 +00001046 The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
1047 unittest framework and runs the interactive examples in each file. If an
1048 example in any file fails, then the synthesized unit test fails, and a
1049 \exception{failureException} exception is raised showing the name of the
1050 file containing the test and a (sometimes approximate) line number.
Edward Loperb3666a32004-09-21 03:00:51 +00001051
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001052 Pass one or more paths (as strings) to text files to be examined.
Edward Loperb3666a32004-09-21 03:00:51 +00001053
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001054 Options may be provided as keyword arguments:
1055
1056 Optional argument \var{module_relative} specifies how
Raymond Hettingerc90ea822004-09-25 08:09:23 +00001057 the filenames in \var{paths} should be interpreted:
Edward Loperb3666a32004-09-21 03:00:51 +00001058
1059 \begin{itemize}
1060 \item If \var{module_relative} is \code{True} (the default), then
Tim Petersb2b26ac2004-09-25 01:51:49 +00001061 each filename specifies an OS-independent module-relative
Edward Loperb3666a32004-09-21 03:00:51 +00001062 path. By default, this path is relative to the calling
1063 module's directory; but if the \var{package} argument is
1064 specified, then it is relative to that package. To ensure
Tim Petersb2b26ac2004-09-25 01:51:49 +00001065 OS-independence, each filename should use \code{/} characters
Edward Loperb3666a32004-09-21 03:00:51 +00001066 to separate path segments, and may not be an absolute path
1067 (i.e., it may not begin with \code{/}).
1068 \item If \var{module_relative} is \code{False}, then each filename
Tim Petersb2b26ac2004-09-25 01:51:49 +00001069 specifies an OS-specific path. The path may be absolute or
Edward Loperb3666a32004-09-21 03:00:51 +00001070 relative; relative paths are resolved with respect to the
1071 current working directory.
1072 \end{itemize}
1073
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001074 Optional argument \var{package} is a Python package or the name
Edward Loperb3666a32004-09-21 03:00:51 +00001075 of a Python package whose directory should be used as the base
1076 directory for module-relative filenames. If no package is
1077 specified, then the calling module's directory is used as the base
1078 directory for module-relative filenames. It is an error to specify
1079 \var{package} if \var{module_relative} is \code{False}.
1080
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001081 Optional argument \var{setUp} specifies a set-up function for
Edward Loperb3666a32004-09-21 03:00:51 +00001082 the test suite. This is called before running the tests in each
1083 file. The \var{setUp} function will be passed a \class{DocTest}
1084 object. The setUp function can access the test globals as the
1085 \var{globs} attribute of the test passed.
1086
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001087 Optional argument \var{tearDown} specifies a tear-down function
Edward Loperb3666a32004-09-21 03:00:51 +00001088 for the test suite. This is called after running the tests in each
1089 file. The \var{tearDown} function will be passed a \class{DocTest}
1090 object. The setUp function can access the test globals as the
1091 \var{globs} attribute of the test passed.
1092
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001093 Optional argument \var{globs} is a dictionary containing the
Edward Loperb3666a32004-09-21 03:00:51 +00001094 initial global variables for the tests. A new copy of this
1095 dictionary is created for each test. By default, \var{globs} is
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001096 a new empty dictionary.
Edward Loperb3666a32004-09-21 03:00:51 +00001097
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001098 Optional argument \var{optionflags} specifies the default
1099 doctest options for the tests, created by or-ing together
1100 individual option flags. See section~\ref{doctest-options}.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001101 See function \function{set_unittest_reportflags()} below for
1102 a better way to set reporting options.
Edward Loperb3666a32004-09-21 03:00:51 +00001103
Edward Lopera4c6a852004-09-27 04:08:20 +00001104 Optional argument \var{parser} specifies a \class{DocTestParser} (or
1105 subclass) that should be used to extract tests from the files. It
1106 defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
1107
Edward Loperb3666a32004-09-21 03:00:51 +00001108 \versionadded{2.4}
1109\end{funcdesc}
1110
1111\begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
1112 globs}\optional{, extraglobs}\optional{,
1113 test_finder}\optional{, setUp}\optional{,
1114 tearDown}\optional{, checker}}
1115 Convert doctest tests for a module to a
1116 \class{\refmodule{unittest}.TestSuite}.
1117
Tim Peters9463d872004-09-26 21:05:03 +00001118 The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
1119 unittest framework and runs each doctest in the module. If any of the
1120 doctests fail, then the synthesized unit test fails, and a
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001121 \exception{failureException} exception is raised showing the name of the
1122 file containing the test and a (sometimes approximate) line number.
Edward Loperb3666a32004-09-21 03:00:51 +00001123
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001124 Optional argument \var{module} provides the module to be tested. It
Edward Loperb3666a32004-09-21 03:00:51 +00001125 can be a module object or a (possibly dotted) module name. If not
1126 specified, the module calling this function is used.
1127
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001128 Optional argument \var{globs} is a dictionary containing the
Edward Loperb3666a32004-09-21 03:00:51 +00001129 initial global variables for the tests. A new copy of this
1130 dictionary is created for each test. By default, \var{globs} is
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001131 a new empty dictionary.
Edward Loperb3666a32004-09-21 03:00:51 +00001132
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001133 Optional argument \var{extraglobs} specifies an extra set of
Edward Loperb3666a32004-09-21 03:00:51 +00001134 global variables, which is merged into \var{globs}. By default, no
1135 extra globals are used.
1136
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001137 Optional argument \var{test_finder} is the \class{DocTestFinder}
Edward Loperb3666a32004-09-21 03:00:51 +00001138 object (or a drop-in replacement) that is used to extract doctests
1139 from the module.
1140
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001141 Optional arguments \var{setUp}, \var{tearDown}, and \var{optionflags}
1142 are the same as for function \function{DocFileSuite()} above.
Edward Loperb3666a32004-09-21 03:00:51 +00001143
1144 \versionadded{2.3}
Tim Peters6a0a64b2004-09-26 02:12:40 +00001145
Edward Loperb3666a32004-09-21 03:00:51 +00001146 \versionchanged[The parameters \var{globs}, \var{extraglobs},
1147 \var{test_finder}, \var{setUp}, \var{tearDown}, and
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001148 \var{optionflags} were added; this function now uses the same search
1149 technique as \function{testmod()}]{2.4}
Edward Loperb3666a32004-09-21 03:00:51 +00001150\end{funcdesc}
1151
Tim Peters6a0a64b2004-09-26 02:12:40 +00001152Under the covers, \function{DocTestSuite()} creates a
Tim Peters9463d872004-09-26 21:05:03 +00001153\class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocTestCase}
1154instances, and \class{DocTestCase} is a subclass of
1155\class{\refmodule{unittest}.TestCase}. \class{DocTestCase} isn't documented
1156here (it's an internal detail), but studying its code can answer questions
1157about the exact details of \refmodule{unittest} integration.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001158
Tim Peters9463d872004-09-26 21:05:03 +00001159Similarly, \function{DocFileSuite()} creates a
1160\class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocFileCase}
1161instances, and \class{DocFileCase} is a subclass of \class{DocTestCase}.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001162
Tim Peters9463d872004-09-26 21:05:03 +00001163So both ways of creating a \class{\refmodule{unittest}.TestSuite} run
1164instances of \class{DocTestCase}. This is important for a subtle reason:
1165when you run \refmodule{doctest} functions yourself, you can control the
1166\refmodule{doctest} options in use directly, by passing option flags to
1167\refmodule{doctest} functions. However, if you're writing a
1168\refmodule{unittest} framework, \refmodule{unittest} ultimately controls
1169when and how tests get run. The framework author typically wants to
1170control \refmodule{doctest} reporting options (perhaps, e.g., specified by
1171command line options), but there's no way to pass options through
1172\refmodule{unittest} to \refmodule{doctest} test runners.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001173
Tim Peters9463d872004-09-26 21:05:03 +00001174For this reason, \refmodule{doctest} also supports a notion of
1175\refmodule{doctest} reporting flags specific to \refmodule{unittest}
1176support, via this function:
Tim Peters6a0a64b2004-09-26 02:12:40 +00001177
1178\begin{funcdesc}{set_unittest_reportflags}{flags}
Tim Peters9463d872004-09-26 21:05:03 +00001179 Set the \refmodule{doctest} reporting flags to use.
Tim Peters6a0a64b2004-09-26 02:12:40 +00001180
1181 Argument \var{flags} or's together option flags. See
1182 section~\ref{doctest-options}. Only "reporting flags" can be used.
1183
Tim Peters9463d872004-09-26 21:05:03 +00001184 This is a module-global setting, and affects all future doctests run by
1185 module \refmodule{unittest}: the \method{runTest()} method of
1186 \class{DocTestCase} looks at the option flags specified for the test case
1187 when the \class{DocTestCase} instance was constructed. If no reporting
1188 flags were specified (which is the typical and expected case),
1189 \refmodule{doctest}'s \refmodule{unittest} reporting flags are or'ed into
1190 the option flags, and the option flags so augmented are passed to the
Tim Peters6a0a64b2004-09-26 02:12:40 +00001191 \class{DocTestRunner} instance created to run the doctest. If any
Tim Peters9463d872004-09-26 21:05:03 +00001192 reporting flags were specified when the \class{DocTestCase} instance was
1193 constructed, \refmodule{doctest}'s \refmodule{unittest} reporting flags
Tim Peters6a0a64b2004-09-26 02:12:40 +00001194 are ignored.
1195
Tim Peters9463d872004-09-26 21:05:03 +00001196 The value of the \refmodule{unittest} reporting flags in effect before the
Tim Peters6a0a64b2004-09-26 02:12:40 +00001197 function was called is returned by the function.
1198
1199 \versionadded{2.4}
1200\end{funcdesc}
1201
1202
Edward Loperb3666a32004-09-21 03:00:51 +00001203\subsection{Advanced API\label{doctest-advanced-api}}
1204
1205The basic API is a simple wrapper that's intended to make doctest easy
Tim Peters8c0a2cf2004-09-25 03:02:23 +00001206to use. It is fairly flexible, and should meet most users' needs;
1207however, if you require more fine-grained control over testing, or
Edward Loperb3666a32004-09-21 03:00:51 +00001208wish to extend doctest's capabilities, then you should use the
1209advanced API.
1210
1211The advanced API revolves around two container classes, which are used
1212to store the interactive examples extracted from doctest cases:
1213
1214\begin{itemize}
1215\item \class{Example}: A single python statement, paired with its
1216 expected output.
1217\item \class{DocTest}: A collection of \class{Example}s, typically
1218 extracted from a single docstring or text file.
1219\end{itemize}
1220
1221Additional processing classes are defined to find, parse, and run, and
1222check doctest examples:
1223
1224\begin{itemize}
1225\item \class{DocTestFinder}: Finds all docstrings in a given module,
1226 and uses a \class{DocTestParser} to create a \class{DocTest}
1227 from every docstring that contains interactive examples.
1228\item \class{DocTestParser}: Creates a \class{DocTest} object from
1229 a string (such as an object's docstring).
1230\item \class{DocTestRunner}: Executes the examples in a
1231 \class{DocTest}, and uses an \class{OutputChecker} to verify
1232 their output.
1233\item \class{OutputChecker}: Compares the actual output from a
1234 doctest example with the expected output, and decides whether
1235 they match.
1236\end{itemize}
1237
Tim Peters3f791252004-09-25 03:50:35 +00001238The relationships among these processing classes are summarized in the
Edward Loperb3666a32004-09-21 03:00:51 +00001239following diagram:
1240
1241\begin{verbatim}
1242 list of:
1243+------+ +---------+
1244|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1245+------+ | ^ +---------+ | ^ (printed)
1246 | | | Example | | |
Tim Peters3f791252004-09-25 03:50:35 +00001247 v | | ... | v |
Edward Loperb3666a32004-09-21 03:00:51 +00001248 DocTestParser | Example | OutputChecker
1249 +---------+
1250\end{verbatim}
1251
1252\subsubsection{DocTest Objects\label{doctest-DocTest}}
1253\begin{classdesc}{DocTest}{examples, globs, name, filename, lineno,
1254 docstring}
1255 A collection of doctest examples that should be run in a single
1256 namespace. The constructor arguments are used to initialize the
1257 member variables of the same names.
1258 \versionadded{2.4}
1259\end{classdesc}
1260
1261\class{DocTest} defines the following member variables. They are
1262initialized by the constructor, and should not be modified directly.
1263
1264\begin{memberdesc}{examples}
1265 A list of \class{Example} objects encoding the individual
1266 interactive Python examples that should be run by this test.
1267\end{memberdesc}
1268
1269\begin{memberdesc}{globs}
1270 The namespace (aka globals) that the examples should be run in.
1271 This is a dictionary mapping names to values. Any changes to the
1272 namespace made by the examples (such as binding new variables)
1273 will be reflected in \member{globs} after the test is run.
1274\end{memberdesc}
1275
1276\begin{memberdesc}{name}
1277 A string name identifying the \class{DocTest}. Typically, this is
1278 the name of the object or file that the test was extracted from.
1279\end{memberdesc}
1280
1281\begin{memberdesc}{filename}
1282 The name of the file that this \class{DocTest} was extracted from;
1283 or \code{None} if the filename is unknown, or if the
1284 \class{DocTest} was not extracted from a file.
1285\end{memberdesc}
1286
1287\begin{memberdesc}{lineno}
1288 The line number within \member{filename} where this
1289 \class{DocTest} begins, or \code{None} if the line number is
1290 unavailable. This line number is zero-based with respect to the
1291 beginning of the file.
1292\end{memberdesc}
1293
1294\begin{memberdesc}{docstring}
1295 The string that the test was extracted from, or `None` if the
1296 string is unavailable, or if the test was not extracted from a
1297 string.
1298\end{memberdesc}
1299
1300\subsubsection{Example Objects\label{doctest-Example}}
1301\begin{classdesc}{Example}{source, want\optional{,
1302 exc_msg}\optional{, lineno}\optional{,
1303 indent}\optional{, options}}
1304 A single interactive example, consisting of a Python statement and
1305 its expected output. The constructor arguments are used to
1306 initialize the member variables of the same names.
1307 \versionadded{2.4}
1308\end{classdesc}
1309
1310\class{Example} defines the following member variables. They are
1311initialized by the constructor, and should not be modified directly.
1312
1313\begin{memberdesc}{source}
1314 A string containing the example's source code. This source code
1315 consists of a single Python statement, and always ends with a
1316 newline; the constructor adds a newline when necessary.
1317\end{memberdesc}
1318
1319\begin{memberdesc}{want}
1320 The expected output from running the example's source code (either
1321 from stdout, or a traceback in case of exception). \member{want}
1322 ends with a newline unless no output is expected, in which case
1323 it's an empty string. The constructor adds a newline when
1324 necessary.
1325\end{memberdesc}
1326
1327\begin{memberdesc}{exc_msg}
1328 The exception message generated by the example, if the example is
1329 expected to generate an exception; or \code{None} if it is not
1330 expected to generate an exception. This exception message is
1331 compared against the return value of
1332 \function{traceback.format_exception_only()}. \member{exc_msg}
1333 ends with a newline unless it's \code{None}. The constructor adds
1334 a newline if needed.
1335\end{memberdesc}
1336
1337\begin{memberdesc}{lineno}
1338 The line number within the string containing this example where
1339 the example begins. This line number is zero-based with respect
1340 to the beginning of the containing string.
1341\end{memberdesc}
1342
1343\begin{memberdesc}{indent}
Tim Peters3f791252004-09-25 03:50:35 +00001344 The example's indentation in the containing string, i.e., the
Edward Loperb3666a32004-09-21 03:00:51 +00001345 number of space characters that preceed the example's first
1346 prompt.
1347\end{memberdesc}
1348
1349\begin{memberdesc}{options}
1350 A dictionary mapping from option flags to \code{True} or
1351 \code{False}, which is used to override default options for this
1352 example. Any option flags not contained in this dictionary are
1353 left at their default value (as specified by the
Tim Peters3f791252004-09-25 03:50:35 +00001354 \class{DocTestRunner}'s \member{optionflags}).
1355 By default, no options are set.
Edward Loperb3666a32004-09-21 03:00:51 +00001356\end{memberdesc}
1357
1358\subsubsection{DocTestFinder objects\label{doctest-DocTestFinder}}
1359\begin{classdesc}{DocTestFinder}{\optional{verbose}\optional{,
1360 parser}\optional{, recurse}\optional{,
1361 exclude_empty}}
1362 A processing class used to extract the \class{DocTest}s that are
1363 relevant to a given object, from its docstring and the docstrings
1364 of its contained objects. \class{DocTest}s can currently be
1365 extracted from the following object types: modules, functions,
1366 classes, methods, staticmethods, classmethods, and properties.
1367
1368 The optional argument \var{verbose} can be used to display the
1369 objects searched by the finder. It defaults to \code{False} (no
1370 output).
1371
1372 The optional argument \var{parser} specifies the
1373 \class{DocTestParser} object (or a drop-in replacement) that is
1374 used to extract doctests from docstrings.
1375
1376 If the optional argument \var{recurse} is false, then
1377 \method{DocTestFinder.find()} will only examine the given object,
1378 and not any contained objects.
1379
1380 If the optional argument \var{exclude_empty} is false, then
1381 \method{DocTestFinder.find()} will include tests for objects with
1382 empty docstrings.
1383
1384 \versionadded{2.4}
1385\end{classdesc}
1386
1387\class{DocTestFinder} defines the following method:
1388
Tim Peters7a082142004-09-25 00:10:53 +00001389\begin{methoddesc}{find}{obj\optional{, name}\optional{,
Edward Loperb3666a32004-09-21 03:00:51 +00001390 module}\optional{, globs}\optional{, extraglobs}}
1391 Return a list of the \class{DocTest}s that are defined by
1392 \var{obj}'s docstring, or by any of its contained objects'
1393 docstrings.
1394
1395 The optional argument \var{name} specifies the object's name; this
1396 name will be used to construct names for the returned
1397 \class{DocTest}s. If \var{name} is not specified, then
Tim Peters3f791252004-09-25 03:50:35 +00001398 \code{\var{obj}.__name__} is used.
Edward Loperb3666a32004-09-21 03:00:51 +00001399
1400 The optional parameter \var{module} is the module that contains
1401 the given object. If the module is not specified or is None, then
1402 the test finder will attempt to automatically determine the
1403 correct module. The object's module is used:
1404
1405 \begin{itemize}
Tim Peters3f791252004-09-25 03:50:35 +00001406 \item As a default namespace, if \var{globs} is not specified.
Edward Loperb3666a32004-09-21 03:00:51 +00001407 \item To prevent the DocTestFinder from extracting DocTests
1408 from objects that are imported from other modules. (Contained
1409 objects with modules other than \var{module} are ignored.)
1410 \item To find the name of the file containing the object.
1411 \item To help find the line number of the object within its file.
1412 \end{itemize}
1413
1414 If \var{module} is \code{False}, no attempt to find the module
1415 will be made. This is obscure, of use mostly in testing doctest
1416 itself: if \var{module} is \code{False}, or is \code{None} but
1417 cannot be found automatically, then all objects are considered to
1418 belong to the (non-existent) module, so all contained objects will
1419 (recursively) be searched for doctests.
1420
1421 The globals for each \class{DocTest} is formed by combining
1422 \var{globs} and \var{extraglobs} (bindings in \var{extraglobs}
Tim Peters3f791252004-09-25 03:50:35 +00001423 override bindings in \var{globs}). A new shallow copy of the globals
Edward Loperb3666a32004-09-21 03:00:51 +00001424 dictionary is created for each \class{DocTest}. If \var{globs} is
1425 not specified, then it defaults to the module's \var{__dict__}, if
1426 specified, or \code{\{\}} otherwise. If \var{extraglobs} is not
1427 specified, then it defaults to \code{\{\}}.
1428\end{methoddesc}
1429
1430\subsubsection{DocTestParser objects\label{doctest-DocTestParser}}
1431\begin{classdesc}{DocTestParser}{}
1432 A processing class used to extract interactive examples from a
1433 string, and use them to create a \class{DocTest} object.
1434 \versionadded{2.4}
1435\end{classdesc}
1436
1437\class{DocTestParser} defines the following methods:
1438
1439\begin{methoddesc}{get_doctest}{string, globs, name, filename, lineno}
1440 Extract all doctest examples from the given string, and collect
1441 them into a \class{DocTest} object.
1442
1443 \var{globs}, \var{name}, \var{filename}, and \var{lineno} are
1444 attributes for the new \class{DocTest} object. See the
1445 documentation for \class{DocTest} for more information.
1446\end{methoddesc}
1447
1448\begin{methoddesc}{get_examples}{string\optional{, name}}
1449 Extract all doctest examples from the given string, and return
1450 them as a list of \class{Example} objects. Line numbers are
1451 0-based. The optional argument \var{name} is a name identifying
1452 this string, and is only used for error messages.
1453\end{methoddesc}
1454
1455\begin{methoddesc}{parse}{string\optional{, name}}
1456 Divide the given string into examples and intervening text, and
1457 return them as a list of alternating \class{Example}s and strings.
1458 Line numbers for the \class{Example}s are 0-based. The optional
1459 argument \var{name} is a name identifying this string, and is only
1460 used for error messages.
1461\end{methoddesc}
1462
1463\subsubsection{DocTestRunner objects\label{doctest-DocTestRunner}}
1464\begin{classdesc}{DocTestRunner}{\optional{checker}\optional{,
1465 verbose}\optional{, optionflags}}
1466 A processing class used to execute and verify the interactive
1467 examples in a \class{DocTest}.
1468
1469 The comparison between expected outputs and actual outputs is done
1470 by an \class{OutputChecker}. This comparison may be customized
1471 with a number of option flags; see section~\ref{doctest-options}
1472 for more information. If the option flags are insufficient, then
1473 the comparison may also be customized by passing a subclass of
1474 \class{OutputChecker} to the constructor.
1475
1476 The test runner's display output can be controlled in two ways.
1477 First, an output function can be passed to
1478 \method{TestRunner.run()}; this function will be called with
1479 strings that should be displayed. It defaults to
1480 \code{sys.stdout.write}. If capturing the output is not
1481 sufficient, then the display output can be also customized by
1482 subclassing DocTestRunner, and overriding the methods
1483 \method{report_start}, \method{report_success},
1484 \method{report_unexpected_exception}, and \method{report_failure}.
1485
1486 The optional keyword argument \var{checker} specifies the
1487 \class{OutputChecker} object (or drop-in replacement) that should
1488 be used to compare the expected outputs to the actual outputs of
1489 doctest examples.
1490
1491 The optional keyword argument \var{verbose} controls the
1492 \class{DocTestRunner}'s verbosity. If \var{verbose} is
1493 \code{True}, then information is printed about each example, as it
1494 is run. If \var{verbose} is \code{False}, then only failures are
1495 printed. If \var{verbose} is unspecified, or \code{None}, then
1496 verbose output is used iff the command-line switch \programopt{-v}
1497 is used.
1498
1499 The optional keyword argument \var{optionflags} can be used to
1500 control how the test runner compares expected output to actual
1501 output, and how it displays failures. For more information, see
1502 section~\ref{doctest-options}.
1503
1504 \versionadded{2.4}
1505\end{classdesc}
1506
1507\class{DocTestParser} defines the following methods:
1508
1509\begin{methoddesc}{report_start}{out, test, example}
1510 Report that the test runner is about to process the given example.
1511 This method is provided to allow subclasses of
1512 \class{DocTestRunner} to customize their output; it should not be
1513 called directly.
1514
1515 \var{example} is the example about to be processed. \var{test} is
1516 the test containing \var{example}. \var{out} is the output
1517 function that was passed to \method{DocTestRunner.run()}.
1518\end{methoddesc}
1519
1520\begin{methoddesc}{report_success}{out, test, example, got}
1521 Report that the given example ran successfully. This method is
1522 provided to allow subclasses of \class{DocTestRunner} to customize
1523 their output; it should not be called directly.
1524
1525 \var{example} is the example about to be processed. \var{got} is
1526 the actual output from the example. \var{test} is the test
1527 containing \var{example}. \var{out} is the output function that
1528 was passed to \method{DocTestRunner.run()}.
1529\end{methoddesc}
1530
1531\begin{methoddesc}{report_failure}{out, test, example, got}
1532 Report that the given example failed. This method is provided to
1533 allow subclasses of \class{DocTestRunner} to customize their
1534 output; it should not be called directly.
1535
1536 \var{example} is the example about to be processed. \var{got} is
1537 the actual output from the example. \var{test} is the test
1538 containing \var{example}. \var{out} is the output function that
1539 was passed to \method{DocTestRunner.run()}.
1540\end{methoddesc}
1541
1542\begin{methoddesc}{report_unexpected_exception}{out, test, example, exc_info}
1543 Report that the given example raised an unexpected exception.
1544 This method is provided to allow subclasses of
1545 \class{DocTestRunner} to customize their output; it should not be
1546 called directly.
1547
1548 \var{example} is the example about to be processed.
1549 \var{exc_info} is a tuple containing information about the
1550 unexpected exception (as returned by \function{sys.exc_info()}).
1551 \var{test} is the test containing \var{example}. \var{out} is the
1552 output function that was passed to \method{DocTestRunner.run()}.
1553\end{methoddesc}
1554
1555\begin{methoddesc}{run}{test\optional{, compileflags}\optional{,
1556 out}\optional{, clear_globs}}
1557 Run the examples in \var{test} (a \class{DocTest} object), and
1558 display the results using the writer function \var{out}.
1559
1560 The examples are run in the namespace \code{test.globs}. If
1561 \var{clear_globs} is true (the default), then this namespace will
1562 be cleared after the test runs, to help with garbage collection.
1563 If you would like to examine the namespace after the test
1564 completes, then use \var{clear_globs=False}.
1565
1566 \var{compileflags} gives the set of flags that should be used by
1567 the Python compiler when running the examples. If not specified,
1568 then it will default to the set of future-import flags that apply
1569 to \var{globs}.
1570
1571 The output of each example is checked using the
1572 \class{DocTestRunner}'s output checker, and the results are
1573 formatted by the \method{DocTestRunner.report_*} methods.
1574\end{methoddesc}
1575
1576\begin{methoddesc}{summarize}{\optional{verbose}}
1577 Print a summary of all the test cases that have been run by this
1578 DocTestRunner, and return a tuple \samp{(\var{failure_count},
1579 \var{test_count})}.
1580
1581 The optional \var{verbose} argument controls how detailed the
1582 summary is. If the verbosity is not specified, then the
1583 \class{DocTestRunner}'s verbosity is used.
1584\end{methoddesc}
1585
1586\subsubsection{OutputChecker objects\label{doctest-OutputChecker}}
1587
1588\begin{classdesc}{OutputChecker}{}
1589 A class used to check the whether the actual output from a doctest
1590 example matches the expected output. \class{OutputChecker}
1591 defines two methods: \method{check_output}, which compares a given
1592 pair of outputs, and returns true if they match; and
1593 \method{output_difference}, which returns a string describing the
1594 differences between two outputs.
1595 \versionadded{2.4}
1596\end{classdesc}
1597
1598\class{OutputChecker} defines the following methods:
1599
1600\begin{methoddesc}{check_output}{want, got, optionflags}
1601 Return \code{True} iff the actual output from an example
1602 (\var{got}) matches the expected output (\var{want}). These
1603 strings are always considered to match if they are identical; but
1604 depending on what option flags the test runner is using, several
1605 non-exact match types are also possible. See
1606 section~\ref{doctest-options} for more information about option
1607 flags.
1608\end{methoddesc}
1609
1610\begin{methoddesc}{output_difference}{example, got, optionflags}
1611 Return a string describing the differences between the expected
1612 output for a given example (\var{example}) and the actual output
1613 (\var{got}). \var{optionflags} is the set of option flags used to
1614 compare \var{want} and \var{got}.
1615\end{methoddesc}
1616
1617\subsection{Debugging\label{doctest-debugging}}
1618
Tim Peters05b05fe2004-09-26 05:09:59 +00001619Doctest provides several mechanisms for debugging doctest examples:
Edward Loperb3666a32004-09-21 03:00:51 +00001620
Tim Peters05b05fe2004-09-26 05:09:59 +00001621\begin{itemize}
1622\item Several functions convert doctests to executable Python
1623 programs, which can be run under the Python debugger, \refmodule{pdb}.
Edward Loperb3666a32004-09-21 03:00:51 +00001624\item The \class{DebugRunner} class is a subclass of
1625 \class{DocTestRunner} that raises an exception for the first
1626 failing example, containing information about that example.
1627 This information can be used to perform post-mortem debugging on
1628 the example.
Tim Peters9463d872004-09-26 21:05:03 +00001629\item The \refmodule{unittest} cases generated by \function{DocTestSuite()}
Tim Peters05b05fe2004-09-26 05:09:59 +00001630 support the \method{debug()} method defined by
Tim Peters9463d872004-09-26 21:05:03 +00001631 \class{\refmodule{unittest}.TestCase}.
1632\item You can add a call to \function{\refmodule{pdb}.set_trace()} in a
1633 doctest example, and you'll drop into the Python debugger when that
Tim Peters05b05fe2004-09-26 05:09:59 +00001634 line is executed. Then you can inspect current values of variables,
1635 and so on. For example, suppose \file{a.py} contains just this
1636 module docstring:
Edward Loperb3666a32004-09-21 03:00:51 +00001637
Tim Peters05b05fe2004-09-26 05:09:59 +00001638\begin{verbatim}
1639"""
1640>>> def f(x):
1641... g(x*2)
1642>>> def g(x):
1643... print x+3
1644... import pdb; pdb.set_trace()
1645>>> f(3)
16469
1647"""
1648\end{verbatim}
Edward Loperb3666a32004-09-21 03:00:51 +00001649
Tim Peters05b05fe2004-09-26 05:09:59 +00001650 Then an interactive Python session may look like this:
Edward Loperb3666a32004-09-21 03:00:51 +00001651
Tim Peters05b05fe2004-09-26 05:09:59 +00001652\begin{verbatim}
1653>>> import a, doctest
1654>>> doctest.testmod(a)
1655--Return--
1656> <doctest a[1]>(3)g()->None
1657-> import pdb; pdb.set_trace()
1658(Pdb) list
1659 1 def g(x):
1660 2 print x+3
1661 3 -> import pdb; pdb.set_trace()
1662[EOF]
1663(Pdb) print x
16646
1665(Pdb) step
1666--Return--
1667> <doctest a[0]>(2)f()->None
1668-> g(x*2)
1669(Pdb) list
1670 1 def f(x):
1671 2 -> g(x*2)
1672[EOF]
1673(Pdb) print x
16743
1675(Pdb) step
1676--Return--
1677> <doctest a[2]>(1)?()->None
1678-> f(3)
1679(Pdb) cont
1680(0, 3)
1681>>>
1682\end{verbatim}
1683
Tim Peters9463d872004-09-26 21:05:03 +00001684 \versionchanged[The ability to use \code{\refmodule{pdb}.set_trace()}
1685 usefully inside doctests was added]{2.4}
Tim Peters05b05fe2004-09-26 05:09:59 +00001686\end{itemize}
1687
1688Functions that convert doctests to Python code, and possibly run
1689the synthesized code under the debugger:
1690
1691\begin{funcdesc}{script_from_examples}{s}
1692 Convert text with examples to a script.
1693
1694 Argument \var{s} is a string containing doctest examples. The string
1695 is converted to a Python script, where doctest examples in \var{s}
1696 are converted to regular code, and everything else is converted to
1697 Python comments. The generated script is returned as a string.
Tim Peters36ee8ce2004-09-26 21:51:25 +00001698 For example,
Tim Peters05b05fe2004-09-26 05:09:59 +00001699
1700 \begin{verbatim}
Tim Peters36ee8ce2004-09-26 21:51:25 +00001701 import doctest
1702 print doctest.script_from_examples(r"""
1703 Set x and y to 1 and 2.
1704 >>> x, y = 1, 2
1705
1706 Print their sum:
1707 >>> print x+y
1708 3
1709 """)
Tim Peters05b05fe2004-09-26 05:09:59 +00001710 \end{verbatim}
1711
Tim Peters36ee8ce2004-09-26 21:51:25 +00001712 displays:
1713
1714 \begin{verbatim}
1715 # Set x and y to 1 and 2.
1716 x, y = 1, 2
1717 #
1718 # Print their sum:
1719 print x+y
1720 # Expected:
1721 ## 3
1722 \end{verbatim}
1723
1724 This function is used internally by other functions (see below), but
1725 can also be useful when you want to transform an interactive Python
1726 session into a Python script.
1727
Tim Peters05b05fe2004-09-26 05:09:59 +00001728 \versionadded{2.4}
1729\end{funcdesc}
1730
1731\begin{funcdesc}{testsource}{module, name}
1732 Convert the doctest for an object to a script.
1733
1734 Argument \var{module} is a module object, or dotted name of a module,
1735 containing the object whose doctests are of interest. Argument
1736 \var{name} is the name (within the module) of the object with the
1737 doctests of interest. The result is a string, containing the
1738 object's docstring converted to a Python script, as described for
1739 \function{script_from_examples()} above. For example, if module
1740 \file{a.py} contains a top-level function \function{f()}, then
1741
Edward Loper456ff912004-09-27 03:30:44 +00001742\begin{verbatim}
1743import a, doctest
1744print doctest.testsource(a, "a.f")
1745\end{verbatim}
Tim Peters05b05fe2004-09-26 05:09:59 +00001746
1747 prints a script version of function \function{f()}'s docstring,
1748 with doctests converted to code, and the rest placed in comments.
1749
Edward Loperb3666a32004-09-21 03:00:51 +00001750 \versionadded{2.3}
1751\end{funcdesc}
1752
Tim Peters05b05fe2004-09-26 05:09:59 +00001753\begin{funcdesc}{debug}{module, name\optional{, pm}}
1754 Debug the doctests for an object.
1755
1756 The \var{module} and \var{name} arguments are the same as for function
1757 \function{testsource()} above. The synthesized Python script for the
1758 named object's docstring is written to a temporary file, and then that
1759 file is run under the control of the Python debugger, \refmodule{pdb}.
1760
1761 A shallow copy of \code{\var{module}.__dict__} is used for both local
1762 and global execution context.
1763
1764 Optional argument \var{pm} controls whether post-mortem debugging is
Tim Peters9463d872004-09-26 21:05:03 +00001765 used. If \var{pm} has a true value, the script file is run directly, and
1766 the debugger gets involved only if the script terminates via raising an
1767 unhandled exception. If it does, then post-mortem debugging is invoked,
1768 via \code{\refmodule{pdb}.post_mortem()}, passing the traceback object
Tim Peters05b05fe2004-09-26 05:09:59 +00001769 from the unhandled exception. If \var{pm} is not specified, or is false,
1770 the script is run under the debugger from the start, via passing an
Tim Peters9463d872004-09-26 21:05:03 +00001771 appropriate \function{execfile()} call to \code{\refmodule{pdb}.run()}.
Tim Peters05b05fe2004-09-26 05:09:59 +00001772
1773 \versionadded{2.3}
1774
1775 \versionchanged[The \var{pm} argument was added]{2.4}
1776\end{funcdesc}
1777
1778\begin{funcdesc}{debug_src}{src\optional{, pm}\optional{, globs}}
1779 Debug the doctests in a string.
1780
1781 This is like function \function{debug()} above, except that
1782 a string containing doctest examples is specified directly, via
1783 the \var{src} argument.
1784
1785 Optional argument \var{pm} has the same meaning as in function
1786 \function{debug()} above.
1787
1788 Optional argument \var{globs} gives a dictionary to use as both
1789 local and global execution context. If not specified, or \code{None},
1790 an empty dictionary is used. If specified, a shallow copy of the
1791 dictionary is used.
1792
1793 \versionadded{2.4}
1794\end{funcdesc}
1795
1796The \class{DebugRunner} class, and the special exceptions it may raise,
1797are of most interest to testing framework authors, and will only be
1798sketched here. See the source code, and especially \class{DebugRunner}'s
1799docstring (which is a doctest!) for more details:
1800
Edward Loperb3666a32004-09-21 03:00:51 +00001801\begin{classdesc}{DebugRunner}{\optional{checker}\optional{,
1802 verbose}\optional{, optionflags}}
1803
1804 A subclass of \class{DocTestRunner} that raises an exception as
1805 soon as a failure is encountered. If an unexpected exception
1806 occurs, an \exception{UnexpectedException} exception is raised,
1807 containing the test, the example, and the original exception. If
1808 the output doesn't match, then a \exception{DocTestFailure}
1809 exception is raised, containing the test, the example, and the
1810 actual output.
1811
1812 For information about the constructor parameters and methods, see
1813 the documentation for \class{DocTestRunner} in
1814 section~\ref{doctest-advanced-api}.
1815\end{classdesc}
1816
Tim Peters05b05fe2004-09-26 05:09:59 +00001817There are two exceptions that may be raised by \class{DebugRunner}
1818instances:
1819
Edward Loperb3666a32004-09-21 03:00:51 +00001820\begin{excclassdesc}{DocTestFailure}{test, example, got}
1821 An exception thrown by \class{DocTestRunner} to signal that a
1822 doctest example's actual output did not match its expected output.
1823 The constructor arguments are used to initialize the member
1824 variables of the same names.
1825\end{excclassdesc}
1826\exception{DocTestFailure} defines the following member variables:
1827\begin{memberdesc}{test}
1828 The \class{DocTest} object that was being run when the example failed.
1829\end{memberdesc}
1830\begin{memberdesc}{example}
1831 The \class{Example} that failed.
1832\end{memberdesc}
1833\begin{memberdesc}{got}
1834 The example's actual output.
1835\end{memberdesc}
1836
Tim Peters05b05fe2004-09-26 05:09:59 +00001837\begin{excclassdesc}{UnexpectedException}{test, example, exc_info}
Edward Loperb3666a32004-09-21 03:00:51 +00001838 An exception thrown by \class{DocTestRunner} to signal that a
1839 doctest example raised an unexpected exception. The constructor
1840 arguments are used to initialize the member variables of the same
1841 names.
1842\end{excclassdesc}
1843\exception{UnexpectedException} defines the following member variables:
1844\begin{memberdesc}{test}
1845 The \class{DocTest} object that was being run when the example failed.
1846\end{memberdesc}
1847\begin{memberdesc}{example}
1848 The \class{Example} that failed.
1849\end{memberdesc}
1850\begin{memberdesc}{exc_info}
1851 A tuple containing information about the unexpected exception, as
1852 returned by \function{sys.exc_info()}.
1853\end{memberdesc}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001854
Edward Loperb3666a32004-09-21 03:00:51 +00001855\subsection{Soapbox\label{doctest-soapbox}}
Tim Peters76882292001-02-17 05:58:44 +00001856
Tim Peters9463d872004-09-26 21:05:03 +00001857As mentioned in the introduction, \refmodule{doctest} has grown to have
Tim Peters3f791252004-09-25 03:50:35 +00001858three primary uses:
Tim Peters76882292001-02-17 05:58:44 +00001859
1860\begin{enumerate}
Edward Loperb3666a32004-09-21 03:00:51 +00001861\item Checking examples in docstrings.
1862\item Regression testing.
Tim Peters3f791252004-09-25 03:50:35 +00001863\item Executable documentation / literate testing.
Fred Drakec1158352001-06-11 14:55:01 +00001864\end{enumerate}
1865
Tim Peters3f791252004-09-25 03:50:35 +00001866These uses have different requirements, and it is important to
Edward Loperb3666a32004-09-21 03:00:51 +00001867distinguish them. In particular, filling your docstrings with obscure
1868test cases makes for bad documentation.
Tim Peters76882292001-02-17 05:58:44 +00001869
Edward Loperb3666a32004-09-21 03:00:51 +00001870When writing a docstring, choose docstring examples with care.
1871There's an art to this that needs to be learned---it may not be
1872natural at first. Examples should add genuine value to the
1873documentation. A good example can often be worth many words.
Fred Drake7a6b4f02003-07-17 16:00:01 +00001874If done with care, the examples will be invaluable for your users, and
1875will pay back the time it takes to collect them many times over as the
1876years go by and things change. I'm still amazed at how often one of
Tim Peters3f791252004-09-25 03:50:35 +00001877my \refmodule{doctest} examples stops working after a "harmless"
Fred Drake7a6b4f02003-07-17 16:00:01 +00001878change.
Tim Peters76882292001-02-17 05:58:44 +00001879
Tim Peters3f791252004-09-25 03:50:35 +00001880Doctest also makes an excellent tool for regression testing, especially if
1881you don't skimp on explanatory text. By interleaving prose and examples,
1882it becomes much easier to keep track of what's actually being tested, and
1883why. When a test fails, good prose can make it much easier to figure out
1884what the problem is, and how it should be fixed. It's true that you could
1885write extensive comments in code-based testing, but few programmers do.
1886Many have found that using doctest approaches instead leads to much clearer
1887tests. Perhaps this is simply because doctest makes writing prose a little
1888easier than writing code, while writing comments in code is a little
1889harder. I think it goes deeper than just that: the natural attitude
1890when writing a doctest-based test is that you want to explain the fine
1891points of your software, and illustrate them with examples. This in
1892turn naturally leads to test files that start with the simplest features,
1893and logically progress to complications and edge cases. A coherent
1894narrative is the result, instead of a collection of isolated functions
1895that test isolated bits of functionality seemingly at random. It's
1896a different attitude, and produces different results, blurring the
1897distinction between testing and explaining.
1898
1899Regression testing is best confined to dedicated objects or files. There
1900are several options for organizing tests:
Edward Loperb3666a32004-09-21 03:00:51 +00001901
1902\begin{itemize}
Tim Peters3f791252004-09-25 03:50:35 +00001903\item Write text files containing test cases as interactive examples,
1904 and test the files using \function{testfile()} or
1905 \function{DocFileSuite()}. This is recommended, although is
1906 easiest to do for new projects, designed from the start to use
1907 doctest.
Edward Loperb3666a32004-09-21 03:00:51 +00001908\item Define functions named \code{_regrtest_\textit{topic}} that
1909 consist of single docstrings, containing test cases for the
1910 named topics. These functions can be included in the same file
1911 as the module, or separated out into a separate test file.
1912\item Define a \code{__test__} dictionary mapping from regression test
1913 topics to docstrings containing test cases.
Edward Loperb3666a32004-09-21 03:00:51 +00001914\end{itemize}