blob: 9f9acd5ddc54a8e688d5a1f704a5d1de225f28fa [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():
81 import doctest, example
82 return doctest.testmod(example)
83
84if __name__ == "__main__":
85 _test()
86\end{verbatim}
87
88If you run \file{example.py} directly from the command line, doctest works
89its magic:
90
91\begin{verbatim}
92$ python example.py
93$
94\end{verbatim}
95
96There's no output! That's normal, and it means all the examples worked.
Fred Drake7eb14632001-02-17 17:32:41 +000097Pass \programopt{-v} to the script, and doctest prints a detailed log
98of what it's trying, and prints a summary at the end:
Tim Peters76882292001-02-17 05:58:44 +000099
100\begin{verbatim}
101$ python example.py -v
102Running example.__doc__
103Trying: factorial(5)
104Expecting: 120
105ok
1060 of 1 examples failed in example.__doc__
107Running example.factorial.__doc__
108Trying: [factorial(n) for n in range(6)]
109Expecting: [1, 1, 2, 6, 24, 120]
110ok
111Trying: [factorial(long(n)) for n in range(6)]
112Expecting: [1, 1, 2, 6, 24, 120]
113ok
114Trying: factorial(30)
115Expecting: 265252859812191058636308480000000L
116ok
117\end{verbatim}
118
119And so on, eventually ending with:
120
121\begin{verbatim}
122Trying: factorial(1e100)
123Expecting:
124Traceback (most recent call last):
125 ...
126OverflowError: n too large
127ok
1280 of 8 examples failed in example.factorial.__doc__
1292 items passed all tests:
130 1 tests in example
131 8 tests in example.factorial
1329 tests in 2 items.
1339 passed and 0 failed.
134Test passed.
135$
136\end{verbatim}
137
138That's all you need to know to start making productive use of doctest! Jump
139in. The docstrings in doctest.py contain detailed information about all
140aspects of doctest, and we'll just cover the more important points here.
141
142\subsection{Normal Usage}
143
144In normal use, end each module \module{M} with:
145
146\begin{verbatim}
147def _test():
148 import doctest, M # replace M with your module's name
149 return doctest.testmod(M) # ditto
150
151if __name__ == "__main__":
152 _test()
153\end{verbatim}
154
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000155If you want to test the module as the main module, you don't need to
Fred Drake5d2f5152003-06-28 03:09:06 +0000156pass M to \function{testmod()}; in this case, it will test the current
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000157module.
158
Tim Peters76882292001-02-17 05:58:44 +0000159Then running the module as a script causes the examples in the docstrings
160to get executed and verified:
161
162\begin{verbatim}
163python M.py
164\end{verbatim}
165
166This won't display anything unless an example fails, in which case the
167failing example(s) and the cause(s) of the failure(s) are printed to stdout,
Fred Drake7eb14632001-02-17 17:32:41 +0000168and the final line of output is \code{'Test failed.'}.
Tim Peters76882292001-02-17 05:58:44 +0000169
Fred Drake7eb14632001-02-17 17:32:41 +0000170Run it with the \programopt{-v} switch instead:
Tim Peters76882292001-02-17 05:58:44 +0000171
172\begin{verbatim}
173python M.py -v
174\end{verbatim}
175
Fred Drake8836e562003-07-17 15:22:47 +0000176and a detailed report of all examples tried is printed to standard
177output, along with assorted summaries at the end.
Tim Peters76882292001-02-17 05:58:44 +0000178
Fred Drake5d2f5152003-06-28 03:09:06 +0000179You can force verbose mode by passing \code{verbose=1} to
180\function{testmod()}, or
Tim Peters76882292001-02-17 05:58:44 +0000181prohibit it by passing \code{verbose=0}. In either of those cases,
Fred Drake5d2f5152003-06-28 03:09:06 +0000182\code{sys.argv} is not examined by \function{testmod()}.
Tim Peters76882292001-02-17 05:58:44 +0000183
Fred Drake5d2f5152003-06-28 03:09:06 +0000184In any case, \function{testmod()} returns a 2-tuple of ints \code{(\var{f},
Fred Drake7eb14632001-02-17 17:32:41 +0000185\var{t})}, where \var{f} is the number of docstring examples that
186failed and \var{t} is the total number of docstring examples
187attempted.
Tim Peters76882292001-02-17 05:58:44 +0000188
189\subsection{Which Docstrings Are Examined?}
190
Fred Drake8836e562003-07-17 15:22:47 +0000191See the docstrings in \file{doctest.py} for all the details. They're
192unsurprising: the module docstring, and all function, class and method
193docstrings are searched. Optionally, the tester can be directed to
194exclude docstrings attached to objects with private names. Objects
195imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000196
Fred Drake7eb14632001-02-17 17:32:41 +0000197In addition, if \code{M.__test__} exists and "is true", it must be a
198dict, and each entry maps a (string) name to a function object, class
199object, or string. Function and class object docstrings found from
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000200\code{M.__test__} are searched even if the the tester has been
Raymond Hettinger943277e2003-07-17 14:47:12 +0000201directed to skip over private names in the rest of the module.
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000202In output, a key \code{K} in \code{M.__test__} appears with name
Tim Peters76882292001-02-17 05:58:44 +0000203
204\begin{verbatim}
Fred Drake8836e562003-07-17 15:22:47 +0000205<name of M>.__test__.K
Tim Peters76882292001-02-17 05:58:44 +0000206\end{verbatim}
207
208Any classes found are recursively searched similarly, to test docstrings in
209their contained methods and nested classes. While private names reached
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000210from \module{M}'s globals can be optionally skipped, all names reached from
Fred Drake7eb14632001-02-17 17:32:41 +0000211\code{M.__test__} are searched.
Tim Peters76882292001-02-17 05:58:44 +0000212
213\subsection{What's the Execution Context?}
214
Fred Drake5d2f5152003-06-28 03:09:06 +0000215By default, each time \function{testmod()} finds a docstring to test, it uses
216a \emph{copy} of \module{M}'s globals, so that running tests on a module
Tim Peters76882292001-02-17 05:58:44 +0000217doesn't change the module's real globals, and so that one test in
218\module{M} can't leave behind crumbs that accidentally allow another test
219to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000220in \module{M}, and names defined earlier in the docstring being run.
Tim Peters76882292001-02-17 05:58:44 +0000221
222You can force use of your own dict as the execution context by passing
223\code{globs=your_dict} to \function{testmod()} instead. Presumably this
Fred Drake7eb14632001-02-17 17:32:41 +0000224would be a copy of \code{M.__dict__} merged with the globals from other
Tim Peters76882292001-02-17 05:58:44 +0000225imported modules.
226
227\subsection{What About Exceptions?}
228
229No problem, as long as the only output generated by the example is the
230traceback itself. For example:
231
232\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000233>>> [1, 2, 3].remove(42)
234Traceback (most recent call last):
235 File "<stdin>", line 1, in ?
236ValueError: list.remove(x): x not in list
237>>>
Tim Peters76882292001-02-17 05:58:44 +0000238\end{verbatim}
239
240Note that only the exception type and value are compared (specifically,
Fred Drake7eb14632001-02-17 17:32:41 +0000241only the last line in the traceback). The various ``File'' lines in
Tim Peters76882292001-02-17 05:58:44 +0000242between can be left out (unless they add significantly to the documentation
243value of the example).
244
245\subsection{Advanced Usage}
246
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000247Several module level functions are available for controlling how doctests
248are run.
Tim Peters76882292001-02-17 05:58:44 +0000249
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000250\begin{funcdesc}{debug}{module, name}
251 Debug a single docstring containing doctests.
252
253 Provide the \var{module} (or dotted name of the module) containing the
254 docstring to be debugged and the \var{name} (within the module) of the
255 object with the docstring to be debugged.
256
257 The doctest examples are extracted (see function \function{testsource()}),
258 and written to a temporary file. The Python debugger, \refmodule{pdb},
Fred Drake8836e562003-07-17 15:22:47 +0000259 is then invoked on that file.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000260 \versionadded{2.3}
261\end{funcdesc}
262
263\begin{funcdesc}{testmod}{}
264 This function provides the most basic interface to the doctests.
265 It creates a local instance of class \class{Tester}, runs appropriate
266 methods of that class, and merges the results into the global \class{Tester}
267 instance, \code{master}.
268
269 To get finer control than \function{testmod()} offers, create an instance
Fred Drake8836e562003-07-17 15:22:47 +0000270 of \class{Tester} with custom policies, or run methods of \code{master}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000271 directly. See \code{Tester.__doc__} for details.
272\end{funcdesc}
273
274\begin{funcdesc}{testsource}{module, name}
275 Extract the doctest examples from a docstring.
276
277 Provide the \var{module} (or dotted name of the module) containing the
278 tests to be extracted and the \var{name} (within the module) of the object
279 with the docstring containing the tests to be extracted.
280
281 The doctest examples are returned as a string containing Python
282 code. The expected output blocks in the examples are converted
283 to Python comments.
284 \versionadded{2.3}
285\end{funcdesc}
286
287\begin{funcdesc}{DocTestSuite}{\optional{module}}
288 Convert doctest tests for a module to a \refmodule{unittest}
289 \class{TestSuite}.
290
291 The returned \class{TestSuite} is to be run by the unittest framework
292 and runs each doctest in the module. If any of the doctests fail,
293 then the synthesized unit test fails, and a \exception{DocTestTestFailure}
294 exception is raised showing the name of the file containing the test and a
295 (sometimes approximate) line number.
296
297 The optional \var{module} argument provides the module to be tested. It
298 can be a module object or a (possibly dotted) module name. If not
Fred Drake8836e562003-07-17 15:22:47 +0000299 specified, the module calling this function is used.
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000300
301 Example using one of the many ways that the \refmodule{unittest} module
302 can use a \class{TestSuite}:
303
304 \begin{verbatim}
305 import unittest
306 import doctest
307 import my_module_with_doctests
308
309 suite = doctest.DocTestSuite(my_module_with_doctests)
310 runner = unittest.TextTestRunner()
311 runner.run(suite)
312 \end{verbatim}
313
314 \versionadded{2.3}
Fred Drake8836e562003-07-17 15:22:47 +0000315 \warning{This function does not currently search \code{M.__test__}
Raymond Hettinger943277e2003-07-17 14:47:12 +0000316 and its search technique does not exactly match \function{testmod()} in
317 every detail. Future versions will bring the two into convergence.}
Raymond Hettinger92f21b12003-07-11 22:32:18 +0000318\end{funcdesc}
Tim Peters76882292001-02-17 05:58:44 +0000319
320
321\subsection{How are Docstring Examples Recognized?}
322
323In most cases a copy-and-paste of an interactive console session works fine
324--- just make sure the leading whitespace is rigidly consistent (you can mix
325tabs and spaces if you're too lazy to do it right, but doctest is not in
326the business of guessing what you think a tab means).
327
328\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000329>>> # comments are ignored
330>>> x = 12
331>>> x
33212
333>>> if x == 13:
334... print "yes"
335... else:
336... print "no"
337... print "NO"
338... print "NO!!!"
339...
340no
341NO
342NO!!!
343>>>
Tim Peters76882292001-02-17 05:58:44 +0000344\end{verbatim}
345
Fred Drake19f3c522001-02-22 23:15:05 +0000346Any expected output must immediately follow the final
347\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
348the expected output (if any) extends to the next \code{'>\code{>}>~'}
349or all-whitespace line.
Tim Peters76882292001-02-17 05:58:44 +0000350
351The fine print:
352
353\begin{itemize}
354
355\item Expected output cannot contain an all-whitespace line, since such a
356 line is taken to signal the end of expected output.
357
358\item Output to stdout is captured, but not output to stderr (exception
359 tracebacks are captured via a different means).
360
361\item If you continue a line via backslashing in an interactive session, or
362 for any other reason use a backslash, you need to double the backslash in
363 the docstring version. This is simply because you're in a string, and so
364 the backslash must be escaped for it to survive intact. Like:
365
366\begin{verbatim}
367>>> if "yes" == \\
368... "y" + \\
369... "es":
370... print 'yes'
371yes
372\end{verbatim}
373
Tim Petersf0768c82001-02-20 10:57:30 +0000374\item The starting column doesn't matter:
Tim Peters76882292001-02-17 05:58:44 +0000375
376\begin{verbatim}
Tim Petersc4089d82001-02-17 18:03:25 +0000377 >>> assert "Easy!"
378 >>> import math
379 >>> math.floor(1.9)
380 1.0
Tim Peters76882292001-02-17 05:58:44 +0000381\end{verbatim}
382
Fred Drake19f3c522001-02-22 23:15:05 +0000383and as many leading whitespace characters are stripped from the
384expected output as appeared in the initial \code{'>\code{>}>~'} line
385that triggered it.
Fred Drake7eb14632001-02-17 17:32:41 +0000386\end{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000387
388\subsection{Warnings}
389
390\begin{enumerate}
391
Tim Peters76882292001-02-17 05:58:44 +0000392\item \module{doctest} is serious about requiring exact matches in expected
393 output. If even a single character doesn't match, the test fails. This
394 will probably surprise you a few times, as you learn exactly what Python
395 does and doesn't guarantee about output. For example, when printing a
396 dict, Python doesn't guarantee that the key-value pairs will be printed
397 in any particular order, so a test like
398
399% Hey! What happened to Monty Python examples?
Tim Petersf0768c82001-02-20 10:57:30 +0000400% Tim: ask Guido -- it's his example!
Tim Peters76882292001-02-17 05:58:44 +0000401\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000402>>> foo()
403{"Hermione": "hippogryph", "Harry": "broomstick"}
404>>>
Tim Peters76882292001-02-17 05:58:44 +0000405\end{verbatim}
406
407is vulnerable! One workaround is to do
408
409\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000410>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
4111
412>>>
Tim Peters76882292001-02-17 05:58:44 +0000413\end{verbatim}
414
415instead. Another is to do
416
417\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000418>>> d = foo().items()
419>>> d.sort()
420>>> d
421[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
Tim Peters76882292001-02-17 05:58:44 +0000422\end{verbatim}
423
424There are others, but you get the idea.
425
426Another bad idea is to print things that embed an object address, like
427
428\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000429>>> id(1.0) # certain to fail some of the time
4307948648
431>>>
Tim Peters76882292001-02-17 05:58:44 +0000432\end{verbatim}
433
434Floating-point numbers are also subject to small output variations across
435platforms, because Python defers to the platform C library for float
436formatting, and C libraries vary widely in quality here.
437
438\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000439>>> 1./7 # risky
4400.14285714285714285
441>>> print 1./7 # safer
4420.142857142857
443>>> print round(1./7, 6) # much safer
4440.142857
Tim Peters76882292001-02-17 05:58:44 +0000445\end{verbatim}
446
447Numbers of the form \code{I/2.**J} are safe across all platforms, and I
448often contrive doctest examples to produce numbers of that form:
449
450\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000451>>> 3./4 # utterly safe
4520.75
Tim Peters76882292001-02-17 05:58:44 +0000453\end{verbatim}
454
455Simple fractions are also easier for people to understand, and that makes
456for better documentation.
457
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000458\item Be careful if you have code that must only execute once.
459
460If you have module-level code that must only execute once, a more foolproof
Fred Drakec1158352001-06-11 14:55:01 +0000461definition of \function{_test()} is
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000462
463\begin{verbatim}
464def _test():
465 import doctest, sys
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000466 doctest.testmod()
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000467\end{verbatim}
Tim Peters6ebe61f2003-06-27 20:48:05 +0000468
469\item WYSIWYG isn't always the case, starting in Python 2.3. The
Fred Drake5d2f5152003-06-28 03:09:06 +0000470 string form of boolean results changed from \code{'0'} and
471 \code{'1'} to \code{'False'} and \code{'True'} in Python 2.3.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000472 This makes it clumsy to write a doctest showing boolean results that
473 passes under multiple versions of Python. In Python 2.3, by default,
474 and as a special case, if an expected output block consists solely
Fred Drake5d2f5152003-06-28 03:09:06 +0000475 of \code{'0'} and the actual output block consists solely of
476 \code{'False'}, that's accepted as an exact match, and similarly for
477 \code{'1'} versus \code{'True'}. This behavior can be turned off by
Tim Peters6ebe61f2003-06-27 20:48:05 +0000478 passing the new (in 2.3) module constant
479 \constant{DONT_ACCEPT_TRUE_FOR_1} as the value of \function{testmod()}'s
480 new (in 2.3) optional \var{optionflags} argument. Some years after
481 the integer spellings of booleans are history, this hack will
482 probably be removed again.
483
Fred Drakec1158352001-06-11 14:55:01 +0000484\end{enumerate}
485
Tim Peters76882292001-02-17 05:58:44 +0000486
487\subsection{Soapbox}
488
489The first word in doctest is "doc", and that's why the author wrote
490doctest: to keep documentation up to date. It so happens that doctest
491makes a pleasant unit testing environment, but that's not its primary
492purpose.
493
494Choose docstring examples with care. There's an art to this that needs to
495be learned --- it may not be natural at first. Examples should add genuine
496value to the documentation. A good example can often be worth many words.
497If possible, show just a few normal cases, show endcases, show interesting
498subtle cases, and show an example of each kind of exception that can be
499raised. You're probably testing for endcases and subtle cases anyway in an
500interactive shell: doctest wants to make it as easy as possible to capture
501those sessions, and will verify they continue to work as designed forever
502after.
503
504If done with care, the examples will be invaluable for your users, and will
505pay back the time it takes to collect them many times over as the years go
506by and "things change". I'm still amazed at how often one of my doctest
507examples stops working after a "harmless" change.
508
509For exhaustive testing, or testing boring cases that add no value to the
Fred Drake7eb14632001-02-17 17:32:41 +0000510docs, define a \code{__test__} dict instead. That's what it's for.