blob: fc95a3125ed1fb96fc0555cdd1cf04be44d0d81d [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
155Then running the module as a script causes the examples in the docstrings
156to get executed and verified:
157
158\begin{verbatim}
159python M.py
160\end{verbatim}
161
162This won't display anything unless an example fails, in which case the
163failing example(s) and the cause(s) of the failure(s) are printed to stdout,
Fred Drake7eb14632001-02-17 17:32:41 +0000164and the final line of output is \code{'Test failed.'}.
Tim Peters76882292001-02-17 05:58:44 +0000165
Fred Drake7eb14632001-02-17 17:32:41 +0000166Run it with the \programopt{-v} switch instead:
Tim Peters76882292001-02-17 05:58:44 +0000167
168\begin{verbatim}
169python M.py -v
170\end{verbatim}
171
Fred Drake7eb14632001-02-17 17:32:41 +0000172and a detailed report of all examples tried is printed to \code{stdout},
Tim Peters76882292001-02-17 05:58:44 +0000173along with assorted summaries at the end.
174
175You can force verbose mode by passing \code{verbose=1} to testmod, or
176prohibit it by passing \code{verbose=0}. In either of those cases,
Fred Drake7eb14632001-02-17 17:32:41 +0000177\code{sys.argv} is not examined by testmod.
Tim Peters76882292001-02-17 05:58:44 +0000178
Fred Drake7eb14632001-02-17 17:32:41 +0000179In any case, testmod returns a 2-tuple of ints \code{(\var{f},
180\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
184\subsection{Which Docstrings Are Examined?}
185
186See \file{docstring.py} for all the details. They're unsurprising: the
187module docstring, and all function, class and method docstrings are
188searched, with the exception of docstrings attached to objects with private
189names.
190
Fred Drake7eb14632001-02-17 17:32:41 +0000191In addition, if \code{M.__test__} exists and "is true", it must be a
192dict, and each entry maps a (string) name to a function object, class
193object, or string. Function and class object docstrings found from
194\code{M.__test__} are searched even if the name is private, and
195strings are searched directly as if they were docstrings. In output,
196a key \code{K} in \code{M.__test__} appears with name
Tim Peters76882292001-02-17 05:58:44 +0000197
198\begin{verbatim}
199 <name of M>.__test__.K
200\end{verbatim}
201
202Any classes found are recursively searched similarly, to test docstrings in
203their contained methods and nested classes. While private names reached
204from \module{M}'s globals are skipped, all names reached from
Fred Drake7eb14632001-02-17 17:32:41 +0000205\code{M.__test__} are searched.
Tim Peters76882292001-02-17 05:58:44 +0000206
207\subsection{What's the Execution Context?}
208
209By default, each time testmod finds a docstring to test, it uses a
210{\em copy} of \module{M}'s globals, so that running tests on a module
211doesn't change the module's real globals, and so that one test in
212\module{M} can't leave behind crumbs that accidentally allow another test
213to work. This means examples can freely use any names defined at top-level
214in \module{M}, and names defined earlier in the docstring being run. It
215also means that sloppy imports (see below) can cause examples in external
216docstrings to use globals inappropriate for them.
217
218You can force use of your own dict as the execution context by passing
219\code{globs=your_dict} to \function{testmod()} instead. Presumably this
Fred Drake7eb14632001-02-17 17:32:41 +0000220would be a copy of \code{M.__dict__} merged with the globals from other
Tim Peters76882292001-02-17 05:58:44 +0000221imported modules.
222
223\subsection{What About Exceptions?}
224
225No problem, as long as the only output generated by the example is the
226traceback itself. For example:
227
228\begin{verbatim}
229 >>> [1, 2, 3].remove(42)
230 Traceback (most recent call last):
231 File "<stdin>", line 1, in ?
232 ValueError: list.remove(x): x not in list
233 >>>
234\end{verbatim}
235
236Note that only the exception type and value are compared (specifically,
Fred Drake7eb14632001-02-17 17:32:41 +0000237only the last line in the traceback). The various ``File'' lines in
Tim Peters76882292001-02-17 05:58:44 +0000238between can be left out (unless they add significantly to the documentation
239value of the example).
240
241\subsection{Advanced Usage}
242
243\function{testmod()} actually creates a local instance of class
Fred Drake7eb14632001-02-17 17:32:41 +0000244\class{Tester}, runs appropriate methods of that class, and merges
245the results into global \class{Tester} instance \code{master}.
Tim Peters76882292001-02-17 05:58:44 +0000246
Fred Drake7eb14632001-02-17 17:32:41 +0000247You can create your own instances of \class{Tester}, and so build your
248own policies, or even run methods of \code{master} directly. See
249\code{Tester.__doc__} for details.
Tim Peters76882292001-02-17 05:58:44 +0000250
251
252\subsection{How are Docstring Examples Recognized?}
253
254In most cases a copy-and-paste of an interactive console session works fine
255--- just make sure the leading whitespace is rigidly consistent (you can mix
256tabs and spaces if you're too lazy to do it right, but doctest is not in
257the business of guessing what you think a tab means).
258
259\begin{verbatim}
260 >>> # comments are ignored
261 >>> x = 12
262 >>> x
263 12
264 >>> if x == 13:
265 ... print "yes"
266 ... else:
267 ... print "no"
268 ... print "NO"
269 ... print "NO!!!"
270 ...
271 no
272 NO
273 NO!!!
274 >>>
275\end{verbatim}
276
277Any expected output must immediately follow the final \code{">>>"} or
278\code{"..."} line containing the code, and the expected output (if any)
Fred Drake7eb14632001-02-17 17:32:41 +0000279extends to the next \code{">>>"} or all-whitespace line.
Tim Peters76882292001-02-17 05:58:44 +0000280
281The fine print:
282
283\begin{itemize}
284
285\item Expected output cannot contain an all-whitespace line, since such a
286 line is taken to signal the end of expected output.
287
288\item Output to stdout is captured, but not output to stderr (exception
289 tracebacks are captured via a different means).
290
291\item If you continue a line via backslashing in an interactive session, or
292 for any other reason use a backslash, you need to double the backslash in
293 the docstring version. This is simply because you're in a string, and so
294 the backslash must be escaped for it to survive intact. Like:
295
296\begin{verbatim}
297>>> if "yes" == \\
298... "y" + \\
299... "es":
300... print 'yes'
301yes
302\end{verbatim}
303
304The starting column doesn't matter:
305
306\begin{verbatim}
307>>> assert "Easy!"
Fred Drake7eb14632001-02-17 17:32:41 +0000308>>> import math
309>>> math.floor(1.9)
3101.0
Tim Peters76882292001-02-17 05:58:44 +0000311\end{verbatim}
312
313and as many leading whitespace characters are stripped from the expected
314output as appeared in the initial ">>>" line that triggered it.
Fred Drake7eb14632001-02-17 17:32:41 +0000315\end{itemize}
Tim Peters76882292001-02-17 05:58:44 +0000316
317\subsection{Warnings}
318
319\begin{enumerate}
320
321\item Sloppy imports can cause trouble; e.g., if you do
322
323\begin{verbatim}
324from XYZ import XYZclass
325\end{verbatim}
326
Fred Drake7eb14632001-02-17 17:32:41 +0000327then \class{XYZclass} is a name in \code{M.__dict__} too, and doctest
328has no way to know that \class{XYZclass} wasn't \emph{defined} in
329\module{M}. So it may try to execute the examples in
330\class{XYZclass}'s docstring, and those in turn may require a
331different set of globals to work correctly. I prefer to do
332``\code{import *}''-friendly imports, a la
Tim Peters76882292001-02-17 05:58:44 +0000333
334\begin{verbatim}
335from XYZ import XYZclass as _XYZclass
336\end{verbatim}
337
338and then the leading underscore makes \class{_XYZclass} a private name so
339testmod skips it by default. Other approaches are described in
340\file{doctest.py}.
341
342\item \module{doctest} is serious about requiring exact matches in expected
343 output. If even a single character doesn't match, the test fails. This
344 will probably surprise you a few times, as you learn exactly what Python
345 does and doesn't guarantee about output. For example, when printing a
346 dict, Python doesn't guarantee that the key-value pairs will be printed
347 in any particular order, so a test like
348
349% Hey! What happened to Monty Python examples?
350\begin{verbatim}
351 >>> foo()
352 {"Hermione": "hippogryph", "Harry": "broomstick"}
353 >>>
354\end{verbatim}
355
356is vulnerable! One workaround is to do
357
358\begin{verbatim}
359 >>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
360 1
361 >>>
362\end{verbatim}
363
364instead. Another is to do
365
366\begin{verbatim}
367 >>> d = foo().items()
368 >>> d.sort()
369 >>> d
370 [('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
371\end{verbatim}
372
373There are others, but you get the idea.
374
375Another bad idea is to print things that embed an object address, like
376
377\begin{verbatim}
378 >>> id(1.0) # certain to fail some of the time
379 7948648
380 >>>
381\end{verbatim}
382
383Floating-point numbers are also subject to small output variations across
384platforms, because Python defers to the platform C library for float
385formatting, and C libraries vary widely in quality here.
386
387\begin{verbatim}
388 >>> 1./7 # risky
389 0.14285714285714285
390 >>> print 1./7 # safer
391 0.142857142857
392 >>> print round(1./7, 6) # much safer
393 0.142857
394\end{verbatim}
395
396Numbers of the form \code{I/2.**J} are safe across all platforms, and I
397often contrive doctest examples to produce numbers of that form:
398
399\begin{verbatim}
400 >>> 3./4 # utterly safe
401 0.75
402\end{verbatim}
403
404Simple fractions are also easier for people to understand, and that makes
405for better documentation.
Fred Drake7eb14632001-02-17 17:32:41 +0000406\end{enumerate}
Tim Peters76882292001-02-17 05:58:44 +0000407
408
409\subsection{Soapbox}
410
411The first word in doctest is "doc", and that's why the author wrote
412doctest: to keep documentation up to date. It so happens that doctest
413makes a pleasant unit testing environment, but that's not its primary
414purpose.
415
416Choose docstring examples with care. There's an art to this that needs to
417be learned --- it may not be natural at first. Examples should add genuine
418value to the documentation. A good example can often be worth many words.
419If possible, show just a few normal cases, show endcases, show interesting
420subtle cases, and show an example of each kind of exception that can be
421raised. You're probably testing for endcases and subtle cases anyway in an
422interactive shell: doctest wants to make it as easy as possible to capture
423those sessions, and will verify they continue to work as designed forever
424after.
425
426If done with care, the examples will be invaluable for your users, and will
427pay back the time it takes to collect them many times over as the years go
428by and "things change". I'm still amazed at how often one of my doctest
429examples stops working after a "harmless" change.
430
431For exhaustive testing, or testing boring cases that add no value to the
Fred Drake7eb14632001-02-17 17:32:41 +0000432docs, define a \code{__test__} dict instead. That's what it's for.