blob: 0fb5c54529f3287c63804209f72c452ff9b1fe7e [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}
5\moduleauthor{Tim Peters}{tim_one@users.sourceforge.net}
6\sectionauthor{Tim Peters}{tim_one@users.sourceforge.net}
7\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
14verify that they work exactly as shown. There are two common ways to
15use doctest:
16
17\begin{enumerate}
18\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.
22\end{enumerate}
23
24Here's a complete but small example:
Tim Peters76882292001-02-17 05:58:44 +000025
26\begin{verbatim}
27"""
Edward Loperb3666a32004-09-21 03:00:51 +000028This is the "example" module.
Tim Peters76882292001-02-17 05:58:44 +000029
Edward Loperb3666a32004-09-21 03:00:51 +000030The example module supplies one function, factorial(). For example,
Tim Peters76882292001-02-17 05:58:44 +000031
32>>> factorial(5)
33120
34"""
35
36def factorial(n):
37 """Return the factorial of n, an exact integer >= 0.
38
39 If the result is small enough to fit in an int, return an int.
40 Else return a long.
41
42 >>> [factorial(n) for n in range(6)]
43 [1, 1, 2, 6, 24, 120]
44 >>> [factorial(long(n)) for n in range(6)]
45 [1, 1, 2, 6, 24, 120]
46 >>> factorial(30)
47 265252859812191058636308480000000L
48 >>> factorial(30L)
49 265252859812191058636308480000000L
50 >>> factorial(-1)
51 Traceback (most recent call last):
52 ...
53 ValueError: n must be >= 0
54
55 Factorials of floats are OK, but the float must be an exact integer:
56 >>> factorial(30.1)
57 Traceback (most recent call last):
58 ...
59 ValueError: n must be exact integer
60 >>> factorial(30.0)
61 265252859812191058636308480000000L
62
63 It must also not be ridiculously large:
64 >>> factorial(1e100)
65 Traceback (most recent call last):
66 ...
67 OverflowError: n too large
68 """
69
70\end{verbatim}
71% allow LaTeX to break here.
72\begin{verbatim}
73
74 import math
75 if not n >= 0:
76 raise ValueError("n must be >= 0")
77 if math.floor(n) != n:
78 raise ValueError("n must be exact integer")
Raymond Hettinger92f21b12003-07-11 22:32:18 +000079 if n+1 == n: # catch a value like 1e300
Tim Peters76882292001-02-17 05:58:44 +000080 raise OverflowError("n too large")
81 result = 1
82 factor = 2
83 while factor <= n:
84 try:
85 result *= factor
86 except OverflowError:
87 result *= long(factor)
88 factor += 1
89 return result
90
91def _test():
Tim Petersc2388a22004-08-10 01:41:28 +000092 import doctest
93 return doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +000094
95if __name__ == "__main__":
96 _test()
97\end{verbatim}
98
Fred Drake7a6b4f02003-07-17 16:00:01 +000099If you run \file{example.py} directly from the command line,
100\module{doctest} works its magic:
Tim Peters76882292001-02-17 05:58:44 +0000101
102\begin{verbatim}
103$ python example.py
104$
105\end{verbatim}
106
Fred Drake7a6b4f02003-07-17 16:00:01 +0000107There's no output! That's normal, and it means all the examples
108worked. Pass \programopt{-v} to the script, and \module{doctest}
109prints a detailed log of what it's trying, and prints a summary at the
110end:
Tim Peters76882292001-02-17 05:58:44 +0000111
112\begin{verbatim}
113$ python example.py -v
Edward Loper6cc13502004-09-19 01:16:44 +0000114Trying:
115 factorial(5)
116Expecting:
117 120
Tim Peters76882292001-02-17 05:58:44 +0000118ok
Edward Loper6cc13502004-09-19 01:16:44 +0000119Trying:
120 [factorial(n) for n in range(6)]
121Expecting:
122 [1, 1, 2, 6, 24, 120]
Tim Peters76882292001-02-17 05:58:44 +0000123ok
Edward Loper6cc13502004-09-19 01:16:44 +0000124Trying:
125 [factorial(long(n)) for n in range(6)]
126Expecting:
127 [1, 1, 2, 6, 24, 120]
Tim Peters41a65ea2004-08-13 03:55:05 +0000128ok
129\end{verbatim}
Tim Peters76882292001-02-17 05:58:44 +0000130
131And so on, eventually ending with:
132
133\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000134Trying:
135 factorial(1e100)
Tim Peters76882292001-02-17 05:58:44 +0000136Expecting:
Tim Petersc2388a22004-08-10 01:41:28 +0000137 Traceback (most recent call last):
138 ...
139 OverflowError: n too large
Tim Peters76882292001-02-17 05:58:44 +0000140ok
Tim Peters76882292001-02-17 05:58:44 +00001412 items passed all tests:
142 1 tests in example
143 8 tests in example.factorial
1449 tests in 2 items.
1459 passed and 0 failed.
146Test passed.
147$
148\end{verbatim}
149
Fred Drake7a6b4f02003-07-17 16:00:01 +0000150That's all you need to know to start making productive use of
Tim Peters41a65ea2004-08-13 03:55:05 +0000151\module{doctest}! Jump in. The following sections provide full
152details. Note that there are many examples of doctests in
153the standard Python test suite and libraries.
Tim Peters76882292001-02-17 05:58:44 +0000154
Edward Loperb3666a32004-09-21 03:00:51 +0000155\subsection{Simple Usage: Checking Examples in
156 Docstrings\label{doctest-simple-testmod}}
Tim Peters76882292001-02-17 05:58:44 +0000157
Tim Peters41a65ea2004-08-13 03:55:05 +0000158The simplest way to start using doctest (but not necessarily the way
159you'll continue to do it) is to end each module \module{M} with:
Tim Peters76882292001-02-17 05:58:44 +0000160
161\begin{verbatim}
162def _test():
Tim Petersc2388a22004-08-10 01:41:28 +0000163 import doctest
164 return doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +0000165
166if __name__ == "__main__":
167 _test()
168\end{verbatim}
169
Tim Petersc2388a22004-08-10 01:41:28 +0000170\module{doctest} then examines docstrings in the module calling
Tim Peters41a65ea2004-08-13 03:55:05 +0000171\function{testmod()}.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000172
Tim Petersc2388a22004-08-10 01:41:28 +0000173Running the module as a script causes the examples in the docstrings
Tim Peters76882292001-02-17 05:58:44 +0000174to get executed and verified:
175
176\begin{verbatim}
177python M.py
178\end{verbatim}
179
180This won't display anything unless an example fails, in which case the
181failing example(s) and the cause(s) of the failure(s) are printed to stdout,
Tim Petersc2388a22004-08-10 01:41:28 +0000182and the final line of output is
Tim Peters26039602004-08-13 01:49:12 +0000183\samp{'***Test Failed*** \var{N} failures.'}, where \var{N} is the
Tim Petersc2388a22004-08-10 01:41:28 +0000184number of examples that failed.
Tim Peters76882292001-02-17 05:58:44 +0000185
Fred Drake7eb14632001-02-17 17:32:41 +0000186Run it with the \programopt{-v} switch instead:
Tim Peters76882292001-02-17 05:58:44 +0000187
188\begin{verbatim}
189python M.py -v
190\end{verbatim}
191
Fred Drake8836e562003-07-17 15:22:47 +0000192and a detailed report of all examples tried is printed to standard
193output, along with assorted summaries at the end.
Tim Peters76882292001-02-17 05:58:44 +0000194
Tim Petersc2388a22004-08-10 01:41:28 +0000195You can force verbose mode by passing \code{verbose=True} to
Fred Drake5d2f5152003-06-28 03:09:06 +0000196\function{testmod()}, or
Tim Petersc2388a22004-08-10 01:41:28 +0000197prohibit it by passing \code{verbose=False}. In either of those cases,
Fred Drake5d2f5152003-06-28 03:09:06 +0000198\code{sys.argv} is not examined by \function{testmod()}.
Tim Peters76882292001-02-17 05:58:44 +0000199
Edward Loperb3666a32004-09-21 03:00:51 +0000200In any case, \function{testmod()} returns a 2-tuple of ints
201\samp{(\var{failure_count}, \var{test_count})}, where
202\var{failure_count} is the number of docstring examples that failed
203and \var{test_count} is the total number of docstring examples tested.
Tim Peters76882292001-02-17 05:58:44 +0000204
Edward Loperb3666a32004-09-21 03:00:51 +0000205For more information on \function{testmod()}, see
206section~\ref{doctest-basic-api}.
207
208\subsection{Simple Usage: Checking Examples in a Text
209 File\label{doctest-simple-testfile}}
210
211Another simple application of doctest is testing interactive examples
212in a text file. This can be done with the \function{testfile()}
213function:
214
215\begin{verbatim}
216import doctest
217doctest.testfile("mytests.txt")
218\end{verbatim}
219
220This short script will execute and verify any interactive Python
221examples contained in the file \file{mytests.txt}. As with
222\function{testmod()}, it won't display anything unless an example
223fails. If an example does fail, then the failing example(s) and the
224cause(s) of the failure(s) are printed to stdout, using the same
225format as \function{testmod()}.
226
227By default, \function{testfile()} looks for files in the calling
228module's directory. See section~\ref{doctest-basic-api} for a
229description of the optional arguments that can be used to tell it to
230look for files in other locations.
231
232Like \function{testmod()}, \function{testfile()}'s verbosity can be
233set with the \programopt{-v} command-line switch or with the optional
234keyword argument \var{verbose}. And like \function{testmod()},
235\function{testfile()} returns a 2-tuple of ints
236\samp{(\var{failure_count}, \var{test_count})}, where
237\var{failure_count} is the number of docstring examples that failed
238and \var{test_count} is the total number of docstring examples tested.
239
240For more information on \function{testfile()}, see
241section~\ref{doctest-basic-api}.
242
243\subsection{How It Works\label{doctest-how-it-works}}
244
245This section examines in detail how doctest works: which docstrings it
246looks at, how it finds interactive examples, what execution context it
247uses, how it handles exceptions, and how option flags can be used to
248control its behavior. This is the information that you need to know
249to write doctest examples; for information about actually running
250doctest on these examples, see the following sections.
251
252\subsubsection{Which Docstrings Are Examined?\label{doctest-which-docstrings}}
Tim Peters76882292001-02-17 05:58:44 +0000253
Tim Peters8a3b69c2004-08-12 22:31:25 +0000254The module docstring, and all function, class and method docstrings are
255searched. Objects imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000256
Fred Drake7eb14632001-02-17 17:32:41 +0000257In addition, if \code{M.__test__} exists and "is true", it must be a
258dict, and each entry maps a (string) name to a function object, class
259object, or string. Function and class object docstrings found from
Tim Peters8a3b69c2004-08-12 22:31:25 +0000260\code{M.__test__} are searched, and strings are treated as if they
261were docstrings. In output, a key \code{K} in \code{M.__test__} appears
262with name
Tim Peters76882292001-02-17 05:58:44 +0000263
264\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000265<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000266\end{verbatim}
267
268Any classes found are recursively searched similarly, to test docstrings in
Tim Peters8a3b69c2004-08-12 22:31:25 +0000269their contained methods and nested classes.
270
271\versionchanged[A "private name" concept is deprecated and no longer
Tim Peters26039602004-08-13 01:49:12 +0000272 documented]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000273
Edward Loperb3666a32004-09-21 03:00:51 +0000274\subsubsection{How are Docstring Examples
275 Recognized?\label{doctest-finding-examples}}
Tim Peters76882292001-02-17 05:58:44 +0000276
Edward Loperb3666a32004-09-21 03:00:51 +0000277In most cases a copy-and-paste of an interactive console session works
278fine, but doctest isn't trying to do an exact emulation of any specific
279Python shell. All hard tab characters are expanded to spaces, using
2808-column tab stops. If you don't believe tabs should mean that, too
281bad: don't use hard tabs, or write your own \class{DocTestParser}
282class.
Tim Peters76882292001-02-17 05:58:44 +0000283
Edward Loperb3666a32004-09-21 03:00:51 +0000284\versionchanged[Expanding tabs to spaces is new; previous versions
285 tried to preserve hard tabs, with confusing results]{2.4}
286
287\begin{verbatim}
288>>> # comments are ignored
289>>> x = 12
290>>> x
29112
292>>> if x == 13:
293... print "yes"
294... else:
295... print "no"
296... print "NO"
297... print "NO!!!"
298...
299no
300NO
301NO!!!
302>>>
303\end{verbatim}
304
305Any expected output must immediately follow the final
306\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
307the expected output (if any) extends to the next \code{'>\code{>}>~'}
308or all-whitespace line.
309
310The fine print:
311
312\begin{itemize}
313
314\item Expected output cannot contain an all-whitespace line, since such a
315 line is taken to signal the end of expected output. If expected
316 output does contain a blank line, put \code{<BLANKLINE>} in your
317 doctest example each place a blank line is expected.
318 \versionchanged[\code{<BLANKLINE>} was added; there was no way to
319 use expected output containing empty lines in
320 previous versions]{2.4}
321
322\item Output to stdout is captured, but not output to stderr (exception
323 tracebacks are captured via a different means).
324
325\item If you continue a line via backslashing in an interactive session,
326 or for any other reason use a backslash, you should use a raw
327 docstring, which will preserve your backslashes exactly as you type
328 them:
329
330\begin{verbatim}
331>>> def f(x):
332... r'''Backslashes in a raw docstring: m\n'''
333>>> print f.__doc__
334Backslashes in a raw docstring: m\n
335\end{verbatim}
336
337 Otherwise, the backslash will be interpreted as part of the string.
338 E.g., the "{\textbackslash}" above would be interpreted as a newline
339 character. Alternatively, you can double each backslash in the
340 doctest version (and not use a raw string):
341
342\begin{verbatim}
343>>> def f(x):
344... '''Backslashes in a raw docstring: m\\n'''
345>>> print f.__doc__
346Backslashes in a raw docstring: m\n
347\end{verbatim}
348
349\item The starting column doesn't matter:
350
351\begin{verbatim}
352 >>> assert "Easy!"
353 >>> import math
354 >>> math.floor(1.9)
355 1.0
356\end{verbatim}
357
358and as many leading whitespace characters are stripped from the
359expected output as appeared in the initial \code{'>\code{>}>~'} line
360that started the example.
361\end{itemize}
362
363\subsubsection{What's the Execution Context?\label{doctest-execution-context}}
364
365By default, each time \module{doctest} finds a docstring to test, it
Tim Peters41a65ea2004-08-13 03:55:05 +0000366uses a \emph{shallow copy} of \module{M}'s globals, so that running tests
Tim Peters76882292001-02-17 05:58:44 +0000367doesn't change the module's real globals, and so that one test in
368\module{M} can't leave behind crumbs that accidentally allow another test
369to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000370in \module{M}, and names defined earlier in the docstring being run.
Tim Peters41a65ea2004-08-13 03:55:05 +0000371Examples cannot see names defined in other docstrings.
Tim Peters76882292001-02-17 05:58:44 +0000372
373You can force use of your own dict as the execution context by passing
Edward Loperb3666a32004-09-21 03:00:51 +0000374\code{globs=your_dict} to \function{testmod()} or
375\function{testfile()} instead.
Tim Peters76882292001-02-17 05:58:44 +0000376
Edward Loperb3666a32004-09-21 03:00:51 +0000377\subsubsection{What About Exceptions?\label{doctest-exceptions}}
Tim Peters76882292001-02-17 05:58:44 +0000378
Tim Petersa07bcd42004-08-26 04:47:31 +0000379No problem, provided that the traceback is the only output produced by
380the example: just paste in the traceback. Since tracebacks contain
381details that are likely to change rapidly (for example, exact file paths
382and line numbers), this is one case where doctest works hard to be
383flexible in what it accepts.
384
385Simple example:
Tim Peters76882292001-02-17 05:58:44 +0000386
387\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000388>>> [1, 2, 3].remove(42)
389Traceback (most recent call last):
390 File "<stdin>", line 1, in ?
391ValueError: list.remove(x): x not in list
Tim Peters76882292001-02-17 05:58:44 +0000392\end{verbatim}
393
Edward Loper19b19582004-08-25 23:07:03 +0000394That doctest succeeds if \exception{ValueError} is raised, with the
Tim Petersa07bcd42004-08-26 04:47:31 +0000395\samp{list.remove(x): x not in list} detail as shown.
Tim Peters41a65ea2004-08-13 03:55:05 +0000396
Edward Loper19b19582004-08-25 23:07:03 +0000397The expected output for an exception must start with a traceback
398header, which may be either of the following two lines, indented the
399same as the first line of the example:
Tim Peters41a65ea2004-08-13 03:55:05 +0000400
401\begin{verbatim}
402Traceback (most recent call last):
403Traceback (innermost last):
404\end{verbatim}
405
Edward Loper19b19582004-08-25 23:07:03 +0000406The traceback header is followed by an optional traceback stack, whose
Tim Petersa07bcd42004-08-26 04:47:31 +0000407contents are ignored by doctest. The traceback stack is typically
408omitted, or copied verbatim from an interactive session.
Edward Loper19b19582004-08-25 23:07:03 +0000409
Tim Petersa07bcd42004-08-26 04:47:31 +0000410The traceback stack is followed by the most interesting part: the
Edward Loper19b19582004-08-25 23:07:03 +0000411line(s) containing the exception type and detail. This is usually the
412last line of a traceback, but can extend across multiple lines if the
Tim Petersa07bcd42004-08-26 04:47:31 +0000413exception has a multi-line detail:
Tim Peters41a65ea2004-08-13 03:55:05 +0000414
415\begin{verbatim}
Edward Loper19b19582004-08-25 23:07:03 +0000416>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000417Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000418 File "<stdin>", line 1, in ?
419ValueError: multi
420 line
421detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000422\end{verbatim}
423
Edward Loper6cc13502004-09-19 01:16:44 +0000424The last three lines (starting with \exception{ValueError}) are
Edward Loper19b19582004-08-25 23:07:03 +0000425compared against the exception's type and detail, and the rest are
426ignored.
Tim Peters41a65ea2004-08-13 03:55:05 +0000427
Edward Loper19b19582004-08-25 23:07:03 +0000428Best practice is to omit the traceback stack, unless it adds
Tim Petersa07bcd42004-08-26 04:47:31 +0000429significant documentation value to the example. So the last example
Tim Peters41a65ea2004-08-13 03:55:05 +0000430is probably better as:
431
432\begin{verbatim}
Edward Loper19b19582004-08-25 23:07:03 +0000433>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000434Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000435 ...
436ValueError: multi
437 line
438detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000439\end{verbatim}
440
Tim Petersa07bcd42004-08-26 04:47:31 +0000441Note that tracebacks are treated very specially. In particular, in the
Tim Peters41a65ea2004-08-13 03:55:05 +0000442rewritten example, the use of \samp{...} is independent of doctest's
Tim Petersa07bcd42004-08-26 04:47:31 +0000443\constant{ELLIPSIS} option. The ellipsis in that example could be left
444out, or could just as well be three (or three hundred) commas or digits,
445or an indented transcript of a Monty Python skit.
446
447Some details you should read once, but won't need to remember:
448
449\begin{itemize}
450
451\item Doctest can't guess whether your expected output came from an
452 exception traceback or from ordinary printing. So, e.g., an example
453 that expects \samp{ValueError: 42 is prime} will pass whether
454 \exception{ValueError} is actually raised or if the example merely
455 prints that traceback text. In practice, ordinary output rarely begins
456 with a traceback header line, so this doesn't create real problems.
457
458\item Each line of the traceback stack (if present) must be indented
459 further than the first line of the example, \emph{or} start with a
460 non-alphanumeric character. The first line following the traceback
461 header indented the same and starting with an alphanumeric is taken
462 to be the start of the exception detail. Of course this does the
463 right thing for genuine tracebacks.
464
Tim Peters1fbf9c52004-09-04 17:21:02 +0000465\item When the \constant{IGNORE_EXCEPTION_DETAIL} doctest option is
466 is specified, everything following the leftmost colon is ignored.
467
Tim Petersa07bcd42004-08-26 04:47:31 +0000468\end{itemize}
Tim Peters41a65ea2004-08-13 03:55:05 +0000469
Tim Peters0e448072004-08-26 01:02:08 +0000470\versionchanged[The ability to handle a multi-line exception detail
471 was added]{2.4}
472
Edward Loperb3666a32004-09-21 03:00:51 +0000473\subsubsection{Option Flags and Directives\label{doctest-options}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000474
Tim Peterscf533552004-08-26 04:50:38 +0000475A number of option flags control various aspects of doctest's
Tim Peters026f8dc2004-08-19 16:38:58 +0000476behavior. Symbolic names for the flags are supplied as module constants,
Tim Peters83e259a2004-08-13 21:55:21 +0000477which can be or'ed together and passed to various functions. The names
Tim Peters026f8dc2004-08-19 16:38:58 +0000478can also be used in doctest directives (see below).
Tim Peters8a3b69c2004-08-12 22:31:25 +0000479
Tim Petersa07bcd42004-08-26 04:47:31 +0000480The first group of options define test semantics, controlling
481aspects of how doctest decides whether actual output matches an
482example's expected output:
483
Tim Peters8a3b69c2004-08-12 22:31:25 +0000484\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
485 By default, if an expected output block contains just \code{1},
486 an actual output block containing just \code{1} or just
487 \code{True} is considered to be a match, and similarly for \code{0}
488 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
489 specified, neither substitution is allowed. The default behavior
490 caters to that Python changed the return type of many functions
491 from integer to boolean; doctests expecting "little integer"
492 output still work in these cases. This option will probably go
493 away, but not for several years.
494\end{datadesc}
495
496\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
497 By default, if an expected output block contains a line
498 containing only the string \code{<BLANKLINE>}, then that line
499 will match a blank line in the actual output. Because a
500 genuinely blank line delimits the expected output, this is
501 the only way to communicate that a blank line is expected. When
502 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
503 is not allowed.
504\end{datadesc}
505
506\begin{datadesc}{NORMALIZE_WHITESPACE}
507 When specified, all sequences of whitespace (blanks and newlines) are
508 treated as equal. Any sequence of whitespace within the expected
509 output will match any sequence of whitespace within the actual output.
510 By default, whitespace must match exactly.
511 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
512 of expected output is very long, and you want to wrap it across
513 multiple lines in your source.
514\end{datadesc}
515
516\begin{datadesc}{ELLIPSIS}
517 When specified, an ellipsis marker (\code{...}) in the expected output
518 can match any substring in the actual output. This includes
Tim Peters026f8dc2004-08-19 16:38:58 +0000519 substrings that span line boundaries, and empty substrings, so it's
520 best to keep usage of this simple. Complicated uses can lead to the
521 same kinds of "oops, it matched too much!" surprises that \regexp{.*}
522 is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000523\end{datadesc}
524
Tim Peters1fbf9c52004-09-04 17:21:02 +0000525\begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
526 When specified, an example that expects an exception passes if
527 an exception of the expected type is raised, even if the exception
528 detail does not match. For example, an example expecting
529 \samp{ValueError: 42} will pass if the actual exception raised is
530 \samp{ValueError: 3*14}, but will fail, e.g., if
531 \exception{TypeError} is raised.
532
533 Note that a similar effect can be obtained using \constant{ELLIPSIS},
534 and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
535 prior to 2.4 become uninteresting. Until then,
536 \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
537 doctest that doesn't care about the exception detail yet continues
538 to pass under Python releases prior to 2.4 (doctest directives
539 appear to be comments to them). For example,
540
541\begin{verbatim}
542>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
543Traceback (most recent call last):
544 File "<stdin>", line 1, in ?
545TypeError: object doesn't support item assignment
546\end{verbatim}
547
548 passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
549 to say "does not" instead of "doesn't".
550
551\end{datadesc}
552
Tim Peters38330fe2004-08-30 16:19:24 +0000553\begin{datadesc}{COMPARISON_FLAGS}
554 A bitmask or'ing together all the comparison flags above.
555\end{datadesc}
556
Tim Petersf33683f2004-08-26 04:52:46 +0000557The second group of options controls how test failures are reported:
Tim Petersa07bcd42004-08-26 04:47:31 +0000558
Edward Loper71f55af2004-08-26 01:41:51 +0000559\begin{datadesc}{REPORT_UDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000560 When specified, failures that involve multi-line expected and
561 actual outputs are displayed using a unified diff.
562\end{datadesc}
563
Edward Loper71f55af2004-08-26 01:41:51 +0000564\begin{datadesc}{REPORT_CDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000565 When specified, failures that involve multi-line expected and
566 actual outputs will be displayed using a context diff.
567\end{datadesc}
568
Edward Loper71f55af2004-08-26 01:41:51 +0000569\begin{datadesc}{REPORT_NDIFF}
Tim Petersc6cbab02004-08-22 19:43:28 +0000570 When specified, differences are computed by \code{difflib.Differ},
571 using the same algorithm as the popular \file{ndiff.py} utility.
572 This is the only method that marks differences within lines as
573 well as across lines. For example, if a line of expected output
574 contains digit \code{1} where actual output contains letter \code{l},
575 a line is inserted with a caret marking the mismatching column
576 positions.
577\end{datadesc}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000578
Edward Lopera89f88d2004-08-26 02:45:51 +0000579\begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
580 When specified, display the first failing example in each doctest,
581 but suppress output for all remaining examples. This will prevent
582 doctest from reporting correct examples that break because of
583 earlier failures; but it might also hide incorrect examples that
584 fail independently of the first failure. When
585 \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
586 examples are still run, and still count towards the total number of
587 failures reported; only the output is suppressed.
588\end{datadesc}
589
Tim Peters38330fe2004-08-30 16:19:24 +0000590\begin{datadesc}{REPORTING_FLAGS}
591 A bitmask or'ing together all the reporting flags above.
592\end{datadesc}
593
Edward Loperb3666a32004-09-21 03:00:51 +0000594"Doctest directives" may be used to modify the option flags for
595individual examples. Doctest directives are expressed as a special
596Python comment following an example's source code:
Tim Peters026f8dc2004-08-19 16:38:58 +0000597
598\begin{productionlist}[doctest]
599 \production{directive}
Edward Loper6cc13502004-09-19 01:16:44 +0000600 {"\#" "doctest:" \token{directive_options}}
601 \production{directive_options}
602 {\token{directive_option} ("," \token{directive_option})*}
603 \production{directive_option}
604 {\token{on_or_off} \token{directive_option_name}}
Tim Peters026f8dc2004-08-19 16:38:58 +0000605 \production{on_or_off}
606 {"+" | "-"}
Edward Loper6cc13502004-09-19 01:16:44 +0000607 \production{directive_option_name}
Tim Peters026f8dc2004-08-19 16:38:58 +0000608 {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
609\end{productionlist}
610
611Whitespace is not allowed between the \code{+} or \code{-} and the
Edward Loper6cc13502004-09-19 01:16:44 +0000612directive option name. The directive option name can be any of the
Edward Loperb3666a32004-09-21 03:00:51 +0000613option flag names explained above.
Tim Peters026f8dc2004-08-19 16:38:58 +0000614
Edward Loperb3666a32004-09-21 03:00:51 +0000615An example's doctest directives modify doctest's behavior for that
616single example. Use \code{+} to enable the named behavior, or
617\code{-} to disable it.
Tim Peters026f8dc2004-08-19 16:38:58 +0000618
619For example, this test passes:
620
621\begin{verbatim}
622>>> print range(20) #doctest: +NORMALIZE_WHITESPACE
623[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
62410, 11, 12, 13, 14, 15, 16, 17, 18, 19]
625\end{verbatim}
626
627Without the directive it would fail, both because the actual output
628doesn't have two blanks before the single-digit list elements, and
629because the actual output is on a single line. This test also passes,
Tim Petersa07bcd42004-08-26 04:47:31 +0000630and also requires a directive to do so:
Tim Peters026f8dc2004-08-19 16:38:58 +0000631
632\begin{verbatim}
633>>> print range(20) # doctest:+ELLIPSIS
634[0, 1, ..., 18, 19]
635\end{verbatim}
636
Edward Loper6cc13502004-09-19 01:16:44 +0000637Multiple directives can be used on a single physical line, separated
638by commas:
Tim Peters026f8dc2004-08-19 16:38:58 +0000639
640\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000641>>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +0000642[0, 1, ..., 18, 19]
643\end{verbatim}
644
Edward Loperb3666a32004-09-21 03:00:51 +0000645If multiple directive comments are used for a single example, then
646they are combined:
Edward Loper6cc13502004-09-19 01:16:44 +0000647
648\begin{verbatim}
649>>> print range(20) # doctest: +ELLIPSIS
650... # doctest: +NORMALIZE_WHITESPACE
651[0, 1, ..., 18, 19]
652\end{verbatim}
653
654As the previous example shows, you can add \samp{...} lines to your
Edward Loperb3666a32004-09-21 03:00:51 +0000655example containing only directives. This can be useful when an
Edward Loper6cc13502004-09-19 01:16:44 +0000656example is too long for a directive to comfortably fit on the same
657line:
658
659\begin{verbatim}
660>>> print range(5) + range(10,20) + range(30,40) + range(50,60)
661... # doctest: +ELLIPSIS
662[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
663\end{verbatim}
664
Tim Peters026f8dc2004-08-19 16:38:58 +0000665Note that since all options are disabled by default, and directives apply
666only to the example they appear in, enabling options (via \code{+} in a
667directive) is usually the only meaningful choice. However, option flags
668can also be passed to functions that run doctests, establishing different
669defaults. In such cases, disabling an option via \code{-} in a directive
670can be useful.
671
Tim Peters8a3b69c2004-08-12 22:31:25 +0000672\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
673 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
Tim Peters1fbf9c52004-09-04 17:21:02 +0000674 \constant{IGNORE_EXCEPTION_DETAIL},
Edward Lopera89f88d2004-08-26 02:45:51 +0000675 \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
Tim Peters38330fe2004-08-30 16:19:24 +0000676 \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
677 \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
Tim Peters026f8dc2004-08-19 16:38:58 +0000678 were added; by default \code{<BLANKLINE>} in expected output
679 matches an empty line in actual output; and doctest directives
680 were added]{2.4}
681
Edward Loperb3666a32004-09-21 03:00:51 +0000682\subsubsection{Warnings\label{doctest-warnings}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000683
Edward Loperb3666a32004-09-21 03:00:51 +0000684\begin{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000685
Edward Loperb3666a32004-09-21 03:00:51 +0000686\item \module{doctest} is serious about requiring exact matches in expected
687 output. If even a single character doesn't match, the test fails. This
688 will probably surprise you a few times, as you learn exactly what Python
689 does and doesn't guarantee about output. For example, when printing a
690 dict, Python doesn't guarantee that the key-value pairs will be printed
691 in any particular order, so a test like
Tim Peters76882292001-02-17 05:58:44 +0000692
Edward Loperb3666a32004-09-21 03:00:51 +0000693% Hey! What happened to Monty Python examples?
694% Tim: ask Guido -- it's his example!
695\begin{verbatim}
696>>> foo()
697{"Hermione": "hippogryph", "Harry": "broomstick"}
698\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000699
Edward Loperb3666a32004-09-21 03:00:51 +0000700is vulnerable! One workaround is to do
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000701
Edward Loperb3666a32004-09-21 03:00:51 +0000702\begin{verbatim}
703>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
704True
705\end{verbatim}
706
707instead. Another is to do
708
709\begin{verbatim}
710>>> d = foo().items()
711>>> d.sort()
712>>> d
713[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
714\end{verbatim}
715
716There are others, but you get the idea.
717
718Another bad idea is to print things that embed an object address, like
719
720\begin{verbatim}
721>>> id(1.0) # certain to fail some of the time
7227948648
723\end{verbatim}
724
725Floating-point numbers are also subject to small output variations across
726platforms, because Python defers to the platform C library for float
727formatting, and C libraries vary widely in quality here.
728
729\begin{verbatim}
730>>> 1./7 # risky
7310.14285714285714285
732>>> print 1./7 # safer
7330.142857142857
734>>> print round(1./7, 6) # much safer
7350.142857
736\end{verbatim}
737
738Numbers of the form \code{I/2.**J} are safe across all platforms, and I
739often contrive doctest examples to produce numbers of that form:
740
741\begin{verbatim}
742>>> 3./4 # utterly safe
7430.75
744\end{verbatim}
745
746Simple fractions are also easier for people to understand, and that makes
747for better documentation.
748
749\item Be careful if you have code that must only execute once.
750
751If you have module-level code that must only execute once, a more foolproof
752definition of \function{_test()} is
753
754% [XX] How is this safer?? The only difference I see is that this
755% imports (but doesn't use) sys. -edloper
756\begin{verbatim}
757def _test():
758 import doctest, sys
759 doctest.testmod()
760\end{verbatim}
761
762\item WYSIWYG isn't always the case, starting in Python 2.3. The
763 string form of boolean results changed from \code{'0'} and
764 \code{'1'} to \code{'False'} and \code{'True'} in Python 2.3.
765 This makes it clumsy to write a doctest showing boolean results that
766 passes under multiple versions of Python. In Python 2.3, by default,
767 and as a special case, if an expected output block consists solely
768 of \code{'0'} and the actual output block consists solely of
769 \code{'False'}, that's accepted as an exact match, and similarly for
770 \code{'1'} versus \code{'True'}. This behavior can be turned off by
771 passing the new (in 2.3) module constant
772 \constant{DONT_ACCEPT_TRUE_FOR_1} as the value of \function{testmod()}'s
773 new (in 2.3) optional \var{optionflags} argument. Some years after
774 the integer spellings of booleans are history, this hack will
775 probably be removed again.
776
777\end{itemize}
778
779\subsection{Basic API\label{doctest-basic-api}}
780
781The functions \function{testmod()} and \function{testfile()} provide a
782simple interface to doctest that should be sufficient for most basic
783uses. For a more informal introduction to these two functions, see
784sections \ref{doctest-simple-testmod} and
785\ref{doctest-simple-testfile}.
786
787\begin{funcdesc}{testfile}{filename\optional{, module_relative}\optional{,
788 name}\optional{, package}\optional{,
789 globs}\optional{, verbose}\optional{,
790 report}\optional{, optionflags}\optional{,
791 extraglobs}\optional{, raise_on_error}}
792
793 All arguments except \var{filename} are optional, and should be
794 specified in keyword form.
795
796 Test examples in the file named \var{filename}. Return
797 \samp{(\var{failure_count}, \var{test_count})}.
798
799 Optional argument \var{module_relative} specifies how the filename
800 should be interpreted:
801
802 \begin{itemize}
803 \item If \var{module_relative} is \code{True} (the default), then
804 \var{filename} specifies an os-independent module-relative
805 path. By default, this path is relative to the calling
806 module's directory; but if the \var{package} argument is
807 specified, then it is relative to that package. To ensure
808 os-independence, \var{filename} should use \code{/} characters
809 to separate path segments, and may not be an absolute path
810 (i.e., it may not begin with \code{/}).
811 \item If \var{module_relative} is \code{False}, then \var{filename}
812 specifies an os-specific path. The path may be absolute or
813 relative; relative paths are resolved with respect to the
814 current working directory.
815 \end{itemize}
816
817 Optional argument \var{name} gives the name of the test; by default,
818 or if \code{None}, \code{os.path.basename(\var{filename})} is used.
819
820 Optional argument \var{package} is a Python package or the name of a
821 Python package whose directory should be used as the base directory
822 for a module-relative filename. If no package is specified, then
823 the calling module's directory is used as the base directory for
824 module-relative filenames. It is an error to specify \var{package}
825 if \var{module_relative} is \code{False}.
826
827 Optional argument \var{globs} gives a dict to be used as the globals
828 when executing examples; by default, or if \code{None},
829 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
830 created for the doctest, so its examples start with a clean slate.
831
832 Optional argument \var{extraglobs} gives a dict merged into the
833 globals used to execute examples. This works like
834 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
835 common key, the associated value in \var{extraglobs} appears in the
836 combined dict. By default, or if \code{None}, no extra globals are
837 used. This is an advanced feature that allows parameterization of
838 doctests. For example, a doctest can be written for a base class, using
839 a generic name for the class, then reused to test any number of
840 subclasses by passing an \var{extraglobs} dict mapping the generic
841 name to the subclass to be tested.
842
843 Optional argument \var{verbose} prints lots of stuff if true, and prints
844 only failures if false; by default, or if \code{None}, it's true
845 if and only if \code{'-v'} is in \code{sys.argv}.
846
847 Optional argument \var{report} prints a summary at the end when true,
848 else prints nothing at the end. In verbose mode, the summary is
849 detailed, else the summary is very brief (in fact, empty if all tests
850 passed).
851
852 Optional argument \var{optionflags} or's together option flags. See
853 see section~\ref{doctest-options}.
854
855 Optional argument \var{raise_on_error} defaults to false. If true,
856 an exception is raised upon the first failure or unexpected exception
857 in an example. This allows failures to be post-mortem debugged.
858 Default behavior is to continue running examples.
859
860 \versionadded{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000861\end{funcdesc}
862
Tim Peters83e259a2004-08-13 21:55:21 +0000863\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
864 globs}\optional{, verbose}\optional{,
865 isprivate}\optional{, report}\optional{,
866 optionflags}\optional{, extraglobs}\optional{,
Tim Peters82788602004-09-13 15:03:17 +0000867 raise_on_error}\optional{, exclude_empty}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000868
Tim Peters83e259a2004-08-13 21:55:21 +0000869 All arguments are optional, and all except for \var{m} should be
870 specified in keyword form.
871
872 Test examples in docstrings in functions and classes reachable
873 from module \var{m} (or the current module if \var{m} is not supplied
874 or is \code{None}), starting with \code{\var{m}.__doc__}.
875
876 Also test examples reachable from dict \code{\var{m}.__test__}, if it
877 exists and is not \code{None}. \code{\var{m}.__test__} maps
878 names (strings) to functions, classes and strings; function and class
879 docstrings are searched for examples; strings are searched directly,
880 as if they were docstrings.
881
882 Only docstrings attached to objects belonging to module \var{m} are
883 searched.
884
885 Return \samp{(\var{failure_count}, \var{test_count})}.
886
887 Optional argument \var{name} gives the name of the module; by default,
888 or if \code{None}, \code{\var{m}.__name__} is used.
889
890 Optional argument \var{globs} gives a dict to be used as the globals
891 when executing examples; by default, or if \code{None},
892 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
893 created for each docstring with examples, so that each docstring's
894 examples start with a clean slate.
895
896 Optional argument \var{extraglobs} gives a dict merged into the
897 globals used to execute examples. This works like
898 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
899 common key, the associated value in \var{extraglobs} appears in the
900 combined dict. By default, or if \code{None}, no extra globals are
901 used. This is an advanced feature that allows parameterization of
902 doctests. For example, a doctest can be written for a base class, using
903 a generic name for the class, then reused to test any number of
904 subclasses by passing an \var{extraglobs} dict mapping the generic
905 name to the subclass to be tested.
906
907 Optional argument \var{verbose} prints lots of stuff if true, and prints
908 only failures if false; by default, or if \code{None}, it's true
909 if and only if \code{'-v'} is in \code{sys.argv}.
910
911 Optional argument \var{report} prints a summary at the end when true,
912 else prints nothing at the end. In verbose mode, the summary is
913 detailed, else the summary is very brief (in fact, empty if all tests
914 passed).
915
916 Optional argument \var{optionflags} or's together option flags. See
Edward Loperb3666a32004-09-21 03:00:51 +0000917 see section~\ref{doctest-options}.
Tim Peters83e259a2004-08-13 21:55:21 +0000918
919 Optional argument \var{raise_on_error} defaults to false. If true,
920 an exception is raised upon the first failure or unexpected exception
921 in an example. This allows failures to be post-mortem debugged.
922 Default behavior is to continue running examples.
923
Tim Peters82788602004-09-13 15:03:17 +0000924 Optional argument \var{exclude_empty} defaults to false. If true,
925 objects for which no doctests are found are excluded from consideration.
926 The default is a backward compatibility hack, so that code still
927 using \method{doctest.master.summarize()} in conjunction with
928 \function{testmod()} continues to get output for objects with no tests.
929 The \var{exclude_empty} argument to the newer \class{DocTestFinder}
930 constructor defaults to true.
931
Tim Peters83e259a2004-08-13 21:55:21 +0000932 Optional argument \var{isprivate} specifies a function used to
933 determine whether a name is private. The default function treats
934 all names as public. \var{isprivate} can be set to
935 \code{doctest.is_private} to skip over names that are
936 private according to Python's underscore naming convention.
937 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
938 If you need to skip tests based on name, filter the list returned by
939 \code{DocTestFinder.find()} instead.}
940
941 \versionchanged[The parameter \var{optionflags} was added]{2.3}
942
Tim Peters82788602004-09-13 15:03:17 +0000943 \versionchanged[The parameters \var{extraglobs}, \var{raise_on_error}
944 and \var{exclude_empty} were added]{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000945\end{funcdesc}
946
Edward Loperb3666a32004-09-21 03:00:51 +0000947\subsection{Unittest API\label{doctest-unittest-api}}
948
949Doctest provides several functions that can be used to create
950\module{unittest} test suites from doctest examples. These test
951suites can then be run using \module{unittest} test runners:
952
953\begin{verbatim}
954 import unittest
955 import doctest
956 import my_module_with_doctests
957
958 suite = doctest.DocTestSuite(my_module_with_doctests)
959 runner = unittest.TextTestRunner()
960 runner.run(suite)
961\end{verbatim}
962
963\begin{funcdesc}{DocFileSuite}{*paths, **kw}
964 Convert doctest tests from one or more text files to a
965 \class{\refmodule{unittest}.TestSuite}.
966
967 The returned \class{TestSuite} is to be run by the unittest
968 framework and runs the interactive examples in each file. If an
969 example in any file fails, then the synthesized unit test fails, and
970 a \exception{failureException} exception is raised showing the
971 name of the file containing the test and a (sometimes approximate)
972 line number.
973
974 A number of options may be provided as keyword arguments:
975
976 The optional argument \var{module_relative} specifies how
977 the the filenames in \var{paths} should be interpreted:
978
979 \begin{itemize}
980 \item If \var{module_relative} is \code{True} (the default), then
981 each filename specifies an os-independent module-relative
982 path. By default, this path is relative to the calling
983 module's directory; but if the \var{package} argument is
984 specified, then it is relative to that package. To ensure
985 os-independence, each filename should use \code{/} characters
986 to separate path segments, and may not be an absolute path
987 (i.e., it may not begin with \code{/}).
988 \item If \var{module_relative} is \code{False}, then each filename
989 specifies an os-specific path. The path may be absolute or
990 relative; relative paths are resolved with respect to the
991 current working directory.
992 \end{itemize}
993
994 The optional argument \var{package} is a Python package or the name
995 of a Python package whose directory should be used as the base
996 directory for module-relative filenames. If no package is
997 specified, then the calling module's directory is used as the base
998 directory for module-relative filenames. It is an error to specify
999 \var{package} if \var{module_relative} is \code{False}.
1000
1001 The optional argument \var{setUp} specifies a set-up function for
1002 the test suite. This is called before running the tests in each
1003 file. The \var{setUp} function will be passed a \class{DocTest}
1004 object. The setUp function can access the test globals as the
1005 \var{globs} attribute of the test passed.
1006
1007 The optional argument \var{tearDown} specifies a tear-down function
1008 for the test suite. This is called after running the tests in each
1009 file. The \var{tearDown} function will be passed a \class{DocTest}
1010 object. The setUp function can access the test globals as the
1011 \var{globs} attribute of the test passed.
1012
1013 The optional argument \var{globs} is a dictionary containing the
1014 initial global variables for the tests. A new copy of this
1015 dictionary is created for each test. By default, \var{globs} is
1016 empty.
1017
1018 The optional argument \var{optionflags} specifies the default
1019 doctest options for the tests. It is created by or-ing together
1020 individual option flags.
1021
1022 \versionadded{2.4}
1023\end{funcdesc}
1024
1025\begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
1026 globs}\optional{, extraglobs}\optional{,
1027 test_finder}\optional{, setUp}\optional{,
1028 tearDown}\optional{, checker}}
1029 Convert doctest tests for a module to a
1030 \class{\refmodule{unittest}.TestSuite}.
1031
1032 The returned \class{TestSuite} is to be run by the unittest framework
1033 and runs each doctest in the module. If any of the doctests fail,
1034 then the synthesized unit test fails, and a \exception{failureException}
1035 exception is raised showing the name of the file containing the test and a
1036 (sometimes approximate) line number.
1037
1038 The optional argument \var{module} provides the module to be tested. It
1039 can be a module object or a (possibly dotted) module name. If not
1040 specified, the module calling this function is used.
1041
1042 The optional argument \var{globs} is a dictionary containing the
1043 initial global variables for the tests. A new copy of this
1044 dictionary is created for each test. By default, \var{globs} is
1045 empty.
1046
1047 The optional argument \var{extraglobs} specifies an extra set of
1048 global variables, which is merged into \var{globs}. By default, no
1049 extra globals are used.
1050
1051 The optional argument \var{test_finder} is the \class{DocTestFinder}
1052 object (or a drop-in replacement) that is used to extract doctests
1053 from the module.
1054
1055 The optional argument \var{setUp} specifies a set-up function for
1056 the test suite. This is called before running the tests in each
1057 file. The \var{setUp} function will be passed a \class{DocTest}
1058 object. The setUp function can access the test globals as the
1059 \var{globs} attribute of the test passed.
1060
1061 The optional argument \var{tearDown} specifies a tear-down function
1062 for the test suite. This is called after running the tests in each
1063 file. The \var{tearDown} function will be passed a \class{DocTest}
1064 object. The setUp function can access the test globals as the
1065 \var{globs} attribute of the test passed.
1066
1067 The optional argument \var{optionflags} specifies the default
1068 doctest options for the tests. It is created by or-ing together
1069 individual option flags.
1070
1071 \versionadded{2.3}
1072 \versionchanged[The parameters \var{globs}, \var{extraglobs},
1073 \var{test_finder}, \var{setUp}, \var{tearDown}, and
1074 \var{optionflags} were added]{2.4}
1075 \versionchanged[This function now uses the same search technique as
1076 \function{testmod()}.]{2.4}
1077\end{funcdesc}
1078
1079\subsection{Advanced API\label{doctest-advanced-api}}
1080
1081The basic API is a simple wrapper that's intended to make doctest easy
1082to use. It is fairly flexible, and should meet most user's needs;
1083however, if you require more fine grained control over testing, or
1084wish to extend doctest's capabilities, then you should use the
1085advanced API.
1086
1087The advanced API revolves around two container classes, which are used
1088to store the interactive examples extracted from doctest cases:
1089
1090\begin{itemize}
1091\item \class{Example}: A single python statement, paired with its
1092 expected output.
1093\item \class{DocTest}: A collection of \class{Example}s, typically
1094 extracted from a single docstring or text file.
1095\end{itemize}
1096
1097Additional processing classes are defined to find, parse, and run, and
1098check doctest examples:
1099
1100\begin{itemize}
1101\item \class{DocTestFinder}: Finds all docstrings in a given module,
1102 and uses a \class{DocTestParser} to create a \class{DocTest}
1103 from every docstring that contains interactive examples.
1104\item \class{DocTestParser}: Creates a \class{DocTest} object from
1105 a string (such as an object's docstring).
1106\item \class{DocTestRunner}: Executes the examples in a
1107 \class{DocTest}, and uses an \class{OutputChecker} to verify
1108 their output.
1109\item \class{OutputChecker}: Compares the actual output from a
1110 doctest example with the expected output, and decides whether
1111 they match.
1112\end{itemize}
1113
1114The relationship between these processing classes is summarized in the
1115following diagram:
1116
1117\begin{verbatim}
1118 list of:
1119+------+ +---------+
1120|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1121+------+ | ^ +---------+ | ^ (printed)
1122 | | | Example | | |
1123 V | | ... | V |
1124 DocTestParser | Example | OutputChecker
1125 +---------+
1126\end{verbatim}
1127
1128\subsubsection{DocTest Objects\label{doctest-DocTest}}
1129\begin{classdesc}{DocTest}{examples, globs, name, filename, lineno,
1130 docstring}
1131 A collection of doctest examples that should be run in a single
1132 namespace. The constructor arguments are used to initialize the
1133 member variables of the same names.
1134 \versionadded{2.4}
1135\end{classdesc}
1136
1137\class{DocTest} defines the following member variables. They are
1138initialized by the constructor, and should not be modified directly.
1139
1140\begin{memberdesc}{examples}
1141 A list of \class{Example} objects encoding the individual
1142 interactive Python examples that should be run by this test.
1143\end{memberdesc}
1144
1145\begin{memberdesc}{globs}
1146 The namespace (aka globals) that the examples should be run in.
1147 This is a dictionary mapping names to values. Any changes to the
1148 namespace made by the examples (such as binding new variables)
1149 will be reflected in \member{globs} after the test is run.
1150\end{memberdesc}
1151
1152\begin{memberdesc}{name}
1153 A string name identifying the \class{DocTest}. Typically, this is
1154 the name of the object or file that the test was extracted from.
1155\end{memberdesc}
1156
1157\begin{memberdesc}{filename}
1158 The name of the file that this \class{DocTest} was extracted from;
1159 or \code{None} if the filename is unknown, or if the
1160 \class{DocTest} was not extracted from a file.
1161\end{memberdesc}
1162
1163\begin{memberdesc}{lineno}
1164 The line number within \member{filename} where this
1165 \class{DocTest} begins, or \code{None} if the line number is
1166 unavailable. This line number is zero-based with respect to the
1167 beginning of the file.
1168\end{memberdesc}
1169
1170\begin{memberdesc}{docstring}
1171 The string that the test was extracted from, or `None` if the
1172 string is unavailable, or if the test was not extracted from a
1173 string.
1174\end{memberdesc}
1175
1176\subsubsection{Example Objects\label{doctest-Example}}
1177\begin{classdesc}{Example}{source, want\optional{,
1178 exc_msg}\optional{, lineno}\optional{,
1179 indent}\optional{, options}}
1180 A single interactive example, consisting of a Python statement and
1181 its expected output. The constructor arguments are used to
1182 initialize the member variables of the same names.
1183 \versionadded{2.4}
1184\end{classdesc}
1185
1186\class{Example} defines the following member variables. They are
1187initialized by the constructor, and should not be modified directly.
1188
1189\begin{memberdesc}{source}
1190 A string containing the example's source code. This source code
1191 consists of a single Python statement, and always ends with a
1192 newline; the constructor adds a newline when necessary.
1193\end{memberdesc}
1194
1195\begin{memberdesc}{want}
1196 The expected output from running the example's source code (either
1197 from stdout, or a traceback in case of exception). \member{want}
1198 ends with a newline unless no output is expected, in which case
1199 it's an empty string. The constructor adds a newline when
1200 necessary.
1201\end{memberdesc}
1202
1203\begin{memberdesc}{exc_msg}
1204 The exception message generated by the example, if the example is
1205 expected to generate an exception; or \code{None} if it is not
1206 expected to generate an exception. This exception message is
1207 compared against the return value of
1208 \function{traceback.format_exception_only()}. \member{exc_msg}
1209 ends with a newline unless it's \code{None}. The constructor adds
1210 a newline if needed.
1211\end{memberdesc}
1212
1213\begin{memberdesc}{lineno}
1214 The line number within the string containing this example where
1215 the example begins. This line number is zero-based with respect
1216 to the beginning of the containing string.
1217\end{memberdesc}
1218
1219\begin{memberdesc}{indent}
1220 The example's indentation in the containing string. I.e., the
1221 number of space characters that preceed the example's first
1222 prompt.
1223\end{memberdesc}
1224
1225\begin{memberdesc}{options}
1226 A dictionary mapping from option flags to \code{True} or
1227 \code{False}, which is used to override default options for this
1228 example. Any option flags not contained in this dictionary are
1229 left at their default value (as specified by the
1230 \class{DocTestRunner}'s
1231\member{optionflags}). By default, no options are set.
1232\end{memberdesc}
1233
1234\subsubsection{DocTestFinder objects\label{doctest-DocTestFinder}}
1235\begin{classdesc}{DocTestFinder}{\optional{verbose}\optional{,
1236 parser}\optional{, recurse}\optional{,
1237 exclude_empty}}
1238 A processing class used to extract the \class{DocTest}s that are
1239 relevant to a given object, from its docstring and the docstrings
1240 of its contained objects. \class{DocTest}s can currently be
1241 extracted from the following object types: modules, functions,
1242 classes, methods, staticmethods, classmethods, and properties.
1243
1244 The optional argument \var{verbose} can be used to display the
1245 objects searched by the finder. It defaults to \code{False} (no
1246 output).
1247
1248 The optional argument \var{parser} specifies the
1249 \class{DocTestParser} object (or a drop-in replacement) that is
1250 used to extract doctests from docstrings.
1251
1252 If the optional argument \var{recurse} is false, then
1253 \method{DocTestFinder.find()} will only examine the given object,
1254 and not any contained objects.
1255
1256 If the optional argument \var{exclude_empty} is false, then
1257 \method{DocTestFinder.find()} will include tests for objects with
1258 empty docstrings.
1259
1260 \versionadded{2.4}
1261\end{classdesc}
1262
1263\class{DocTestFinder} defines the following method:
1264
1265\begin{methoddesc}{find}{obj\optional{, name}\optional{,
1266 module}\optional{, globs}\optional{, extraglobs}}
1267 Return a list of the \class{DocTest}s that are defined by
1268 \var{obj}'s docstring, or by any of its contained objects'
1269 docstrings.
1270
1271 The optional argument \var{name} specifies the object's name; this
1272 name will be used to construct names for the returned
1273 \class{DocTest}s. If \var{name} is not specified, then
1274 \code{var.__name__} is used.
1275
1276 The optional parameter \var{module} is the module that contains
1277 the given object. If the module is not specified or is None, then
1278 the test finder will attempt to automatically determine the
1279 correct module. The object's module is used:
1280
1281 \begin{itemize}
1282 \item As a default namespace, if `globs` is not specified.
1283 \item To prevent the DocTestFinder from extracting DocTests
1284 from objects that are imported from other modules. (Contained
1285 objects with modules other than \var{module} are ignored.)
1286 \item To find the name of the file containing the object.
1287 \item To help find the line number of the object within its file.
1288 \end{itemize}
1289
1290 If \var{module} is \code{False}, no attempt to find the module
1291 will be made. This is obscure, of use mostly in testing doctest
1292 itself: if \var{module} is \code{False}, or is \code{None} but
1293 cannot be found automatically, then all objects are considered to
1294 belong to the (non-existent) module, so all contained objects will
1295 (recursively) be searched for doctests.
1296
1297 The globals for each \class{DocTest} is formed by combining
1298 \var{globs} and \var{extraglobs} (bindings in \var{extraglobs}
1299 override bindings in \var{globs}). A new copy of the globals
1300 dictionary is created for each \class{DocTest}. If \var{globs} is
1301 not specified, then it defaults to the module's \var{__dict__}, if
1302 specified, or \code{\{\}} otherwise. If \var{extraglobs} is not
1303 specified, then it defaults to \code{\{\}}.
1304\end{methoddesc}
1305
1306\subsubsection{DocTestParser objects\label{doctest-DocTestParser}}
1307\begin{classdesc}{DocTestParser}{}
1308 A processing class used to extract interactive examples from a
1309 string, and use them to create a \class{DocTest} object.
1310 \versionadded{2.4}
1311\end{classdesc}
1312
1313\class{DocTestParser} defines the following methods:
1314
1315\begin{methoddesc}{get_doctest}{string, globs, name, filename, lineno}
1316 Extract all doctest examples from the given string, and collect
1317 them into a \class{DocTest} object.
1318
1319 \var{globs}, \var{name}, \var{filename}, and \var{lineno} are
1320 attributes for the new \class{DocTest} object. See the
1321 documentation for \class{DocTest} for more information.
1322\end{methoddesc}
1323
1324\begin{methoddesc}{get_examples}{string\optional{, name}}
1325 Extract all doctest examples from the given string, and return
1326 them as a list of \class{Example} objects. Line numbers are
1327 0-based. The optional argument \var{name} is a name identifying
1328 this string, and is only used for error messages.
1329\end{methoddesc}
1330
1331\begin{methoddesc}{parse}{string\optional{, name}}
1332 Divide the given string into examples and intervening text, and
1333 return them as a list of alternating \class{Example}s and strings.
1334 Line numbers for the \class{Example}s are 0-based. The optional
1335 argument \var{name} is a name identifying this string, and is only
1336 used for error messages.
1337\end{methoddesc}
1338
1339\subsubsection{DocTestRunner objects\label{doctest-DocTestRunner}}
1340\begin{classdesc}{DocTestRunner}{\optional{checker}\optional{,
1341 verbose}\optional{, optionflags}}
1342 A processing class used to execute and verify the interactive
1343 examples in a \class{DocTest}.
1344
1345 The comparison between expected outputs and actual outputs is done
1346 by an \class{OutputChecker}. This comparison may be customized
1347 with a number of option flags; see section~\ref{doctest-options}
1348 for more information. If the option flags are insufficient, then
1349 the comparison may also be customized by passing a subclass of
1350 \class{OutputChecker} to the constructor.
1351
1352 The test runner's display output can be controlled in two ways.
1353 First, an output function can be passed to
1354 \method{TestRunner.run()}; this function will be called with
1355 strings that should be displayed. It defaults to
1356 \code{sys.stdout.write}. If capturing the output is not
1357 sufficient, then the display output can be also customized by
1358 subclassing DocTestRunner, and overriding the methods
1359 \method{report_start}, \method{report_success},
1360 \method{report_unexpected_exception}, and \method{report_failure}.
1361
1362 The optional keyword argument \var{checker} specifies the
1363 \class{OutputChecker} object (or drop-in replacement) that should
1364 be used to compare the expected outputs to the actual outputs of
1365 doctest examples.
1366
1367 The optional keyword argument \var{verbose} controls the
1368 \class{DocTestRunner}'s verbosity. If \var{verbose} is
1369 \code{True}, then information is printed about each example, as it
1370 is run. If \var{verbose} is \code{False}, then only failures are
1371 printed. If \var{verbose} is unspecified, or \code{None}, then
1372 verbose output is used iff the command-line switch \programopt{-v}
1373 is used.
1374
1375 The optional keyword argument \var{optionflags} can be used to
1376 control how the test runner compares expected output to actual
1377 output, and how it displays failures. For more information, see
1378 section~\ref{doctest-options}.
1379
1380 \versionadded{2.4}
1381\end{classdesc}
1382
1383\class{DocTestParser} defines the following methods:
1384
1385\begin{methoddesc}{report_start}{out, test, example}
1386 Report that the test runner is about to process the given example.
1387 This method is provided to allow subclasses of
1388 \class{DocTestRunner} to customize their output; it should not be
1389 called directly.
1390
1391 \var{example} is the example about to be processed. \var{test} is
1392 the test containing \var{example}. \var{out} is the output
1393 function that was passed to \method{DocTestRunner.run()}.
1394\end{methoddesc}
1395
1396\begin{methoddesc}{report_success}{out, test, example, got}
1397 Report that the given example ran successfully. This method is
1398 provided to allow subclasses of \class{DocTestRunner} to customize
1399 their output; it should not be called directly.
1400
1401 \var{example} is the example about to be processed. \var{got} is
1402 the actual output from the example. \var{test} is the test
1403 containing \var{example}. \var{out} is the output function that
1404 was passed to \method{DocTestRunner.run()}.
1405\end{methoddesc}
1406
1407\begin{methoddesc}{report_failure}{out, test, example, got}
1408 Report that the given example failed. This method is provided to
1409 allow subclasses of \class{DocTestRunner} to customize their
1410 output; it should not be called directly.
1411
1412 \var{example} is the example about to be processed. \var{got} is
1413 the actual output from the example. \var{test} is the test
1414 containing \var{example}. \var{out} is the output function that
1415 was passed to \method{DocTestRunner.run()}.
1416\end{methoddesc}
1417
1418\begin{methoddesc}{report_unexpected_exception}{out, test, example, exc_info}
1419 Report that the given example raised an unexpected exception.
1420 This method is provided to allow subclasses of
1421 \class{DocTestRunner} to customize their output; it should not be
1422 called directly.
1423
1424 \var{example} is the example about to be processed.
1425 \var{exc_info} is a tuple containing information about the
1426 unexpected exception (as returned by \function{sys.exc_info()}).
1427 \var{test} is the test containing \var{example}. \var{out} is the
1428 output function that was passed to \method{DocTestRunner.run()}.
1429\end{methoddesc}
1430
1431\begin{methoddesc}{run}{test\optional{, compileflags}\optional{,
1432 out}\optional{, clear_globs}}
1433 Run the examples in \var{test} (a \class{DocTest} object), and
1434 display the results using the writer function \var{out}.
1435
1436 The examples are run in the namespace \code{test.globs}. If
1437 \var{clear_globs} is true (the default), then this namespace will
1438 be cleared after the test runs, to help with garbage collection.
1439 If you would like to examine the namespace after the test
1440 completes, then use \var{clear_globs=False}.
1441
1442 \var{compileflags} gives the set of flags that should be used by
1443 the Python compiler when running the examples. If not specified,
1444 then it will default to the set of future-import flags that apply
1445 to \var{globs}.
1446
1447 The output of each example is checked using the
1448 \class{DocTestRunner}'s output checker, and the results are
1449 formatted by the \method{DocTestRunner.report_*} methods.
1450\end{methoddesc}
1451
1452\begin{methoddesc}{summarize}{\optional{verbose}}
1453 Print a summary of all the test cases that have been run by this
1454 DocTestRunner, and return a tuple \samp{(\var{failure_count},
1455 \var{test_count})}.
1456
1457 The optional \var{verbose} argument controls how detailed the
1458 summary is. If the verbosity is not specified, then the
1459 \class{DocTestRunner}'s verbosity is used.
1460\end{methoddesc}
1461
1462\subsubsection{OutputChecker objects\label{doctest-OutputChecker}}
1463
1464\begin{classdesc}{OutputChecker}{}
1465 A class used to check the whether the actual output from a doctest
1466 example matches the expected output. \class{OutputChecker}
1467 defines two methods: \method{check_output}, which compares a given
1468 pair of outputs, and returns true if they match; and
1469 \method{output_difference}, which returns a string describing the
1470 differences between two outputs.
1471 \versionadded{2.4}
1472\end{classdesc}
1473
1474\class{OutputChecker} defines the following methods:
1475
1476\begin{methoddesc}{check_output}{want, got, optionflags}
1477 Return \code{True} iff the actual output from an example
1478 (\var{got}) matches the expected output (\var{want}). These
1479 strings are always considered to match if they are identical; but
1480 depending on what option flags the test runner is using, several
1481 non-exact match types are also possible. See
1482 section~\ref{doctest-options} for more information about option
1483 flags.
1484\end{methoddesc}
1485
1486\begin{methoddesc}{output_difference}{example, got, optionflags}
1487 Return a string describing the differences between the expected
1488 output for a given example (\var{example}) and the actual output
1489 (\var{got}). \var{optionflags} is the set of option flags used to
1490 compare \var{want} and \var{got}.
1491\end{methoddesc}
1492
1493\subsection{Debugging\label{doctest-debugging}}
1494
1495Doctest provides three mechanisms for debugging doctest examples:
1496
1497\begin{enumerate}
1498\item The \function{debug()} function converts a specified doctest
1499 to a Python script, and executes that script using \module{pdb}.
1500\item The \class{DebugRunner} class is a subclass of
1501 \class{DocTestRunner} that raises an exception for the first
1502 failing example, containing information about that example.
1503 This information can be used to perform post-mortem debugging on
1504 the example.
1505\item The unittest cases generated by \function{DocTestSuite()}
1506 support the \method{debug} method defined by
1507 \class{unittest.TestCase}.
1508\end{enumerate}
1509
1510\begin{funcdesc}{debug}{module, name}
1511 Debug a single doctest docstring.
1512
1513 Provide the \var{module} (or dotted name of the module) containing
1514 the docstring to be debugged and the fully qualified dotted
1515 \var{name} of the object with the docstring to be debugged.
1516
1517 The doctest examples are extracted (see function \function{testsource()}),
1518 and written to a temporary file. The Python debugger, \refmodule{pdb},
1519 is then invoked on that file.
1520 \versionadded{2.3}
1521\end{funcdesc}
1522
1523\begin{classdesc}{DebugRunner}{\optional{checker}\optional{,
1524 verbose}\optional{, optionflags}}
1525
1526 A subclass of \class{DocTestRunner} that raises an exception as
1527 soon as a failure is encountered. If an unexpected exception
1528 occurs, an \exception{UnexpectedException} exception is raised,
1529 containing the test, the example, and the original exception. If
1530 the output doesn't match, then a \exception{DocTestFailure}
1531 exception is raised, containing the test, the example, and the
1532 actual output.
1533
1534 For information about the constructor parameters and methods, see
1535 the documentation for \class{DocTestRunner} in
1536 section~\ref{doctest-advanced-api}.
1537\end{classdesc}
1538
1539\begin{excclassdesc}{DocTestFailure}{test, example, got}
1540 An exception thrown by \class{DocTestRunner} to signal that a
1541 doctest example's actual output did not match its expected output.
1542 The constructor arguments are used to initialize the member
1543 variables of the same names.
1544\end{excclassdesc}
1545\exception{DocTestFailure} defines the following member variables:
1546\begin{memberdesc}{test}
1547 The \class{DocTest} object that was being run when the example failed.
1548\end{memberdesc}
1549\begin{memberdesc}{example}
1550 The \class{Example} that failed.
1551\end{memberdesc}
1552\begin{memberdesc}{got}
1553 The example's actual output.
1554\end{memberdesc}
1555
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001556\begin{funcdesc}{testsource}{module, name}
1557 Extract the doctest examples from a docstring.
1558
1559 Provide the \var{module} (or dotted name of the module) containing the
1560 tests to be extracted and the \var{name} (within the module) of the object
1561 with the docstring containing the tests to be extracted.
1562
1563 The doctest examples are returned as a string containing Python
1564 code. The expected output blocks in the examples are converted
1565 to Python comments.
1566 \versionadded{2.3}
1567\end{funcdesc}
1568
Edward Loperb3666a32004-09-21 03:00:51 +00001569\begin{excclassdesc}{UnexpectedException}{test, example, got}
1570 An exception thrown by \class{DocTestRunner} to signal that a
1571 doctest example raised an unexpected exception. The constructor
1572 arguments are used to initialize the member variables of the same
1573 names.
1574\end{excclassdesc}
1575\exception{UnexpectedException} 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}{exc_info}
1583 A tuple containing information about the unexpected exception, as
1584 returned by \function{sys.exc_info()}.
1585\end{memberdesc}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001586
Edward Loperb3666a32004-09-21 03:00:51 +00001587\begin{funcdesc}{register_optionflag}{name}
1588 Create a new option flag with a given name, and return the new
1589 flag's integer value. \function{register_optionflag()} can be
1590 used when subclassing \class{OutputChecker} or
1591 \class{DocTestRunner} to create new options that are supported by
1592 your subclasses. \function{register_optionflag} should always be
1593 called using the following idiom:
1594\begin{verbatim}
1595 MY_FLAG = register_optionflag('MY_FLAG')
1596\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001597\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +00001598
Edward Loperb3666a32004-09-21 03:00:51 +00001599\subsection{Soapbox\label{doctest-soapbox}}
Tim Peters76882292001-02-17 05:58:44 +00001600
Edward Loperb3666a32004-09-21 03:00:51 +00001601As mentioned in the introduction, \module{doctest} has two primary
1602uses:
Tim Peters76882292001-02-17 05:58:44 +00001603
1604\begin{enumerate}
Edward Loperb3666a32004-09-21 03:00:51 +00001605\item Checking examples in docstrings.
1606\item Regression testing.
Fred Drakec1158352001-06-11 14:55:01 +00001607\end{enumerate}
1608
Edward Loperb3666a32004-09-21 03:00:51 +00001609These two uses have different requirements, and it is important to
1610distinguish them. In particular, filling your docstrings with obscure
1611test cases makes for bad documentation.
Tim Peters76882292001-02-17 05:58:44 +00001612
Edward Loperb3666a32004-09-21 03:00:51 +00001613When writing a docstring, choose docstring examples with care.
1614There's an art to this that needs to be learned---it may not be
1615natural at first. Examples should add genuine value to the
1616documentation. A good example can often be worth many words.
1617% [edloper] I think this may be excessive for many cases; let's
1618% just leave it to the user's judgement:
1619%% If possible, show just a few normal cases, show endcases, show
1620%% interesting subtle cases, and show an example of each kind of
1621%% exception that can be raised. You're probably testing for endcases
1622%% and subtle cases anyway in an interactive shell:
1623%% \refmodule{doctest} wants to make it as easy as possible to capture
1624%% those sessions, and will verify they continue to work as designed
1625%% forever after.
Fred Drake7a6b4f02003-07-17 16:00:01 +00001626If done with care, the examples will be invaluable for your users, and
1627will pay back the time it takes to collect them many times over as the
1628years go by and things change. I'm still amazed at how often one of
1629my \refmodule{doctest} examples stops working after a ``harmless''
1630change.
Tim Peters76882292001-02-17 05:58:44 +00001631
Edward Loperb3666a32004-09-21 03:00:51 +00001632Doctest also makes an excellent tool for writing regression testing.
1633By interleaving prose and examples, it becomes much easier to keep
1634track of what's actually being tested, and why. When a test fails,
1635the prose descriptions makes it much easier to figure out what the
1636problem is, and how it should be fixed. Regression testing is best
1637confined to dedicated objects or files. There are several options for
1638organizing regressions:
1639
1640\begin{itemize}
1641\item Define functions named \code{_regrtest_\textit{topic}} that
1642 consist of single docstrings, containing test cases for the
1643 named topics. These functions can be included in the same file
1644 as the module, or separated out into a separate test file.
1645\item Define a \code{__test__} dictionary mapping from regression test
1646 topics to docstrings containing test cases.
1647\item Write a text file containing test cases as interactive examples,
1648 and test that file using \function{testfunc()}.
1649\end{itemize}
1650
1651
1652