blob: 9a795e949b36b58340eb7639fe4361c1103adbcb [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")
68 if n+1 == n: # e.g., 1e300
69 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
156pass M to \function{testmod}; in this case, it will test the current
157module.
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 Drake7eb14632001-02-17 17:32:41 +0000176and a detailed report of all examples tried is printed to \code{stdout},
Tim Peters76882292001-02-17 05:58:44 +0000177along with assorted summaries at the end.
178
179You can force verbose mode by passing \code{verbose=1} to testmod, or
180prohibit it by passing \code{verbose=0}. In either of those cases,
Fred Drake7eb14632001-02-17 17:32:41 +0000181\code{sys.argv} is not examined by testmod.
Tim Peters76882292001-02-17 05:58:44 +0000182
Fred Drake7eb14632001-02-17 17:32:41 +0000183In any case, testmod returns a 2-tuple of ints \code{(\var{f},
184\var{t})}, where \var{f} is the number of docstring examples that
185failed and \var{t} is the total number of docstring examples
186attempted.
Tim Peters76882292001-02-17 05:58:44 +0000187
188\subsection{Which Docstrings Are Examined?}
189
190See \file{docstring.py} for all the details. They're unsurprising: the
191module docstring, and all function, class and method docstrings are
192searched, with the exception of docstrings attached to objects with private
Tim Peters0481d242001-10-02 21:01:22 +0000193names. Objects imported into the module are not searched.
Tim Peters76882292001-02-17 05:58:44 +0000194
Fred Drake7eb14632001-02-17 17:32:41 +0000195In addition, if \code{M.__test__} exists and "is true", it must be a
196dict, and each entry maps a (string) name to a function object, class
197object, or string. Function and class object docstrings found from
198\code{M.__test__} are searched even if the name is private, and
199strings are searched directly as if they were docstrings. In output,
200a key \code{K} in \code{M.__test__} appears with name
Tim Peters76882292001-02-17 05:58:44 +0000201
202\begin{verbatim}
203 <name of M>.__test__.K
204\end{verbatim}
205
206Any classes found are recursively searched similarly, to test docstrings in
207their contained methods and nested classes. While private names reached
208from \module{M}'s globals are skipped, all names reached from
Fred Drake7eb14632001-02-17 17:32:41 +0000209\code{M.__test__} are searched.
Tim Peters76882292001-02-17 05:58:44 +0000210
211\subsection{What's the Execution Context?}
212
213By default, each time testmod finds a docstring to test, it uses a
Fred Drake4cf12272001-04-05 18:31:27 +0000214\emph{copy} of \module{M}'s globals, so that running tests on a module
Tim Peters76882292001-02-17 05:58:44 +0000215doesn't change the module's real globals, and so that one test in
216\module{M} can't leave behind crumbs that accidentally allow another test
217to work. This means examples can freely use any names defined at top-level
Tim Peters0481d242001-10-02 21:01:22 +0000218in \module{M}, and names defined earlier in the docstring being run.
Tim Peters76882292001-02-17 05:58:44 +0000219
220You can force use of your own dict as the execution context by passing
221\code{globs=your_dict} to \function{testmod()} instead. Presumably this
Fred Drake7eb14632001-02-17 17:32:41 +0000222would be a copy of \code{M.__dict__} merged with the globals from other
Tim Peters76882292001-02-17 05:58:44 +0000223imported modules.
224
225\subsection{What About Exceptions?}
226
227No problem, as long as the only output generated by the example is the
228traceback itself. For example:
229
230\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000231>>> [1, 2, 3].remove(42)
232Traceback (most recent call last):
233 File "<stdin>", line 1, in ?
234ValueError: list.remove(x): x not in list
235>>>
Tim Peters76882292001-02-17 05:58:44 +0000236\end{verbatim}
237
238Note that only the exception type and value are compared (specifically,
Fred Drake7eb14632001-02-17 17:32:41 +0000239only the last line in the traceback). The various ``File'' lines in
Tim Peters76882292001-02-17 05:58:44 +0000240between can be left out (unless they add significantly to the documentation
241value of the example).
242
243\subsection{Advanced Usage}
244
245\function{testmod()} actually creates a local instance of class
Fred Drake7eb14632001-02-17 17:32:41 +0000246\class{Tester}, runs appropriate methods of that class, and merges
247the results into global \class{Tester} instance \code{master}.
Tim Peters76882292001-02-17 05:58:44 +0000248
Fred Drake7eb14632001-02-17 17:32:41 +0000249You can create your own instances of \class{Tester}, and so build your
250own policies, or even run methods of \code{master} directly. See
251\code{Tester.__doc__} for details.
Tim Peters76882292001-02-17 05:58:44 +0000252
253
254\subsection{How are Docstring Examples Recognized?}
255
256In most cases a copy-and-paste of an interactive console session works fine
257--- just make sure the leading whitespace is rigidly consistent (you can mix
258tabs and spaces if you're too lazy to do it right, but doctest is not in
259the business of guessing what you think a tab means).
260
261\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000262>>> # comments are ignored
263>>> x = 12
264>>> x
26512
266>>> if x == 13:
267... print "yes"
268... else:
269... print "no"
270... print "NO"
271... print "NO!!!"
272...
273no
274NO
275NO!!!
276>>>
Tim Peters76882292001-02-17 05:58:44 +0000277\end{verbatim}
278
Fred Drake19f3c522001-02-22 23:15:05 +0000279Any expected output must immediately follow the final
280\code{'>\code{>}>~'} or \code{'...~'} line containing the code, and
281the expected output (if any) extends to the next \code{'>\code{>}>~'}
282or all-whitespace line.
Tim Peters76882292001-02-17 05:58:44 +0000283
284The fine print:
285
286\begin{itemize}
287
288\item Expected output cannot contain an all-whitespace line, since such a
289 line is taken to signal the end of expected output.
290
291\item Output to stdout is captured, but not output to stderr (exception
292 tracebacks are captured via a different means).
293
294\item If you continue a line via backslashing in an interactive session, or
295 for any other reason use a backslash, you need to double the backslash in
296 the docstring version. This is simply because you're in a string, and so
297 the backslash must be escaped for it to survive intact. Like:
298
299\begin{verbatim}
300>>> if "yes" == \\
301... "y" + \\
302... "es":
303... print 'yes'
304yes
305\end{verbatim}
306
Tim Petersf0768c82001-02-20 10:57:30 +0000307\item The starting column doesn't matter:
Tim Peters76882292001-02-17 05:58:44 +0000308
309\begin{verbatim}
Tim Petersc4089d82001-02-17 18:03:25 +0000310 >>> assert "Easy!"
311 >>> import math
312 >>> math.floor(1.9)
313 1.0
Tim Peters76882292001-02-17 05:58:44 +0000314\end{verbatim}
315
Fred Drake19f3c522001-02-22 23:15:05 +0000316and as many leading whitespace characters are stripped from the
317expected output as appeared in the initial \code{'>\code{>}>~'} line
318that triggered it.
Fred Drake7eb14632001-02-17 17:32:41 +0000319\end{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000320
321\subsection{Warnings}
322
323\begin{enumerate}
324
Tim Peters76882292001-02-17 05:58:44 +0000325\item \module{doctest} is serious about requiring exact matches in expected
326 output. If even a single character doesn't match, the test fails. This
327 will probably surprise you a few times, as you learn exactly what Python
328 does and doesn't guarantee about output. For example, when printing a
329 dict, Python doesn't guarantee that the key-value pairs will be printed
330 in any particular order, so a test like
331
332% Hey! What happened to Monty Python examples?
Tim Petersf0768c82001-02-20 10:57:30 +0000333% Tim: ask Guido -- it's his example!
Tim Peters76882292001-02-17 05:58:44 +0000334\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000335>>> foo()
336{"Hermione": "hippogryph", "Harry": "broomstick"}
337>>>
Tim Peters76882292001-02-17 05:58:44 +0000338\end{verbatim}
339
340is vulnerable! One workaround is to do
341
342\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000343>>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
3441
345>>>
Tim Peters76882292001-02-17 05:58:44 +0000346\end{verbatim}
347
348instead. Another is to do
349
350\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000351>>> d = foo().items()
352>>> d.sort()
353>>> d
354[('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
Tim Peters76882292001-02-17 05:58:44 +0000355\end{verbatim}
356
357There are others, but you get the idea.
358
359Another bad idea is to print things that embed an object address, like
360
361\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000362>>> id(1.0) # certain to fail some of the time
3637948648
364>>>
Tim Peters76882292001-02-17 05:58:44 +0000365\end{verbatim}
366
367Floating-point numbers are also subject to small output variations across
368platforms, because Python defers to the platform C library for float
369formatting, and C libraries vary widely in quality here.
370
371\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000372>>> 1./7 # risky
3730.14285714285714285
374>>> print 1./7 # safer
3750.142857142857
376>>> print round(1./7, 6) # much safer
3770.142857
Tim Peters76882292001-02-17 05:58:44 +0000378\end{verbatim}
379
380Numbers of the form \code{I/2.**J} are safe across all platforms, and I
381often contrive doctest examples to produce numbers of that form:
382
383\begin{verbatim}
Fred Drake19f3c522001-02-22 23:15:05 +0000384>>> 3./4 # utterly safe
3850.75
Tim Peters76882292001-02-17 05:58:44 +0000386\end{verbatim}
387
388Simple fractions are also easier for people to understand, and that makes
389for better documentation.
390
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000391\item Be careful if you have code that must only execute once.
392
393If you have module-level code that must only execute once, a more foolproof
Fred Drakec1158352001-06-11 14:55:01 +0000394definition of \function{_test()} is
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000395
396\begin{verbatim}
397def _test():
398 import doctest, sys
Martin v. Löwis4581cfa2002-11-22 08:23:09 +0000399 doctest.testmod()
Skip Montanaro1dc98c42001-06-08 14:40:28 +0000400\end{verbatim}
Fred Drakec1158352001-06-11 14:55:01 +0000401\end{enumerate}
402
Tim Peters76882292001-02-17 05:58:44 +0000403
404\subsection{Soapbox}
405
406The first word in doctest is "doc", and that's why the author wrote
407doctest: to keep documentation up to date. It so happens that doctest
408makes a pleasant unit testing environment, but that's not its primary
409purpose.
410
411Choose docstring examples with care. There's an art to this that needs to
412be learned --- it may not be natural at first. Examples should add genuine
413value to the documentation. A good example can often be worth many words.
414If possible, show just a few normal cases, show endcases, show interesting
415subtle cases, and show an example of each kind of exception that can be
416raised. You're probably testing for endcases and subtle cases anyway in an
417interactive shell: doctest wants to make it as easy as possible to capture
418those sessions, and will verify they continue to work as designed forever
419after.
420
421If done with care, the examples will be invaluable for your users, and will
422pay back the time it takes to collect them many times over as the years go
423by and "things change". I'm still amazed at how often one of my doctest
424examples stops working after a "harmless" change.
425
426For exhaustive testing, or testing boring cases that add no value to the
Fred Drake7eb14632001-02-17 17:32:41 +0000427docs, define a \code{__test__} dict instead. That's what it's for.