blob: 4d55fec8db3403c383699103d5b1bbe7043694d4 [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
Edward Loperb3666a32004-09-21 03:00:51 +000012The \module{doctest} module searches for pieces of text that look like
13interactive 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,
101\module{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
109worked. Pass \programopt{-v} to the script, and \module{doctest}
110prints 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 Peters41a65ea2004-08-13 03:55:05 +0000154\module{doctest}! Jump in. The following sections provide full
155details. 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 Peters06cc8472004-09-25 00:49:53 +0000174\module{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
395By default, each time \module{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 Loper19b19582004-08-25 23:07:03 +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 Loper19b19582004-08-25 23:07:03 +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
Tim Petersa07bcd42004-08-26 04:47:31 +0000498\end{itemize}
Tim Peters41a65ea2004-08-13 03:55:05 +0000499
Tim Peters39c5de02004-09-25 01:22:29 +0000500\versionchanged[The ability to handle a multi-line exception detail,
501 and the \constant{IGNORE_EXCEPTION_DETAIL} doctest option,
502 were added]{2.4}
Tim Peters0e448072004-08-26 01:02:08 +0000503
Edward Loperb3666a32004-09-21 03:00:51 +0000504\subsubsection{Option Flags and Directives\label{doctest-options}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000505
Tim Peterscf533552004-08-26 04:50:38 +0000506A number of option flags control various aspects of doctest's
Tim Peters026f8dc2004-08-19 16:38:58 +0000507behavior. Symbolic names for the flags are supplied as module constants,
Tim Peters83e259a2004-08-13 21:55:21 +0000508which can be or'ed together and passed to various functions. The names
Tim Peters026f8dc2004-08-19 16:38:58 +0000509can also be used in doctest directives (see below).
Tim Peters8a3b69c2004-08-12 22:31:25 +0000510
Tim Petersa07bcd42004-08-26 04:47:31 +0000511The first group of options define test semantics, controlling
512aspects of how doctest decides whether actual output matches an
513example's expected output:
514
Tim Peters8a3b69c2004-08-12 22:31:25 +0000515\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
516 By default, if an expected output block contains just \code{1},
517 an actual output block containing just \code{1} or just
518 \code{True} is considered to be a match, and similarly for \code{0}
519 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
520 specified, neither substitution is allowed. The default behavior
521 caters to that Python changed the return type of many functions
522 from integer to boolean; doctests expecting "little integer"
523 output still work in these cases. This option will probably go
524 away, but not for several years.
525\end{datadesc}
526
527\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
528 By default, if an expected output block contains a line
529 containing only the string \code{<BLANKLINE>}, then that line
530 will match a blank line in the actual output. Because a
531 genuinely blank line delimits the expected output, this is
532 the only way to communicate that a blank line is expected. When
533 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
534 is not allowed.
535\end{datadesc}
536
537\begin{datadesc}{NORMALIZE_WHITESPACE}
538 When specified, all sequences of whitespace (blanks and newlines) are
539 treated as equal. Any sequence of whitespace within the expected
540 output will match any sequence of whitespace within the actual output.
541 By default, whitespace must match exactly.
542 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
543 of expected output is very long, and you want to wrap it across
544 multiple lines in your source.
545\end{datadesc}
546
547\begin{datadesc}{ELLIPSIS}
548 When specified, an ellipsis marker (\code{...}) in the expected output
549 can match any substring in the actual output. This includes
Tim Peters026f8dc2004-08-19 16:38:58 +0000550 substrings that span line boundaries, and empty substrings, so it's
551 best to keep usage of this simple. Complicated uses can lead to the
552 same kinds of "oops, it matched too much!" surprises that \regexp{.*}
553 is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000554\end{datadesc}
555
Tim Peters1fbf9c52004-09-04 17:21:02 +0000556\begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
557 When specified, an example that expects an exception passes if
558 an exception of the expected type is raised, even if the exception
559 detail does not match. For example, an example expecting
560 \samp{ValueError: 42} will pass if the actual exception raised is
561 \samp{ValueError: 3*14}, but will fail, e.g., if
562 \exception{TypeError} is raised.
563
564 Note that a similar effect can be obtained using \constant{ELLIPSIS},
565 and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
566 prior to 2.4 become uninteresting. Until then,
567 \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
568 doctest that doesn't care about the exception detail yet continues
569 to pass under Python releases prior to 2.4 (doctest directives
570 appear to be comments to them). For example,
571
572\begin{verbatim}
573>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
574Traceback (most recent call last):
575 File "<stdin>", line 1, in ?
576TypeError: object doesn't support item assignment
577\end{verbatim}
578
579 passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
580 to say "does not" instead of "doesn't".
581
582\end{datadesc}
583
Tim Peters38330fe2004-08-30 16:19:24 +0000584\begin{datadesc}{COMPARISON_FLAGS}
585 A bitmask or'ing together all the comparison flags above.
586\end{datadesc}
587
Tim Petersf33683f2004-08-26 04:52:46 +0000588The second group of options controls how test failures are reported:
Tim Petersa07bcd42004-08-26 04:47:31 +0000589
Edward Loper71f55af2004-08-26 01:41:51 +0000590\begin{datadesc}{REPORT_UDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000591 When specified, failures that involve multi-line expected and
592 actual outputs are displayed using a unified diff.
593\end{datadesc}
594
Edward Loper71f55af2004-08-26 01:41:51 +0000595\begin{datadesc}{REPORT_CDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000596 When specified, failures that involve multi-line expected and
597 actual outputs will be displayed using a context diff.
598\end{datadesc}
599
Edward Loper71f55af2004-08-26 01:41:51 +0000600\begin{datadesc}{REPORT_NDIFF}
Tim Petersc6cbab02004-08-22 19:43:28 +0000601 When specified, differences are computed by \code{difflib.Differ},
602 using the same algorithm as the popular \file{ndiff.py} utility.
603 This is the only method that marks differences within lines as
604 well as across lines. For example, if a line of expected output
605 contains digit \code{1} where actual output contains letter \code{l},
606 a line is inserted with a caret marking the mismatching column
607 positions.
608\end{datadesc}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000609
Edward Lopera89f88d2004-08-26 02:45:51 +0000610\begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
611 When specified, display the first failing example in each doctest,
612 but suppress output for all remaining examples. This will prevent
613 doctest from reporting correct examples that break because of
614 earlier failures; but it might also hide incorrect examples that
615 fail independently of the first failure. When
616 \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
617 examples are still run, and still count towards the total number of
618 failures reported; only the output is suppressed.
619\end{datadesc}
620
Tim Peters38330fe2004-08-30 16:19:24 +0000621\begin{datadesc}{REPORTING_FLAGS}
622 A bitmask or'ing together all the reporting flags above.
623\end{datadesc}
624
Edward Loperb3666a32004-09-21 03:00:51 +0000625"Doctest directives" may be used to modify the option flags for
626individual examples. Doctest directives are expressed as a special
627Python comment following an example's source code:
Tim Peters026f8dc2004-08-19 16:38:58 +0000628
629\begin{productionlist}[doctest]
630 \production{directive}
Edward Loper6cc13502004-09-19 01:16:44 +0000631 {"\#" "doctest:" \token{directive_options}}
632 \production{directive_options}
633 {\token{directive_option} ("," \token{directive_option})*}
634 \production{directive_option}
635 {\token{on_or_off} \token{directive_option_name}}
Tim Peters026f8dc2004-08-19 16:38:58 +0000636 \production{on_or_off}
637 {"+" | "-"}
Edward Loper6cc13502004-09-19 01:16:44 +0000638 \production{directive_option_name}
Tim Peters026f8dc2004-08-19 16:38:58 +0000639 {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
640\end{productionlist}
641
642Whitespace is not allowed between the \code{+} or \code{-} and the
Edward Loper6cc13502004-09-19 01:16:44 +0000643directive option name. The directive option name can be any of the
Edward Loperb3666a32004-09-21 03:00:51 +0000644option flag names explained above.
Tim Peters026f8dc2004-08-19 16:38:58 +0000645
Edward Loperb3666a32004-09-21 03:00:51 +0000646An example's doctest directives modify doctest's behavior for that
647single example. Use \code{+} to enable the named behavior, or
648\code{-} to disable it.
Tim Peters026f8dc2004-08-19 16:38:58 +0000649
650For example, this test passes:
651
652\begin{verbatim}
653>>> print range(20) #doctest: +NORMALIZE_WHITESPACE
654[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
65510, 11, 12, 13, 14, 15, 16, 17, 18, 19]
656\end{verbatim}
657
658Without the directive it would fail, both because the actual output
659doesn't have two blanks before the single-digit list elements, and
660because the actual output is on a single line. This test also passes,
Tim Petersa07bcd42004-08-26 04:47:31 +0000661and also requires a directive to do so:
Tim Peters026f8dc2004-08-19 16:38:58 +0000662
663\begin{verbatim}
664>>> print range(20) # doctest:+ELLIPSIS
665[0, 1, ..., 18, 19]
666\end{verbatim}
667
Edward Loper6cc13502004-09-19 01:16:44 +0000668Multiple directives can be used on a single physical line, separated
669by commas:
Tim Peters026f8dc2004-08-19 16:38:58 +0000670
671\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000672>>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +0000673[0, 1, ..., 18, 19]
674\end{verbatim}
675
Edward Loperb3666a32004-09-21 03:00:51 +0000676If multiple directive comments are used for a single example, then
677they are combined:
Edward Loper6cc13502004-09-19 01:16:44 +0000678
679\begin{verbatim}
680>>> print range(20) # doctest: +ELLIPSIS
681... # doctest: +NORMALIZE_WHITESPACE
682[0, 1, ..., 18, 19]
683\end{verbatim}
684
685As the previous example shows, you can add \samp{...} lines to your
Edward Loperb3666a32004-09-21 03:00:51 +0000686example containing only directives. This can be useful when an
Edward Loper6cc13502004-09-19 01:16:44 +0000687example is too long for a directive to comfortably fit on the same
688line:
689
690\begin{verbatim}
691>>> print range(5) + range(10,20) + range(30,40) + range(50,60)
692... # doctest: +ELLIPSIS
693[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
694\end{verbatim}
695
Tim Peters026f8dc2004-08-19 16:38:58 +0000696Note that since all options are disabled by default, and directives apply
697only to the example they appear in, enabling options (via \code{+} in a
698directive) is usually the only meaningful choice. However, option flags
699can also be passed to functions that run doctests, establishing different
700defaults. In such cases, disabling an option via \code{-} in a directive
701can be useful.
702
Tim Peters8a3b69c2004-08-12 22:31:25 +0000703\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
704 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
Tim Peters1fbf9c52004-09-04 17:21:02 +0000705 \constant{IGNORE_EXCEPTION_DETAIL},
Edward Lopera89f88d2004-08-26 02:45:51 +0000706 \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
Tim Peters38330fe2004-08-30 16:19:24 +0000707 \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
708 \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
Tim Peters026f8dc2004-08-19 16:38:58 +0000709 were added; by default \code{<BLANKLINE>} in expected output
710 matches an empty line in actual output; and doctest directives
711 were added]{2.4}
712
Edward Loperb3666a32004-09-21 03:00:51 +0000713\subsubsection{Warnings\label{doctest-warnings}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000714
Edward Loperb3666a32004-09-21 03:00:51 +0000715\begin{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000716
Edward Loperb3666a32004-09-21 03:00:51 +0000717\item \module{doctest} is serious about requiring exact matches in expected
718 output. If even a single character doesn't match, the test fails. This
719 will probably surprise you a few times, as you learn exactly what Python
720 does and doesn't guarantee about output. For example, when printing a
721 dict, Python doesn't guarantee that the key-value pairs will be printed
722 in any particular order, so a test like
Tim Peters76882292001-02-17 05:58:44 +0000723
Edward Loperb3666a32004-09-21 03:00:51 +0000724% Hey! What happened to Monty Python examples?
725% Tim: ask Guido -- it's his example!
726\begin{verbatim}
727>>> foo()
728{"Hermione": "hippogryph", "Harry": "broomstick"}
729\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000730
Edward Loperb3666a32004-09-21 03:00:51 +0000731is vulnerable! One workaround is to do
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000732
Edward Loperb3666a32004-09-21 03:00:51 +0000733\begin{verbatim}
734>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
735True
736\end{verbatim}
737
738instead. Another is to do
739
740\begin{verbatim}
741>>> d = foo().items()
742>>> d.sort()
743>>> d
744[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
745\end{verbatim}
746
747There are others, but you get the idea.
748
749Another bad idea is to print things that embed an object address, like
750
751\begin{verbatim}
752>>> id(1.0) # certain to fail some of the time
7537948648
Tim Peters39c5de02004-09-25 01:22:29 +0000754>>> class C: pass
755>>> C() # the default repr() for instances embeds an address
756<__main__.C instance at 0x00AC18F0>
757\end{verbatim}
758
759The \constant{ELLIPSIS} directive gives a nice approach for the last
760example:
761
762\begin{verbatim}
763>>> C() #doctest: +ELLIPSIS
764<__main__.C instance at 0x...>
Edward Loperb3666a32004-09-21 03:00:51 +0000765\end{verbatim}
766
767Floating-point numbers are also subject to small output variations across
768platforms, because Python defers to the platform C library for float
769formatting, and C libraries vary widely in quality here.
770
771\begin{verbatim}
772>>> 1./7 # risky
7730.14285714285714285
774>>> print 1./7 # safer
7750.142857142857
776>>> print round(1./7, 6) # much safer
7770.142857
778\end{verbatim}
779
780Numbers of the form \code{I/2.**J} are safe across all platforms, and I
781often contrive doctest examples to produce numbers of that form:
782
783\begin{verbatim}
784>>> 3./4 # utterly safe
7850.75
786\end{verbatim}
787
788Simple fractions are also easier for people to understand, and that makes
789for better documentation.
790
Edward Loperb3666a32004-09-21 03:00:51 +0000791\end{itemize}
792
793\subsection{Basic API\label{doctest-basic-api}}
794
795The functions \function{testmod()} and \function{testfile()} provide a
796simple interface to doctest that should be sufficient for most basic
797uses. For a more informal introduction to these two functions, see
798sections \ref{doctest-simple-testmod} and
799\ref{doctest-simple-testfile}.
800
801\begin{funcdesc}{testfile}{filename\optional{, module_relative}\optional{,
802 name}\optional{, package}\optional{,
803 globs}\optional{, verbose}\optional{,
804 report}\optional{, optionflags}\optional{,
805 extraglobs}\optional{, raise_on_error}}
806
807 All arguments except \var{filename} are optional, and should be
808 specified in keyword form.
809
810 Test examples in the file named \var{filename}. Return
811 \samp{(\var{failure_count}, \var{test_count})}.
812
813 Optional argument \var{module_relative} specifies how the filename
814 should be interpreted:
815
816 \begin{itemize}
817 \item If \var{module_relative} is \code{True} (the default), then
818 \var{filename} specifies an os-independent module-relative
819 path. By default, this path is relative to the calling
820 module's directory; but if the \var{package} argument is
821 specified, then it is relative to that package. To ensure
822 os-independence, \var{filename} should use \code{/} characters
823 to separate path segments, and may not be an absolute path
824 (i.e., it may not begin with \code{/}).
825 \item If \var{module_relative} is \code{False}, then \var{filename}
826 specifies an os-specific path. The path may be absolute or
827 relative; relative paths are resolved with respect to the
828 current working directory.
829 \end{itemize}
830
831 Optional argument \var{name} gives the name of the test; by default,
832 or if \code{None}, \code{os.path.basename(\var{filename})} is used.
833
834 Optional argument \var{package} is a Python package or the name of a
835 Python package whose directory should be used as the base directory
836 for a module-relative filename. If no package is specified, then
837 the calling module's directory is used as the base directory for
838 module-relative filenames. It is an error to specify \var{package}
839 if \var{module_relative} is \code{False}.
840
841 Optional argument \var{globs} gives a dict to be used as the globals
842 when executing examples; by default, or if \code{None},
843 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
844 created for the doctest, so its examples start with a clean slate.
845
846 Optional argument \var{extraglobs} gives a dict merged into the
847 globals used to execute examples. This works like
848 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
849 common key, the associated value in \var{extraglobs} appears in the
850 combined dict. By default, or if \code{None}, no extra globals are
851 used. This is an advanced feature that allows parameterization of
852 doctests. For example, a doctest can be written for a base class, using
853 a generic name for the class, then reused to test any number of
854 subclasses by passing an \var{extraglobs} dict mapping the generic
855 name to the subclass to be tested.
856
857 Optional argument \var{verbose} prints lots of stuff if true, and prints
858 only failures if false; by default, or if \code{None}, it's true
859 if and only if \code{'-v'} is in \code{sys.argv}.
860
861 Optional argument \var{report} prints a summary at the end when true,
862 else prints nothing at the end. In verbose mode, the summary is
863 detailed, else the summary is very brief (in fact, empty if all tests
864 passed).
865
866 Optional argument \var{optionflags} or's together option flags. See
867 see section~\ref{doctest-options}.
868
869 Optional argument \var{raise_on_error} defaults to false. If true,
870 an exception is raised upon the first failure or unexpected exception
871 in an example. This allows failures to be post-mortem debugged.
872 Default behavior is to continue running examples.
873
874 \versionadded{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000875\end{funcdesc}
876
Tim Peters83e259a2004-08-13 21:55:21 +0000877\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
878 globs}\optional{, verbose}\optional{,
879 isprivate}\optional{, report}\optional{,
880 optionflags}\optional{, extraglobs}\optional{,
Tim Peters82788602004-09-13 15:03:17 +0000881 raise_on_error}\optional{, exclude_empty}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000882
Tim Peters83e259a2004-08-13 21:55:21 +0000883 All arguments are optional, and all except for \var{m} should be
884 specified in keyword form.
885
886 Test examples in docstrings in functions and classes reachable
887 from module \var{m} (or the current module if \var{m} is not supplied
888 or is \code{None}), starting with \code{\var{m}.__doc__}.
889
890 Also test examples reachable from dict \code{\var{m}.__test__}, if it
891 exists and is not \code{None}. \code{\var{m}.__test__} maps
892 names (strings) to functions, classes and strings; function and class
893 docstrings are searched for examples; strings are searched directly,
894 as if they were docstrings.
895
896 Only docstrings attached to objects belonging to module \var{m} are
897 searched.
898
899 Return \samp{(\var{failure_count}, \var{test_count})}.
900
901 Optional argument \var{name} gives the name of the module; by default,
902 or if \code{None}, \code{\var{m}.__name__} is used.
903
904 Optional argument \var{globs} gives a dict to be used as the globals
905 when executing examples; by default, or if \code{None},
906 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
907 created for each docstring with examples, so that each docstring's
908 examples start with a clean slate.
909
910 Optional argument \var{extraglobs} gives a dict merged into the
911 globals used to execute examples. This works like
912 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
913 common key, the associated value in \var{extraglobs} appears in the
914 combined dict. By default, or if \code{None}, no extra globals are
915 used. This is an advanced feature that allows parameterization of
916 doctests. For example, a doctest can be written for a base class, using
917 a generic name for the class, then reused to test any number of
918 subclasses by passing an \var{extraglobs} dict mapping the generic
919 name to the subclass to be tested.
920
921 Optional argument \var{verbose} prints lots of stuff if true, and prints
922 only failures if false; by default, or if \code{None}, it's true
923 if and only if \code{'-v'} is in \code{sys.argv}.
924
925 Optional argument \var{report} prints a summary at the end when true,
926 else prints nothing at the end. In verbose mode, the summary is
927 detailed, else the summary is very brief (in fact, empty if all tests
928 passed).
929
930 Optional argument \var{optionflags} or's together option flags. See
Edward Loperb3666a32004-09-21 03:00:51 +0000931 see section~\ref{doctest-options}.
Tim Peters83e259a2004-08-13 21:55:21 +0000932
933 Optional argument \var{raise_on_error} defaults to false. If true,
934 an exception is raised upon the first failure or unexpected exception
935 in an example. This allows failures to be post-mortem debugged.
936 Default behavior is to continue running examples.
937
Tim Peters82788602004-09-13 15:03:17 +0000938 Optional argument \var{exclude_empty} defaults to false. If true,
939 objects for which no doctests are found are excluded from consideration.
940 The default is a backward compatibility hack, so that code still
941 using \method{doctest.master.summarize()} in conjunction with
942 \function{testmod()} continues to get output for objects with no tests.
943 The \var{exclude_empty} argument to the newer \class{DocTestFinder}
944 constructor defaults to true.
945
Tim Peters83e259a2004-08-13 21:55:21 +0000946 Optional argument \var{isprivate} specifies a function used to
947 determine whether a name is private. The default function treats
948 all names as public. \var{isprivate} can be set to
949 \code{doctest.is_private} to skip over names that are
950 private according to Python's underscore naming convention.
951 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
952 If you need to skip tests based on name, filter the list returned by
953 \code{DocTestFinder.find()} instead.}
954
955 \versionchanged[The parameter \var{optionflags} was added]{2.3}
956
Tim Peters82788602004-09-13 15:03:17 +0000957 \versionchanged[The parameters \var{extraglobs}, \var{raise_on_error}
958 and \var{exclude_empty} were added]{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000959\end{funcdesc}
960
Edward Loperb3666a32004-09-21 03:00:51 +0000961\subsection{Unittest API\label{doctest-unittest-api}}
962
963Doctest provides several functions that can be used to create
964\module{unittest} test suites from doctest examples. These test
965suites can then be run using \module{unittest} test runners:
966
967\begin{verbatim}
968 import unittest
969 import doctest
970 import my_module_with_doctests
971
972 suite = doctest.DocTestSuite(my_module_with_doctests)
973 runner = unittest.TextTestRunner()
974 runner.run(suite)
975\end{verbatim}
976
977\begin{funcdesc}{DocFileSuite}{*paths, **kw}
978 Convert doctest tests from one or more text files to a
979 \class{\refmodule{unittest}.TestSuite}.
980
981 The returned \class{TestSuite} is to be run by the unittest
982 framework and runs the interactive examples in each file. If an
983 example in any file fails, then the synthesized unit test fails, and
984 a \exception{failureException} exception is raised showing the
985 name of the file containing the test and a (sometimes approximate)
986 line number.
987
988 A number of options may be provided as keyword arguments:
989
990 The optional argument \var{module_relative} specifies how
991 the the filenames in \var{paths} should be interpreted:
992
993 \begin{itemize}
994 \item If \var{module_relative} is \code{True} (the default), then
995 each filename specifies an os-independent module-relative
996 path. By default, this path is relative to the calling
997 module's directory; but if the \var{package} argument is
998 specified, then it is relative to that package. To ensure
999 os-independence, each filename should use \code{/} characters
1000 to separate path segments, and may not be an absolute path
1001 (i.e., it may not begin with \code{/}).
1002 \item If \var{module_relative} is \code{False}, then each filename
1003 specifies an os-specific path. The path may be absolute or
1004 relative; relative paths are resolved with respect to the
1005 current working directory.
1006 \end{itemize}
1007
1008 The optional argument \var{package} is a Python package or the name
1009 of a Python package whose directory should be used as the base
1010 directory for module-relative filenames. If no package is
1011 specified, then the calling module's directory is used as the base
1012 directory for module-relative filenames. It is an error to specify
1013 \var{package} if \var{module_relative} is \code{False}.
1014
1015 The optional argument \var{setUp} specifies a set-up function for
1016 the test suite. This is called before running the tests in each
1017 file. The \var{setUp} function will be passed a \class{DocTest}
1018 object. The setUp function can access the test globals as the
1019 \var{globs} attribute of the test passed.
1020
1021 The optional argument \var{tearDown} specifies a tear-down function
1022 for the test suite. This is called after running the tests in each
1023 file. The \var{tearDown} function will be passed a \class{DocTest}
1024 object. The setUp function can access the test globals as the
1025 \var{globs} attribute of the test passed.
1026
1027 The optional argument \var{globs} is a dictionary containing the
1028 initial global variables for the tests. A new copy of this
1029 dictionary is created for each test. By default, \var{globs} is
1030 empty.
1031
1032 The optional argument \var{optionflags} specifies the default
1033 doctest options for the tests. It is created by or-ing together
1034 individual option flags.
1035
1036 \versionadded{2.4}
1037\end{funcdesc}
1038
1039\begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
1040 globs}\optional{, extraglobs}\optional{,
1041 test_finder}\optional{, setUp}\optional{,
1042 tearDown}\optional{, checker}}
1043 Convert doctest tests for a module to a
1044 \class{\refmodule{unittest}.TestSuite}.
1045
1046 The returned \class{TestSuite} is to be run by the unittest framework
1047 and runs each doctest in the module. If any of the doctests fail,
1048 then the synthesized unit test fails, and a \exception{failureException}
1049 exception is raised showing the name of the file containing the test and a
1050 (sometimes approximate) line number.
1051
1052 The optional argument \var{module} provides the module to be tested. It
1053 can be a module object or a (possibly dotted) module name. If not
1054 specified, the module calling this function is used.
1055
1056 The optional argument \var{globs} is a dictionary containing the
1057 initial global variables for the tests. A new copy of this
1058 dictionary is created for each test. By default, \var{globs} is
1059 empty.
1060
1061 The optional argument \var{extraglobs} specifies an extra set of
1062 global variables, which is merged into \var{globs}. By default, no
1063 extra globals are used.
1064
1065 The optional argument \var{test_finder} is the \class{DocTestFinder}
1066 object (or a drop-in replacement) that is used to extract doctests
1067 from the module.
1068
1069 The optional argument \var{setUp} specifies a set-up function for
1070 the test suite. This is called before running the tests in each
1071 file. The \var{setUp} function will be passed a \class{DocTest}
1072 object. The setUp function can access the test globals as the
1073 \var{globs} attribute of the test passed.
1074
1075 The optional argument \var{tearDown} specifies a tear-down function
1076 for the test suite. This is called after running the tests in each
1077 file. The \var{tearDown} function will be passed a \class{DocTest}
1078 object. The setUp function can access the test globals as the
1079 \var{globs} attribute of the test passed.
1080
1081 The optional argument \var{optionflags} specifies the default
1082 doctest options for the tests. It is created by or-ing together
1083 individual option flags.
1084
1085 \versionadded{2.3}
1086 \versionchanged[The parameters \var{globs}, \var{extraglobs},
1087 \var{test_finder}, \var{setUp}, \var{tearDown}, and
1088 \var{optionflags} were added]{2.4}
1089 \versionchanged[This function now uses the same search technique as
1090 \function{testmod()}.]{2.4}
1091\end{funcdesc}
1092
1093\subsection{Advanced API\label{doctest-advanced-api}}
1094
1095The basic API is a simple wrapper that's intended to make doctest easy
1096to use. It is fairly flexible, and should meet most user's needs;
1097however, if you require more fine grained control over testing, or
1098wish to extend doctest's capabilities, then you should use the
1099advanced API.
1100
1101The advanced API revolves around two container classes, which are used
1102to store the interactive examples extracted from doctest cases:
1103
1104\begin{itemize}
1105\item \class{Example}: A single python statement, paired with its
1106 expected output.
1107\item \class{DocTest}: A collection of \class{Example}s, typically
1108 extracted from a single docstring or text file.
1109\end{itemize}
1110
1111Additional processing classes are defined to find, parse, and run, and
1112check doctest examples:
1113
1114\begin{itemize}
1115\item \class{DocTestFinder}: Finds all docstrings in a given module,
1116 and uses a \class{DocTestParser} to create a \class{DocTest}
1117 from every docstring that contains interactive examples.
1118\item \class{DocTestParser}: Creates a \class{DocTest} object from
1119 a string (such as an object's docstring).
1120\item \class{DocTestRunner}: Executes the examples in a
1121 \class{DocTest}, and uses an \class{OutputChecker} to verify
1122 their output.
1123\item \class{OutputChecker}: Compares the actual output from a
1124 doctest example with the expected output, and decides whether
1125 they match.
1126\end{itemize}
1127
1128The relationship between these processing classes is summarized in the
1129following diagram:
1130
1131\begin{verbatim}
1132 list of:
1133+------+ +---------+
1134|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1135+------+ | ^ +---------+ | ^ (printed)
1136 | | | Example | | |
1137 V | | ... | V |
1138 DocTestParser | Example | OutputChecker
1139 +---------+
1140\end{verbatim}
1141
1142\subsubsection{DocTest Objects\label{doctest-DocTest}}
1143\begin{classdesc}{DocTest}{examples, globs, name, filename, lineno,
1144 docstring}
1145 A collection of doctest examples that should be run in a single
1146 namespace. The constructor arguments are used to initialize the
1147 member variables of the same names.
1148 \versionadded{2.4}
1149\end{classdesc}
1150
1151\class{DocTest} defines the following member variables. They are
1152initialized by the constructor, and should not be modified directly.
1153
1154\begin{memberdesc}{examples}
1155 A list of \class{Example} objects encoding the individual
1156 interactive Python examples that should be run by this test.
1157\end{memberdesc}
1158
1159\begin{memberdesc}{globs}
1160 The namespace (aka globals) that the examples should be run in.
1161 This is a dictionary mapping names to values. Any changes to the
1162 namespace made by the examples (such as binding new variables)
1163 will be reflected in \member{globs} after the test is run.
1164\end{memberdesc}
1165
1166\begin{memberdesc}{name}
1167 A string name identifying the \class{DocTest}. Typically, this is
1168 the name of the object or file that the test was extracted from.
1169\end{memberdesc}
1170
1171\begin{memberdesc}{filename}
1172 The name of the file that this \class{DocTest} was extracted from;
1173 or \code{None} if the filename is unknown, or if the
1174 \class{DocTest} was not extracted from a file.
1175\end{memberdesc}
1176
1177\begin{memberdesc}{lineno}
1178 The line number within \member{filename} where this
1179 \class{DocTest} begins, or \code{None} if the line number is
1180 unavailable. This line number is zero-based with respect to the
1181 beginning of the file.
1182\end{memberdesc}
1183
1184\begin{memberdesc}{docstring}
1185 The string that the test was extracted from, or `None` if the
1186 string is unavailable, or if the test was not extracted from a
1187 string.
1188\end{memberdesc}
1189
1190\subsubsection{Example Objects\label{doctest-Example}}
1191\begin{classdesc}{Example}{source, want\optional{,
1192 exc_msg}\optional{, lineno}\optional{,
1193 indent}\optional{, options}}
1194 A single interactive example, consisting of a Python statement and
1195 its expected output. The constructor arguments are used to
1196 initialize the member variables of the same names.
1197 \versionadded{2.4}
1198\end{classdesc}
1199
1200\class{Example} defines the following member variables. They are
1201initialized by the constructor, and should not be modified directly.
1202
1203\begin{memberdesc}{source}
1204 A string containing the example's source code. This source code
1205 consists of a single Python statement, and always ends with a
1206 newline; the constructor adds a newline when necessary.
1207\end{memberdesc}
1208
1209\begin{memberdesc}{want}
1210 The expected output from running the example's source code (either
1211 from stdout, or a traceback in case of exception). \member{want}
1212 ends with a newline unless no output is expected, in which case
1213 it's an empty string. The constructor adds a newline when
1214 necessary.
1215\end{memberdesc}
1216
1217\begin{memberdesc}{exc_msg}
1218 The exception message generated by the example, if the example is
1219 expected to generate an exception; or \code{None} if it is not
1220 expected to generate an exception. This exception message is
1221 compared against the return value of
1222 \function{traceback.format_exception_only()}. \member{exc_msg}
1223 ends with a newline unless it's \code{None}. The constructor adds
1224 a newline if needed.
1225\end{memberdesc}
1226
1227\begin{memberdesc}{lineno}
1228 The line number within the string containing this example where
1229 the example begins. This line number is zero-based with respect
1230 to the beginning of the containing string.
1231\end{memberdesc}
1232
1233\begin{memberdesc}{indent}
1234 The example's indentation in the containing string. I.e., the
1235 number of space characters that preceed the example's first
1236 prompt.
1237\end{memberdesc}
1238
1239\begin{memberdesc}{options}
1240 A dictionary mapping from option flags to \code{True} or
1241 \code{False}, which is used to override default options for this
1242 example. Any option flags not contained in this dictionary are
1243 left at their default value (as specified by the
1244 \class{DocTestRunner}'s
1245\member{optionflags}). By default, no options are set.
1246\end{memberdesc}
1247
1248\subsubsection{DocTestFinder objects\label{doctest-DocTestFinder}}
1249\begin{classdesc}{DocTestFinder}{\optional{verbose}\optional{,
1250 parser}\optional{, recurse}\optional{,
1251 exclude_empty}}
1252 A processing class used to extract the \class{DocTest}s that are
1253 relevant to a given object, from its docstring and the docstrings
1254 of its contained objects. \class{DocTest}s can currently be
1255 extracted from the following object types: modules, functions,
1256 classes, methods, staticmethods, classmethods, and properties.
1257
1258 The optional argument \var{verbose} can be used to display the
1259 objects searched by the finder. It defaults to \code{False} (no
1260 output).
1261
1262 The optional argument \var{parser} specifies the
1263 \class{DocTestParser} object (or a drop-in replacement) that is
1264 used to extract doctests from docstrings.
1265
1266 If the optional argument \var{recurse} is false, then
1267 \method{DocTestFinder.find()} will only examine the given object,
1268 and not any contained objects.
1269
1270 If the optional argument \var{exclude_empty} is false, then
1271 \method{DocTestFinder.find()} will include tests for objects with
1272 empty docstrings.
1273
1274 \versionadded{2.4}
1275\end{classdesc}
1276
1277\class{DocTestFinder} defines the following method:
1278
Tim Peters7a082142004-09-25 00:10:53 +00001279\begin{methoddesc}{find}{obj\optional{, name}\optional{,
Edward Loperb3666a32004-09-21 03:00:51 +00001280 module}\optional{, globs}\optional{, extraglobs}}
1281 Return a list of the \class{DocTest}s that are defined by
1282 \var{obj}'s docstring, or by any of its contained objects'
1283 docstrings.
1284
1285 The optional argument \var{name} specifies the object's name; this
1286 name will be used to construct names for the returned
1287 \class{DocTest}s. If \var{name} is not specified, then
1288 \code{var.__name__} is used.
1289
1290 The optional parameter \var{module} is the module that contains
1291 the given object. If the module is not specified or is None, then
1292 the test finder will attempt to automatically determine the
1293 correct module. The object's module is used:
1294
1295 \begin{itemize}
1296 \item As a default namespace, if `globs` is not specified.
1297 \item To prevent the DocTestFinder from extracting DocTests
1298 from objects that are imported from other modules. (Contained
1299 objects with modules other than \var{module} are ignored.)
1300 \item To find the name of the file containing the object.
1301 \item To help find the line number of the object within its file.
1302 \end{itemize}
1303
1304 If \var{module} is \code{False}, no attempt to find the module
1305 will be made. This is obscure, of use mostly in testing doctest
1306 itself: if \var{module} is \code{False}, or is \code{None} but
1307 cannot be found automatically, then all objects are considered to
1308 belong to the (non-existent) module, so all contained objects will
1309 (recursively) be searched for doctests.
1310
1311 The globals for each \class{DocTest} is formed by combining
1312 \var{globs} and \var{extraglobs} (bindings in \var{extraglobs}
1313 override bindings in \var{globs}). A new copy of the globals
1314 dictionary is created for each \class{DocTest}. If \var{globs} is
1315 not specified, then it defaults to the module's \var{__dict__}, if
1316 specified, or \code{\{\}} otherwise. If \var{extraglobs} is not
1317 specified, then it defaults to \code{\{\}}.
1318\end{methoddesc}
1319
1320\subsubsection{DocTestParser objects\label{doctest-DocTestParser}}
1321\begin{classdesc}{DocTestParser}{}
1322 A processing class used to extract interactive examples from a
1323 string, and use them to create a \class{DocTest} object.
1324 \versionadded{2.4}
1325\end{classdesc}
1326
1327\class{DocTestParser} defines the following methods:
1328
1329\begin{methoddesc}{get_doctest}{string, globs, name, filename, lineno}
1330 Extract all doctest examples from the given string, and collect
1331 them into a \class{DocTest} object.
1332
1333 \var{globs}, \var{name}, \var{filename}, and \var{lineno} are
1334 attributes for the new \class{DocTest} object. See the
1335 documentation for \class{DocTest} for more information.
1336\end{methoddesc}
1337
1338\begin{methoddesc}{get_examples}{string\optional{, name}}
1339 Extract all doctest examples from the given string, and return
1340 them as a list of \class{Example} objects. Line numbers are
1341 0-based. The optional argument \var{name} is a name identifying
1342 this string, and is only used for error messages.
1343\end{methoddesc}
1344
1345\begin{methoddesc}{parse}{string\optional{, name}}
1346 Divide the given string into examples and intervening text, and
1347 return them as a list of alternating \class{Example}s and strings.
1348 Line numbers for the \class{Example}s are 0-based. The optional
1349 argument \var{name} is a name identifying this string, and is only
1350 used for error messages.
1351\end{methoddesc}
1352
1353\subsubsection{DocTestRunner objects\label{doctest-DocTestRunner}}
1354\begin{classdesc}{DocTestRunner}{\optional{checker}\optional{,
1355 verbose}\optional{, optionflags}}
1356 A processing class used to execute and verify the interactive
1357 examples in a \class{DocTest}.
1358
1359 The comparison between expected outputs and actual outputs is done
1360 by an \class{OutputChecker}. This comparison may be customized
1361 with a number of option flags; see section~\ref{doctest-options}
1362 for more information. If the option flags are insufficient, then
1363 the comparison may also be customized by passing a subclass of
1364 \class{OutputChecker} to the constructor.
1365
1366 The test runner's display output can be controlled in two ways.
1367 First, an output function can be passed to
1368 \method{TestRunner.run()}; this function will be called with
1369 strings that should be displayed. It defaults to
1370 \code{sys.stdout.write}. If capturing the output is not
1371 sufficient, then the display output can be also customized by
1372 subclassing DocTestRunner, and overriding the methods
1373 \method{report_start}, \method{report_success},
1374 \method{report_unexpected_exception}, and \method{report_failure}.
1375
1376 The optional keyword argument \var{checker} specifies the
1377 \class{OutputChecker} object (or drop-in replacement) that should
1378 be used to compare the expected outputs to the actual outputs of
1379 doctest examples.
1380
1381 The optional keyword argument \var{verbose} controls the
1382 \class{DocTestRunner}'s verbosity. If \var{verbose} is
1383 \code{True}, then information is printed about each example, as it
1384 is run. If \var{verbose} is \code{False}, then only failures are
1385 printed. If \var{verbose} is unspecified, or \code{None}, then
1386 verbose output is used iff the command-line switch \programopt{-v}
1387 is used.
1388
1389 The optional keyword argument \var{optionflags} can be used to
1390 control how the test runner compares expected output to actual
1391 output, and how it displays failures. For more information, see
1392 section~\ref{doctest-options}.
1393
1394 \versionadded{2.4}
1395\end{classdesc}
1396
1397\class{DocTestParser} defines the following methods:
1398
1399\begin{methoddesc}{report_start}{out, test, example}
1400 Report that the test runner is about to process the given example.
1401 This method is provided to allow subclasses of
1402 \class{DocTestRunner} to customize their output; it should not be
1403 called directly.
1404
1405 \var{example} is the example about to be processed. \var{test} is
1406 the test containing \var{example}. \var{out} is the output
1407 function that was passed to \method{DocTestRunner.run()}.
1408\end{methoddesc}
1409
1410\begin{methoddesc}{report_success}{out, test, example, got}
1411 Report that the given example ran successfully. This method is
1412 provided to allow subclasses of \class{DocTestRunner} to customize
1413 their output; it should not be called directly.
1414
1415 \var{example} is the example about to be processed. \var{got} is
1416 the actual output from the example. \var{test} is the test
1417 containing \var{example}. \var{out} is the output function that
1418 was passed to \method{DocTestRunner.run()}.
1419\end{methoddesc}
1420
1421\begin{methoddesc}{report_failure}{out, test, example, got}
1422 Report that the given example failed. This method is provided to
1423 allow subclasses of \class{DocTestRunner} to customize their
1424 output; it should not be called directly.
1425
1426 \var{example} is the example about to be processed. \var{got} is
1427 the actual output from the example. \var{test} is the test
1428 containing \var{example}. \var{out} is the output function that
1429 was passed to \method{DocTestRunner.run()}.
1430\end{methoddesc}
1431
1432\begin{methoddesc}{report_unexpected_exception}{out, test, example, exc_info}
1433 Report that the given example raised an unexpected exception.
1434 This method is provided to allow subclasses of
1435 \class{DocTestRunner} to customize their output; it should not be
1436 called directly.
1437
1438 \var{example} is the example about to be processed.
1439 \var{exc_info} is a tuple containing information about the
1440 unexpected exception (as returned by \function{sys.exc_info()}).
1441 \var{test} is the test containing \var{example}. \var{out} is the
1442 output function that was passed to \method{DocTestRunner.run()}.
1443\end{methoddesc}
1444
1445\begin{methoddesc}{run}{test\optional{, compileflags}\optional{,
1446 out}\optional{, clear_globs}}
1447 Run the examples in \var{test} (a \class{DocTest} object), and
1448 display the results using the writer function \var{out}.
1449
1450 The examples are run in the namespace \code{test.globs}. If
1451 \var{clear_globs} is true (the default), then this namespace will
1452 be cleared after the test runs, to help with garbage collection.
1453 If you would like to examine the namespace after the test
1454 completes, then use \var{clear_globs=False}.
1455
1456 \var{compileflags} gives the set of flags that should be used by
1457 the Python compiler when running the examples. If not specified,
1458 then it will default to the set of future-import flags that apply
1459 to \var{globs}.
1460
1461 The output of each example is checked using the
1462 \class{DocTestRunner}'s output checker, and the results are
1463 formatted by the \method{DocTestRunner.report_*} methods.
1464\end{methoddesc}
1465
1466\begin{methoddesc}{summarize}{\optional{verbose}}
1467 Print a summary of all the test cases that have been run by this
1468 DocTestRunner, and return a tuple \samp{(\var{failure_count},
1469 \var{test_count})}.
1470
1471 The optional \var{verbose} argument controls how detailed the
1472 summary is. If the verbosity is not specified, then the
1473 \class{DocTestRunner}'s verbosity is used.
1474\end{methoddesc}
1475
1476\subsubsection{OutputChecker objects\label{doctest-OutputChecker}}
1477
1478\begin{classdesc}{OutputChecker}{}
1479 A class used to check the whether the actual output from a doctest
1480 example matches the expected output. \class{OutputChecker}
1481 defines two methods: \method{check_output}, which compares a given
1482 pair of outputs, and returns true if they match; and
1483 \method{output_difference}, which returns a string describing the
1484 differences between two outputs.
1485 \versionadded{2.4}
1486\end{classdesc}
1487
1488\class{OutputChecker} defines the following methods:
1489
1490\begin{methoddesc}{check_output}{want, got, optionflags}
1491 Return \code{True} iff the actual output from an example
1492 (\var{got}) matches the expected output (\var{want}). These
1493 strings are always considered to match if they are identical; but
1494 depending on what option flags the test runner is using, several
1495 non-exact match types are also possible. See
1496 section~\ref{doctest-options} for more information about option
1497 flags.
1498\end{methoddesc}
1499
1500\begin{methoddesc}{output_difference}{example, got, optionflags}
1501 Return a string describing the differences between the expected
1502 output for a given example (\var{example}) and the actual output
1503 (\var{got}). \var{optionflags} is the set of option flags used to
1504 compare \var{want} and \var{got}.
1505\end{methoddesc}
1506
1507\subsection{Debugging\label{doctest-debugging}}
1508
1509Doctest provides three mechanisms for debugging doctest examples:
1510
1511\begin{enumerate}
1512\item The \function{debug()} function converts a specified doctest
1513 to a Python script, and executes that script using \module{pdb}.
1514\item The \class{DebugRunner} class is a subclass of
1515 \class{DocTestRunner} that raises an exception for the first
1516 failing example, containing information about that example.
1517 This information can be used to perform post-mortem debugging on
1518 the example.
1519\item The unittest cases generated by \function{DocTestSuite()}
1520 support the \method{debug} method defined by
1521 \class{unittest.TestCase}.
1522\end{enumerate}
1523
1524\begin{funcdesc}{debug}{module, name}
1525 Debug a single doctest docstring.
1526
1527 Provide the \var{module} (or dotted name of the module) containing
1528 the docstring to be debugged and the fully qualified dotted
1529 \var{name} of the object with the docstring to be debugged.
1530
1531 The doctest examples are extracted (see function \function{testsource()}),
1532 and written to a temporary file. The Python debugger, \refmodule{pdb},
1533 is then invoked on that file.
1534 \versionadded{2.3}
1535\end{funcdesc}
1536
1537\begin{classdesc}{DebugRunner}{\optional{checker}\optional{,
1538 verbose}\optional{, optionflags}}
1539
1540 A subclass of \class{DocTestRunner} that raises an exception as
1541 soon as a failure is encountered. If an unexpected exception
1542 occurs, an \exception{UnexpectedException} exception is raised,
1543 containing the test, the example, and the original exception. If
1544 the output doesn't match, then a \exception{DocTestFailure}
1545 exception is raised, containing the test, the example, and the
1546 actual output.
1547
1548 For information about the constructor parameters and methods, see
1549 the documentation for \class{DocTestRunner} in
1550 section~\ref{doctest-advanced-api}.
1551\end{classdesc}
1552
1553\begin{excclassdesc}{DocTestFailure}{test, example, got}
1554 An exception thrown by \class{DocTestRunner} to signal that a
1555 doctest example's actual output did not match its expected output.
1556 The constructor arguments are used to initialize the member
1557 variables of the same names.
1558\end{excclassdesc}
1559\exception{DocTestFailure} defines the following member variables:
1560\begin{memberdesc}{test}
1561 The \class{DocTest} object that was being run when the example failed.
1562\end{memberdesc}
1563\begin{memberdesc}{example}
1564 The \class{Example} that failed.
1565\end{memberdesc}
1566\begin{memberdesc}{got}
1567 The example's actual output.
1568\end{memberdesc}
1569
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001570\begin{funcdesc}{testsource}{module, name}
1571 Extract the doctest examples from a docstring.
1572
1573 Provide the \var{module} (or dotted name of the module) containing the
1574 tests to be extracted and the \var{name} (within the module) of the object
1575 with the docstring containing the tests to be extracted.
1576
1577 The doctest examples are returned as a string containing Python
1578 code. The expected output blocks in the examples are converted
1579 to Python comments.
1580 \versionadded{2.3}
1581\end{funcdesc}
1582
Edward Loperb3666a32004-09-21 03:00:51 +00001583\begin{excclassdesc}{UnexpectedException}{test, example, got}
1584 An exception thrown by \class{DocTestRunner} to signal that a
1585 doctest example raised an unexpected exception. The constructor
1586 arguments are used to initialize the member variables of the same
1587 names.
1588\end{excclassdesc}
1589\exception{UnexpectedException} defines the following member variables:
1590\begin{memberdesc}{test}
1591 The \class{DocTest} object that was being run when the example failed.
1592\end{memberdesc}
1593\begin{memberdesc}{example}
1594 The \class{Example} that failed.
1595\end{memberdesc}
1596\begin{memberdesc}{exc_info}
1597 A tuple containing information about the unexpected exception, as
1598 returned by \function{sys.exc_info()}.
1599\end{memberdesc}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001600
Edward Loperb3666a32004-09-21 03:00:51 +00001601\begin{funcdesc}{register_optionflag}{name}
1602 Create a new option flag with a given name, and return the new
1603 flag's integer value. \function{register_optionflag()} can be
1604 used when subclassing \class{OutputChecker} or
1605 \class{DocTestRunner} to create new options that are supported by
1606 your subclasses. \function{register_optionflag} should always be
1607 called using the following idiom:
1608\begin{verbatim}
1609 MY_FLAG = register_optionflag('MY_FLAG')
1610\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001611\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +00001612
Edward Loperb3666a32004-09-21 03:00:51 +00001613\subsection{Soapbox\label{doctest-soapbox}}
Tim Peters76882292001-02-17 05:58:44 +00001614
Edward Loperb3666a32004-09-21 03:00:51 +00001615As mentioned in the introduction, \module{doctest} has two primary
1616uses:
Tim Peters76882292001-02-17 05:58:44 +00001617
1618\begin{enumerate}
Edward Loperb3666a32004-09-21 03:00:51 +00001619\item Checking examples in docstrings.
1620\item Regression testing.
Fred Drakec1158352001-06-11 14:55:01 +00001621\end{enumerate}
1622
Edward Loperb3666a32004-09-21 03:00:51 +00001623These two uses have different requirements, and it is important to
1624distinguish them. In particular, filling your docstrings with obscure
1625test cases makes for bad documentation.
Tim Peters76882292001-02-17 05:58:44 +00001626
Edward Loperb3666a32004-09-21 03:00:51 +00001627When writing a docstring, choose docstring examples with care.
1628There's an art to this that needs to be learned---it may not be
1629natural at first. Examples should add genuine value to the
1630documentation. A good example can often be worth many words.
1631% [edloper] I think this may be excessive for many cases; let's
1632% just leave it to the user's judgement:
1633%% If possible, show just a few normal cases, show endcases, show
1634%% interesting subtle cases, and show an example of each kind of
1635%% exception that can be raised. You're probably testing for endcases
1636%% and subtle cases anyway in an interactive shell:
1637%% \refmodule{doctest} wants to make it as easy as possible to capture
1638%% those sessions, and will verify they continue to work as designed
1639%% forever after.
Fred Drake7a6b4f02003-07-17 16:00:01 +00001640If done with care, the examples will be invaluable for your users, and
1641will pay back the time it takes to collect them many times over as the
1642years go by and things change. I'm still amazed at how often one of
1643my \refmodule{doctest} examples stops working after a ``harmless''
1644change.
Tim Peters76882292001-02-17 05:58:44 +00001645
Edward Loperb3666a32004-09-21 03:00:51 +00001646Doctest also makes an excellent tool for writing regression testing.
1647By interleaving prose and examples, it becomes much easier to keep
1648track of what's actually being tested, and why. When a test fails,
1649the prose descriptions makes it much easier to figure out what the
1650problem is, and how it should be fixed. Regression testing is best
1651confined to dedicated objects or files. There are several options for
1652organizing regressions:
1653
1654\begin{itemize}
1655\item Define functions named \code{_regrtest_\textit{topic}} that
1656 consist of single docstrings, containing test cases for the
1657 named topics. These functions can be included in the same file
1658 as the module, or separated out into a separate test file.
1659\item Define a \code{__test__} dictionary mapping from regression test
1660 topics to docstrings containing test cases.
1661\item Write a text file containing test cases as interactive examples,
1662 and test that file using \function{testfunc()}.
1663\end{itemize}
1664
1665
1666