blob: e5b637a5b3aea4010453e9dafda0562477ed849f [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 Petersc2388a22004-08-10 01:41:28 +0000111ok\end{verbatim}
Tim Peters76882292001-02-17 05:58:44 +0000112
113And so on, eventually ending with:
114
115\begin{verbatim}
116Trying: factorial(1e100)
117Expecting:
Tim Petersc2388a22004-08-10 01:41:28 +0000118 Traceback (most recent call last):
119 ...
120 OverflowError: n too large
Tim Peters76882292001-02-17 05:58:44 +0000121ok
Tim Peters76882292001-02-17 05:58:44 +00001222 items passed all tests:
123 1 tests in example
124 8 tests in example.factorial
1259 tests in 2 items.
1269 passed and 0 failed.
127Test passed.
128$
129\end{verbatim}
130
Fred Drake7a6b4f02003-07-17 16:00:01 +0000131That's all you need to know to start making productive use of
Tim Petersc2388a22004-08-10 01:41:28 +0000132\module{doctest}! Jump in.
Tim Peters76882292001-02-17 05:58:44 +0000133
Tim Petersc2388a22004-08-10 01:41:28 +0000134\subsection{Simple Usage}
Tim Peters76882292001-02-17 05:58:44 +0000135
Tim Petersc2388a22004-08-10 01:41:28 +0000136The simplest (not necessarily the best) way to start using doctest is to
137end each module \module{M} with:
Tim Peters76882292001-02-17 05:58:44 +0000138
139\begin{verbatim}
140def _test():
Tim Petersc2388a22004-08-10 01:41:28 +0000141 import doctest
142 return doctest.testmod()
Tim Peters76882292001-02-17 05:58:44 +0000143
144if __name__ == "__main__":
145 _test()
146\end{verbatim}
147
Tim Petersc2388a22004-08-10 01:41:28 +0000148\module{doctest} then examines docstrings in the module calling
149\function{testmod()}. If you want to test a different module, you can
150pass that module object to \function{testmod()}.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000151
Tim Petersc2388a22004-08-10 01:41:28 +0000152Running the module as a script causes the examples in the docstrings
Tim Peters76882292001-02-17 05:58:44 +0000153to get executed and verified:
154
155\begin{verbatim}
156python M.py
157\end{verbatim}
158
159This won't display anything unless an example fails, in which case the
160failing example(s) and the cause(s) of the failure(s) are printed to stdout,
Tim Petersc2388a22004-08-10 01:41:28 +0000161and the final line of output is
Tim Peters26039602004-08-13 01:49:12 +0000162\samp{'***Test Failed*** \var{N} failures.'}, where \var{N} is the
Tim Petersc2388a22004-08-10 01:41:28 +0000163number of examples that failed.
Tim Peters76882292001-02-17 05:58:44 +0000164
Fred Drake7eb14632001-02-17 17:32:41 +0000165Run it with the \programopt{-v} switch instead:
Tim Peters76882292001-02-17 05:58:44 +0000166
167\begin{verbatim}
168python M.py -v
169\end{verbatim}
170
Fred Drake8836e562003-07-17 15:22:47 +0000171and a detailed report of all examples tried is printed to standard
172output, along with assorted summaries at the end.
Tim Peters76882292001-02-17 05:58:44 +0000173
Tim Petersc2388a22004-08-10 01:41:28 +0000174You can force verbose mode by passing \code{verbose=True} to
Fred Drake5d2f5152003-06-28 03:09:06 +0000175\function{testmod()}, or
Tim Petersc2388a22004-08-10 01:41:28 +0000176prohibit it by passing \code{verbose=False}. In either of those cases,
Fred Drake5d2f5152003-06-28 03:09:06 +0000177\code{sys.argv} is not examined by \function{testmod()}.
Tim Peters76882292001-02-17 05:58:44 +0000178
Fred Drake5d2f5152003-06-28 03:09:06 +0000179In any case, \function{testmod()} returns a 2-tuple of ints \code{(\var{f},
Fred Drake7eb14632001-02-17 17:32:41 +0000180\var{t})}, where \var{f} is the number of docstring examples that
181failed and \var{t} is the total number of docstring examples
182attempted.
Tim Peters76882292001-02-17 05:58:44 +0000183
Tim Petersc2388a22004-08-10 01:41:28 +0000184\begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
185 globs}\optional{, verbose}\optional{,
186 isprivate}\optional{, report}\optional{,
187 optionflags}\optional{, extraglobs}\optional{,
188 raise_on_error}}
189
190 All arguments are optional, and all except for \var{m} should be
191 specified in keyword form.
192
193 Test examples in docstrings in functions and classes reachable
194 from module \var{m} (or the current module if \var{m} is not supplied
195 or is \code{None}), starting with \code{\var{m}.__doc__}.
196
197 Also test examples reachable from dict \code{\var{m}.__test__}, if it
198 exists and is not \code{None}. \code{\var{m}.__test__} maps
199 names (strings) to functions, classes and strings; function and class
200 docstrings are searched for examples; strings are searched directly,
201 as if they were docstrings.
202
203 Only docstrings attached to objects belonging to module \var{m} are
204 searched.
205
Tim Peters26039602004-08-13 01:49:12 +0000206 Return \samp{(\var{failure_count}, \var{test_count})}.
Tim Petersc2388a22004-08-10 01:41:28 +0000207
208 Optional argument \var{name} gives the name of the module; by default,
209 or if \code{None}, \code{\var{m}.__name__} is used.
210
211 Optional argument \var{globs} gives a dict to be used as the globals
212 when executing examples; by default, or if \code{None},
213 \code{\var{m}.__dict__} is used. A new shallow copy of this dict is
214 created for each docstring with examples, so that each docstring's
215 examples start with a clean slate.
216
Tim Peters8a3b69c2004-08-12 22:31:25 +0000217 Optional argument \var{extraglobs} gives a dict merged into the
Tim Petersc2388a22004-08-10 01:41:28 +0000218 globals used to execute examples. This works like
219 \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
220 common key, the associated value in \var{extraglobs} appears in the
221 combined dict. By default, or if \code{None}, no extra globals are
222 used. This is an advanced feature that allows parameterization of
223 doctests. For example, a doctest can be written for a base class, using
224 a generic name for the class, then reused to test any number of
225 subclasses by passing an \var{extraglobs} dict mapping the generic
226 name to the subclass to be tested.
227
228 Optional argument \var{verbose} prints lots of stuff if true, and prints
229 only failures if false; by default, or if \code{None}, it's true
Tim Peters26039602004-08-13 01:49:12 +0000230 if and only if \code{'-v'} is in \code{sys.argv}.
Tim Petersc2388a22004-08-10 01:41:28 +0000231
232 Optional argument \var{report} prints a summary at the end when true,
233 else prints nothing at the end. In verbose mode, the summary is
234 detailed, else the summary is very brief (in fact, empty if all tests
235 passed).
236
Tim Peters8a3b69c2004-08-12 22:31:25 +0000237 Optional argument \var{optionflags} or's together option flags. See
238 see section \ref{doctest-options}.
Tim Petersc2388a22004-08-10 01:41:28 +0000239
240 Optional argument \var{raise_on_error} defaults to false. If true,
241 an exception is raised upon the first failure or unexpected exception
242 in an example. This allows failures to be post-mortem debugged.
243 Default behavior is to continue running examples.
244
245 Optional argument \var{isprivate} specifies a function used to
246 determine whether a name is private. The default function treats
247 all names as public. \var{isprivate} can be set to
Tim Peters26039602004-08-13 01:49:12 +0000248 \code{doctest.is_private} to skip over names that are
Tim Petersc2388a22004-08-10 01:41:28 +0000249 private according to Python's underscore naming convention.
250 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
251 If you need to skip tests based on name, filter the list returned by
Fred Drake9d92d5a2004-08-10 15:41:03 +0000252 \code{DocTestFinder.find()} instead.}
Tim Petersc2388a22004-08-10 01:41:28 +0000253
254% """ [XX] This is no longer true:
255% Advanced tomfoolery: testmod runs methods of a local instance of
256% class doctest.Tester, then merges the results into (or creates)
257% global Tester instance doctest.master. Methods of doctest.master
258% can be called directly too, if you want to do something unusual.
259% Passing report=0 to testmod is especially useful then, to delay
260% displaying a summary. Invoke doctest.master.summarize(verbose)
261% when you're done fiddling.
262
263 \versionchanged[The parameter \var{optionflags} was added]{2.3}
264
Tim Petersc2388a22004-08-10 01:41:28 +0000265 \versionchanged[The parameters \var{extraglobs} and \var{raise_on_error}
266 were added]{2.4}
267\end{funcdesc}
268
269
Tim Peters76882292001-02-17 05:58:44 +0000270\subsection{Which Docstrings Are Examined?}
271
Tim Peters8a3b69c2004-08-12 22:31:25 +0000272The module docstring, and all function, class and method docstrings are
273searched. Objects imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000274
Fred Drake7eb14632001-02-17 17:32:41 +0000275In addition, if \code{M.__test__} exists and "is true", it must be a
276dict, and each entry maps a (string) name to a function object, class
277object, or string. Function and class object docstrings found from
Tim Peters8a3b69c2004-08-12 22:31:25 +0000278\code{M.__test__} are searched, and strings are treated as if they
279were docstrings. In output, a key \code{K} in \code{M.__test__} appears
280with name
Tim Peters76882292001-02-17 05:58:44 +0000281
282\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000283<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000284\end{verbatim}
285
286Any classes found are recursively searched similarly, to test docstrings in
Tim Peters8a3b69c2004-08-12 22:31:25 +0000287their contained methods and nested classes.
288
289\versionchanged[A "private name" concept is deprecated and no longer
Tim Peters26039602004-08-13 01:49:12 +0000290 documented]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000291
Tim Peters76882292001-02-17 05:58:44 +0000292
293\subsection{What's the Execution Context?}
294
Fred Drake5d2f5152003-06-28 03:09:06 +0000295By default, each time \function{testmod()} finds a docstring to test, it uses
296a \emph{copy} of \module{M}'s globals, so that running tests on a module
Tim Peters76882292001-02-17 05:58:44 +0000297doesn't change the module's real globals, and so that one test in
298\module{M} can't leave behind crumbs that accidentally allow another test
299to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000300in \module{M}, and names defined earlier in the docstring being run.
Tim Peters76882292001-02-17 05:58:44 +0000301
302You can force use of your own dict as the execution context by passing
303\code{globs=your_dict} to \function{testmod()} instead. Presumably this
Fred Drake7eb14632001-02-17 17:32:41 +0000304would be a copy of \code{M.__dict__} merged with the globals from other
Tim Peters76882292001-02-17 05:58:44 +0000305imported modules.
306
307\subsection{What About Exceptions?}
308
309No problem, as long as the only output generated by the example is the
310traceback itself. For example:
311
312\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000313>>> [1, 2, 3].remove(42)
314Traceback (most recent call last):
315 File "<stdin>", line 1, in ?
316ValueError: list.remove(x): x not in list
317>>>
Tim Peters76882292001-02-17 05:58:44 +0000318\end{verbatim}
319
320Note that only the exception type and value are compared (specifically,
Fred Drake7eb14632001-02-17 17:32:41 +0000321only the last line in the traceback). The various ``File'' lines in
Tim Peters76882292001-02-17 05:58:44 +0000322between can be left out (unless they add significantly to the documentation
323value of the example).
324
Tim Peters8a3b69c2004-08-12 22:31:25 +0000325\subsection{Option Flags and Directive Names\label{doctest-options}}
326
327A number of option flags control various aspects of doctest's behavior.
328Symbolic names for the flags are supplied as module constants, which
329can be or'ed together and passed to various functions. The names can
330also be used in doctest directives.
331
332\begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
333 By default, if an expected output block contains just \code{1},
334 an actual output block containing just \code{1} or just
335 \code{True} is considered to be a match, and similarly for \code{0}
336 versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
337 specified, neither substitution is allowed. The default behavior
338 caters to that Python changed the return type of many functions
339 from integer to boolean; doctests expecting "little integer"
340 output still work in these cases. This option will probably go
341 away, but not for several years.
342\end{datadesc}
343
344\begin{datadesc}{DONT_ACCEPT_BLANKLINE}
345 By default, if an expected output block contains a line
346 containing only the string \code{<BLANKLINE>}, then that line
347 will match a blank line in the actual output. Because a
348 genuinely blank line delimits the expected output, this is
349 the only way to communicate that a blank line is expected. When
350 \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
351 is not allowed.
352\end{datadesc}
353
354\begin{datadesc}{NORMALIZE_WHITESPACE}
355 When specified, all sequences of whitespace (blanks and newlines) are
356 treated as equal. Any sequence of whitespace within the expected
357 output will match any sequence of whitespace within the actual output.
358 By default, whitespace must match exactly.
359 \constant{NORMALIZE_WHITESPACE} is especially useful when a line
360 of expected output is very long, and you want to wrap it across
361 multiple lines in your source.
362\end{datadesc}
363
364\begin{datadesc}{ELLIPSIS}
365 When specified, an ellipsis marker (\code{...}) in the expected output
366 can match any substring in the actual output. This includes
367 substrings that span line boundaries, so it's best to keep usage of
368 this simple. Complicated uses can lead to the same kinds of
Tim Peters26039602004-08-13 01:49:12 +0000369 surprises that \regexp{.*} is prone to in regular expressions.
Tim Peters8a3b69c2004-08-12 22:31:25 +0000370\end{datadesc}
371
372\begin{datadesc}{UNIFIED_DIFF}
373 When specified, failures that involve multi-line expected and
374 actual outputs are displayed using a unified diff.
375\end{datadesc}
376
377\begin{datadesc}{CONTEXT_DIFF}
378 When specified, failures that involve multi-line expected and
379 actual outputs will be displayed using a context diff.
380\end{datadesc}
381
382
383\versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
384 \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
385 \constant{UNIFIED_DIFF}, and \constant{CONTEXT_DIFF}
386 were added, and \code{<BLANKLINE>} in expected output matches
Tim Peters26039602004-08-13 01:49:12 +0000387 an empty line in actual output by default]{2.4}
Tim Peters8a3b69c2004-08-12 22:31:25 +0000388
Tim Peters76882292001-02-17 05:58:44 +0000389\subsection{Advanced Usage}
390
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000391Several module level functions are available for controlling how doctests
392are run.
Tim Peters76882292001-02-17 05:58:44 +0000393
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000394\begin{funcdesc}{debug}{module, name}
395 Debug a single docstring containing doctests.
396
397 Provide the \var{module} (or dotted name of the module) containing the
398 docstring to be debugged and the \var{name} (within the module) of the
399 object with the docstring to be debugged.
400
401 The doctest examples are extracted (see function \function{testsource()}),
402 and written to a temporary file. The Python debugger, \refmodule{pdb},
Fred Drake8836e562003-07-17 15:22:47 +0000403 is then invoked on that file.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000404 \versionadded{2.3}
405\end{funcdesc}
406
407\begin{funcdesc}{testmod}{}
408 This function provides the most basic interface to the doctests.
409 It creates a local instance of class \class{Tester}, runs appropriate
410 methods of that class, and merges the results into the global \class{Tester}
411 instance, \code{master}.
412
413 To get finer control than \function{testmod()} offers, create an instance
Fred Drake8836e562003-07-17 15:22:47 +0000414 of \class{Tester} with custom policies, or run methods of \code{master}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000415 directly. See \code{Tester.__doc__} for details.
416\end{funcdesc}
417
418\begin{funcdesc}{testsource}{module, name}
419 Extract the doctest examples from a docstring.
420
421 Provide the \var{module} (or dotted name of the module) containing the
422 tests to be extracted and the \var{name} (within the module) of the object
423 with the docstring containing the tests to be extracted.
424
425 The doctest examples are returned as a string containing Python
426 code. The expected output blocks in the examples are converted
427 to Python comments.
428 \versionadded{2.3}
429\end{funcdesc}
430
431\begin{funcdesc}{DocTestSuite}{\optional{module}}
Fred Drake7a6b4f02003-07-17 16:00:01 +0000432 Convert doctest tests for a module to a
433 \class{\refmodule{unittest}.TestSuite}.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000434
435 The returned \class{TestSuite} is to be run by the unittest framework
436 and runs each doctest in the module. If any of the doctests fail,
437 then the synthesized unit test fails, and a \exception{DocTestTestFailure}
438 exception is raised showing the name of the file containing the test and a
439 (sometimes approximate) line number.
440
441 The optional \var{module} argument provides the module to be tested. It
442 can be a module object or a (possibly dotted) module name. If not
Fred Drake8836e562003-07-17 15:22:47 +0000443 specified, the module calling this function is used.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000444
445 Example using one of the many ways that the \refmodule{unittest} module
446 can use a \class{TestSuite}:
447
448 \begin{verbatim}
449 import unittest
450 import doctest
451 import my_module_with_doctests
452
453 suite = doctest.DocTestSuite(my_module_with_doctests)
454 runner = unittest.TextTestRunner()
455 runner.run(suite)
456 \end{verbatim}
457
458 \versionadded{2.3}
Fred Drake8836e562003-07-17 15:22:47 +0000459 \warning{This function does not currently search \code{M.__test__}
Raymond Hettinger943277e2003-07-17 14:47:12 +0000460 and its search technique does not exactly match \function{testmod()} in
461 every detail. Future versions will bring the two into convergence.}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000462\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +0000463
464
465\subsection{How are Docstring Examples Recognized?}
466
Fred Drake7a6b4f02003-07-17 16:00:01 +0000467In most cases a copy-and-paste of an interactive console session works
468fine---just make sure the leading whitespace is rigidly consistent
469(you can mix tabs and spaces if you're too lazy to do it right, but
470\module{doctest} is not in the business of guessing what you think a tab
471means).
Tim Peters76882292001-02-17 05:58:44 +0000472
473\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000474>>> # comments are ignored
475>>> x = 12
476>>> x
47712
478>>> if x == 13:
479... print "yes"
480... else:
481... print "no"
482... print "NO"
483... print "NO!!!"
484...
485no
486NO
487NO!!!
488>>>
Tim Peters76882292001-02-17 05:58:44 +0000489\end{verbatim}
490
Fred Drake19f3c522001-02-22 23:15:05 +0000491Any expected output must immediately follow the final
492\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
493the expected output (if any) extends to the next \code{'>\code{>}>~'}
494or all-whitespace line.
Tim Peters76882292001-02-17 05:58:44 +0000495
496The fine print:
497
498\begin{itemize}
499
500\item Expected output cannot contain an all-whitespace line, since such a
501 line is taken to signal the end of expected output.
502
503\item Output to stdout is captured, but not output to stderr (exception
504 tracebacks are captured via a different means).
505
Martin v. Löwis92816de2004-05-31 19:01:00 +0000506\item If you continue a line via backslashing in an interactive session,
507 or for any other reason use a backslash, you should use a raw
508 docstring, which will preserve your backslahses exactly as you type
509 them:
Tim Peters76882292001-02-17 05:58:44 +0000510
511\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000512>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000513... r'''Backslashes in a raw docstring: m\n'''
514>>> print f.__doc__
515Backslashes in a raw docstring: m\n
516\end{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000517
Martin v. Löwis92816de2004-05-31 19:01:00 +0000518 Otherwise, the backslash will be interpreted as part of the string.
519 E.g., the "\textbackslash" above would be interpreted as a newline
520 character. Alternatively, you can double each backslash in the
521 doctest version (and not use a raw string):
522
523\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000524>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000525... '''Backslashes in a raw docstring: m\\n'''
526>>> print f.__doc__
527Backslashes in a raw docstring: m\n
Tim Peters76882292001-02-17 05:58:44 +0000528\end{verbatim}
529
Tim Petersf0768c82001-02-20 10:57:30 +0000530\item The starting column doesn't matter:
Tim Peters76882292001-02-17 05:58:44 +0000531
532\begin{verbatim}
Tim Petersc4089d82001-02-17 18:03:25 +0000533 >>> assert "Easy!"
534 >>> import math
535 >>> math.floor(1.9)
536 1.0
Tim Peters76882292001-02-17 05:58:44 +0000537\end{verbatim}
538
Fred Drake19f3c522001-02-22 23:15:05 +0000539and as many leading whitespace characters are stripped from the
540expected output as appeared in the initial \code{'>\code{>}>~'} line
541that triggered it.
Fred Drake7eb14632001-02-17 17:32:41 +0000542\end{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000543
544\subsection{Warnings}
545
546\begin{enumerate}
547
Tim Peters76882292001-02-17 05:58:44 +0000548\item \module{doctest} is serious about requiring exact matches in expected
549 output. If even a single character doesn't match, the test fails. This
550 will probably surprise you a few times, as you learn exactly what Python
551 does and doesn't guarantee about output. For example, when printing a
552 dict, Python doesn't guarantee that the key-value pairs will be printed
553 in any particular order, so a test like
554
555% Hey! What happened to Monty Python examples?
Tim Petersf0768c82001-02-20 10:57:30 +0000556% Tim: ask Guido -- it's his example!
Tim Peters76882292001-02-17 05:58:44 +0000557\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000558>>> foo()
559{"Hermione": "hippogryph", "Harry": "broomstick"}
560>>>
Tim Peters76882292001-02-17 05:58:44 +0000561\end{verbatim}
562
563is vulnerable! One workaround is to do
564
565\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000566>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
Martin v. Löwisccabed32003-11-27 19:48:03 +0000567True
Fred Drake19f3c522001-02-22 23:15:05 +0000568>>>
Tim Peters76882292001-02-17 05:58:44 +0000569\end{verbatim}
570
571instead. Another is to do
572
573\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000574>>> d = foo().items()
575>>> d.sort()
576>>> d
577[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
Tim Peters76882292001-02-17 05:58:44 +0000578\end{verbatim}
579
580There are others, but you get the idea.
581
582Another bad idea is to print things that embed an object address, like
583
584\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000585>>> id(1.0) # certain to fail some of the time
5867948648
587>>>
Tim Peters76882292001-02-17 05:58:44 +0000588\end{verbatim}
589
590Floating-point numbers are also subject to small output variations across
591platforms, because Python defers to the platform C library for float
592formatting, and C libraries vary widely in quality here.
593
594\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000595>>> 1./7 # risky
5960.14285714285714285
597>>> print 1./7 # safer
5980.142857142857
599>>> print round(1./7, 6) # much safer
6000.142857
Tim Peters76882292001-02-17 05:58:44 +0000601\end{verbatim}
602
603Numbers of the form \code{I/2.**J} are safe across all platforms, and I
604often contrive doctest examples to produce numbers of that form:
605
606\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000607>>> 3./4 # utterly safe
6080.75
Tim Peters76882292001-02-17 05:58:44 +0000609\end{verbatim}
610
611Simple fractions are also easier for people to understand, and that makes
612for better documentation.
613
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000614\item Be careful if you have code that must only execute once.
615
616If you have module-level code that must only execute once, a more foolproof
Fred Drakec1158352001-06-11 14:55:01 +0000617definition of \function{_test()} is
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000618
619\begin{verbatim}
620def _test():
621 import doctest, sys
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000622 doctest.testmod()
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000623\end{verbatim}
Tim Peters6ebe61f2003-06-27 20:48:05 +0000624
625\item WYSIWYG isn't always the case, starting in Python 2.3. The
Fred Drake5d2f5152003-06-28 03:09:06 +0000626 string form of boolean results changed from \code{'0'} and
627 \code{'1'} to \code{'False'} and \code{'True'} in Python 2.3.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000628 This makes it clumsy to write a doctest showing boolean results that
629 passes under multiple versions of Python. In Python 2.3, by default,
630 and as a special case, if an expected output block consists solely
Fred Drake5d2f5152003-06-28 03:09:06 +0000631 of \code{'0'} and the actual output block consists solely of
632 \code{'False'}, that's accepted as an exact match, and similarly for
633 \code{'1'} versus \code{'True'}. This behavior can be turned off by
Tim Peters6ebe61f2003-06-27 20:48:05 +0000634 passing the new (in 2.3) module constant
635 \constant{DONT_ACCEPT_TRUE_FOR_1} as the value of \function{testmod()}'s
636 new (in 2.3) optional \var{optionflags} argument. Some years after
637 the integer spellings of booleans are history, this hack will
638 probably be removed again.
639
Fred Drakec1158352001-06-11 14:55:01 +0000640\end{enumerate}
641
Tim Peters76882292001-02-17 05:58:44 +0000642
643\subsection{Soapbox}
644
Fred Drake7a6b4f02003-07-17 16:00:01 +0000645The first word in ``doctest'' is ``doc,'' and that's why the author
646wrote \refmodule{doctest}: to keep documentation up to date. It so
647happens that \refmodule{doctest} makes a pleasant unit testing
648environment, but that's not its primary purpose.
Tim Peters76882292001-02-17 05:58:44 +0000649
Fred Drake7a6b4f02003-07-17 16:00:01 +0000650Choose docstring examples with care. There's an art to this that
651needs to be learned---it may not be natural at first. Examples should
652add genuine value to the documentation. A good example can often be
653worth many words. If possible, show just a few normal cases, show
654endcases, show interesting subtle cases, and show an example of each
655kind of exception that can be raised. You're probably testing for
656endcases and subtle cases anyway in an interactive shell:
657\refmodule{doctest} wants to make it as easy as possible to capture
658those sessions, and will verify they continue to work as designed
659forever after.
Tim Peters76882292001-02-17 05:58:44 +0000660
Fred Drake7a6b4f02003-07-17 16:00:01 +0000661If done with care, the examples will be invaluable for your users, and
662will pay back the time it takes to collect them many times over as the
663years go by and things change. I'm still amazed at how often one of
664my \refmodule{doctest} examples stops working after a ``harmless''
665change.
Tim Peters76882292001-02-17 05:58:44 +0000666
667For exhaustive testing, or testing boring cases that add no value to the
Fred Drake7eb14632001-02-17 17:32:41 +0000668docs, define a \code{__test__} dict instead. That's what it's for.