blob: 374f851ac34b0cec7932c43bcf5199705f7f921c [file] [log] [blame]
Tim Peters76882292001-02-17 05:58:44 +00001\section{\module{doctest} ---
2 Test docstrings represent reality}
3
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}
8
9\modulesynopsis{A framework for verifying examples in docstrings.}
10
11The \module{doctest} module searches a module's docstrings for text that looks
12like an interactive Python session, then executes all such sessions to verify
13they still work exactly as shown. Here's a complete but small example:
14
15\begin{verbatim}
16"""
17This is module example.
18
19Example supplies one function, factorial. For example,
20
21>>> factorial(5)
22120
23"""
24
25def factorial(n):
26 """Return the factorial of n, an exact integer >= 0.
27
28 If the result is small enough to fit in an int, return an int.
29 Else return a long.
30
31 >>> [factorial(n) for n in range(6)]
32 [1, 1, 2, 6, 24, 120]
33 >>> [factorial(long(n)) for n in range(6)]
34 [1, 1, 2, 6, 24, 120]
35 >>> factorial(30)
36 265252859812191058636308480000000L
37 >>> factorial(30L)
38 265252859812191058636308480000000L
39 >>> factorial(-1)
40 Traceback (most recent call last):
41 ...
42 ValueError: n must be >= 0
43
44 Factorials of floats are OK, but the float must be an exact integer:
45 >>> factorial(30.1)
46 Traceback (most recent call last):
47 ...
48 ValueError: n must be exact integer
49 >>> factorial(30.0)
50 265252859812191058636308480000000L
51
52 It must also not be ridiculously large:
53 >>> factorial(1e100)
54 Traceback (most recent call last):
55 ...
56 OverflowError: n too large
57 """
58
59\end{verbatim}
60% allow LaTeX to break here.
61\begin{verbatim}
62
63 import math
64 if not n >= 0:
65 raise ValueError("n must be >= 0")
66 if math.floor(n) != n:
67 raise ValueError("n must be exact integer")
Raymond Hettinger92f21b12003-07-11 22:32:18 +000068 if n+1 == n: # catch a value like 1e300
Tim Peters76882292001-02-17 05:58:44 +000069 raise OverflowError("n too large")
70 result = 1
71 factor = 2
72 while factor <= n:
73 try:
74 result *= factor
75 except OverflowError:
76 result *= long(factor)
77 factor += 1
78 return result
79
80def _test():
Tim Petersc2388a22004-08-10 01:41:28 +000081 import doctest
82 return doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +000083
84if __name__ == "__main__":
85 _test()
86\end{verbatim}
87
Fred Drake7a6b4f02003-07-17 16:00:01 +000088If you run \file{example.py} directly from the command line,
89\module{doctest} works its magic:
Tim Peters76882292001-02-17 05:58:44 +000090
91\begin{verbatim}
92$ python example.py
93$
94\end{verbatim}
95
Fred Drake7a6b4f02003-07-17 16:00:01 +000096There's no output! That's normal, and it means all the examples
97worked. Pass \programopt{-v} to the script, and \module{doctest}
98prints a detailed log of what it's trying, and prints a summary at the
99end:
Tim Peters76882292001-02-17 05:58:44 +0000100
101\begin{verbatim}
102$ python example.py -v
Tim Peters76882292001-02-17 05:58:44 +0000103Trying: factorial(5)
104Expecting: 120
105ok
Tim Peters76882292001-02-17 05:58:44 +0000106Trying: [factorial(n) for n in range(6)]
107Expecting: [1, 1, 2, 6, 24, 120]
108ok
109Trying: [factorial(long(n)) for n in range(6)]
110Expecting: [1, 1, 2, 6, 24, 120]
Tim Peters41a65ea2004-08-13 03:55:05 +0000111ok
112\end{verbatim}
Tim Peters76882292001-02-17 05:58:44 +0000113
114And so on, eventually ending with:
115
116\begin{verbatim}
117Trying: factorial(1e100)
118Expecting:
Tim Petersc2388a22004-08-10 01:41:28 +0000119 Traceback (most recent call last):
120 ...
121 OverflowError: n too large
Tim Peters76882292001-02-17 05:58:44 +0000122ok
Tim Peters76882292001-02-17 05:58:44 +00001232 items passed all tests:
124 1 tests in example
125 8 tests in example.factorial
1269 tests in 2 items.
1279 passed and 0 failed.
128Test passed.
129$
130\end{verbatim}
131
Fred Drake7a6b4f02003-07-17 16:00:01 +0000132That's all you need to know to start making productive use of
Tim Peters41a65ea2004-08-13 03:55:05 +0000133\module{doctest}! Jump in. The following sections provide full
134details. Note that there are many examples of doctests in
135the standard Python test suite and libraries.
Tim Peters76882292001-02-17 05:58:44 +0000136
Tim Petersc2388a22004-08-10 01:41:28 +0000137\subsection{Simple Usage}
Tim Peters76882292001-02-17 05:58:44 +0000138
Tim Peters41a65ea2004-08-13 03:55:05 +0000139The simplest way to start using doctest (but not necessarily the way
140you'll continue to do it) is to end each module \module{M} with:
Tim Peters76882292001-02-17 05:58:44 +0000141
142\begin{verbatim}
143def _test():
Tim Petersc2388a22004-08-10 01:41:28 +0000144 import doctest
145 return doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +0000146
147if __name__ == "__main__":
148 _test()
149\end{verbatim}
150
Tim Petersc2388a22004-08-10 01:41:28 +0000151\module{doctest} then examines docstrings in the module calling
Tim Peters41a65ea2004-08-13 03:55:05 +0000152\function{testmod()}.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000153
Tim Petersc2388a22004-08-10 01:41:28 +0000154Running the module as a script causes the examples in the docstrings
Tim Peters76882292001-02-17 05:58:44 +0000155to get executed and verified:
156
157\begin{verbatim}
158python M.py
159\end{verbatim}
160
161This won't display anything unless an example fails, in which case the
162failing example(s) and the cause(s) of the failure(s) are printed to stdout,
Tim Petersc2388a22004-08-10 01:41:28 +0000163and the final line of output is
Tim Peters26039602004-08-13 01:49:12 +0000164\samp{'***Test Failed*** \var{N} failures.'}, where \var{N} is the
Tim Petersc2388a22004-08-10 01:41:28 +0000165number of examples that failed.
Tim Peters76882292001-02-17 05:58:44 +0000166
Fred Drake7eb14632001-02-17 17:32:41 +0000167Run it with the \programopt{-v} switch instead:
Tim Peters76882292001-02-17 05:58:44 +0000168
169\begin{verbatim}
170python M.py -v
171\end{verbatim}
172
Fred Drake8836e562003-07-17 15:22:47 +0000173and a detailed report of all examples tried is printed to standard
174output, along with assorted summaries at the end.
Tim Peters76882292001-02-17 05:58:44 +0000175
Tim Petersc2388a22004-08-10 01:41:28 +0000176You can force verbose mode by passing \code{verbose=True} to
Fred Drake5d2f5152003-06-28 03:09:06 +0000177\function{testmod()}, or
Tim Petersc2388a22004-08-10 01:41:28 +0000178prohibit it by passing \code{verbose=False}. In either of those cases,
Fred Drake5d2f5152003-06-28 03:09:06 +0000179\code{sys.argv} is not examined by \function{testmod()}.
Tim Peters76882292001-02-17 05:58:44 +0000180
Fred Drake5d2f5152003-06-28 03:09:06 +0000181In any case, \function{testmod()} returns a 2-tuple of ints \code{(\var{f},
Fred Drake7eb14632001-02-17 17:32:41 +0000182\var{t})}, where \var{f} is the number of docstring examples that
183failed and \var{t} is the total number of docstring examples
184attempted.
Tim Peters76882292001-02-17 05:58:44 +0000185
186\subsection{Which Docstrings Are Examined?}
187
Tim Peters8a3b69c2004-08-12 22:31:25 +0000188The module docstring, and all function, class and method docstrings are
189searched. Objects imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000190
Fred Drake7eb14632001-02-17 17:32:41 +0000191In addition, if \code{M.__test__} exists and "is true", it must be a
192dict, and each entry maps a (string) name to a function object, class
193object, or string. Function and class object docstrings found from
Tim Peters8a3b69c2004-08-12 22:31:25 +0000194\code{M.__test__} are searched, and strings are treated as if they
195were docstrings. In output, a key \code{K} in \code{M.__test__} appears
196with name
Tim Peters76882292001-02-17 05:58:44 +0000197
198\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000199<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000200\end{verbatim}
201
202Any classes found are recursively searched similarly, to test docstrings in
Tim Peters8a3b69c2004-08-12 22:31:25 +0000203their contained methods and nested classes.
204
205\versionchanged[A "private name" concept is deprecated and no longer
Tim Peters26039602004-08-13 01:49:12 +0000206 documented]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000207
Tim Peters76882292001-02-17 05:58:44 +0000208
209\subsection{What's the Execution Context?}
210
Tim Peters41a65ea2004-08-13 03:55:05 +0000211By default, each time \function{testmod()} finds a docstring to test, it
212uses a \emph{shallow copy} of \module{M}'s globals, so that running tests
Tim Peters76882292001-02-17 05:58:44 +0000213doesn't change the module's real globals, and so that one test in
214\module{M} can't leave behind crumbs that accidentally allow another test
215to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000216in \module{M}, and names defined earlier in the docstring being run.
Tim Peters41a65ea2004-08-13 03:55:05 +0000217Examples cannot see names defined in other docstrings.
Tim Peters76882292001-02-17 05:58:44 +0000218
219You can force use of your own dict as the execution context by passing
Tim Peters41a65ea2004-08-13 03:55:05 +0000220\code{globs=your_dict} to \function{testmod()} instead.
Tim Peters76882292001-02-17 05:58:44 +0000221
222\subsection{What About Exceptions?}
223
Tim Petersa07bcd42004-08-26 04:47:31 +0000224No problem, provided that the traceback is the only output produced by
225the example: just paste in the traceback. Since tracebacks contain
226details that are likely to change rapidly (for example, exact file paths
227and line numbers), this is one case where doctest works hard to be
228flexible in what it accepts.
229
230Simple example:
Tim Peters76882292001-02-17 05:58:44 +0000231
232\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000233>>> [1, 2, 3].remove(42)
234Traceback (most recent call last):
235 File "<stdin>", line 1, in ?
236ValueError: list.remove(x): x not in list
Tim Peters76882292001-02-17 05:58:44 +0000237\end{verbatim}
238
Edward Loper19b19582004-08-25 23:07:03 +0000239That doctest succeeds if \exception{ValueError} is raised, with the
Tim Petersa07bcd42004-08-26 04:47:31 +0000240\samp{list.remove(x): x not in list} detail as shown.
Tim Peters41a65ea2004-08-13 03:55:05 +0000241
Edward Loper19b19582004-08-25 23:07:03 +0000242The expected output for an exception must start with a traceback
243header, which may be either of the following two lines, indented the
244same as the first line of the example:
Tim Peters41a65ea2004-08-13 03:55:05 +0000245
246\begin{verbatim}
247Traceback (most recent call last):
248Traceback (innermost last):
249\end{verbatim}
250
Edward Loper19b19582004-08-25 23:07:03 +0000251The traceback header is followed by an optional traceback stack, whose
Tim Petersa07bcd42004-08-26 04:47:31 +0000252contents are ignored by doctest. The traceback stack is typically
253omitted, or copied verbatim from an interactive session.
Edward Loper19b19582004-08-25 23:07:03 +0000254
Tim Petersa07bcd42004-08-26 04:47:31 +0000255The traceback stack is followed by the most interesting part: the
Edward Loper19b19582004-08-25 23:07:03 +0000256line(s) containing the exception type and detail. This is usually the
257last line of a traceback, but can extend across multiple lines if the
Tim Petersa07bcd42004-08-26 04:47:31 +0000258exception has a multi-line detail:
Tim Peters41a65ea2004-08-13 03:55:05 +0000259
260\begin{verbatim}
Edward Loper19b19582004-08-25 23:07:03 +0000261>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000262Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000263 File "<stdin>", line 1, in ?
264ValueError: multi
265 line
266detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000267\end{verbatim}
268
Edward Loper19b19582004-08-25 23:07:03 +0000269The last three (starting with \exception{ValueError}) lines are
270compared against the exception's type and detail, and the rest are
271ignored.
Tim Peters41a65ea2004-08-13 03:55:05 +0000272
Edward Loper19b19582004-08-25 23:07:03 +0000273Best practice is to omit the traceback stack, unless it adds
Tim Petersa07bcd42004-08-26 04:47:31 +0000274significant documentation value to the example. So the last example
Tim Peters41a65ea2004-08-13 03:55:05 +0000275is probably better as:
276
277\begin{verbatim}
Edward Loper19b19582004-08-25 23:07:03 +0000278>>> raise ValueError('multi\n line\ndetail')
Tim Peters41a65ea2004-08-13 03:55:05 +0000279Traceback (most recent call last):
Edward Loper19b19582004-08-25 23:07:03 +0000280 ...
281ValueError: multi
282 line
283detail
Tim Peters41a65ea2004-08-13 03:55:05 +0000284\end{verbatim}
285
Tim Petersa07bcd42004-08-26 04:47:31 +0000286Note that tracebacks are treated very specially. In particular, in the
Tim Peters41a65ea2004-08-13 03:55:05 +0000287rewritten example, the use of \samp{...} is independent of doctest's
Tim Petersa07bcd42004-08-26 04:47:31 +0000288\constant{ELLIPSIS} option. The ellipsis in that example could be left
289out, or could just as well be three (or three hundred) commas or digits,
290or an indented transcript of a Monty Python skit.
291
292Some details you should read once, but won't need to remember:
293
294\begin{itemize}
295
296\item Doctest can't guess whether your expected output came from an
297 exception traceback or from ordinary printing. So, e.g., an example
298 that expects \samp{ValueError: 42 is prime} will pass whether
299 \exception{ValueError} is actually raised or if the example merely
300 prints that traceback text. In practice, ordinary output rarely begins
301 with a traceback header line, so this doesn't create real problems.
302
303\item Each line of the traceback stack (if present) must be indented
304 further than the first line of the example, \emph{or} start with a
305 non-alphanumeric character. The first line following the traceback
306 header indented the same and starting with an alphanumeric is taken
307 to be the start of the exception detail. Of course this does the
308 right thing for genuine tracebacks.
309
Tim Peters1fbf9c52004-09-04 17:21:02 +0000310\item When the \constant{IGNORE_EXCEPTION_DETAIL} doctest option is
311 is specified, everything following the leftmost colon is ignored.
312
Tim Petersa07bcd42004-08-26 04:47:31 +0000313\end{itemize}
Tim Peters41a65ea2004-08-13 03:55:05 +0000314
Tim Peters0e448072004-08-26 01:02:08 +0000315\versionchanged[The ability to handle a multi-line exception detail
316 was added]{2.4}
317
Tim Petersa07bcd42004-08-26 04:47:31 +0000318
Tim Peters026f8dc2004-08-19 16:38:58 +0000319\subsection{Option Flags and Directives\label{doctest-options}}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000320
Tim Peterscf533552004-08-26 04:50:38 +0000321A number of option flags control various aspects of doctest's
Tim Peters026f8dc2004-08-19 16:38:58 +0000322behavior. Symbolic names for the flags are supplied as module constants,
Tim Peters83e259a2004-08-13 21:55:21 +0000323which can be or'ed together and passed to various functions. The names
Tim Peters026f8dc2004-08-19 16:38:58 +0000324can also be used in doctest directives (see below).
Tim Peters8a3b69c2004-08-12 22:31:25 +0000325
Tim Petersa07bcd42004-08-26 04:47:31 +0000326The first group of options define test semantics, controlling
327aspects of how doctest decides whether actual output matches an
328example's expected output:
329
Tim Peters8a3b69c2004-08-12 22:31:25 +0000330\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
331 By default, if an expected output block contains just \code{1},
332 an actual output block containing just \code{1} or just
333 \code{True} is considered to be a match, and similarly for \code{0}
334 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
335 specified, neither substitution is allowed. The default behavior
336 caters to that Python changed the return type of many functions
337 from integer to boolean; doctests expecting "little integer"
338 output still work in these cases. This option will probably go
339 away, but not for several years.
340\end{datadesc}
341
342\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
343 By default, if an expected output block contains a line
344 containing only the string \code{<BLANKLINE>}, then that line
345 will match a blank line in the actual output. Because a
346 genuinely blank line delimits the expected output, this is
347 the only way to communicate that a blank line is expected. When
348 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
349 is not allowed.
350\end{datadesc}
351
352\begin{datadesc}{NORMALIZE_WHITESPACE}
353 When specified, all sequences of whitespace (blanks and newlines) are
354 treated as equal. Any sequence of whitespace within the expected
355 output will match any sequence of whitespace within the actual output.
356 By default, whitespace must match exactly.
357 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
358 of expected output is very long, and you want to wrap it across
359 multiple lines in your source.
360\end{datadesc}
361
362\begin{datadesc}{ELLIPSIS}
363 When specified, an ellipsis marker (\code{...}) in the expected output
364 can match any substring in the actual output. This includes
Tim Peters026f8dc2004-08-19 16:38:58 +0000365 substrings that span line boundaries, and empty substrings, so it's
366 best to keep usage of this simple. Complicated uses can lead to the
367 same kinds of "oops, it matched too much!" surprises that \regexp{.*}
368 is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000369\end{datadesc}
370
Tim Peters1fbf9c52004-09-04 17:21:02 +0000371\begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
372 When specified, an example that expects an exception passes if
373 an exception of the expected type is raised, even if the exception
374 detail does not match. For example, an example expecting
375 \samp{ValueError: 42} will pass if the actual exception raised is
376 \samp{ValueError: 3*14}, but will fail, e.g., if
377 \exception{TypeError} is raised.
378
379 Note that a similar effect can be obtained using \constant{ELLIPSIS},
380 and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
381 prior to 2.4 become uninteresting. Until then,
382 \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
383 doctest that doesn't care about the exception detail yet continues
384 to pass under Python releases prior to 2.4 (doctest directives
385 appear to be comments to them). For example,
386
387\begin{verbatim}
388>>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
389Traceback (most recent call last):
390 File "<stdin>", line 1, in ?
391TypeError: object doesn't support item assignment
392\end{verbatim}
393
394 passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
395 to say "does not" instead of "doesn't".
396
397\end{datadesc}
398
Tim Peters38330fe2004-08-30 16:19:24 +0000399\begin{datadesc}{COMPARISON_FLAGS}
400 A bitmask or'ing together all the comparison flags above.
401\end{datadesc}
402
Tim Petersf33683f2004-08-26 04:52:46 +0000403The second group of options controls how test failures are reported:
Tim Petersa07bcd42004-08-26 04:47:31 +0000404
Edward Loper71f55af2004-08-26 01:41:51 +0000405\begin{datadesc}{REPORT_UDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000406 When specified, failures that involve multi-line expected and
407 actual outputs are displayed using a unified diff.
408\end{datadesc}
409
Edward Loper71f55af2004-08-26 01:41:51 +0000410\begin{datadesc}{REPORT_CDIFF}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000411 When specified, failures that involve multi-line expected and
412 actual outputs will be displayed using a context diff.
413\end{datadesc}
414
Edward Loper71f55af2004-08-26 01:41:51 +0000415\begin{datadesc}{REPORT_NDIFF}
Tim Petersc6cbab02004-08-22 19:43:28 +0000416 When specified, differences are computed by \code{difflib.Differ},
417 using the same algorithm as the popular \file{ndiff.py} utility.
418 This is the only method that marks differences within lines as
419 well as across lines. For example, if a line of expected output
420 contains digit \code{1} where actual output contains letter \code{l},
421 a line is inserted with a caret marking the mismatching column
422 positions.
423\end{datadesc}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000424
Edward Lopera89f88d2004-08-26 02:45:51 +0000425\begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
426 When specified, display the first failing example in each doctest,
427 but suppress output for all remaining examples. This will prevent
428 doctest from reporting correct examples that break because of
429 earlier failures; but it might also hide incorrect examples that
430 fail independently of the first failure. When
431 \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
432 examples are still run, and still count towards the total number of
433 failures reported; only the output is suppressed.
434\end{datadesc}
435
Tim Peters38330fe2004-08-30 16:19:24 +0000436\begin{datadesc}{REPORTING_FLAGS}
437 A bitmask or'ing together all the reporting flags above.
438\end{datadesc}
439
Tim Peters026f8dc2004-08-19 16:38:58 +0000440A "doctest directive" is a trailing Python comment on a line of a doctest
441example:
442
443\begin{productionlist}[doctest]
444 \production{directive}
Johannes Gijsbersc8906182004-08-20 14:37:05 +0000445 {"\#" "doctest:" \token{on_or_off} \token{directive_name}}
Tim Peters026f8dc2004-08-19 16:38:58 +0000446 \production{on_or_off}
447 {"+" | "-"}
448 \production{directive_name}
449 {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
450\end{productionlist}
451
452Whitespace is not allowed between the \code{+} or \code{-} and the
453directive name. The directive name can be any of the option names
454explained above.
455
456The doctest directives appearing in a single example modify doctest's
457behavior for that single example. Use \code{+} to enable the named
458behavior, or \code{-} to disable it.
459
460For example, this test passes:
461
462\begin{verbatim}
463>>> print range(20) #doctest: +NORMALIZE_WHITESPACE
464[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
46510, 11, 12, 13, 14, 15, 16, 17, 18, 19]
466\end{verbatim}
467
468Without the directive it would fail, both because the actual output
469doesn't have two blanks before the single-digit list elements, and
470because the actual output is on a single line. This test also passes,
Tim Petersa07bcd42004-08-26 04:47:31 +0000471and also requires a directive to do so:
Tim Peters026f8dc2004-08-19 16:38:58 +0000472
473\begin{verbatim}
474>>> print range(20) # doctest:+ELLIPSIS
475[0, 1, ..., 18, 19]
476\end{verbatim}
477
478Only one directive per physical line is accepted. If you want to
479use multiple directives for a single example, you can add
480\samp{...} lines to your example containing only directives:
481
482\begin{verbatim}
483>>> print range(20) #doctest: +ELLIPSIS
484... #doctest: +NORMALIZE_WHITESPACE
485[0, 1, ..., 18, 19]
486\end{verbatim}
487
488Note that since all options are disabled by default, and directives apply
489only to the example they appear in, enabling options (via \code{+} in a
490directive) is usually the only meaningful choice. However, option flags
491can also be passed to functions that run doctests, establishing different
492defaults. In such cases, disabling an option via \code{-} in a directive
493can be useful.
494
Tim Peters8a3b69c2004-08-12 22:31:25 +0000495\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
496 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
Tim Peters1fbf9c52004-09-04 17:21:02 +0000497 \constant{IGNORE_EXCEPTION_DETAIL},
Edward Lopera89f88d2004-08-26 02:45:51 +0000498 \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
Tim Peters38330fe2004-08-30 16:19:24 +0000499 \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
500 \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
Tim Peters026f8dc2004-08-19 16:38:58 +0000501 were added; by default \code{<BLANKLINE>} in expected output
502 matches an empty line in actual output; and doctest directives
503 were added]{2.4}
504
Tim Peters8a3b69c2004-08-12 22:31:25 +0000505
Tim Peters76882292001-02-17 05:58:44 +0000506\subsection{Advanced Usage}
507
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000508Several module level functions are available for controlling how doctests
509are run.
Tim Peters76882292001-02-17 05:58:44 +0000510
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000511\begin{funcdesc}{debug}{module, name}
512 Debug a single docstring containing doctests.
513
514 Provide the \var{module} (or dotted name of the module) containing the
515 docstring to be debugged and the \var{name} (within the module) of the
516 object with the docstring to be debugged.
517
518 The doctest examples are extracted (see function \function{testsource()}),
519 and written to a temporary file. The Python debugger, \refmodule{pdb},
Fred Drake8836e562003-07-17 15:22:47 +0000520 is then invoked on that file.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000521 \versionadded{2.3}
522\end{funcdesc}
523
Tim Peters83e259a2004-08-13 21:55:21 +0000524\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
525 globs}\optional{, verbose}\optional{,
526 isprivate}\optional{, report}\optional{,
527 optionflags}\optional{, extraglobs}\optional{,
528 raise_on_error}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000529
Tim Peters83e259a2004-08-13 21:55:21 +0000530 All arguments are optional, and all except for \var{m} should be
531 specified in keyword form.
532
533 Test examples in docstrings in functions and classes reachable
534 from module \var{m} (or the current module if \var{m} is not supplied
535 or is \code{None}), starting with \code{\var{m}.__doc__}.
536
537 Also test examples reachable from dict \code{\var{m}.__test__}, if it
538 exists and is not \code{None}. \code{\var{m}.__test__} maps
539 names (strings) to functions, classes and strings; function and class
540 docstrings are searched for examples; strings are searched directly,
541 as if they were docstrings.
542
543 Only docstrings attached to objects belonging to module \var{m} are
544 searched.
545
546 Return \samp{(\var{failure_count}, \var{test_count})}.
547
548 Optional argument \var{name} gives the name of the module; by default,
549 or if \code{None}, \code{\var{m}.__name__} is used.
550
551 Optional argument \var{globs} gives a dict to be used as the globals
552 when executing examples; by default, or if \code{None},
553 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
554 created for each docstring with examples, so that each docstring's
555 examples start with a clean slate.
556
557 Optional argument \var{extraglobs} gives a dict merged into the
558 globals used to execute examples. This works like
559 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
560 common key, the associated value in \var{extraglobs} appears in the
561 combined dict. By default, or if \code{None}, no extra globals are
562 used. This is an advanced feature that allows parameterization of
563 doctests. For example, a doctest can be written for a base class, using
564 a generic name for the class, then reused to test any number of
565 subclasses by passing an \var{extraglobs} dict mapping the generic
566 name to the subclass to be tested.
567
568 Optional argument \var{verbose} prints lots of stuff if true, and prints
569 only failures if false; by default, or if \code{None}, it's true
570 if and only if \code{'-v'} is in \code{sys.argv}.
571
572 Optional argument \var{report} prints a summary at the end when true,
573 else prints nothing at the end. In verbose mode, the summary is
574 detailed, else the summary is very brief (in fact, empty if all tests
575 passed).
576
577 Optional argument \var{optionflags} or's together option flags. See
578 see section \ref{doctest-options}.
579
580 Optional argument \var{raise_on_error} defaults to false. If true,
581 an exception is raised upon the first failure or unexpected exception
582 in an example. This allows failures to be post-mortem debugged.
583 Default behavior is to continue running examples.
584
585 Optional argument \var{isprivate} specifies a function used to
586 determine whether a name is private. The default function treats
587 all names as public. \var{isprivate} can be set to
588 \code{doctest.is_private} to skip over names that are
589 private according to Python's underscore naming convention.
590 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
591 If you need to skip tests based on name, filter the list returned by
592 \code{DocTestFinder.find()} instead.}
593
594 \versionchanged[The parameter \var{optionflags} was added]{2.3}
595
596 \versionchanged[The parameters \var{extraglobs} and \var{raise_on_error}
597 were added]{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000598\end{funcdesc}
599
600\begin{funcdesc}{testsource}{module, name}
601 Extract the doctest examples from a docstring.
602
603 Provide the \var{module} (or dotted name of the module) containing the
604 tests to be extracted and the \var{name} (within the module) of the object
605 with the docstring containing the tests to be extracted.
606
607 The doctest examples are returned as a string containing Python
608 code. The expected output blocks in the examples are converted
609 to Python comments.
610 \versionadded{2.3}
611\end{funcdesc}
612
613\begin{funcdesc}{DocTestSuite}{\optional{module}}
Fred Drake7a6b4f02003-07-17 16:00:01 +0000614 Convert doctest tests for a module to a
615 \class{\refmodule{unittest}.TestSuite}.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000616
617 The returned \class{TestSuite} is to be run by the unittest framework
618 and runs each doctest in the module. If any of the doctests fail,
619 then the synthesized unit test fails, and a \exception{DocTestTestFailure}
620 exception is raised showing the name of the file containing the test and a
621 (sometimes approximate) line number.
622
623 The optional \var{module} argument provides the module to be tested. It
624 can be a module object or a (possibly dotted) module name. If not
Fred Drake8836e562003-07-17 15:22:47 +0000625 specified, the module calling this function is used.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000626
627 Example using one of the many ways that the \refmodule{unittest} module
628 can use a \class{TestSuite}:
629
630 \begin{verbatim}
631 import unittest
632 import doctest
633 import my_module_with_doctests
634
635 suite = doctest.DocTestSuite(my_module_with_doctests)
636 runner = unittest.TextTestRunner()
637 runner.run(suite)
638 \end{verbatim}
639
640 \versionadded{2.3}
Fred Drake8836e562003-07-17 15:22:47 +0000641 \warning{This function does not currently search \code{M.__test__}
Raymond Hettinger943277e2003-07-17 14:47:12 +0000642 and its search technique does not exactly match \function{testmod()} in
643 every detail. Future versions will bring the two into convergence.}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000644\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +0000645
646
647\subsection{How are Docstring Examples Recognized?}
648
Fred Drake7a6b4f02003-07-17 16:00:01 +0000649In most cases a copy-and-paste of an interactive console session works
Tim Peters83e259a2004-08-13 21:55:21 +0000650fine, but doctest isn't trying to do an exact emulation of any specific
651Python shell. All hard tab characters are expanded to spaces, using
6528-column tab stops. If you don't believe tabs should mean that, too
653bad: don't use hard tabs, or write your own \class{DocTestParser}
654class.
655
656\versionchanged[Expanding tabs to spaces is new; previous versions
657 tried to preserve hard tabs, with confusing results]{2.4}
Tim Peters76882292001-02-17 05:58:44 +0000658
659\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000660>>> # comments are ignored
661>>> x = 12
662>>> x
66312
664>>> if x == 13:
665... print "yes"
666... else:
667... print "no"
668... print "NO"
669... print "NO!!!"
670...
671no
672NO
673NO!!!
674>>>
Tim Peters76882292001-02-17 05:58:44 +0000675\end{verbatim}
676
Fred Drake19f3c522001-02-22 23:15:05 +0000677Any expected output must immediately follow the final
678\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
679the expected output (if any) extends to the next \code{'>\code{>}>~'}
680or all-whitespace line.
Tim Peters76882292001-02-17 05:58:44 +0000681
682The fine print:
683
684\begin{itemize}
685
686\item Expected output cannot contain an all-whitespace line, since such a
Tim Peters83e259a2004-08-13 21:55:21 +0000687 line is taken to signal the end of expected output. If expected
688 output does contain a blank line, put \code{<BLANKLINE>} in your
689 doctest example each place a blank line is expected.
690 \versionchanged[\code{<BLANKLINE>} was added; there was no way to
691 use expected output containing empty lines in
692 previous versions]{2.4}
Tim Peters76882292001-02-17 05:58:44 +0000693
694\item Output to stdout is captured, but not output to stderr (exception
695 tracebacks are captured via a different means).
696
Martin v. Löwis92816de2004-05-31 19:01:00 +0000697\item If you continue a line via backslashing in an interactive session,
698 or for any other reason use a backslash, you should use a raw
699 docstring, which will preserve your backslahses exactly as you type
700 them:
Tim Peters76882292001-02-17 05:58:44 +0000701
702\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000703>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000704... r'''Backslashes in a raw docstring: m\n'''
705>>> print f.__doc__
706Backslashes in a raw docstring: m\n
707\end{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000708
Martin v. Löwis92816de2004-05-31 19:01:00 +0000709 Otherwise, the backslash will be interpreted as part of the string.
Edward Loper19b19582004-08-25 23:07:03 +0000710 E.g., the "{\textbackslash}" above would be interpreted as a newline
Martin v. Löwis92816de2004-05-31 19:01:00 +0000711 character. Alternatively, you can double each backslash in the
712 doctest version (and not use a raw string):
713
714\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000715>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000716... '''Backslashes in a raw docstring: m\\n'''
717>>> print f.__doc__
718Backslashes in a raw docstring: m\n
Tim Peters76882292001-02-17 05:58:44 +0000719\end{verbatim}
720
Tim Petersf0768c82001-02-20 10:57:30 +0000721\item The starting column doesn't matter:
Tim Peters76882292001-02-17 05:58:44 +0000722
723\begin{verbatim}
Tim Petersc4089d82001-02-17 18:03:25 +0000724 >>> assert "Easy!"
725 >>> import math
726 >>> math.floor(1.9)
727 1.0
Tim Peters76882292001-02-17 05:58:44 +0000728\end{verbatim}
729
Fred Drake19f3c522001-02-22 23:15:05 +0000730and as many leading whitespace characters are stripped from the
731expected output as appeared in the initial \code{'>\code{>}>~'} line
Tim Peters83e259a2004-08-13 21:55:21 +0000732that started the example.
Fred Drake7eb14632001-02-17 17:32:41 +0000733\end{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000734
735\subsection{Warnings}
736
737\begin{enumerate}
738
Tim Peters76882292001-02-17 05:58:44 +0000739\item \module{doctest} is serious about requiring exact matches in expected
740 output. If even a single character doesn't match, the test fails. This
741 will probably surprise you a few times, as you learn exactly what Python
742 does and doesn't guarantee about output. For example, when printing a
743 dict, Python doesn't guarantee that the key-value pairs will be printed
744 in any particular order, so a test like
745
746% Hey! What happened to Monty Python examples?
Tim Petersf0768c82001-02-20 10:57:30 +0000747% Tim: ask Guido -- it's his example!
Tim Peters76882292001-02-17 05:58:44 +0000748\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000749>>> foo()
750{"Hermione": "hippogryph", "Harry": "broomstick"}
751>>>
Tim Peters76882292001-02-17 05:58:44 +0000752\end{verbatim}
753
754is vulnerable! One workaround is to do
755
756\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000757>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
Martin v. Löwisccabed32003-11-27 19:48:03 +0000758True
Fred Drake19f3c522001-02-22 23:15:05 +0000759>>>
Tim Peters76882292001-02-17 05:58:44 +0000760\end{verbatim}
761
762instead. Another is to do
763
764\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000765>>> d = foo().items()
766>>> d.sort()
767>>> d
768[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
Tim Peters76882292001-02-17 05:58:44 +0000769\end{verbatim}
770
771There are others, but you get the idea.
772
773Another bad idea is to print things that embed an object address, like
774
775\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000776>>> id(1.0) # certain to fail some of the time
7777948648
778>>>
Tim Peters76882292001-02-17 05:58:44 +0000779\end{verbatim}
780
781Floating-point numbers are also subject to small output variations across
782platforms, because Python defers to the platform C library for float
783formatting, and C libraries vary widely in quality here.
784
785\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000786>>> 1./7 # risky
7870.14285714285714285
788>>> print 1./7 # safer
7890.142857142857
790>>> print round(1./7, 6) # much safer
7910.142857
Tim Peters76882292001-02-17 05:58:44 +0000792\end{verbatim}
793
794Numbers of the form \code{I/2.**J} are safe across all platforms, and I
795often contrive doctest examples to produce numbers of that form:
796
797\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000798>>> 3./4 # utterly safe
7990.75
Tim Peters76882292001-02-17 05:58:44 +0000800\end{verbatim}
801
802Simple fractions are also easier for people to understand, and that makes
803for better documentation.
804
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000805\item Be careful if you have code that must only execute once.
806
807If you have module-level code that must only execute once, a more foolproof
Fred Drakec1158352001-06-11 14:55:01 +0000808definition of \function{_test()} is
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000809
810\begin{verbatim}
811def _test():
812 import doctest, sys
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000813 doctest.testmod()
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000814\end{verbatim}
Tim Peters6ebe61f2003-06-27 20:48:05 +0000815
816\item WYSIWYG isn't always the case, starting in Python 2.3. The
Fred Drake5d2f5152003-06-28 03:09:06 +0000817 string form of boolean results changed from \code{'0'} and
818 \code{'1'} to \code{'False'} and \code{'True'} in Python 2.3.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000819 This makes it clumsy to write a doctest showing boolean results that
820 passes under multiple versions of Python. In Python 2.3, by default,
821 and as a special case, if an expected output block consists solely
Fred Drake5d2f5152003-06-28 03:09:06 +0000822 of \code{'0'} and the actual output block consists solely of
823 \code{'False'}, that's accepted as an exact match, and similarly for
824 \code{'1'} versus \code{'True'}. This behavior can be turned off by
Tim Peters6ebe61f2003-06-27 20:48:05 +0000825 passing the new (in 2.3) module constant
826 \constant{DONT_ACCEPT_TRUE_FOR_1} as the value of \function{testmod()}'s
827 new (in 2.3) optional \var{optionflags} argument. Some years after
828 the integer spellings of booleans are history, this hack will
829 probably be removed again.
830
Fred Drakec1158352001-06-11 14:55:01 +0000831\end{enumerate}
832
Tim Peters76882292001-02-17 05:58:44 +0000833
834\subsection{Soapbox}
835
Fred Drake7a6b4f02003-07-17 16:00:01 +0000836The first word in ``doctest'' is ``doc,'' and that's why the author
837wrote \refmodule{doctest}: to keep documentation up to date. It so
838happens that \refmodule{doctest} makes a pleasant unit testing
839environment, but that's not its primary purpose.
Tim Peters76882292001-02-17 05:58:44 +0000840
Fred Drake7a6b4f02003-07-17 16:00:01 +0000841Choose docstring examples with care. There's an art to this that
842needs to be learned---it may not be natural at first. Examples should
843add genuine value to the documentation. A good example can often be
844worth many words. If possible, show just a few normal cases, show
845endcases, show interesting subtle cases, and show an example of each
846kind of exception that can be raised. You're probably testing for
847endcases and subtle cases anyway in an interactive shell:
848\refmodule{doctest} wants to make it as easy as possible to capture
849those sessions, and will verify they continue to work as designed
850forever after.
Tim Peters76882292001-02-17 05:58:44 +0000851
Fred Drake7a6b4f02003-07-17 16:00:01 +0000852If done with care, the examples will be invaluable for your users, and
853will pay back the time it takes to collect them many times over as the
854years go by and things change. I'm still amazed at how often one of
855my \refmodule{doctest} examples stops working after a ``harmless''
856change.
Tim Peters76882292001-02-17 05:58:44 +0000857
858For exhaustive testing, or testing boring cases that add no value to the
Fred Drake7eb14632001-02-17 17:32:41 +0000859docs, define a \code{__test__} dict instead. That's what it's for.