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