blob: 63c041835648cb2416403f7861d5422dcfc1b383 [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
168 return doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +0000169
170if __name__ == "__main__":
171 _test()
172\end{verbatim}
173
Tim Petersc2388a22004-08-10 01:41:28 +0000174\module{doctest} then examines docstrings in the module calling
Tim Peters41a65ea2004-08-13 03:55:05 +0000175\function{testmod()}.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000176
Tim Petersc2388a22004-08-10 01:41:28 +0000177Running the module as a script causes the examples in the docstrings
Tim Peters76882292001-02-17 05:58:44 +0000178to get executed and verified:
179
180\begin{verbatim}
181python M.py
182\end{verbatim}
183
184This won't display anything unless an example fails, in which case the
185failing example(s) and the cause(s) of the failure(s) are printed to stdout,
Tim Petersc2388a22004-08-10 01:41:28 +0000186and the final line of output is
Tim Peters26039602004-08-13 01:49:12 +0000187\samp{'***Test Failed*** \var{N} failures.'}, where \var{N} is the
Tim Petersc2388a22004-08-10 01:41:28 +0000188number of examples that failed.
Tim Peters76882292001-02-17 05:58:44 +0000189
Fred Drake7eb14632001-02-17 17:32:41 +0000190Run it with the \programopt{-v} switch instead:
Tim Peters76882292001-02-17 05:58:44 +0000191
192\begin{verbatim}
193python M.py -v
194\end{verbatim}
195
Fred Drake8836e562003-07-17 15:22:47 +0000196and a detailed report of all examples tried is printed to standard
197output, along with assorted summaries at the end.
Tim Peters76882292001-02-17 05:58:44 +0000198
Tim Petersc2388a22004-08-10 01:41:28 +0000199You can force verbose mode by passing \code{verbose=True} to
Fred Drake5d2f5152003-06-28 03:09:06 +0000200\function{testmod()}, or
Tim Petersc2388a22004-08-10 01:41:28 +0000201prohibit it by passing \code{verbose=False}. In either of those cases,
Fred Drake5d2f5152003-06-28 03:09:06 +0000202\code{sys.argv} is not examined by \function{testmod()}.
Tim Peters76882292001-02-17 05:58:44 +0000203
Edward Loperb3666a32004-09-21 03:00:51 +0000204In any case, \function{testmod()} returns a 2-tuple of ints
205\samp{(\var{failure_count}, \var{test_count})}, where
206\var{failure_count} is the number of docstring examples that failed
207and \var{test_count} is the total number of docstring examples tested.
Tim Peters76882292001-02-17 05:58:44 +0000208
Edward Loperb3666a32004-09-21 03:00:51 +0000209For more information on \function{testmod()}, see
210section~\ref{doctest-basic-api}.
211
212\subsection{Simple Usage: Checking Examples in a Text
213 File\label{doctest-simple-testfile}}
214
215Another simple application of doctest is testing interactive examples
216in a text file. This can be done with the \function{testfile()}
217function:
218
219\begin{verbatim}
220import doctest
221doctest.testfile("mytests.txt")
222\end{verbatim}
223
224This short script will execute and verify any interactive Python
225examples contained in the file \file{mytests.txt}. As with
226\function{testmod()}, it won't display anything unless an example
227fails. If an example does fail, then the failing example(s) and the
228cause(s) of the failure(s) are printed to stdout, using the same
229format as \function{testmod()}.
230
231By default, \function{testfile()} looks for files in the calling
232module's directory. See section~\ref{doctest-basic-api} for a
233description of the optional arguments that can be used to tell it to
234look for files in other locations.
235
236Like \function{testmod()}, \function{testfile()}'s verbosity can be
237set with the \programopt{-v} command-line switch or with the optional
238keyword argument \var{verbose}. And like \function{testmod()},
239\function{testfile()} returns a 2-tuple of ints
240\samp{(\var{failure_count}, \var{test_count})}, where
241\var{failure_count} is the number of docstring examples that failed
242and \var{test_count} is the total number of docstring examples tested.
243
244For more information on \function{testfile()}, see
245section~\ref{doctest-basic-api}.
246
247\subsection{How It Works\label{doctest-how-it-works}}
248
249This section examines in detail how doctest works: which docstrings it
250looks at, how it finds interactive examples, what execution context it
251uses, how it handles exceptions, and how option flags can be used to
252control its behavior. This is the information that you need to know
253to write doctest examples; for information about actually running
254doctest on these examples, see the following sections.
255
256\subsubsection{Which Docstrings Are Examined?\label{doctest-which-docstrings}}
Tim Peters76882292001-02-17 05:58:44 +0000257
Tim Peters8a3b69c2004-08-12 22:31:25 +0000258The module docstring, and all function, class and method docstrings are
259searched. Objects imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000260
Fred Drake7eb14632001-02-17 17:32:41 +0000261In addition, if \code{M.__test__} exists and "is true", it must be a
262dict, and each entry maps a (string) name to a function object, class
263object, or string. Function and class object docstrings found from
Tim Peters8a3b69c2004-08-12 22:31:25 +0000264\code{M.__test__} are searched, and strings are treated as if they
265were docstrings. In output, a key \code{K} in \code{M.__test__} appears
266with name
Tim Peters76882292001-02-17 05:58:44 +0000267
268\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000269<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000270\end{verbatim}
271
272Any classes found are recursively searched similarly, to test docstrings in
Tim Peters8a3b69c2004-08-12 22:31:25 +0000273their contained methods and nested classes.
274
275\versionchanged[A "private name" concept is deprecated and no longer
Tim Peters26039602004-08-13 01:49:12 +0000276 documented]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000277
Edward Loperb3666a32004-09-21 03:00:51 +0000278\subsubsection{How are Docstring Examples
279 Recognized?\label{doctest-finding-examples}}
Tim Peters76882292001-02-17 05:58:44 +0000280
Edward Loperb3666a32004-09-21 03:00:51 +0000281In most cases a copy-and-paste of an interactive console session works
282fine, but doctest isn't trying to do an exact emulation of any specific
283Python shell. All hard tab characters are expanded to spaces, using
2848-column tab stops. If you don't believe tabs should mean that, too
285bad: don't use hard tabs, or write your own \class{DocTestParser}
286class.
Tim Peters76882292001-02-17 05:58:44 +0000287
Edward Loperb3666a32004-09-21 03:00:51 +0000288\versionchanged[Expanding tabs to spaces is new; previous versions
289 tried to preserve hard tabs, with confusing results]{2.4}
290
291\begin{verbatim}
292>>> # comments are ignored
293>>> x = 12
294>>> x
29512
296>>> if x == 13:
297... print "yes"
298... else:
299... print "no"
300... print "NO"
301... print "NO!!!"
302...
303no
304NO
305NO!!!
306>>>
307\end{verbatim}
308
309Any expected output must immediately follow the final
310\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
311the expected output (if any) extends to the next \code{'>\code{>}>~'}
312or all-whitespace line.
313
314The fine print:
315
316\begin{itemize}
317
318\item Expected output cannot contain an all-whitespace line, since such a
319 line is taken to signal the end of expected output. If expected
320 output does contain a blank line, put \code{<BLANKLINE>} in your
321 doctest example each place a blank line is expected.
322 \versionchanged[\code{<BLANKLINE>} was added; there was no way to
323 use expected output containing empty lines in
324 previous versions]{2.4}
325
326\item Output to stdout is captured, but not output to stderr (exception
327 tracebacks are captured via a different means).
328
329\item If you continue a line via backslashing in an interactive session,
330 or for any other reason use a backslash, you should use a raw
331 docstring, which will preserve your backslashes exactly as you type
332 them:
333
334\begin{verbatim}
335>>> def f(x):
336... r'''Backslashes in a raw docstring: m\n'''
337>>> print f.__doc__
338Backslashes in a raw docstring: m\n
339\end{verbatim}
340
341 Otherwise, the backslash will be interpreted as part of the string.
342 E.g., the "{\textbackslash}" above would be interpreted as a newline
343 character. Alternatively, you can double each backslash in the
344 doctest version (and not use a raw string):
345
346\begin{verbatim}
347>>> def f(x):
348... '''Backslashes in a raw docstring: m\\n'''
349>>> print f.__doc__
350Backslashes in a raw docstring: m\n
351\end{verbatim}
352
353\item The starting column doesn't matter:
354
355\begin{verbatim}
356 >>> assert "Easy!"
357 >>> import math
358 >>> math.floor(1.9)
359 1.0
360\end{verbatim}
361
362and as many leading whitespace characters are stripped from the
363expected output as appeared in the initial \code{'>\code{>}>~'} line
364that started the example.
365\end{itemize}
366
367\subsubsection{What's the Execution Context?\label{doctest-execution-context}}
368
369By default, each time \module{doctest} finds a docstring to test, it
Tim Peters41a65ea2004-08-13 03:55:05 +0000370uses a \emph{shallow copy} of \module{M}'s globals, so that running tests
Tim Peters76882292001-02-17 05:58:44 +0000371doesn't change the module's real globals, and so that one test in
372\module{M} can't leave behind crumbs that accidentally allow another test
373to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000374in \module{M}, and names defined earlier in the docstring being run.
Tim Peters41a65ea2004-08-13 03:55:05 +0000375Examples cannot see names defined in other docstrings.
Tim Peters76882292001-02-17 05:58:44 +0000376
377You can force use of your own dict as the execution context by passing
Edward Loperb3666a32004-09-21 03:00:51 +0000378\code{globs=your_dict} to \function{testmod()} or
379\function{testfile()} instead.
Tim Peters76882292001-02-17 05:58:44 +0000380
Edward Loperb3666a32004-09-21 03:00:51 +0000381\subsubsection{What About Exceptions?\label{doctest-exceptions}}
Tim Peters76882292001-02-17 05:58:44 +0000382
Tim Petersa07bcd42004-08-26 04:47:31 +0000383No problem, provided that the traceback is the only output produced by
384the example: just paste in the traceback. Since tracebacks contain
385details that are likely to change rapidly (for example, exact file paths
386and line numbers), this is one case where doctest works hard to be
387flexible in what it accepts.
388
389Simple example:
Tim Peters76882292001-02-17 05:58:44 +0000390
391\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000392>>> [1, 2, 3].remove(42)
393Traceback (most recent call last):
394 File "<stdin>", line 1, in ?
395ValueError: list.remove(x): x not in list
Tim Peters76882292001-02-17 05:58:44 +0000396\end{verbatim}
397
Edward Loper19b19582004-08-25 23:07:03 +0000398That doctest succeeds if \exception{ValueError} is raised, with the
Tim Petersa07bcd42004-08-26 04:47:31 +0000399\samp{list.remove(x): x not in list} detail as shown.
Tim Peters41a65ea2004-08-13 03:55:05 +0000400
Edward Loper19b19582004-08-25 23:07:03 +0000401The expected output for an exception must start with a traceback
402header, which may be either of the following two lines, indented the
403same as the first line of the example:
Tim Peters41a65ea2004-08-13 03:55:05 +0000404
405\begin{verbatim}
406Traceback (most recent call last):
407Traceback (innermost last):
408\end{verbatim}
409
Edward Loper19b19582004-08-25 23:07:03 +0000410The traceback header is followed by an optional traceback stack, whose
Tim Petersa07bcd42004-08-26 04:47:31 +0000411contents are ignored by doctest. The traceback stack is typically
412omitted, or copied verbatim from an interactive session.
Edward Loper19b19582004-08-25 23:07:03 +0000413
Tim Petersa07bcd42004-08-26 04:47:31 +0000414The traceback stack is followed by the most interesting part: the
Edward Loper19b19582004-08-25 23:07:03 +0000415line(s) containing the exception type and detail. This is usually the
416last line of a traceback, but can extend across multiple lines if the
Tim Petersa07bcd42004-08-26 04:47:31 +0000417exception has a multi-line detail:
Tim Peters41a65ea2004-08-13 03:55:05 +0000418
419\begin{verbatim}
Edward Loper19b19582004-08-25 23:07:03 +0000420>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000421Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000422 File "<stdin>", line 1, in ?
423ValueError: multi
424 line
425detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000426\end{verbatim}
427
Edward Loper6cc13502004-09-19 01:16:44 +0000428The last three lines (starting with \exception{ValueError}) are
Edward Loper19b19582004-08-25 23:07:03 +0000429compared against the exception's type and detail, and the rest are
430ignored.
Tim Peters41a65ea2004-08-13 03:55:05 +0000431
Edward Loper19b19582004-08-25 23:07:03 +0000432Best practice is to omit the traceback stack, unless it adds
Tim Petersa07bcd42004-08-26 04:47:31 +0000433significant documentation value to the example. So the last example
Tim Peters41a65ea2004-08-13 03:55:05 +0000434is probably better as:
435
436\begin{verbatim}
Edward Loper19b19582004-08-25 23:07:03 +0000437>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000438Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000439 ...
440ValueError: multi
441 line
442detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000443\end{verbatim}
444
Tim Petersa07bcd42004-08-26 04:47:31 +0000445Note that tracebacks are treated very specially. In particular, in the
Tim Peters41a65ea2004-08-13 03:55:05 +0000446rewritten example, the use of \samp{...} is independent of doctest's
Tim Petersa07bcd42004-08-26 04:47:31 +0000447\constant{ELLIPSIS} option. The ellipsis in that example could be left
448out, or could just as well be three (or three hundred) commas or digits,
449or an indented transcript of a Monty Python skit.
450
451Some details you should read once, but won't need to remember:
452
453\begin{itemize}
454
455\item Doctest can't guess whether your expected output came from an
456 exception traceback or from ordinary printing. So, e.g., an example
457 that expects \samp{ValueError: 42 is prime} will pass whether
458 \exception{ValueError} is actually raised or if the example merely
459 prints that traceback text. In practice, ordinary output rarely begins
460 with a traceback header line, so this doesn't create real problems.
461
462\item Each line of the traceback stack (if present) must be indented
463 further than the first line of the example, \emph{or} start with a
464 non-alphanumeric character. The first line following the traceback
465 header indented the same and starting with an alphanumeric is taken
466 to be the start of the exception detail. Of course this does the
467 right thing for genuine tracebacks.
468
Tim Peters1fbf9c52004-09-04 17:21:02 +0000469\item When the \constant{IGNORE_EXCEPTION_DETAIL} doctest option is
470 is specified, everything following the leftmost colon is ignored.
471
Tim Petersa07bcd42004-08-26 04:47:31 +0000472\end{itemize}
Tim Peters41a65ea2004-08-13 03:55:05 +0000473
Tim Peters0e448072004-08-26 01:02:08 +0000474\versionchanged[The ability to handle a multi-line exception detail
475 was added]{2.4}
476
Edward Loperb3666a32004-09-21 03:00:51 +0000477\subsubsection{Option Flags and Directives\label{doctest-options}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000478
Tim Peterscf533552004-08-26 04:50:38 +0000479A number of option flags control various aspects of doctest's
Tim Peters026f8dc2004-08-19 16:38:58 +0000480behavior. Symbolic names for the flags are supplied as module constants,
Tim Peters83e259a2004-08-13 21:55:21 +0000481which can be or'ed together and passed to various functions. The names
Tim Peters026f8dc2004-08-19 16:38:58 +0000482can also be used in doctest directives (see below).
Tim Peters8a3b69c2004-08-12 22:31:25 +0000483
Tim Petersa07bcd42004-08-26 04:47:31 +0000484The first group of options define test semantics, controlling
485aspects of how doctest decides whether actual output matches an
486example's expected output:
487
Tim Peters8a3b69c2004-08-12 22:31:25 +0000488\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
489 By default, if an expected output block contains just \code{1},
490 an actual output block containing just \code{1} or just
491 \code{True} is considered to be a match, and similarly for \code{0}
492 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
493 specified, neither substitution is allowed. The default behavior
494 caters to that Python changed the return type of many functions
495 from integer to boolean; doctests expecting "little integer"
496 output still work in these cases. This option will probably go
497 away, but not for several years.
498\end{datadesc}
499
500\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
501 By default, if an expected output block contains a line
502 containing only the string \code{<BLANKLINE>}, then that line
503 will match a blank line in the actual output. Because a
504 genuinely blank line delimits the expected output, this is
505 the only way to communicate that a blank line is expected. When
506 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
507 is not allowed.
508\end{datadesc}
509
510\begin{datadesc}{NORMALIZE_WHITESPACE}
511 When specified, all sequences of whitespace (blanks and newlines) are
512 treated as equal. Any sequence of whitespace within the expected
513 output will match any sequence of whitespace within the actual output.
514 By default, whitespace must match exactly.
515 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
516 of expected output is very long, and you want to wrap it across
517 multiple lines in your source.
518\end{datadesc}
519
520\begin{datadesc}{ELLIPSIS}
521 When specified, an ellipsis marker (\code{...}) in the expected output
522 can match any substring in the actual output. This includes
Tim Peters026f8dc2004-08-19 16:38:58 +0000523 substrings that span line boundaries, and empty substrings, so it's
524 best to keep usage of this simple. Complicated uses can lead to the
525 same kinds of "oops, it matched too much!" surprises that \regexp{.*}
526 is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000527\end{datadesc}
528
Tim Peters1fbf9c52004-09-04 17:21:02 +0000529\begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
530 When specified, an example that expects an exception passes if
531 an exception of the expected type is raised, even if the exception
532 detail does not match. For example, an example expecting
533 \samp{ValueError: 42} will pass if the actual exception raised is
534 \samp{ValueError: 3*14}, but will fail, e.g., if
535 \exception{TypeError} is raised.
536
537 Note that a similar effect can be obtained using \constant{ELLIPSIS},
538 and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
539 prior to 2.4 become uninteresting. Until then,
540 \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
541 doctest that doesn't care about the exception detail yet continues
542 to pass under Python releases prior to 2.4 (doctest directives
543 appear to be comments to them). For example,
544
545\begin{verbatim}
546>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
547Traceback (most recent call last):
548 File "<stdin>", line 1, in ?
549TypeError: object doesn't support item assignment
550\end{verbatim}
551
552 passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
553 to say "does not" instead of "doesn't".
554
555\end{datadesc}
556
Tim Peters38330fe2004-08-30 16:19:24 +0000557\begin{datadesc}{COMPARISON_FLAGS}
558 A bitmask or'ing together all the comparison flags above.
559\end{datadesc}
560
Tim Petersf33683f2004-08-26 04:52:46 +0000561The second group of options controls how test failures are reported:
Tim Petersa07bcd42004-08-26 04:47:31 +0000562
Edward Loper71f55af2004-08-26 01:41:51 +0000563\begin{datadesc}{REPORT_UDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000564 When specified, failures that involve multi-line expected and
565 actual outputs are displayed using a unified diff.
566\end{datadesc}
567
Edward Loper71f55af2004-08-26 01:41:51 +0000568\begin{datadesc}{REPORT_CDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000569 When specified, failures that involve multi-line expected and
570 actual outputs will be displayed using a context diff.
571\end{datadesc}
572
Edward Loper71f55af2004-08-26 01:41:51 +0000573\begin{datadesc}{REPORT_NDIFF}
Tim Petersc6cbab02004-08-22 19:43:28 +0000574 When specified, differences are computed by \code{difflib.Differ},
575 using the same algorithm as the popular \file{ndiff.py} utility.
576 This is the only method that marks differences within lines as
577 well as across lines. For example, if a line of expected output
578 contains digit \code{1} where actual output contains letter \code{l},
579 a line is inserted with a caret marking the mismatching column
580 positions.
581\end{datadesc}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000582
Edward Lopera89f88d2004-08-26 02:45:51 +0000583\begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
584 When specified, display the first failing example in each doctest,
585 but suppress output for all remaining examples. This will prevent
586 doctest from reporting correct examples that break because of
587 earlier failures; but it might also hide incorrect examples that
588 fail independently of the first failure. When
589 \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
590 examples are still run, and still count towards the total number of
591 failures reported; only the output is suppressed.
592\end{datadesc}
593
Tim Peters38330fe2004-08-30 16:19:24 +0000594\begin{datadesc}{REPORTING_FLAGS}
595 A bitmask or'ing together all the reporting flags above.
596\end{datadesc}
597
Edward Loperb3666a32004-09-21 03:00:51 +0000598"Doctest directives" may be used to modify the option flags for
599individual examples. Doctest directives are expressed as a special
600Python comment following an example's source code:
Tim Peters026f8dc2004-08-19 16:38:58 +0000601
602\begin{productionlist}[doctest]
603 \production{directive}
Edward Loper6cc13502004-09-19 01:16:44 +0000604 {"\#" "doctest:" \token{directive_options}}
605 \production{directive_options}
606 {\token{directive_option} ("," \token{directive_option})*}
607 \production{directive_option}
608 {\token{on_or_off} \token{directive_option_name}}
Tim Peters026f8dc2004-08-19 16:38:58 +0000609 \production{on_or_off}
610 {"+" | "-"}
Edward Loper6cc13502004-09-19 01:16:44 +0000611 \production{directive_option_name}
Tim Peters026f8dc2004-08-19 16:38:58 +0000612 {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
613\end{productionlist}
614
615Whitespace is not allowed between the \code{+} or \code{-} and the
Edward Loper6cc13502004-09-19 01:16:44 +0000616directive option name. The directive option name can be any of the
Edward Loperb3666a32004-09-21 03:00:51 +0000617option flag names explained above.
Tim Peters026f8dc2004-08-19 16:38:58 +0000618
Edward Loperb3666a32004-09-21 03:00:51 +0000619An example's doctest directives modify doctest's behavior for that
620single example. Use \code{+} to enable the named behavior, or
621\code{-} to disable it.
Tim Peters026f8dc2004-08-19 16:38:58 +0000622
623For example, this test passes:
624
625\begin{verbatim}
626>>> print range(20) #doctest: +NORMALIZE_WHITESPACE
627[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
62810, 11, 12, 13, 14, 15, 16, 17, 18, 19]
629\end{verbatim}
630
631Without the directive it would fail, both because the actual output
632doesn't have two blanks before the single-digit list elements, and
633because the actual output is on a single line. This test also passes,
Tim Petersa07bcd42004-08-26 04:47:31 +0000634and also requires a directive to do so:
Tim Peters026f8dc2004-08-19 16:38:58 +0000635
636\begin{verbatim}
637>>> print range(20) # doctest:+ELLIPSIS
638[0, 1, ..., 18, 19]
639\end{verbatim}
640
Edward Loper6cc13502004-09-19 01:16:44 +0000641Multiple directives can be used on a single physical line, separated
642by commas:
Tim Peters026f8dc2004-08-19 16:38:58 +0000643
644\begin{verbatim}
Edward Loper6cc13502004-09-19 01:16:44 +0000645>>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Tim Peters026f8dc2004-08-19 16:38:58 +0000646[0, 1, ..., 18, 19]
647\end{verbatim}
648
Edward Loperb3666a32004-09-21 03:00:51 +0000649If multiple directive comments are used for a single example, then
650they are combined:
Edward Loper6cc13502004-09-19 01:16:44 +0000651
652\begin{verbatim}
653>>> print range(20) # doctest: +ELLIPSIS
654... # doctest: +NORMALIZE_WHITESPACE
655[0, 1, ..., 18, 19]
656\end{verbatim}
657
658As the previous example shows, you can add \samp{...} lines to your
Edward Loperb3666a32004-09-21 03:00:51 +0000659example containing only directives. This can be useful when an
Edward Loper6cc13502004-09-19 01:16:44 +0000660example is too long for a directive to comfortably fit on the same
661line:
662
663\begin{verbatim}
664>>> print range(5) + range(10,20) + range(30,40) + range(50,60)
665... # doctest: +ELLIPSIS
666[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
667\end{verbatim}
668
Tim Peters026f8dc2004-08-19 16:38:58 +0000669Note that since all options are disabled by default, and directives apply
670only to the example they appear in, enabling options (via \code{+} in a
671directive) is usually the only meaningful choice. However, option flags
672can also be passed to functions that run doctests, establishing different
673defaults. In such cases, disabling an option via \code{-} in a directive
674can be useful.
675
Tim Peters8a3b69c2004-08-12 22:31:25 +0000676\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
677 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
Tim Peters1fbf9c52004-09-04 17:21:02 +0000678 \constant{IGNORE_EXCEPTION_DETAIL},
Edward Lopera89f88d2004-08-26 02:45:51 +0000679 \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
Tim Peters38330fe2004-08-30 16:19:24 +0000680 \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
681 \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
Tim Peters026f8dc2004-08-19 16:38:58 +0000682 were added; by default \code{<BLANKLINE>} in expected output
683 matches an empty line in actual output; and doctest directives
684 were added]{2.4}
685
Edward Loperb3666a32004-09-21 03:00:51 +0000686\subsubsection{Warnings\label{doctest-warnings}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000687
Edward Loperb3666a32004-09-21 03:00:51 +0000688\begin{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000689
Edward Loperb3666a32004-09-21 03:00:51 +0000690\item \module{doctest} is serious about requiring exact matches in expected
691 output. If even a single character doesn't match, the test fails. This
692 will probably surprise you a few times, as you learn exactly what Python
693 does and doesn't guarantee about output. For example, when printing a
694 dict, Python doesn't guarantee that the key-value pairs will be printed
695 in any particular order, so a test like
Tim Peters76882292001-02-17 05:58:44 +0000696
Edward Loperb3666a32004-09-21 03:00:51 +0000697% Hey! What happened to Monty Python examples?
698% Tim: ask Guido -- it's his example!
699\begin{verbatim}
700>>> foo()
701{"Hermione": "hippogryph", "Harry": "broomstick"}
702\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000703
Edward Loperb3666a32004-09-21 03:00:51 +0000704is vulnerable! One workaround is to do
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000705
Edward Loperb3666a32004-09-21 03:00:51 +0000706\begin{verbatim}
707>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
708True
709\end{verbatim}
710
711instead. Another is to do
712
713\begin{verbatim}
714>>> d = foo().items()
715>>> d.sort()
716>>> d
717[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
718\end{verbatim}
719
720There are others, but you get the idea.
721
722Another bad idea is to print things that embed an object address, like
723
724\begin{verbatim}
725>>> id(1.0) # certain to fail some of the time
7267948648
727\end{verbatim}
728
729Floating-point numbers are also subject to small output variations across
730platforms, because Python defers to the platform C library for float
731formatting, and C libraries vary widely in quality here.
732
733\begin{verbatim}
734>>> 1./7 # risky
7350.14285714285714285
736>>> print 1./7 # safer
7370.142857142857
738>>> print round(1./7, 6) # much safer
7390.142857
740\end{verbatim}
741
742Numbers of the form \code{I/2.**J} are safe across all platforms, and I
743often contrive doctest examples to produce numbers of that form:
744
745\begin{verbatim}
746>>> 3./4 # utterly safe
7470.75
748\end{verbatim}
749
750Simple fractions are also easier for people to understand, and that makes
751for better documentation.
752
753\item Be careful if you have code that must only execute once.
754
755If you have module-level code that must only execute once, a more foolproof
756definition of \function{_test()} is
757
758% [XX] How is this safer?? The only difference I see is that this
759% imports (but doesn't use) sys. -edloper
760\begin{verbatim}
761def _test():
762 import doctest, sys
763 doctest.testmod()
764\end{verbatim}
765
766\item WYSIWYG isn't always the case, starting in Python 2.3. The
767 string form of boolean results changed from \code{'0'} and
768 \code{'1'} to \code{'False'} and \code{'True'} in Python 2.3.
769 This makes it clumsy to write a doctest showing boolean results that
770 passes under multiple versions of Python. In Python 2.3, by default,
771 and as a special case, if an expected output block consists solely
772 of \code{'0'} and the actual output block consists solely of
773 \code{'False'}, that's accepted as an exact match, and similarly for
774 \code{'1'} versus \code{'True'}. This behavior can be turned off by
775 passing the new (in 2.3) module constant
776 \constant{DONT_ACCEPT_TRUE_FOR_1} as the value of \function{testmod()}'s
777 new (in 2.3) optional \var{optionflags} argument. Some years after
778 the integer spellings of booleans are history, this hack will
779 probably be removed again.
780
781\end{itemize}
782
783\subsection{Basic API\label{doctest-basic-api}}
784
785The functions \function{testmod()} and \function{testfile()} provide a
786simple interface to doctest that should be sufficient for most basic
787uses. For a more informal introduction to these two functions, see
788sections \ref{doctest-simple-testmod} and
789\ref{doctest-simple-testfile}.
790
791\begin{funcdesc}{testfile}{filename\optional{, module_relative}\optional{,
792 name}\optional{, package}\optional{,
793 globs}\optional{, verbose}\optional{,
794 report}\optional{, optionflags}\optional{,
795 extraglobs}\optional{, raise_on_error}}
796
797 All arguments except \var{filename} are optional, and should be
798 specified in keyword form.
799
800 Test examples in the file named \var{filename}. Return
801 \samp{(\var{failure_count}, \var{test_count})}.
802
803 Optional argument \var{module_relative} specifies how the filename
804 should be interpreted:
805
806 \begin{itemize}
807 \item If \var{module_relative} is \code{True} (the default), then
808 \var{filename} specifies an os-independent module-relative
809 path. By default, this path is relative to the calling
810 module's directory; but if the \var{package} argument is
811 specified, then it is relative to that package. To ensure
812 os-independence, \var{filename} should use \code{/} characters
813 to separate path segments, and may not be an absolute path
814 (i.e., it may not begin with \code{/}).
815 \item If \var{module_relative} is \code{False}, then \var{filename}
816 specifies an os-specific path. The path may be absolute or
817 relative; relative paths are resolved with respect to the
818 current working directory.
819 \end{itemize}
820
821 Optional argument \var{name} gives the name of the test; by default,
822 or if \code{None}, \code{os.path.basename(\var{filename})} is used.
823
824 Optional argument \var{package} is a Python package or the name of a
825 Python package whose directory should be used as the base directory
826 for a module-relative filename. If no package is specified, then
827 the calling module's directory is used as the base directory for
828 module-relative filenames. It is an error to specify \var{package}
829 if \var{module_relative} is \code{False}.
830
831 Optional argument \var{globs} gives a dict to be used as the globals
832 when executing examples; by default, or if \code{None},
833 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
834 created for the doctest, so its examples start with a clean slate.
835
836 Optional argument \var{extraglobs} gives a dict merged into the
837 globals used to execute examples. This works like
838 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
839 common key, the associated value in \var{extraglobs} appears in the
840 combined dict. By default, or if \code{None}, no extra globals are
841 used. This is an advanced feature that allows parameterization of
842 doctests. For example, a doctest can be written for a base class, using
843 a generic name for the class, then reused to test any number of
844 subclasses by passing an \var{extraglobs} dict mapping the generic
845 name to the subclass to be tested.
846
847 Optional argument \var{verbose} prints lots of stuff if true, and prints
848 only failures if false; by default, or if \code{None}, it's true
849 if and only if \code{'-v'} is in \code{sys.argv}.
850
851 Optional argument \var{report} prints a summary at the end when true,
852 else prints nothing at the end. In verbose mode, the summary is
853 detailed, else the summary is very brief (in fact, empty if all tests
854 passed).
855
856 Optional argument \var{optionflags} or's together option flags. See
857 see section~\ref{doctest-options}.
858
859 Optional argument \var{raise_on_error} defaults to false. If true,
860 an exception is raised upon the first failure or unexpected exception
861 in an example. This allows failures to be post-mortem debugged.
862 Default behavior is to continue running examples.
863
864 \versionadded{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000865\end{funcdesc}
866
Tim Peters83e259a2004-08-13 21:55:21 +0000867\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
868 globs}\optional{, verbose}\optional{,
869 isprivate}\optional{, report}\optional{,
870 optionflags}\optional{, extraglobs}\optional{,
Tim Peters82788602004-09-13 15:03:17 +0000871 raise_on_error}\optional{, exclude_empty}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000872
Tim Peters83e259a2004-08-13 21:55:21 +0000873 All arguments are optional, and all except for \var{m} should be
874 specified in keyword form.
875
876 Test examples in docstrings in functions and classes reachable
877 from module \var{m} (or the current module if \var{m} is not supplied
878 or is \code{None}), starting with \code{\var{m}.__doc__}.
879
880 Also test examples reachable from dict \code{\var{m}.__test__}, if it
881 exists and is not \code{None}. \code{\var{m}.__test__} maps
882 names (strings) to functions, classes and strings; function and class
883 docstrings are searched for examples; strings are searched directly,
884 as if they were docstrings.
885
886 Only docstrings attached to objects belonging to module \var{m} are
887 searched.
888
889 Return \samp{(\var{failure_count}, \var{test_count})}.
890
891 Optional argument \var{name} gives the name of the module; by default,
892 or if \code{None}, \code{\var{m}.__name__} is used.
893
894 Optional argument \var{globs} gives a dict to be used as the globals
895 when executing examples; by default, or if \code{None},
896 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
897 created for each docstring with examples, so that each docstring's
898 examples start with a clean slate.
899
900 Optional argument \var{extraglobs} gives a dict merged into the
901 globals used to execute examples. This works like
902 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
903 common key, the associated value in \var{extraglobs} appears in the
904 combined dict. By default, or if \code{None}, no extra globals are
905 used. This is an advanced feature that allows parameterization of
906 doctests. For example, a doctest can be written for a base class, using
907 a generic name for the class, then reused to test any number of
908 subclasses by passing an \var{extraglobs} dict mapping the generic
909 name to the subclass to be tested.
910
911 Optional argument \var{verbose} prints lots of stuff if true, and prints
912 only failures if false; by default, or if \code{None}, it's true
913 if and only if \code{'-v'} is in \code{sys.argv}.
914
915 Optional argument \var{report} prints a summary at the end when true,
916 else prints nothing at the end. In verbose mode, the summary is
917 detailed, else the summary is very brief (in fact, empty if all tests
918 passed).
919
920 Optional argument \var{optionflags} or's together option flags. See
Edward Loperb3666a32004-09-21 03:00:51 +0000921 see section~\ref{doctest-options}.
Tim Peters83e259a2004-08-13 21:55:21 +0000922
923 Optional argument \var{raise_on_error} defaults to false. If true,
924 an exception is raised upon the first failure or unexpected exception
925 in an example. This allows failures to be post-mortem debugged.
926 Default behavior is to continue running examples.
927
Tim Peters82788602004-09-13 15:03:17 +0000928 Optional argument \var{exclude_empty} defaults to false. If true,
929 objects for which no doctests are found are excluded from consideration.
930 The default is a backward compatibility hack, so that code still
931 using \method{doctest.master.summarize()} in conjunction with
932 \function{testmod()} continues to get output for objects with no tests.
933 The \var{exclude_empty} argument to the newer \class{DocTestFinder}
934 constructor defaults to true.
935
Tim Peters83e259a2004-08-13 21:55:21 +0000936 Optional argument \var{isprivate} specifies a function used to
937 determine whether a name is private. The default function treats
938 all names as public. \var{isprivate} can be set to
939 \code{doctest.is_private} to skip over names that are
940 private according to Python's underscore naming convention.
941 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
942 If you need to skip tests based on name, filter the list returned by
943 \code{DocTestFinder.find()} instead.}
944
945 \versionchanged[The parameter \var{optionflags} was added]{2.3}
946
Tim Peters82788602004-09-13 15:03:17 +0000947 \versionchanged[The parameters \var{extraglobs}, \var{raise_on_error}
948 and \var{exclude_empty} were added]{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000949\end{funcdesc}
950
Edward Loperb3666a32004-09-21 03:00:51 +0000951\subsection{Unittest API\label{doctest-unittest-api}}
952
953Doctest provides several functions that can be used to create
954\module{unittest} test suites from doctest examples. These test
955suites can then be run using \module{unittest} test runners:
956
957\begin{verbatim}
958 import unittest
959 import doctest
960 import my_module_with_doctests
961
962 suite = doctest.DocTestSuite(my_module_with_doctests)
963 runner = unittest.TextTestRunner()
964 runner.run(suite)
965\end{verbatim}
966
967\begin{funcdesc}{DocFileSuite}{*paths, **kw}
968 Convert doctest tests from one or more text files to a
969 \class{\refmodule{unittest}.TestSuite}.
970
971 The returned \class{TestSuite} is to be run by the unittest
972 framework and runs the interactive examples in each file. If an
973 example in any file fails, then the synthesized unit test fails, and
974 a \exception{failureException} exception is raised showing the
975 name of the file containing the test and a (sometimes approximate)
976 line number.
977
978 A number of options may be provided as keyword arguments:
979
980 The optional argument \var{module_relative} specifies how
981 the the filenames in \var{paths} should be interpreted:
982
983 \begin{itemize}
984 \item If \var{module_relative} is \code{True} (the default), then
985 each filename specifies an os-independent module-relative
986 path. By default, this path is relative to the calling
987 module's directory; but if the \var{package} argument is
988 specified, then it is relative to that package. To ensure
989 os-independence, each filename should use \code{/} characters
990 to separate path segments, and may not be an absolute path
991 (i.e., it may not begin with \code{/}).
992 \item If \var{module_relative} is \code{False}, then each filename
993 specifies an os-specific path. The path may be absolute or
994 relative; relative paths are resolved with respect to the
995 current working directory.
996 \end{itemize}
997
998 The optional argument \var{package} is a Python package or the name
999 of a Python package whose directory should be used as the base
1000 directory for module-relative filenames. If no package is
1001 specified, then the calling module's directory is used as the base
1002 directory for module-relative filenames. It is an error to specify
1003 \var{package} if \var{module_relative} is \code{False}.
1004
1005 The optional argument \var{setUp} specifies a set-up function for
1006 the test suite. This is called before running the tests in each
1007 file. The \var{setUp} function will be passed a \class{DocTest}
1008 object. The setUp function can access the test globals as the
1009 \var{globs} attribute of the test passed.
1010
1011 The optional argument \var{tearDown} specifies a tear-down function
1012 for the test suite. This is called after running the tests in each
1013 file. The \var{tearDown} function will be passed a \class{DocTest}
1014 object. The setUp function can access the test globals as the
1015 \var{globs} attribute of the test passed.
1016
1017 The optional argument \var{globs} is a dictionary containing the
1018 initial global variables for the tests. A new copy of this
1019 dictionary is created for each test. By default, \var{globs} is
1020 empty.
1021
1022 The optional argument \var{optionflags} specifies the default
1023 doctest options for the tests. It is created by or-ing together
1024 individual option flags.
1025
1026 \versionadded{2.4}
1027\end{funcdesc}
1028
1029\begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
1030 globs}\optional{, extraglobs}\optional{,
1031 test_finder}\optional{, setUp}\optional{,
1032 tearDown}\optional{, checker}}
1033 Convert doctest tests for a module to a
1034 \class{\refmodule{unittest}.TestSuite}.
1035
1036 The returned \class{TestSuite} is to be run by the unittest framework
1037 and runs each doctest in the module. If any of the doctests fail,
1038 then the synthesized unit test fails, and a \exception{failureException}
1039 exception is raised showing the name of the file containing the test and a
1040 (sometimes approximate) line number.
1041
1042 The optional argument \var{module} provides the module to be tested. It
1043 can be a module object or a (possibly dotted) module name. If not
1044 specified, the module calling this function is used.
1045
1046 The optional argument \var{globs} is a dictionary containing the
1047 initial global variables for the tests. A new copy of this
1048 dictionary is created for each test. By default, \var{globs} is
1049 empty.
1050
1051 The optional argument \var{extraglobs} specifies an extra set of
1052 global variables, which is merged into \var{globs}. By default, no
1053 extra globals are used.
1054
1055 The optional argument \var{test_finder} is the \class{DocTestFinder}
1056 object (or a drop-in replacement) that is used to extract doctests
1057 from the module.
1058
1059 The optional argument \var{setUp} specifies a set-up function for
1060 the test suite. This is called before running the tests in each
1061 file. The \var{setUp} function will be passed a \class{DocTest}
1062 object. The setUp function can access the test globals as the
1063 \var{globs} attribute of the test passed.
1064
1065 The optional argument \var{tearDown} specifies a tear-down function
1066 for the test suite. This is called after running the tests in each
1067 file. The \var{tearDown} function will be passed a \class{DocTest}
1068 object. The setUp function can access the test globals as the
1069 \var{globs} attribute of the test passed.
1070
1071 The optional argument \var{optionflags} specifies the default
1072 doctest options for the tests. It is created by or-ing together
1073 individual option flags.
1074
1075 \versionadded{2.3}
1076 \versionchanged[The parameters \var{globs}, \var{extraglobs},
1077 \var{test_finder}, \var{setUp}, \var{tearDown}, and
1078 \var{optionflags} were added]{2.4}
1079 \versionchanged[This function now uses the same search technique as
1080 \function{testmod()}.]{2.4}
1081\end{funcdesc}
1082
1083\subsection{Advanced API\label{doctest-advanced-api}}
1084
1085The basic API is a simple wrapper that's intended to make doctest easy
1086to use. It is fairly flexible, and should meet most user's needs;
1087however, if you require more fine grained control over testing, or
1088wish to extend doctest's capabilities, then you should use the
1089advanced API.
1090
1091The advanced API revolves around two container classes, which are used
1092to store the interactive examples extracted from doctest cases:
1093
1094\begin{itemize}
1095\item \class{Example}: A single python statement, paired with its
1096 expected output.
1097\item \class{DocTest}: A collection of \class{Example}s, typically
1098 extracted from a single docstring or text file.
1099\end{itemize}
1100
1101Additional processing classes are defined to find, parse, and run, and
1102check doctest examples:
1103
1104\begin{itemize}
1105\item \class{DocTestFinder}: Finds all docstrings in a given module,
1106 and uses a \class{DocTestParser} to create a \class{DocTest}
1107 from every docstring that contains interactive examples.
1108\item \class{DocTestParser}: Creates a \class{DocTest} object from
1109 a string (such as an object's docstring).
1110\item \class{DocTestRunner}: Executes the examples in a
1111 \class{DocTest}, and uses an \class{OutputChecker} to verify
1112 their output.
1113\item \class{OutputChecker}: Compares the actual output from a
1114 doctest example with the expected output, and decides whether
1115 they match.
1116\end{itemize}
1117
1118The relationship between these processing classes is summarized in the
1119following diagram:
1120
1121\begin{verbatim}
1122 list of:
1123+------+ +---------+
1124|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1125+------+ | ^ +---------+ | ^ (printed)
1126 | | | Example | | |
1127 V | | ... | V |
1128 DocTestParser | Example | OutputChecker
1129 +---------+
1130\end{verbatim}
1131
1132\subsubsection{DocTest Objects\label{doctest-DocTest}}
1133\begin{classdesc}{DocTest}{examples, globs, name, filename, lineno,
1134 docstring}
1135 A collection of doctest examples that should be run in a single
1136 namespace. The constructor arguments are used to initialize the
1137 member variables of the same names.
1138 \versionadded{2.4}
1139\end{classdesc}
1140
1141\class{DocTest} defines the following member variables. They are
1142initialized by the constructor, and should not be modified directly.
1143
1144\begin{memberdesc}{examples}
1145 A list of \class{Example} objects encoding the individual
1146 interactive Python examples that should be run by this test.
1147\end{memberdesc}
1148
1149\begin{memberdesc}{globs}
1150 The namespace (aka globals) that the examples should be run in.
1151 This is a dictionary mapping names to values. Any changes to the
1152 namespace made by the examples (such as binding new variables)
1153 will be reflected in \member{globs} after the test is run.
1154\end{memberdesc}
1155
1156\begin{memberdesc}{name}
1157 A string name identifying the \class{DocTest}. Typically, this is
1158 the name of the object or file that the test was extracted from.
1159\end{memberdesc}
1160
1161\begin{memberdesc}{filename}
1162 The name of the file that this \class{DocTest} was extracted from;
1163 or \code{None} if the filename is unknown, or if the
1164 \class{DocTest} was not extracted from a file.
1165\end{memberdesc}
1166
1167\begin{memberdesc}{lineno}
1168 The line number within \member{filename} where this
1169 \class{DocTest} begins, or \code{None} if the line number is
1170 unavailable. This line number is zero-based with respect to the
1171 beginning of the file.
1172\end{memberdesc}
1173
1174\begin{memberdesc}{docstring}
1175 The string that the test was extracted from, or `None` if the
1176 string is unavailable, or if the test was not extracted from a
1177 string.
1178\end{memberdesc}
1179
1180\subsubsection{Example Objects\label{doctest-Example}}
1181\begin{classdesc}{Example}{source, want\optional{,
1182 exc_msg}\optional{, lineno}\optional{,
1183 indent}\optional{, options}}
1184 A single interactive example, consisting of a Python statement and
1185 its expected output. The constructor arguments are used to
1186 initialize the member variables of the same names.
1187 \versionadded{2.4}
1188\end{classdesc}
1189
1190\class{Example} defines the following member variables. They are
1191initialized by the constructor, and should not be modified directly.
1192
1193\begin{memberdesc}{source}
1194 A string containing the example's source code. This source code
1195 consists of a single Python statement, and always ends with a
1196 newline; the constructor adds a newline when necessary.
1197\end{memberdesc}
1198
1199\begin{memberdesc}{want}
1200 The expected output from running the example's source code (either
1201 from stdout, or a traceback in case of exception). \member{want}
1202 ends with a newline unless no output is expected, in which case
1203 it's an empty string. The constructor adds a newline when
1204 necessary.
1205\end{memberdesc}
1206
1207\begin{memberdesc}{exc_msg}
1208 The exception message generated by the example, if the example is
1209 expected to generate an exception; or \code{None} if it is not
1210 expected to generate an exception. This exception message is
1211 compared against the return value of
1212 \function{traceback.format_exception_only()}. \member{exc_msg}
1213 ends with a newline unless it's \code{None}. The constructor adds
1214 a newline if needed.
1215\end{memberdesc}
1216
1217\begin{memberdesc}{lineno}
1218 The line number within the string containing this example where
1219 the example begins. This line number is zero-based with respect
1220 to the beginning of the containing string.
1221\end{memberdesc}
1222
1223\begin{memberdesc}{indent}
1224 The example's indentation in the containing string. I.e., the
1225 number of space characters that preceed the example's first
1226 prompt.
1227\end{memberdesc}
1228
1229\begin{memberdesc}{options}
1230 A dictionary mapping from option flags to \code{True} or
1231 \code{False}, which is used to override default options for this
1232 example. Any option flags not contained in this dictionary are
1233 left at their default value (as specified by the
1234 \class{DocTestRunner}'s
1235\member{optionflags}). By default, no options are set.
1236\end{memberdesc}
1237
1238\subsubsection{DocTestFinder objects\label{doctest-DocTestFinder}}
1239\begin{classdesc}{DocTestFinder}{\optional{verbose}\optional{,
1240 parser}\optional{, recurse}\optional{,
1241 exclude_empty}}
1242 A processing class used to extract the \class{DocTest}s that are
1243 relevant to a given object, from its docstring and the docstrings
1244 of its contained objects. \class{DocTest}s can currently be
1245 extracted from the following object types: modules, functions,
1246 classes, methods, staticmethods, classmethods, and properties.
1247
1248 The optional argument \var{verbose} can be used to display the
1249 objects searched by the finder. It defaults to \code{False} (no
1250 output).
1251
1252 The optional argument \var{parser} specifies the
1253 \class{DocTestParser} object (or a drop-in replacement) that is
1254 used to extract doctests from docstrings.
1255
1256 If the optional argument \var{recurse} is false, then
1257 \method{DocTestFinder.find()} will only examine the given object,
1258 and not any contained objects.
1259
1260 If the optional argument \var{exclude_empty} is false, then
1261 \method{DocTestFinder.find()} will include tests for objects with
1262 empty docstrings.
1263
1264 \versionadded{2.4}
1265\end{classdesc}
1266
1267\class{DocTestFinder} defines the following method:
1268
Tim Peters7a082142004-09-25 00:10:53 +00001269\begin{methoddesc}{find}{obj\optional{, name}\optional{,
Edward Loperb3666a32004-09-21 03:00:51 +00001270 module}\optional{, globs}\optional{, extraglobs}}
1271 Return a list of the \class{DocTest}s that are defined by
1272 \var{obj}'s docstring, or by any of its contained objects'
1273 docstrings.
1274
1275 The optional argument \var{name} specifies the object's name; this
1276 name will be used to construct names for the returned
1277 \class{DocTest}s. If \var{name} is not specified, then
1278 \code{var.__name__} is used.
1279
1280 The optional parameter \var{module} is the module that contains
1281 the given object. If the module is not specified or is None, then
1282 the test finder will attempt to automatically determine the
1283 correct module. The object's module is used:
1284
1285 \begin{itemize}
1286 \item As a default namespace, if `globs` is not specified.
1287 \item To prevent the DocTestFinder from extracting DocTests
1288 from objects that are imported from other modules. (Contained
1289 objects with modules other than \var{module} are ignored.)
1290 \item To find the name of the file containing the object.
1291 \item To help find the line number of the object within its file.
1292 \end{itemize}
1293
1294 If \var{module} is \code{False}, no attempt to find the module
1295 will be made. This is obscure, of use mostly in testing doctest
1296 itself: if \var{module} is \code{False}, or is \code{None} but
1297 cannot be found automatically, then all objects are considered to
1298 belong to the (non-existent) module, so all contained objects will
1299 (recursively) be searched for doctests.
1300
1301 The globals for each \class{DocTest} is formed by combining
1302 \var{globs} and \var{extraglobs} (bindings in \var{extraglobs}
1303 override bindings in \var{globs}). A new copy of the globals
1304 dictionary is created for each \class{DocTest}. If \var{globs} is
1305 not specified, then it defaults to the module's \var{__dict__}, if
1306 specified, or \code{\{\}} otherwise. If \var{extraglobs} is not
1307 specified, then it defaults to \code{\{\}}.
1308\end{methoddesc}
1309
1310\subsubsection{DocTestParser objects\label{doctest-DocTestParser}}
1311\begin{classdesc}{DocTestParser}{}
1312 A processing class used to extract interactive examples from a
1313 string, and use them to create a \class{DocTest} object.
1314 \versionadded{2.4}
1315\end{classdesc}
1316
1317\class{DocTestParser} defines the following methods:
1318
1319\begin{methoddesc}{get_doctest}{string, globs, name, filename, lineno}
1320 Extract all doctest examples from the given string, and collect
1321 them into a \class{DocTest} object.
1322
1323 \var{globs}, \var{name}, \var{filename}, and \var{lineno} are
1324 attributes for the new \class{DocTest} object. See the
1325 documentation for \class{DocTest} for more information.
1326\end{methoddesc}
1327
1328\begin{methoddesc}{get_examples}{string\optional{, name}}
1329 Extract all doctest examples from the given string, and return
1330 them as a list of \class{Example} objects. Line numbers are
1331 0-based. The optional argument \var{name} is a name identifying
1332 this string, and is only used for error messages.
1333\end{methoddesc}
1334
1335\begin{methoddesc}{parse}{string\optional{, name}}
1336 Divide the given string into examples and intervening text, and
1337 return them as a list of alternating \class{Example}s and strings.
1338 Line numbers for the \class{Example}s are 0-based. The optional
1339 argument \var{name} is a name identifying this string, and is only
1340 used for error messages.
1341\end{methoddesc}
1342
1343\subsubsection{DocTestRunner objects\label{doctest-DocTestRunner}}
1344\begin{classdesc}{DocTestRunner}{\optional{checker}\optional{,
1345 verbose}\optional{, optionflags}}
1346 A processing class used to execute and verify the interactive
1347 examples in a \class{DocTest}.
1348
1349 The comparison between expected outputs and actual outputs is done
1350 by an \class{OutputChecker}. This comparison may be customized
1351 with a number of option flags; see section~\ref{doctest-options}
1352 for more information. If the option flags are insufficient, then
1353 the comparison may also be customized by passing a subclass of
1354 \class{OutputChecker} to the constructor.
1355
1356 The test runner's display output can be controlled in two ways.
1357 First, an output function can be passed to
1358 \method{TestRunner.run()}; this function will be called with
1359 strings that should be displayed. It defaults to
1360 \code{sys.stdout.write}. If capturing the output is not
1361 sufficient, then the display output can be also customized by
1362 subclassing DocTestRunner, and overriding the methods
1363 \method{report_start}, \method{report_success},
1364 \method{report_unexpected_exception}, and \method{report_failure}.
1365
1366 The optional keyword argument \var{checker} specifies the
1367 \class{OutputChecker} object (or drop-in replacement) that should
1368 be used to compare the expected outputs to the actual outputs of
1369 doctest examples.
1370
1371 The optional keyword argument \var{verbose} controls the
1372 \class{DocTestRunner}'s verbosity. If \var{verbose} is
1373 \code{True}, then information is printed about each example, as it
1374 is run. If \var{verbose} is \code{False}, then only failures are
1375 printed. If \var{verbose} is unspecified, or \code{None}, then
1376 verbose output is used iff the command-line switch \programopt{-v}
1377 is used.
1378
1379 The optional keyword argument \var{optionflags} can be used to
1380 control how the test runner compares expected output to actual
1381 output, and how it displays failures. For more information, see
1382 section~\ref{doctest-options}.
1383
1384 \versionadded{2.4}
1385\end{classdesc}
1386
1387\class{DocTestParser} defines the following methods:
1388
1389\begin{methoddesc}{report_start}{out, test, example}
1390 Report that the test runner is about to process the given example.
1391 This method is provided to allow subclasses of
1392 \class{DocTestRunner} to customize their output; it should not be
1393 called directly.
1394
1395 \var{example} is the example about to be processed. \var{test} is
1396 the test containing \var{example}. \var{out} is the output
1397 function that was passed to \method{DocTestRunner.run()}.
1398\end{methoddesc}
1399
1400\begin{methoddesc}{report_success}{out, test, example, got}
1401 Report that the given example ran successfully. This method is
1402 provided to allow subclasses of \class{DocTestRunner} to customize
1403 their output; it should not be called directly.
1404
1405 \var{example} is the example about to be processed. \var{got} is
1406 the actual output from the example. \var{test} is the test
1407 containing \var{example}. \var{out} is the output function that
1408 was passed to \method{DocTestRunner.run()}.
1409\end{methoddesc}
1410
1411\begin{methoddesc}{report_failure}{out, test, example, got}
1412 Report that the given example failed. This method is provided to
1413 allow subclasses of \class{DocTestRunner} to customize their
1414 output; it should not be called directly.
1415
1416 \var{example} is the example about to be processed. \var{got} is
1417 the actual output from the example. \var{test} is the test
1418 containing \var{example}. \var{out} is the output function that
1419 was passed to \method{DocTestRunner.run()}.
1420\end{methoddesc}
1421
1422\begin{methoddesc}{report_unexpected_exception}{out, test, example, exc_info}
1423 Report that the given example raised an unexpected exception.
1424 This method is provided to allow subclasses of
1425 \class{DocTestRunner} to customize their output; it should not be
1426 called directly.
1427
1428 \var{example} is the example about to be processed.
1429 \var{exc_info} is a tuple containing information about the
1430 unexpected exception (as returned by \function{sys.exc_info()}).
1431 \var{test} is the test containing \var{example}. \var{out} is the
1432 output function that was passed to \method{DocTestRunner.run()}.
1433\end{methoddesc}
1434
1435\begin{methoddesc}{run}{test\optional{, compileflags}\optional{,
1436 out}\optional{, clear_globs}}
1437 Run the examples in \var{test} (a \class{DocTest} object), and
1438 display the results using the writer function \var{out}.
1439
1440 The examples are run in the namespace \code{test.globs}. If
1441 \var{clear_globs} is true (the default), then this namespace will
1442 be cleared after the test runs, to help with garbage collection.
1443 If you would like to examine the namespace after the test
1444 completes, then use \var{clear_globs=False}.
1445
1446 \var{compileflags} gives the set of flags that should be used by
1447 the Python compiler when running the examples. If not specified,
1448 then it will default to the set of future-import flags that apply
1449 to \var{globs}.
1450
1451 The output of each example is checked using the
1452 \class{DocTestRunner}'s output checker, and the results are
1453 formatted by the \method{DocTestRunner.report_*} methods.
1454\end{methoddesc}
1455
1456\begin{methoddesc}{summarize}{\optional{verbose}}
1457 Print a summary of all the test cases that have been run by this
1458 DocTestRunner, and return a tuple \samp{(\var{failure_count},
1459 \var{test_count})}.
1460
1461 The optional \var{verbose} argument controls how detailed the
1462 summary is. If the verbosity is not specified, then the
1463 \class{DocTestRunner}'s verbosity is used.
1464\end{methoddesc}
1465
1466\subsubsection{OutputChecker objects\label{doctest-OutputChecker}}
1467
1468\begin{classdesc}{OutputChecker}{}
1469 A class used to check the whether the actual output from a doctest
1470 example matches the expected output. \class{OutputChecker}
1471 defines two methods: \method{check_output}, which compares a given
1472 pair of outputs, and returns true if they match; and
1473 \method{output_difference}, which returns a string describing the
1474 differences between two outputs.
1475 \versionadded{2.4}
1476\end{classdesc}
1477
1478\class{OutputChecker} defines the following methods:
1479
1480\begin{methoddesc}{check_output}{want, got, optionflags}
1481 Return \code{True} iff the actual output from an example
1482 (\var{got}) matches the expected output (\var{want}). These
1483 strings are always considered to match if they are identical; but
1484 depending on what option flags the test runner is using, several
1485 non-exact match types are also possible. See
1486 section~\ref{doctest-options} for more information about option
1487 flags.
1488\end{methoddesc}
1489
1490\begin{methoddesc}{output_difference}{example, got, optionflags}
1491 Return a string describing the differences between the expected
1492 output for a given example (\var{example}) and the actual output
1493 (\var{got}). \var{optionflags} is the set of option flags used to
1494 compare \var{want} and \var{got}.
1495\end{methoddesc}
1496
1497\subsection{Debugging\label{doctest-debugging}}
1498
1499Doctest provides three mechanisms for debugging doctest examples:
1500
1501\begin{enumerate}
1502\item The \function{debug()} function converts a specified doctest
1503 to a Python script, and executes that script using \module{pdb}.
1504\item The \class{DebugRunner} class is a subclass of
1505 \class{DocTestRunner} that raises an exception for the first
1506 failing example, containing information about that example.
1507 This information can be used to perform post-mortem debugging on
1508 the example.
1509\item The unittest cases generated by \function{DocTestSuite()}
1510 support the \method{debug} method defined by
1511 \class{unittest.TestCase}.
1512\end{enumerate}
1513
1514\begin{funcdesc}{debug}{module, name}
1515 Debug a single doctest docstring.
1516
1517 Provide the \var{module} (or dotted name of the module) containing
1518 the docstring to be debugged and the fully qualified dotted
1519 \var{name} of the object with the docstring to be debugged.
1520
1521 The doctest examples are extracted (see function \function{testsource()}),
1522 and written to a temporary file. The Python debugger, \refmodule{pdb},
1523 is then invoked on that file.
1524 \versionadded{2.3}
1525\end{funcdesc}
1526
1527\begin{classdesc}{DebugRunner}{\optional{checker}\optional{,
1528 verbose}\optional{, optionflags}}
1529
1530 A subclass of \class{DocTestRunner} that raises an exception as
1531 soon as a failure is encountered. If an unexpected exception
1532 occurs, an \exception{UnexpectedException} exception is raised,
1533 containing the test, the example, and the original exception. If
1534 the output doesn't match, then a \exception{DocTestFailure}
1535 exception is raised, containing the test, the example, and the
1536 actual output.
1537
1538 For information about the constructor parameters and methods, see
1539 the documentation for \class{DocTestRunner} in
1540 section~\ref{doctest-advanced-api}.
1541\end{classdesc}
1542
1543\begin{excclassdesc}{DocTestFailure}{test, example, got}
1544 An exception thrown by \class{DocTestRunner} to signal that a
1545 doctest example's actual output did not match its expected output.
1546 The constructor arguments are used to initialize the member
1547 variables of the same names.
1548\end{excclassdesc}
1549\exception{DocTestFailure} defines the following member variables:
1550\begin{memberdesc}{test}
1551 The \class{DocTest} object that was being run when the example failed.
1552\end{memberdesc}
1553\begin{memberdesc}{example}
1554 The \class{Example} that failed.
1555\end{memberdesc}
1556\begin{memberdesc}{got}
1557 The example's actual output.
1558\end{memberdesc}
1559
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001560\begin{funcdesc}{testsource}{module, name}
1561 Extract the doctest examples from a docstring.
1562
1563 Provide the \var{module} (or dotted name of the module) containing the
1564 tests to be extracted and the \var{name} (within the module) of the object
1565 with the docstring containing the tests to be extracted.
1566
1567 The doctest examples are returned as a string containing Python
1568 code. The expected output blocks in the examples are converted
1569 to Python comments.
1570 \versionadded{2.3}
1571\end{funcdesc}
1572
Edward Loperb3666a32004-09-21 03:00:51 +00001573\begin{excclassdesc}{UnexpectedException}{test, example, got}
1574 An exception thrown by \class{DocTestRunner} to signal that a
1575 doctest example raised an unexpected exception. The constructor
1576 arguments are used to initialize the member variables of the same
1577 names.
1578\end{excclassdesc}
1579\exception{UnexpectedException} defines the following member variables:
1580\begin{memberdesc}{test}
1581 The \class{DocTest} object that was being run when the example failed.
1582\end{memberdesc}
1583\begin{memberdesc}{example}
1584 The \class{Example} that failed.
1585\end{memberdesc}
1586\begin{memberdesc}{exc_info}
1587 A tuple containing information about the unexpected exception, as
1588 returned by \function{sys.exc_info()}.
1589\end{memberdesc}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001590
Edward Loperb3666a32004-09-21 03:00:51 +00001591\begin{funcdesc}{register_optionflag}{name}
1592 Create a new option flag with a given name, and return the new
1593 flag's integer value. \function{register_optionflag()} can be
1594 used when subclassing \class{OutputChecker} or
1595 \class{DocTestRunner} to create new options that are supported by
1596 your subclasses. \function{register_optionflag} should always be
1597 called using the following idiom:
1598\begin{verbatim}
1599 MY_FLAG = register_optionflag('MY_FLAG')
1600\end{verbatim}
Raymond Hettinger92f21b12003-07-11 22:32:18 +00001601\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +00001602
Edward Loperb3666a32004-09-21 03:00:51 +00001603\subsection{Soapbox\label{doctest-soapbox}}
Tim Peters76882292001-02-17 05:58:44 +00001604
Edward Loperb3666a32004-09-21 03:00:51 +00001605As mentioned in the introduction, \module{doctest} has two primary
1606uses:
Tim Peters76882292001-02-17 05:58:44 +00001607
1608\begin{enumerate}
Edward Loperb3666a32004-09-21 03:00:51 +00001609\item Checking examples in docstrings.
1610\item Regression testing.
Fred Drakec1158352001-06-11 14:55:01 +00001611\end{enumerate}
1612
Edward Loperb3666a32004-09-21 03:00:51 +00001613These two uses have different requirements, and it is important to
1614distinguish them. In particular, filling your docstrings with obscure
1615test cases makes for bad documentation.
Tim Peters76882292001-02-17 05:58:44 +00001616
Edward Loperb3666a32004-09-21 03:00:51 +00001617When writing a docstring, choose docstring examples with care.
1618There's an art to this that needs to be learned---it may not be
1619natural at first. Examples should add genuine value to the
1620documentation. A good example can often be worth many words.
1621% [edloper] I think this may be excessive for many cases; let's
1622% just leave it to the user's judgement:
1623%% If possible, show just a few normal cases, show endcases, show
1624%% interesting subtle cases, and show an example of each kind of
1625%% exception that can be raised. You're probably testing for endcases
1626%% and subtle cases anyway in an interactive shell:
1627%% \refmodule{doctest} wants to make it as easy as possible to capture
1628%% those sessions, and will verify they continue to work as designed
1629%% forever after.
Fred Drake7a6b4f02003-07-17 16:00:01 +00001630If done with care, the examples will be invaluable for your users, and
1631will pay back the time it takes to collect them many times over as the
1632years go by and things change. I'm still amazed at how often one of
1633my \refmodule{doctest} examples stops working after a ``harmless''
1634change.
Tim Peters76882292001-02-17 05:58:44 +00001635
Edward Loperb3666a32004-09-21 03:00:51 +00001636Doctest also makes an excellent tool for writing regression testing.
1637By interleaving prose and examples, it becomes much easier to keep
1638track of what's actually being tested, and why. When a test fails,
1639the prose descriptions makes it much easier to figure out what the
1640problem is, and how it should be fixed. Regression testing is best
1641confined to dedicated objects or files. There are several options for
1642organizing regressions:
1643
1644\begin{itemize}
1645\item Define functions named \code{_regrtest_\textit{topic}} that
1646 consist of single docstrings, containing test cases for the
1647 named topics. These functions can be included in the same file
1648 as the module, or separated out into a separate test file.
1649\item Define a \code{__test__} dictionary mapping from regression test
1650 topics to docstrings containing test cases.
1651\item Write a text file containing test cases as interactive examples,
1652 and test that file using \function{testfunc()}.
1653\end{itemize}
1654
1655
1656