blob: c51ba2d2bc7b43a954b21225b2e0649b07af393f [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
162\\code{'***Test Failed*** \var{N} failures.'}, where \var{N} is the
163number 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
206 Return \code{(#failures, #tests)}.
207
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
217 Optional argument \var{extraglobs} gives a dicti merged into the
218 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
230 if and only if \code{'-v'} is in \code{\module{sys}.argv}.
231
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
237 Optional argument \var{optionflags} or's together module constants,
238 and defaults to 0.
239
240% Possible values:
241%
242% DONT_ACCEPT_TRUE_FOR_1
243% By default, if an expected output block contains just "1",
244% an actual output block containing just "True" is considered
245% to be a match, and similarly for "0" versus "False". When
246% DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
247% is allowed.
248%
249% DONT_ACCEPT_BLANKLINE
250% By default, if an expected output block contains a line
251% containing only the string "<BLANKLINE>", then that line
252% will match a blank line in the actual output. When
253% DONT_ACCEPT_BLANKLINE is specified, this substitution is
254% not allowed.
255%
256% NORMALIZE_WHITESPACE
257% When NORMALIZE_WHITESPACE is specified, all sequences of
258% whitespace are treated as equal. I.e., any sequence of
259% whitespace within the expected output will match any
260% sequence of whitespace within the actual output.
261%
262% ELLIPSIS
263% When ELLIPSIS is specified, then an ellipsis marker
264% ("...") in the expected output can match any substring in
265% the actual output.
266%
267% UNIFIED_DIFF
268% When UNIFIED_DIFF is specified, failures that involve
269% multi-line expected and actual outputs will be displayed
270% using a unified diff.
271%
272% CONTEXT_DIFF
273% When CONTEXT_DIFF is specified, failures that involve
274% multi-line expected and actual outputs will be displayed
275% using a context diff.
276
277 Optional argument \var{raise_on_error} defaults to false. If true,
278 an exception is raised upon the first failure or unexpected exception
279 in an example. This allows failures to be post-mortem debugged.
280 Default behavior is to continue running examples.
281
282 Optional argument \var{isprivate} specifies a function used to
283 determine whether a name is private. The default function treats
284 all names as public. \var{isprivate} can be set to
285 \code{\module{doctest}.is_private} to skip over names that are
286 private according to Python's underscore naming convention.
287 \deprecated{2.4}{\var{isprivate} was a stupid idea -- don't use it.
288 If you need to skip tests based on name, filter the list returned by
289 \code{\class{DocTestFinder.find()} instead.}
290
291% """ [XX] This is no longer true:
292% Advanced tomfoolery: testmod runs methods of a local instance of
293% class doctest.Tester, then merges the results into (or creates)
294% global Tester instance doctest.master. Methods of doctest.master
295% can be called directly too, if you want to do something unusual.
296% Passing report=0 to testmod is especially useful then, to delay
297% displaying a summary. Invoke doctest.master.summarize(verbose)
298% when you're done fiddling.
299
300 \versionchanged[The parameter \var{optionflags} was added]{2.3}
301
302 \versionchanged[Many new module constants for use with \var{optionflags}
303 were added]{2.4}
304
305 \versionchanged[The parameters \var{extraglobs} and \var{raise_on_error}
306 were added]{2.4}
307\end{funcdesc}
308
309
Tim Peters76882292001-02-17 05:58:44 +0000310\subsection{Which Docstrings Are Examined?}
311
Fred Drake8836e562003-07-17 15:22:47 +0000312See the docstrings in \file{doctest.py} for all the details. They're
313unsurprising: the module docstring, and all function, class and method
314docstrings are searched. Optionally, the tester can be directed to
315exclude docstrings attached to objects with private names. Objects
316imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000317
Fred Drake7eb14632001-02-17 17:32:41 +0000318In addition, if \code{M.__test__} exists and "is true", it must be a
319dict, and each entry maps a (string) name to a function object, class
320object, or string. Function and class object docstrings found from
Raymond Hettingerf17d65d2003-08-12 00:01:16 +0000321\code{M.__test__} are searched even if the tester has been
Raymond Hettinger943277e2003-07-17 14:47:12 +0000322directed to skip over private names in the rest of the module.
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000323In output, a key \code{K} in \code{M.__test__} appears with name
Tim Peters76882292001-02-17 05:58:44 +0000324
325\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000326<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000327\end{verbatim}
328
329Any classes found are recursively searched similarly, to test docstrings in
330their contained methods and nested classes. While private names reached
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000331from \module{M}'s globals can be optionally skipped, all names reached from
Fred Drake7eb14632001-02-17 17:32:41 +0000332\code{M.__test__} are searched.
Tim Peters76882292001-02-17 05:58:44 +0000333
334\subsection{What's the Execution Context?}
335
Fred Drake5d2f5152003-06-28 03:09:06 +0000336By default, each time \function{testmod()} finds a docstring to test, it uses
337a \emph{copy} of \module{M}'s globals, so that running tests on a module
Tim Peters76882292001-02-17 05:58:44 +0000338doesn't change the module's real globals, and so that one test in
339\module{M} can't leave behind crumbs that accidentally allow another test
340to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000341in \module{M}, and names defined earlier in the docstring being run.
Tim Peters76882292001-02-17 05:58:44 +0000342
343You can force use of your own dict as the execution context by passing
344\code{globs=your_dict} to \function{testmod()} instead. Presumably this
Fred Drake7eb14632001-02-17 17:32:41 +0000345would be a copy of \code{M.__dict__} merged with the globals from other
Tim Peters76882292001-02-17 05:58:44 +0000346imported modules.
347
348\subsection{What About Exceptions?}
349
350No problem, as long as the only output generated by the example is the
351traceback itself. For example:
352
353\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000354>>> [1, 2, 3].remove(42)
355Traceback (most recent call last):
356 File "<stdin>", line 1, in ?
357ValueError: list.remove(x): x not in list
358>>>
Tim Peters76882292001-02-17 05:58:44 +0000359\end{verbatim}
360
361Note that only the exception type and value are compared (specifically,
Fred Drake7eb14632001-02-17 17:32:41 +0000362only the last line in the traceback). The various ``File'' lines in
Tim Peters76882292001-02-17 05:58:44 +0000363between can be left out (unless they add significantly to the documentation
364value of the example).
365
366\subsection{Advanced Usage}
367
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000368Several module level functions are available for controlling how doctests
369are run.
Tim Peters76882292001-02-17 05:58:44 +0000370
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000371\begin{funcdesc}{debug}{module, name}
372 Debug a single docstring containing doctests.
373
374 Provide the \var{module} (or dotted name of the module) containing the
375 docstring to be debugged and the \var{name} (within the module) of the
376 object with the docstring to be debugged.
377
378 The doctest examples are extracted (see function \function{testsource()}),
379 and written to a temporary file. The Python debugger, \refmodule{pdb},
Fred Drake8836e562003-07-17 15:22:47 +0000380 is then invoked on that file.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000381 \versionadded{2.3}
382\end{funcdesc}
383
384\begin{funcdesc}{testmod}{}
385 This function provides the most basic interface to the doctests.
386 It creates a local instance of class \class{Tester}, runs appropriate
387 methods of that class, and merges the results into the global \class{Tester}
388 instance, \code{master}.
389
390 To get finer control than \function{testmod()} offers, create an instance
Fred Drake8836e562003-07-17 15:22:47 +0000391 of \class{Tester} with custom policies, or run methods of \code{master}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000392 directly. See \code{Tester.__doc__} for details.
393\end{funcdesc}
394
395\begin{funcdesc}{testsource}{module, name}
396 Extract the doctest examples from a docstring.
397
398 Provide the \var{module} (or dotted name of the module) containing the
399 tests to be extracted and the \var{name} (within the module) of the object
400 with the docstring containing the tests to be extracted.
401
402 The doctest examples are returned as a string containing Python
403 code. The expected output blocks in the examples are converted
404 to Python comments.
405 \versionadded{2.3}
406\end{funcdesc}
407
408\begin{funcdesc}{DocTestSuite}{\optional{module}}
Fred Drake7a6b4f02003-07-17 16:00:01 +0000409 Convert doctest tests for a module to a
410 \class{\refmodule{unittest}.TestSuite}.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000411
412 The returned \class{TestSuite} is to be run by the unittest framework
413 and runs each doctest in the module. If any of the doctests fail,
414 then the synthesized unit test fails, and a \exception{DocTestTestFailure}
415 exception is raised showing the name of the file containing the test and a
416 (sometimes approximate) line number.
417
418 The optional \var{module} argument provides the module to be tested. It
419 can be a module object or a (possibly dotted) module name. If not
Fred Drake8836e562003-07-17 15:22:47 +0000420 specified, the module calling this function is used.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000421
422 Example using one of the many ways that the \refmodule{unittest} module
423 can use a \class{TestSuite}:
424
425 \begin{verbatim}
426 import unittest
427 import doctest
428 import my_module_with_doctests
429
430 suite = doctest.DocTestSuite(my_module_with_doctests)
431 runner = unittest.TextTestRunner()
432 runner.run(suite)
433 \end{verbatim}
434
435 \versionadded{2.3}
Fred Drake8836e562003-07-17 15:22:47 +0000436 \warning{This function does not currently search \code{M.__test__}
Raymond Hettinger943277e2003-07-17 14:47:12 +0000437 and its search technique does not exactly match \function{testmod()} in
438 every detail. Future versions will bring the two into convergence.}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000439\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +0000440
441
442\subsection{How are Docstring Examples Recognized?}
443
Fred Drake7a6b4f02003-07-17 16:00:01 +0000444In most cases a copy-and-paste of an interactive console session works
445fine---just make sure the leading whitespace is rigidly consistent
446(you can mix tabs and spaces if you're too lazy to do it right, but
447\module{doctest} is not in the business of guessing what you think a tab
448means).
Tim Peters76882292001-02-17 05:58:44 +0000449
450\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000451>>> # comments are ignored
452>>> x = 12
453>>> x
45412
455>>> if x == 13:
456... print "yes"
457... else:
458... print "no"
459... print "NO"
460... print "NO!!!"
461...
462no
463NO
464NO!!!
465>>>
Tim Peters76882292001-02-17 05:58:44 +0000466\end{verbatim}
467
Fred Drake19f3c522001-02-22 23:15:05 +0000468Any expected output must immediately follow the final
469\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
470the expected output (if any) extends to the next \code{'>\code{>}>~'}
471or all-whitespace line.
Tim Peters76882292001-02-17 05:58:44 +0000472
473The fine print:
474
475\begin{itemize}
476
477\item Expected output cannot contain an all-whitespace line, since such a
478 line is taken to signal the end of expected output.
479
480\item Output to stdout is captured, but not output to stderr (exception
481 tracebacks are captured via a different means).
482
Martin v. Löwis92816de2004-05-31 19:01:00 +0000483\item If you continue a line via backslashing in an interactive session,
484 or for any other reason use a backslash, you should use a raw
485 docstring, which will preserve your backslahses exactly as you type
486 them:
Tim Peters76882292001-02-17 05:58:44 +0000487
488\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000489>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000490... r'''Backslashes in a raw docstring: m\n'''
491>>> print f.__doc__
492Backslashes in a raw docstring: m\n
493\end{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000494
Martin v. Löwis92816de2004-05-31 19:01:00 +0000495 Otherwise, the backslash will be interpreted as part of the string.
496 E.g., the "\textbackslash" above would be interpreted as a newline
497 character. Alternatively, you can double each backslash in the
498 doctest version (and not use a raw string):
499
500\begin{verbatim}
Tim Peters336689b2004-07-23 02:48:24 +0000501>>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000502... '''Backslashes in a raw docstring: m\\n'''
503>>> print f.__doc__
504Backslashes in a raw docstring: m\n
Tim Peters76882292001-02-17 05:58:44 +0000505\end{verbatim}
506
Tim Petersf0768c82001-02-20 10:57:30 +0000507\item The starting column doesn't matter:
Tim Peters76882292001-02-17 05:58:44 +0000508
509\begin{verbatim}
Tim Petersc4089d82001-02-17 18:03:25 +0000510 >>> assert "Easy!"
511 >>> import math
512 >>> math.floor(1.9)
513 1.0
Tim Peters76882292001-02-17 05:58:44 +0000514\end{verbatim}
515
Fred Drake19f3c522001-02-22 23:15:05 +0000516and as many leading whitespace characters are stripped from the
517expected output as appeared in the initial \code{'>\code{>}>~'} line
518that triggered it.
Fred Drake7eb14632001-02-17 17:32:41 +0000519\end{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000520
521\subsection{Warnings}
522
523\begin{enumerate}
524
Tim Peters76882292001-02-17 05:58:44 +0000525\item \module{doctest} is serious about requiring exact matches in expected
526 output. If even a single character doesn't match, the test fails. This
527 will probably surprise you a few times, as you learn exactly what Python
528 does and doesn't guarantee about output. For example, when printing a
529 dict, Python doesn't guarantee that the key-value pairs will be printed
530 in any particular order, so a test like
531
532% Hey! What happened to Monty Python examples?
Tim Petersf0768c82001-02-20 10:57:30 +0000533% Tim: ask Guido -- it's his example!
Tim Peters76882292001-02-17 05:58:44 +0000534\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000535>>> foo()
536{"Hermione": "hippogryph", "Harry": "broomstick"}
537>>>
Tim Peters76882292001-02-17 05:58:44 +0000538\end{verbatim}
539
540is vulnerable! One workaround is to do
541
542\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000543>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
Martin v. Löwisccabed32003-11-27 19:48:03 +0000544True
Fred Drake19f3c522001-02-22 23:15:05 +0000545>>>
Tim Peters76882292001-02-17 05:58:44 +0000546\end{verbatim}
547
548instead. Another is to do
549
550\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000551>>> d = foo().items()
552>>> d.sort()
553>>> d
554[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
Tim Peters76882292001-02-17 05:58:44 +0000555\end{verbatim}
556
557There are others, but you get the idea.
558
559Another bad idea is to print things that embed an object address, like
560
561\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000562>>> id(1.0) # certain to fail some of the time
5637948648
564>>>
Tim Peters76882292001-02-17 05:58:44 +0000565\end{verbatim}
566
567Floating-point numbers are also subject to small output variations across
568platforms, because Python defers to the platform C library for float
569formatting, and C libraries vary widely in quality here.
570
571\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000572>>> 1./7 # risky
5730.14285714285714285
574>>> print 1./7 # safer
5750.142857142857
576>>> print round(1./7, 6) # much safer
5770.142857
Tim Peters76882292001-02-17 05:58:44 +0000578\end{verbatim}
579
580Numbers of the form \code{I/2.**J} are safe across all platforms, and I
581often contrive doctest examples to produce numbers of that form:
582
583\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000584>>> 3./4 # utterly safe
5850.75
Tim Peters76882292001-02-17 05:58:44 +0000586\end{verbatim}
587
588Simple fractions are also easier for people to understand, and that makes
589for better documentation.
590
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000591\item Be careful if you have code that must only execute once.
592
593If you have module-level code that must only execute once, a more foolproof
Fred Drakec1158352001-06-11 14:55:01 +0000594definition of \function{_test()} is
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000595
596\begin{verbatim}
597def _test():
598 import doctest, sys
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000599 doctest.testmod()
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000600\end{verbatim}
Tim Peters6ebe61f2003-06-27 20:48:05 +0000601
602\item WYSIWYG isn't always the case, starting in Python 2.3. The
Fred Drake5d2f5152003-06-28 03:09:06 +0000603 string form of boolean results changed from \code{'0'} and
604 \code{'1'} to \code{'False'} and \code{'True'} in Python 2.3.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000605 This makes it clumsy to write a doctest showing boolean results that
606 passes under multiple versions of Python. In Python 2.3, by default,
607 and as a special case, if an expected output block consists solely
Fred Drake5d2f5152003-06-28 03:09:06 +0000608 of \code{'0'} and the actual output block consists solely of
609 \code{'False'}, that's accepted as an exact match, and similarly for
610 \code{'1'} versus \code{'True'}. This behavior can be turned off by
Tim Peters6ebe61f2003-06-27 20:48:05 +0000611 passing the new (in 2.3) module constant
612 \constant{DONT_ACCEPT_TRUE_FOR_1} as the value of \function{testmod()}'s
613 new (in 2.3) optional \var{optionflags} argument. Some years after
614 the integer spellings of booleans are history, this hack will
615 probably be removed again.
616
Fred Drakec1158352001-06-11 14:55:01 +0000617\end{enumerate}
618
Tim Peters76882292001-02-17 05:58:44 +0000619
620\subsection{Soapbox}
621
Fred Drake7a6b4f02003-07-17 16:00:01 +0000622The first word in ``doctest'' is ``doc,'' and that's why the author
623wrote \refmodule{doctest}: to keep documentation up to date. It so
624happens that \refmodule{doctest} makes a pleasant unit testing
625environment, but that's not its primary purpose.
Tim Peters76882292001-02-17 05:58:44 +0000626
Fred Drake7a6b4f02003-07-17 16:00:01 +0000627Choose docstring examples with care. There's an art to this that
628needs to be learned---it may not be natural at first. Examples should
629add genuine value to the documentation. A good example can often be
630worth many words. If possible, show just a few normal cases, show
631endcases, show interesting subtle cases, and show an example of each
632kind of exception that can be raised. You're probably testing for
633endcases and subtle cases anyway in an interactive shell:
634\refmodule{doctest} wants to make it as easy as possible to capture
635those sessions, and will verify they continue to work as designed
636forever after.
Tim Peters76882292001-02-17 05:58:44 +0000637
Fred Drake7a6b4f02003-07-17 16:00:01 +0000638If done with care, the examples will be invaluable for your users, and
639will pay back the time it takes to collect them many times over as the
640years go by and things change. I'm still amazed at how often one of
641my \refmodule{doctest} examples stops working after a ``harmless''
642change.
Tim Peters76882292001-02-17 05:58:44 +0000643
644For exhaustive testing, or testing boring cases that add no value to the
Fred Drake7eb14632001-02-17 17:32:41 +0000645docs, define a \code{__test__} dict instead. That's what it's for.