blob: 282fb3a3ced62d1c4ab744d9b51a96921c9764e8 [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 Peters41a65ea2004-08-13 03:55:05 +0000224No problem: just paste in the expected traceback. Since
225tracebacks contain details that are likely to change
226rapidly (for example, exact file paths and line numbers), this is one
227case where doctest works hard to be flexible in what it accepts.
228This makes the full story involved, but you really don't have
229to remember much. Simple example:
Tim Peters76882292001-02-17 05:58:44 +0000230
231\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000232>>> [1, 2, 3].remove(42)
233Traceback (most recent call last):
234 File "<stdin>", line 1, in ?
235ValueError: list.remove(x): x not in list
Tim Peters76882292001-02-17 05:58:44 +0000236\end{verbatim}
237
Tim Peters41a65ea2004-08-13 03:55:05 +0000238That doctest succeeds if, and only if, \exception{ValueError} is raised,
239with the \samp{list.remove(x): x not in list} detail as shown.
240
241The expected output for an exception is divided into four parts.
242First, an example may produce some normal output before an exception
243is raised, although that's unusual. The "normal output" is taken to
244be everything until the first "Traceback" line, and is usually an
245empty string. Next, the traceback line must be one of these two, and
246indented the same as the first line in the example:
247
248\begin{verbatim}
249Traceback (most recent call last):
250Traceback (innermost last):
251\end{verbatim}
252
253The most interesting part is the last part: the line(s) starting with the
254exception type and detail. This is usually the last line of a traceback,
255but can extend across any number of lines. After the "Traceback" line,
256doctest simply ignores everything until the first line indented the same as
257the first line of the example, \emph{and} starting with an alphanumeric
258character. This example illustrates the complexities that are possible:
259
260\begin{verbatim}
261>>> print 1, 2; raise ValueError('printed 1\nand 2\n but not 3')
2621 2
263Traceback (most recent call last):
264... indented the same, but doesn't start with an alphanumeric
265 not indented the same, so ignored too
266 File "/Python23/lib/doctest.py", line 442, in _run_examples_inner
267 compileflags, 1) in globs
268 File "<string>", line 1, in ? # and all these are ignored
269ValueError: printed 1
270and 2
271 but not 3
272\end{verbatim}
273
274The first (\samp{1 2}) and last three (starting with
275\exception{ValueError}) lines are compared, and the rest are ignored.
276
277Best practice is to omit the ``File'' lines, unless they add
278significant documentation value to the example. So the example above
279is probably better as:
280
281\begin{verbatim}
282>>> print 1, 2; raise ValueError('printed 1\nand 2\n but not 3')
2831 2
284Traceback (most recent call last):
285 ...
286ValueError: printed 1
287and 2
288 but not 3
289\end{verbatim}
290
291Note the tracebacks are treated very specially. In particular, in the
292rewritten example, the use of \samp{...} is independent of doctest's
293\constant{ELLIPSIS} option. The ellipsis in that example could
294be left out, or could just as well be three (or three hundred) commas.
295
296\versionchanged[The abilities to check both normal output and an
297 exception in a single example, and to have a multi-line
298 exception detail, were added]{2.4}
299
Tim Peters76882292001-02-17 05:58:44 +0000300
Tim Peters8a3b69c2004-08-12 22:31:25 +0000301\subsection{Option Flags and Directive Names\label{doctest-options}}
302
Tim Peters83e259a2004-08-13 21:55:21 +0000303A number of option flags control various aspects of doctest's comparison
304behavior. Symbolic names for the flags are supplied as module constants,
305which can be or'ed together and passed to various functions. The names
306can also be used in doctest directives.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000307
308\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
309 By default, if an expected output block contains just \code{1},
310 an actual output block containing just \code{1} or just
311 \code{True} is considered to be a match, and similarly for \code{0}
312 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
313 specified, neither substitution is allowed. The default behavior
314 caters to that Python changed the return type of many functions
315 from integer to boolean; doctests expecting "little integer"
316 output still work in these cases. This option will probably go
317 away, but not for several years.
318\end{datadesc}
319
320\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
321 By default, if an expected output block contains a line
322 containing only the string \code{<BLANKLINE>}, then that line
323 will match a blank line in the actual output. Because a
324 genuinely blank line delimits the expected output, this is
325 the only way to communicate that a blank line is expected. When
326 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
327 is not allowed.
328\end{datadesc}
329
330\begin{datadesc}{NORMALIZE_WHITESPACE}
331 When specified, all sequences of whitespace (blanks and newlines) are
332 treated as equal. Any sequence of whitespace within the expected
333 output will match any sequence of whitespace within the actual output.
334 By default, whitespace must match exactly.
335 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
336 of expected output is very long, and you want to wrap it across
337 multiple lines in your source.
338\end{datadesc}
339
340\begin{datadesc}{ELLIPSIS}
341 When specified, an ellipsis marker (\code{...}) in the expected output
342 can match any substring in the actual output. This includes
343 substrings that span line boundaries, so it's best to keep usage of
344 this simple. Complicated uses can lead to the same kinds of
Tim Peters26039602004-08-13 01:49:12 +0000345 surprises that \regexp{.*} is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000346\end{datadesc}
347
348\begin{datadesc}{UNIFIED_DIFF}
349 When specified, failures that involve multi-line expected and
350 actual outputs are displayed using a unified diff.
351\end{datadesc}
352
353\begin{datadesc}{CONTEXT_DIFF}
354 When specified, failures that involve multi-line expected and
355 actual outputs will be displayed using a context diff.
356\end{datadesc}
357
358
359\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
360 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
361 \constant{UNIFIED_DIFF}, and \constant{CONTEXT_DIFF}
Tim Peters83e259a2004-08-13 21:55:21 +0000362 were added, and by default \code{<BLANKLINE>} in expected output
363 matches an empty line in actual output]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000364
Tim Peters76882292001-02-17 05:58:44 +0000365\subsection{Advanced Usage}
366
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000367Several module level functions are available for controlling how doctests
368are run.
Tim Peters76882292001-02-17 05:58:44 +0000369
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000370\begin{funcdesc}{debug}{module, name}
371 Debug a single docstring containing doctests.
372
373 Provide the \var{module} (or dotted name of the module) containing the
374 docstring to be debugged and the \var{name} (within the module) of the
375 object with the docstring to be debugged.
376
377 The doctest examples are extracted (see function \function{testsource()}),
378 and written to a temporary file. The Python debugger, \refmodule{pdb},
Fred Drake8836e562003-07-17 15:22:47 +0000379 is then invoked on that file.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000380 \versionadded{2.3}
381\end{funcdesc}
382
Tim Peters83e259a2004-08-13 21:55:21 +0000383\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
384 globs}\optional{, verbose}\optional{,
385 isprivate}\optional{, report}\optional{,
386 optionflags}\optional{, extraglobs}\optional{,
387 raise_on_error}}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000388
Tim Peters83e259a2004-08-13 21:55:21 +0000389 All arguments are optional, and all except for \var{m} should be
390 specified in keyword form.
391
392 Test examples in docstrings in functions and classes reachable
393 from module \var{m} (or the current module if \var{m} is not supplied
394 or is \code{None}), starting with \code{\var{m}.__doc__}.
395
396 Also test examples reachable from dict \code{\var{m}.__test__}, if it
397 exists and is not \code{None}. \code{\var{m}.__test__} maps
398 names (strings) to functions, classes and strings; function and class
399 docstrings are searched for examples; strings are searched directly,
400 as if they were docstrings.
401
402 Only docstrings attached to objects belonging to module \var{m} are
403 searched.
404
405 Return \samp{(\var{failure_count}, \var{test_count})}.
406
407 Optional argument \var{name} gives the name of the module; by default,
408 or if \code{None}, \code{\var{m}.__name__} is used.
409
410 Optional argument \var{globs} gives a dict to be used as the globals
411 when executing examples; by default, or if \code{None},
412 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
413 created for each docstring with examples, so that each docstring's
414 examples start with a clean slate.
415
416 Optional argument \var{extraglobs} gives a dict merged into the
417 globals used to execute examples. This works like
418 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
419 common key, the associated value in \var{extraglobs} appears in the
420 combined dict. By default, or if \code{None}, no extra globals are
421 used. This is an advanced feature that allows parameterization of
422 doctests. For example, a doctest can be written for a base class, using
423 a generic name for the class, then reused to test any number of
424 subclasses by passing an \var{extraglobs} dict mapping the generic
425 name to the subclass to be tested.
426
427 Optional argument \var{verbose} prints lots of stuff if true, and prints
428 only failures if false; by default, or if \code{None}, it's true
429 if and only if \code{'-v'} is in \code{sys.argv}.
430
431 Optional argument \var{report} prints a summary at the end when true,
432 else prints nothing at the end. In verbose mode, the summary is
433 detailed, else the summary is very brief (in fact, empty if all tests
434 passed).
435
436 Optional argument \var{optionflags} or's together option flags. See
437 see section \ref{doctest-options}.
438
439 Optional argument \var{raise_on_error} defaults to false. If true,
440 an exception is raised upon the first failure or unexpected exception
441 in an example. This allows failures to be post-mortem debugged.
442 Default behavior is to continue running examples.
443
444 Optional argument \var{isprivate} specifies a function used to
445 determine whether a name is private. The default function treats
446 all names as public. \var{isprivate} can be set to
447 \code{doctest.is_private} to skip over names that are
448 private according to Python's underscore naming convention.
449 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
450 If you need to skip tests based on name, filter the list returned by
451 \code{DocTestFinder.find()} instead.}
452
453 \versionchanged[The parameter \var{optionflags} was added]{2.3}
454
455 \versionchanged[The parameters \var{extraglobs} and \var{raise_on_error}
456 were added]{2.4}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000457\end{funcdesc}
458
459\begin{funcdesc}{testsource}{module, name}
460 Extract the doctest examples from a docstring.
461
462 Provide the \var{module} (or dotted name of the module) containing the
463 tests to be extracted and the \var{name} (within the module) of the object
464 with the docstring containing the tests to be extracted.
465
466 The doctest examples are returned as a string containing Python
467 code. The expected output blocks in the examples are converted
468 to Python comments.
469 \versionadded{2.3}
470\end{funcdesc}
471
472\begin{funcdesc}{DocTestSuite}{\optional{module}}
Fred Drake7a6b4f02003-07-17 16:00:01 +0000473 Convert doctest tests for a module to a
474 \class{\refmodule{unittest}.TestSuite}.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000475
476 The returned \class{TestSuite} is to be run by the unittest framework
477 and runs each doctest in the module. If any of the doctests fail,
478 then the synthesized unit test fails, and a \exception{DocTestTestFailure}
479 exception is raised showing the name of the file containing the test and a
480 (sometimes approximate) line number.
481
482 The optional \var{module} argument provides the module to be tested. It
483 can be a module object or a (possibly dotted) module name. If not
Fred Drake8836e562003-07-17 15:22:47 +0000484 specified, the module calling this function is used.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000485
486 Example using one of the many ways that the \refmodule{unittest} module
487 can use a \class{TestSuite}:
488
489 \begin{verbatim}
490 import unittest
491 import doctest
492 import my_module_with_doctests
493
494 suite = doctest.DocTestSuite(my_module_with_doctests)
495 runner = unittest.TextTestRunner()
496 runner.run(suite)
497 \end{verbatim}
498
499 \versionadded{2.3}
Fred Drake8836e562003-07-17 15:22:47 +0000500 \warning{This function does not currently search \code{M.__test__}
Raymond Hettinger943277e2003-07-17 14:47:12 +0000501 and its search technique does not exactly match \function{testmod()} in
502 every detail. Future versions will bring the two into convergence.}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000503\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +0000504
505
506\subsection{How are Docstring Examples Recognized?}
507
Fred Drake7a6b4f02003-07-17 16:00:01 +0000508In most cases a copy-and-paste of an interactive console session works
Tim Peters83e259a2004-08-13 21:55:21 +0000509fine, but doctest isn't trying to do an exact emulation of any specific
510Python shell. All hard tab characters are expanded to spaces, using
5118-column tab stops. If you don't believe tabs should mean that, too
512bad: don't use hard tabs, or write your own \class{DocTestParser}
513class.
514
515\versionchanged[Expanding tabs to spaces is new; previous versions
516 tried to preserve hard tabs, with confusing results]{2.4}
Tim Peters76882292001-02-17 05:58:44 +0000517
518\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000519>>> # comments are ignored
520>>> x = 12
521>>> x
52212
523>>> if x == 13:
524... print "yes"
525... else:
526... print "no"
527... print "NO"
528... print "NO!!!"
529...
530no
531NO
532NO!!!
533>>>
Tim Peters76882292001-02-17 05:58:44 +0000534\end{verbatim}
535
Fred Drake19f3c522001-02-22 23:15:05 +0000536Any expected output must immediately follow the final
537\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
538the expected output (if any) extends to the next \code{'>\code{>}>~'}
539or all-whitespace line.
Tim Peters76882292001-02-17 05:58:44 +0000540
541The fine print:
542
543\begin{itemize}
544
545\item Expected output cannot contain an all-whitespace line, since such a
Tim Peters83e259a2004-08-13 21:55:21 +0000546 line is taken to signal the end of expected output. If expected
547 output does contain a blank line, put \code{<BLANKLINE>} in your
548 doctest example each place a blank line is expected.
549 \versionchanged[\code{<BLANKLINE>} was added; there was no way to
550 use expected output containing empty lines in
551 previous versions]{2.4}
Tim Peters76882292001-02-17 05:58:44 +0000552
553\item Output to stdout is captured, but not output to stderr (exception
554 tracebacks are captured via a different means).
555
Martin v. Löwis92816de2004-05-31 19:01:00 +0000556\item If you continue a line via backslashing in an interactive session,
557 or for any other reason use a backslash, you should use a raw
558 docstring, which will preserve your backslahses exactly as you type
559 them:
Tim Peters76882292001-02-17 05:58:44 +0000560
561\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000562>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000563... r'''Backslashes in a raw docstring: m\n'''
564>>> print f.__doc__
565Backslashes in a raw docstring: m\n
566\end{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000567
Martin v. Löwis92816de2004-05-31 19:01:00 +0000568 Otherwise, the backslash will be interpreted as part of the string.
569 E.g., the "\textbackslash" above would be interpreted as a newline
570 character. Alternatively, you can double each backslash in the
571 doctest version (and not use a raw string):
572
573\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000574>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000575... '''Backslashes in a raw docstring: m\\n'''
576>>> print f.__doc__
577Backslashes in a raw docstring: m\n
Tim Peters76882292001-02-17 05:58:44 +0000578\end{verbatim}
579
Tim Petersf0768c82001-02-20 10:57:30 +0000580\item The starting column doesn't matter:
Tim Peters76882292001-02-17 05:58:44 +0000581
582\begin{verbatim}
Tim Petersc4089d82001-02-17 18:03:25 +0000583 >>> assert "Easy!"
584 >>> import math
585 >>> math.floor(1.9)
586 1.0
Tim Peters76882292001-02-17 05:58:44 +0000587\end{verbatim}
588
Fred Drake19f3c522001-02-22 23:15:05 +0000589and as many leading whitespace characters are stripped from the
590expected output as appeared in the initial \code{'>\code{>}>~'} line
Tim Peters83e259a2004-08-13 21:55:21 +0000591that started the example.
Fred Drake7eb14632001-02-17 17:32:41 +0000592\end{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000593
594\subsection{Warnings}
595
596\begin{enumerate}
597
Tim Peters76882292001-02-17 05:58:44 +0000598\item \module{doctest} is serious about requiring exact matches in expected
599 output. If even a single character doesn't match, the test fails. This
600 will probably surprise you a few times, as you learn exactly what Python
601 does and doesn't guarantee about output. For example, when printing a
602 dict, Python doesn't guarantee that the key-value pairs will be printed
603 in any particular order, so a test like
604
605% Hey! What happened to Monty Python examples?
Tim Petersf0768c82001-02-20 10:57:30 +0000606% Tim: ask Guido -- it's his example!
Tim Peters76882292001-02-17 05:58:44 +0000607\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000608>>> foo()
609{"Hermione": "hippogryph", "Harry": "broomstick"}
610>>>
Tim Peters76882292001-02-17 05:58:44 +0000611\end{verbatim}
612
613is vulnerable! One workaround is to do
614
615\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000616>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
Martin v. Löwisccabed32003-11-27 19:48:03 +0000617True
Fred Drake19f3c522001-02-22 23:15:05 +0000618>>>
Tim Peters76882292001-02-17 05:58:44 +0000619\end{verbatim}
620
621instead. Another is to do
622
623\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000624>>> d = foo().items()
625>>> d.sort()
626>>> d
627[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
Tim Peters76882292001-02-17 05:58:44 +0000628\end{verbatim}
629
630There are others, but you get the idea.
631
632Another bad idea is to print things that embed an object address, like
633
634\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000635>>> id(1.0) # certain to fail some of the time
6367948648
637>>>
Tim Peters76882292001-02-17 05:58:44 +0000638\end{verbatim}
639
640Floating-point numbers are also subject to small output variations across
641platforms, because Python defers to the platform C library for float
642formatting, and C libraries vary widely in quality here.
643
644\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000645>>> 1./7 # risky
6460.14285714285714285
647>>> print 1./7 # safer
6480.142857142857
649>>> print round(1./7, 6) # much safer
6500.142857
Tim Peters76882292001-02-17 05:58:44 +0000651\end{verbatim}
652
653Numbers of the form \code{I/2.**J} are safe across all platforms, and I
654often contrive doctest examples to produce numbers of that form:
655
656\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000657>>> 3./4 # utterly safe
6580.75
Tim Peters76882292001-02-17 05:58:44 +0000659\end{verbatim}
660
661Simple fractions are also easier for people to understand, and that makes
662for better documentation.
663
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000664\item Be careful if you have code that must only execute once.
665
666If you have module-level code that must only execute once, a more foolproof
Fred Drakec1158352001-06-11 14:55:01 +0000667definition of \function{_test()} is
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000668
669\begin{verbatim}
670def _test():
671 import doctest, sys
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000672 doctest.testmod()
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000673\end{verbatim}
Tim Peters6ebe61f2003-06-27 20:48:05 +0000674
675\item WYSIWYG isn't always the case, starting in Python 2.3. The
Fred Drake5d2f5152003-06-28 03:09:06 +0000676 string form of boolean results changed from \code{'0'} and
677 \code{'1'} to \code{'False'} and \code{'True'} in Python 2.3.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000678 This makes it clumsy to write a doctest showing boolean results that
679 passes under multiple versions of Python. In Python 2.3, by default,
680 and as a special case, if an expected output block consists solely
Fred Drake5d2f5152003-06-28 03:09:06 +0000681 of \code{'0'} and the actual output block consists solely of
682 \code{'False'}, that's accepted as an exact match, and similarly for
683 \code{'1'} versus \code{'True'}. This behavior can be turned off by
Tim Peters6ebe61f2003-06-27 20:48:05 +0000684 passing the new (in 2.3) module constant
685 \constant{DONT_ACCEPT_TRUE_FOR_1} as the value of \function{testmod()}'s
686 new (in 2.3) optional \var{optionflags} argument. Some years after
687 the integer spellings of booleans are history, this hack will
688 probably be removed again.
689
Fred Drakec1158352001-06-11 14:55:01 +0000690\end{enumerate}
691
Tim Peters76882292001-02-17 05:58:44 +0000692
693\subsection{Soapbox}
694
Fred Drake7a6b4f02003-07-17 16:00:01 +0000695The first word in ``doctest'' is ``doc,'' and that's why the author
696wrote \refmodule{doctest}: to keep documentation up to date. It so
697happens that \refmodule{doctest} makes a pleasant unit testing
698environment, but that's not its primary purpose.
Tim Peters76882292001-02-17 05:58:44 +0000699
Fred Drake7a6b4f02003-07-17 16:00:01 +0000700Choose docstring examples with care. There's an art to this that
701needs to be learned---it may not be natural at first. Examples should
702add genuine value to the documentation. A good example can often be
703worth many words. If possible, show just a few normal cases, show
704endcases, show interesting subtle cases, and show an example of each
705kind of exception that can be raised. You're probably testing for
706endcases and subtle cases anyway in an interactive shell:
707\refmodule{doctest} wants to make it as easy as possible to capture
708those sessions, and will verify they continue to work as designed
709forever after.
Tim Peters76882292001-02-17 05:58:44 +0000710
Fred Drake7a6b4f02003-07-17 16:00:01 +0000711If done with care, the examples will be invaluable for your users, and
712will pay back the time it takes to collect them many times over as the
713years go by and things change. I'm still amazed at how often one of
714my \refmodule{doctest} examples stops working after a ``harmless''
715change.
Tim Peters76882292001-02-17 05:58:44 +0000716
717For exhaustive testing, or testing boring cases that add no value to the
Fred Drake7eb14632001-02-17 17:32:41 +0000718docs, define a \code{__test__} dict instead. That's what it's for.