1 | \section{\module{doctest} ---
|
---|
2 | Test interactive Python examples}
|
---|
3 |
|
---|
4 | \declaremodule{standard}{doctest}
|
---|
5 | \moduleauthor{Tim Peters}{tim@python.org}
|
---|
6 | \sectionauthor{Tim Peters}{tim@python.org}
|
---|
7 | \sectionauthor{Moshe Zadka}{moshez@debian.org}
|
---|
8 | \sectionauthor{Edward Loper}{edloper@users.sourceforge.net}
|
---|
9 |
|
---|
10 | \modulesynopsis{A framework for verifying interactive Python examples.}
|
---|
11 |
|
---|
12 | The \refmodule{doctest} module searches for pieces of text that look like
|
---|
13 | interactive Python sessions, and then executes those sessions to
|
---|
14 | verify that they work exactly as shown. There are several common ways to
|
---|
15 | use doctest:
|
---|
16 |
|
---|
17 | \begin{itemize}
|
---|
18 | \item To check that a module's docstrings are up-to-date by verifying
|
---|
19 | that all interactive examples still work as documented.
|
---|
20 | \item To perform regression testing by verifying that interactive
|
---|
21 | examples from a test file or a test object work as expected.
|
---|
22 | \item To write tutorial documentation for a package, liberally
|
---|
23 | illustrated with input-output examples. Depending on whether
|
---|
24 | the examples or the expository text are emphasized, this has
|
---|
25 | the flavor of "literate testing" or "executable documentation".
|
---|
26 | \end{itemize}
|
---|
27 |
|
---|
28 | Here's a complete but small example module:
|
---|
29 |
|
---|
30 | \begin{verbatim}
|
---|
31 | """
|
---|
32 | This is the "example" module.
|
---|
33 |
|
---|
34 | The example module supplies one function, factorial(). For example,
|
---|
35 |
|
---|
36 | >>> factorial(5)
|
---|
37 | 120
|
---|
38 | """
|
---|
39 |
|
---|
40 | def factorial(n):
|
---|
41 | """Return the factorial of n, an exact integer >= 0.
|
---|
42 |
|
---|
43 | If the result is small enough to fit in an int, return an int.
|
---|
44 | Else return a long.
|
---|
45 |
|
---|
46 | >>> [factorial(n) for n in range(6)]
|
---|
47 | [1, 1, 2, 6, 24, 120]
|
---|
48 | >>> [factorial(long(n)) for n in range(6)]
|
---|
49 | [1, 1, 2, 6, 24, 120]
|
---|
50 | >>> factorial(30)
|
---|
51 | 265252859812191058636308480000000L
|
---|
52 | >>> factorial(30L)
|
---|
53 | 265252859812191058636308480000000L
|
---|
54 | >>> factorial(-1)
|
---|
55 | Traceback (most recent call last):
|
---|
56 | ...
|
---|
57 | ValueError: n must be >= 0
|
---|
58 |
|
---|
59 | Factorials of floats are OK, but the float must be an exact integer:
|
---|
60 | >>> factorial(30.1)
|
---|
61 | Traceback (most recent call last):
|
---|
62 | ...
|
---|
63 | ValueError: n must be exact integer
|
---|
64 | >>> factorial(30.0)
|
---|
65 | 265252859812191058636308480000000L
|
---|
66 |
|
---|
67 | It must also not be ridiculously large:
|
---|
68 | >>> factorial(1e100)
|
---|
69 | Traceback (most recent call last):
|
---|
70 | ...
|
---|
71 | OverflowError: n too large
|
---|
72 | """
|
---|
73 |
|
---|
74 | \end{verbatim}
|
---|
75 | % allow LaTeX to break here.
|
---|
76 | \begin{verbatim}
|
---|
77 |
|
---|
78 | import math
|
---|
79 | if not n >= 0:
|
---|
80 | raise ValueError("n must be >= 0")
|
---|
81 | if math.floor(n) != n:
|
---|
82 | raise ValueError("n must be exact integer")
|
---|
83 | if n+1 == n: # catch a value like 1e300
|
---|
84 | raise OverflowError("n too large")
|
---|
85 | result = 1
|
---|
86 | factor = 2
|
---|
87 | while factor <= n:
|
---|
88 | result *= factor
|
---|
89 | factor += 1
|
---|
90 | return result
|
---|
91 |
|
---|
92 | def _test():
|
---|
93 | import doctest
|
---|
94 | doctest.testmod()
|
---|
95 |
|
---|
96 | if __name__ == "__main__":
|
---|
97 | _test()
|
---|
98 | \end{verbatim}
|
---|
99 |
|
---|
100 | If you run \file{example.py} directly from the command line,
|
---|
101 | \refmodule{doctest} works its magic:
|
---|
102 |
|
---|
103 | \begin{verbatim}
|
---|
104 | $ python example.py
|
---|
105 | $
|
---|
106 | \end{verbatim}
|
---|
107 |
|
---|
108 | There's no output! That's normal, and it means all the examples
|
---|
109 | worked. Pass \programopt{-v} to the script, and \refmodule{doctest}
|
---|
110 | prints a detailed log of what it's trying, and prints a summary at the
|
---|
111 | end:
|
---|
112 |
|
---|
113 | \begin{verbatim}
|
---|
114 | $ python example.py -v
|
---|
115 | Trying:
|
---|
116 | factorial(5)
|
---|
117 | Expecting:
|
---|
118 | 120
|
---|
119 | ok
|
---|
120 | Trying:
|
---|
121 | [factorial(n) for n in range(6)]
|
---|
122 | Expecting:
|
---|
123 | [1, 1, 2, 6, 24, 120]
|
---|
124 | ok
|
---|
125 | Trying:
|
---|
126 | [factorial(long(n)) for n in range(6)]
|
---|
127 | Expecting:
|
---|
128 | [1, 1, 2, 6, 24, 120]
|
---|
129 | ok
|
---|
130 | \end{verbatim}
|
---|
131 |
|
---|
132 | And so on, eventually ending with:
|
---|
133 |
|
---|
134 | \begin{verbatim}
|
---|
135 | Trying:
|
---|
136 | factorial(1e100)
|
---|
137 | Expecting:
|
---|
138 | Traceback (most recent call last):
|
---|
139 | ...
|
---|
140 | OverflowError: n too large
|
---|
141 | ok
|
---|
142 | 1 items had no tests:
|
---|
143 | __main__._test
|
---|
144 | 2 items passed all tests:
|
---|
145 | 1 tests in __main__
|
---|
146 | 8 tests in __main__.factorial
|
---|
147 | 9 tests in 3 items.
|
---|
148 | 9 passed and 0 failed.
|
---|
149 | Test passed.
|
---|
150 | $
|
---|
151 | \end{verbatim}
|
---|
152 |
|
---|
153 | That's all you need to know to start making productive use of
|
---|
154 | \refmodule{doctest}! Jump in. The following sections provide full
|
---|
155 | details. Note that there are many examples of doctests in
|
---|
156 | the standard Python test suite and libraries. Especially useful examples
|
---|
157 | can be found in the standard test file \file{Lib/test/test_doctest.py}.
|
---|
158 |
|
---|
159 | \subsection{Simple Usage: Checking Examples in
|
---|
160 | Docstrings\label{doctest-simple-testmod}}
|
---|
161 |
|
---|
162 | The simplest way to start using doctest (but not necessarily the way
|
---|
163 | you'll continue to do it) is to end each module \module{M} with:
|
---|
164 |
|
---|
165 | \begin{verbatim}
|
---|
166 | def _test():
|
---|
167 | import doctest
|
---|
168 | doctest.testmod()
|
---|
169 |
|
---|
170 | if __name__ == "__main__":
|
---|
171 | _test()
|
---|
172 | \end{verbatim}
|
---|
173 |
|
---|
174 | \refmodule{doctest} then examines docstrings in module \module{M}.
|
---|
175 |
|
---|
176 | Running the module as a script causes the examples in the docstrings
|
---|
177 | to get executed and verified:
|
---|
178 |
|
---|
179 | \begin{verbatim}
|
---|
180 | python M.py
|
---|
181 | \end{verbatim}
|
---|
182 |
|
---|
183 | This won't display anything unless an example fails, in which case the
|
---|
184 | failing example(s) and the cause(s) of the failure(s) are printed to stdout,
|
---|
185 | and the final line of output is
|
---|
186 | \samp{***Test Failed*** \var{N} failures.}, where \var{N} is the
|
---|
187 | number of examples that failed.
|
---|
188 |
|
---|
189 | Run it with the \programopt{-v} switch instead:
|
---|
190 |
|
---|
191 | \begin{verbatim}
|
---|
192 | python M.py -v
|
---|
193 | \end{verbatim}
|
---|
194 |
|
---|
195 | and a detailed report of all examples tried is printed to standard
|
---|
196 | output, along with assorted summaries at the end.
|
---|
197 |
|
---|
198 | You can force verbose mode by passing \code{verbose=True} to
|
---|
199 | \function{testmod()}, or
|
---|
200 | prohibit it by passing \code{verbose=False}. In either of those cases,
|
---|
201 | \code{sys.argv} is not examined by \function{testmod()} (so passing
|
---|
202 | \programopt{-v} or not has no effect).
|
---|
203 |
|
---|
204 | For more information on \function{testmod()}, see
|
---|
205 | section~\ref{doctest-basic-api}.
|
---|
206 |
|
---|
207 | \subsection{Simple Usage: Checking Examples in a Text
|
---|
208 | File\label{doctest-simple-testfile}}
|
---|
209 |
|
---|
210 | Another simple application of doctest is testing interactive examples
|
---|
211 | in a text file. This can be done with the \function{testfile()}
|
---|
212 | function:
|
---|
213 |
|
---|
214 | \begin{verbatim}
|
---|
215 | import doctest
|
---|
216 | doctest.testfile("example.txt")
|
---|
217 | \end{verbatim}
|
---|
218 |
|
---|
219 | That short script executes and verifies any interactive Python
|
---|
220 | examples contained in the file \file{example.txt}. The file content
|
---|
221 | is treated as if it were a single giant docstring; the file doesn't
|
---|
222 | need to contain a Python program! For example, perhaps \file{example.txt}
|
---|
223 | contains this:
|
---|
224 |
|
---|
225 | \begin{verbatim}
|
---|
226 | The ``example`` module
|
---|
227 | ======================
|
---|
228 |
|
---|
229 | Using ``factorial``
|
---|
230 | -------------------
|
---|
231 |
|
---|
232 | This is an example text file in reStructuredText format. First import
|
---|
233 | ``factorial`` from the ``example`` module:
|
---|
234 |
|
---|
235 | >>> from example import factorial
|
---|
236 |
|
---|
237 | Now use it:
|
---|
238 |
|
---|
239 | >>> factorial(6)
|
---|
240 | 120
|
---|
241 | \end{verbatim}
|
---|
242 |
|
---|
243 | Running \code{doctest.testfile("example.txt")} then finds the error
|
---|
244 | in this documentation:
|
---|
245 |
|
---|
246 | \begin{verbatim}
|
---|
247 | File "./example.txt", line 14, in example.txt
|
---|
248 | Failed example:
|
---|
249 | factorial(6)
|
---|
250 | Expected:
|
---|
251 | 120
|
---|
252 | Got:
|
---|
253 | 720
|
---|
254 | \end{verbatim}
|
---|
255 |
|
---|
256 | As with \function{testmod()}, \function{testfile()} won't display anything
|
---|
257 | unless an example fails. If an example does fail, then the failing
|
---|
258 | example(s) and the cause(s) of the failure(s) are printed to stdout, using
|
---|
259 | the same format as \function{testmod()}.
|
---|
260 |
|
---|
261 | By default, \function{testfile()} looks for files in the calling
|
---|
262 | module's directory. See section~\ref{doctest-basic-api} for a
|
---|
263 | description of the optional arguments that can be used to tell it to
|
---|
264 | look for files in other locations.
|
---|
265 |
|
---|
266 | Like \function{testmod()}, \function{testfile()}'s verbosity can be
|
---|
267 | set with the \programopt{-v} command-line switch or with the optional
|
---|
268 | keyword argument \var{verbose}.
|
---|
269 |
|
---|
270 | For more information on \function{testfile()}, see
|
---|
271 | section~\ref{doctest-basic-api}.
|
---|
272 |
|
---|
273 | \subsection{How It Works\label{doctest-how-it-works}}
|
---|
274 |
|
---|
275 | This section examines in detail how doctest works: which docstrings it
|
---|
276 | looks at, how it finds interactive examples, what execution context it
|
---|
277 | uses, how it handles exceptions, and how option flags can be used to
|
---|
278 | control its behavior. This is the information that you need to know
|
---|
279 | to write doctest examples; for information about actually running
|
---|
280 | doctest on these examples, see the following sections.
|
---|
281 |
|
---|
282 | \subsubsection{Which Docstrings Are Examined?\label{doctest-which-docstrings}}
|
---|
283 |
|
---|
284 | The module docstring, and all function, class and method docstrings are
|
---|
285 | searched. Objects imported into the module are not searched.
|
---|
286 |
|
---|
287 | In addition, if \code{M.__test__} exists and "is true", it must be a
|
---|
288 | dict, and each entry maps a (string) name to a function object, class
|
---|
289 | object, or string. Function and class object docstrings found from
|
---|
290 | \code{M.__test__} are searched, and strings are treated as if they
|
---|
291 | were docstrings. In output, a key \code{K} in \code{M.__test__} appears
|
---|
292 | with name
|
---|
293 |
|
---|
294 | \begin{verbatim}
|
---|
295 | <name of M>.__test__.K
|
---|
296 | \end{verbatim}
|
---|
297 |
|
---|
298 | Any classes found are recursively searched similarly, to test docstrings in
|
---|
299 | their contained methods and nested classes.
|
---|
300 |
|
---|
301 | \versionchanged[A "private name" concept is deprecated and no longer
|
---|
302 | documented]{2.4}
|
---|
303 |
|
---|
304 | \subsubsection{How are Docstring Examples
|
---|
305 | Recognized?\label{doctest-finding-examples}}
|
---|
306 |
|
---|
307 | In most cases a copy-and-paste of an interactive console session works
|
---|
308 | fine, but doctest isn't trying to do an exact emulation of any specific
|
---|
309 | Python shell. All hard tab characters are expanded to spaces, using
|
---|
310 | 8-column tab stops. If you don't believe tabs should mean that, too
|
---|
311 | bad: don't use hard tabs, or write your own \class{DocTestParser}
|
---|
312 | class.
|
---|
313 |
|
---|
314 | \versionchanged[Expanding tabs to spaces is new; previous versions
|
---|
315 | tried to preserve hard tabs, with confusing results]{2.4}
|
---|
316 |
|
---|
317 | \begin{verbatim}
|
---|
318 | >>> # comments are ignored
|
---|
319 | >>> x = 12
|
---|
320 | >>> x
|
---|
321 | 12
|
---|
322 | >>> if x == 13:
|
---|
323 | ... print "yes"
|
---|
324 | ... else:
|
---|
325 | ... print "no"
|
---|
326 | ... print "NO"
|
---|
327 | ... print "NO!!!"
|
---|
328 | ...
|
---|
329 | no
|
---|
330 | NO
|
---|
331 | NO!!!
|
---|
332 | >>>
|
---|
333 | \end{verbatim}
|
---|
334 |
|
---|
335 | Any expected output must immediately follow the final
|
---|
336 | \code{'>>>~'} or \code{'...~'} line containing the code, and
|
---|
337 | the expected output (if any) extends to the next \code{'>>>~'}
|
---|
338 | or all-whitespace line.
|
---|
339 |
|
---|
340 | The fine print:
|
---|
341 |
|
---|
342 | \begin{itemize}
|
---|
343 |
|
---|
344 | \item Expected output cannot contain an all-whitespace line, since such a
|
---|
345 | line is taken to signal the end of expected output. If expected
|
---|
346 | output does contain a blank line, put \code{<BLANKLINE>} in your
|
---|
347 | doctest example each place a blank line is expected.
|
---|
348 | \versionchanged[\code{<BLANKLINE>} was added; there was no way to
|
---|
349 | use expected output containing empty lines in
|
---|
350 | previous versions]{2.4}
|
---|
351 |
|
---|
352 | \item Output to stdout is captured, but not output to stderr (exception
|
---|
353 | tracebacks are captured via a different means).
|
---|
354 |
|
---|
355 | \item If you continue a line via backslashing in an interactive session,
|
---|
356 | or for any other reason use a backslash, you should use a raw
|
---|
357 | docstring, which will preserve your backslashes exactly as you type
|
---|
358 | them:
|
---|
359 |
|
---|
360 | \begin{verbatim}
|
---|
361 | >>> def f(x):
|
---|
362 | ... r'''Backslashes in a raw docstring: m\n'''
|
---|
363 | >>> print f.__doc__
|
---|
364 | Backslashes in a raw docstring: m\n
|
---|
365 | \end{verbatim}
|
---|
366 |
|
---|
367 | Otherwise, the backslash will be interpreted as part of the string.
|
---|
368 | For example, the "{\textbackslash}" above would be interpreted as a
|
---|
369 | newline character. Alternatively, you can double each backslash in the
|
---|
370 | doctest version (and not use a raw string):
|
---|
371 |
|
---|
372 | \begin{verbatim}
|
---|
373 | >>> def f(x):
|
---|
374 | ... '''Backslashes in a raw docstring: m\\n'''
|
---|
375 | >>> print f.__doc__
|
---|
376 | Backslashes in a raw docstring: m\n
|
---|
377 | \end{verbatim}
|
---|
378 |
|
---|
379 | \item The starting column doesn't matter:
|
---|
380 |
|
---|
381 | \begin{verbatim}
|
---|
382 | >>> assert "Easy!"
|
---|
383 | >>> import math
|
---|
384 | >>> math.floor(1.9)
|
---|
385 | 1.0
|
---|
386 | \end{verbatim}
|
---|
387 |
|
---|
388 | and as many leading whitespace characters are stripped from the
|
---|
389 | expected output as appeared in the initial \code{'>>>~'} line
|
---|
390 | that started the example.
|
---|
391 | \end{itemize}
|
---|
392 |
|
---|
393 | \subsubsection{What's the Execution Context?\label{doctest-execution-context}}
|
---|
394 |
|
---|
395 | By default, each time \refmodule{doctest} finds a docstring to test, it
|
---|
396 | uses a \emph{shallow copy} of \module{M}'s globals, so that running tests
|
---|
397 | doesn't change the module's real globals, and so that one test in
|
---|
398 | \module{M} can't leave behind crumbs that accidentally allow another test
|
---|
399 | to work. This means examples can freely use any names defined at top-level
|
---|
400 | in \module{M}, and names defined earlier in the docstring being run.
|
---|
401 | Examples cannot see names defined in other docstrings.
|
---|
402 |
|
---|
403 | You can force use of your own dict as the execution context by passing
|
---|
404 | \code{globs=your_dict} to \function{testmod()} or
|
---|
405 | \function{testfile()} instead.
|
---|
406 |
|
---|
407 | \subsubsection{What About Exceptions?\label{doctest-exceptions}}
|
---|
408 |
|
---|
409 | No problem, provided that the traceback is the only output produced by
|
---|
410 | the example: just paste in the traceback.\footnote{Examples containing
|
---|
411 | both expected output and an exception are not supported. Trying
|
---|
412 | to guess where one ends and the other begins is too error-prone,
|
---|
413 | and that also makes for a confusing test.}
|
---|
414 | Since tracebacks contain details that are likely to change rapidly (for
|
---|
415 | example, exact file paths and line numbers), this is one case where doctest
|
---|
416 | works hard to be flexible in what it accepts.
|
---|
417 |
|
---|
418 | Simple example:
|
---|
419 |
|
---|
420 | \begin{verbatim}
|
---|
421 | >>> [1, 2, 3].remove(42)
|
---|
422 | Traceback (most recent call last):
|
---|
423 | File "<stdin>", line 1, in ?
|
---|
424 | ValueError: list.remove(x): x not in list
|
---|
425 | \end{verbatim}
|
---|
426 |
|
---|
427 | That doctest succeeds if \exception{ValueError} is raised, with the
|
---|
428 | \samp{list.remove(x): x not in list} detail as shown.
|
---|
429 |
|
---|
430 | The expected output for an exception must start with a traceback
|
---|
431 | header, which may be either of the following two lines, indented the
|
---|
432 | same as the first line of the example:
|
---|
433 |
|
---|
434 | \begin{verbatim}
|
---|
435 | Traceback (most recent call last):
|
---|
436 | Traceback (innermost last):
|
---|
437 | \end{verbatim}
|
---|
438 |
|
---|
439 | The traceback header is followed by an optional traceback stack, whose
|
---|
440 | contents are ignored by doctest. The traceback stack is typically
|
---|
441 | omitted, or copied verbatim from an interactive session.
|
---|
442 |
|
---|
443 | The traceback stack is followed by the most interesting part: the
|
---|
444 | line(s) containing the exception type and detail. This is usually the
|
---|
445 | last line of a traceback, but can extend across multiple lines if the
|
---|
446 | exception has a multi-line detail:
|
---|
447 |
|
---|
448 | \begin{verbatim}
|
---|
449 | >>> raise ValueError('multi\n line\ndetail')
|
---|
450 | Traceback (most recent call last):
|
---|
451 | File "<stdin>", line 1, in ?
|
---|
452 | ValueError: multi
|
---|
453 | line
|
---|
454 | detail
|
---|
455 | \end{verbatim}
|
---|
456 |
|
---|
457 | The last three lines (starting with \exception{ValueError}) are
|
---|
458 | compared against the exception's type and detail, and the rest are
|
---|
459 | ignored.
|
---|
460 |
|
---|
461 | Best practice is to omit the traceback stack, unless it adds
|
---|
462 | significant documentation value to the example. So the last example
|
---|
463 | is probably better as:
|
---|
464 |
|
---|
465 | \begin{verbatim}
|
---|
466 | >>> raise ValueError('multi\n line\ndetail')
|
---|
467 | Traceback (most recent call last):
|
---|
468 | ...
|
---|
469 | ValueError: multi
|
---|
470 | line
|
---|
471 | detail
|
---|
472 | \end{verbatim}
|
---|
473 |
|
---|
474 | Note that tracebacks are treated very specially. In particular, in the
|
---|
475 | rewritten example, the use of \samp{...} is independent of doctest's
|
---|
476 | \constant{ELLIPSIS} option. The ellipsis in that example could be left
|
---|
477 | out, or could just as well be three (or three hundred) commas or digits,
|
---|
478 | or an indented transcript of a Monty Python skit.
|
---|
479 |
|
---|
480 | Some details you should read once, but won't need to remember:
|
---|
481 |
|
---|
482 | \begin{itemize}
|
---|
483 |
|
---|
484 | \item Doctest can't guess whether your expected output came from an
|
---|
485 | exception traceback or from ordinary printing. So, e.g., an example
|
---|
486 | that expects \samp{ValueError: 42 is prime} will pass whether
|
---|
487 | \exception{ValueError} is actually raised or if the example merely
|
---|
488 | prints that traceback text. In practice, ordinary output rarely begins
|
---|
489 | with a traceback header line, so this doesn't create real problems.
|
---|
490 |
|
---|
491 | \item Each line of the traceback stack (if present) must be indented
|
---|
492 | further than the first line of the example, \emph{or} start with a
|
---|
493 | non-alphanumeric character. The first line following the traceback
|
---|
494 | header indented the same and starting with an alphanumeric is taken
|
---|
495 | to be the start of the exception detail. Of course this does the
|
---|
496 | right thing for genuine tracebacks.
|
---|
497 |
|
---|
498 | \item When the \constant{IGNORE_EXCEPTION_DETAIL} doctest option is
|
---|
499 | is specified, everything following the leftmost colon is ignored.
|
---|
500 |
|
---|
501 | \item The interactive shell omits the traceback header line for some
|
---|
502 | \exception{SyntaxError}s. But doctest uses the traceback header
|
---|
503 | line to distinguish exceptions from non-exceptions. So in the rare
|
---|
504 | case where you need to test a \exception{SyntaxError} that omits the
|
---|
505 | traceback header, you will need to manually add the traceback header
|
---|
506 | line to your test example.
|
---|
507 |
|
---|
508 | \item For some \exception{SyntaxError}s, Python displays the character
|
---|
509 | position of the syntax error, using a \code{\^} marker:
|
---|
510 |
|
---|
511 | \begin{verbatim}
|
---|
512 | >>> 1 1
|
---|
513 | File "<stdin>", line 1
|
---|
514 | 1 1
|
---|
515 | ^
|
---|
516 | SyntaxError: invalid syntax
|
---|
517 | \end{verbatim}
|
---|
518 |
|
---|
519 | Since the lines showing the position of the error come before the
|
---|
520 | exception type and detail, they are not checked by doctest. For
|
---|
521 | example, the following test would pass, even though it puts the
|
---|
522 | \code{\^} marker in the wrong location:
|
---|
523 |
|
---|
524 | \begin{verbatim}
|
---|
525 | >>> 1 1
|
---|
526 | Traceback (most recent call last):
|
---|
527 | File "<stdin>", line 1
|
---|
528 | 1 1
|
---|
529 | ^
|
---|
530 | SyntaxError: invalid syntax
|
---|
531 | \end{verbatim}
|
---|
532 |
|
---|
533 | \end{itemize}
|
---|
534 |
|
---|
535 | \versionchanged[The ability to handle a multi-line exception detail,
|
---|
536 | and the \constant{IGNORE_EXCEPTION_DETAIL} doctest option,
|
---|
537 | were added]{2.4}
|
---|
538 |
|
---|
539 | \subsubsection{Option Flags and Directives\label{doctest-options}}
|
---|
540 |
|
---|
541 | A number of option flags control various aspects of doctest's
|
---|
542 | behavior. Symbolic names for the flags are supplied as module constants,
|
---|
543 | which can be or'ed together and passed to various functions. The names
|
---|
544 | can also be used in doctest directives (see below).
|
---|
545 |
|
---|
546 | The first group of options define test semantics, controlling
|
---|
547 | aspects of how doctest decides whether actual output matches an
|
---|
548 | example's expected output:
|
---|
549 |
|
---|
550 | \begin{datadesc}{DONT_ACCEPT_TRUE_FOR_1}
|
---|
551 | By default, if an expected output block contains just \code{1},
|
---|
552 | an actual output block containing just \code{1} or just
|
---|
553 | \code{True} is considered to be a match, and similarly for \code{0}
|
---|
554 | versus \code{False}. When \constant{DONT_ACCEPT_TRUE_FOR_1} is
|
---|
555 | specified, neither substitution is allowed. The default behavior
|
---|
556 | caters to that Python changed the return type of many functions
|
---|
557 | from integer to boolean; doctests expecting "little integer"
|
---|
558 | output still work in these cases. This option will probably go
|
---|
559 | away, but not for several years.
|
---|
560 | \end{datadesc}
|
---|
561 |
|
---|
562 | \begin{datadesc}{DONT_ACCEPT_BLANKLINE}
|
---|
563 | By default, if an expected output block contains a line
|
---|
564 | containing only the string \code{<BLANKLINE>}, then that line
|
---|
565 | will match a blank line in the actual output. Because a
|
---|
566 | genuinely blank line delimits the expected output, this is
|
---|
567 | the only way to communicate that a blank line is expected. When
|
---|
568 | \constant{DONT_ACCEPT_BLANKLINE} is specified, this substitution
|
---|
569 | is not allowed.
|
---|
570 | \end{datadesc}
|
---|
571 |
|
---|
572 | \begin{datadesc}{NORMALIZE_WHITESPACE}
|
---|
573 | When specified, all sequences of whitespace (blanks and newlines) are
|
---|
574 | treated as equal. Any sequence of whitespace within the expected
|
---|
575 | output will match any sequence of whitespace within the actual output.
|
---|
576 | By default, whitespace must match exactly.
|
---|
577 | \constant{NORMALIZE_WHITESPACE} is especially useful when a line
|
---|
578 | of expected output is very long, and you want to wrap it across
|
---|
579 | multiple lines in your source.
|
---|
580 | \end{datadesc}
|
---|
581 |
|
---|
582 | \begin{datadesc}{ELLIPSIS}
|
---|
583 | When specified, an ellipsis marker (\code{...}) in the expected output
|
---|
584 | can match any substring in the actual output. This includes
|
---|
585 | substrings that span line boundaries, and empty substrings, so it's
|
---|
586 | best to keep usage of this simple. Complicated uses can lead to the
|
---|
587 | same kinds of "oops, it matched too much!" surprises that \regexp{.*}
|
---|
588 | is prone to in regular expressions.
|
---|
589 | \end{datadesc}
|
---|
590 |
|
---|
591 | \begin{datadesc}{IGNORE_EXCEPTION_DETAIL}
|
---|
592 | When specified, an example that expects an exception passes if
|
---|
593 | an exception of the expected type is raised, even if the exception
|
---|
594 | detail does not match. For example, an example expecting
|
---|
595 | \samp{ValueError: 42} will pass if the actual exception raised is
|
---|
596 | \samp{ValueError: 3*14}, but will fail, e.g., if
|
---|
597 | \exception{TypeError} is raised.
|
---|
598 |
|
---|
599 | Note that a similar effect can be obtained using \constant{ELLIPSIS},
|
---|
600 | and \constant{IGNORE_EXCEPTION_DETAIL} may go away when Python releases
|
---|
601 | prior to 2.4 become uninteresting. Until then,
|
---|
602 | \constant{IGNORE_EXCEPTION_DETAIL} is the only clear way to write a
|
---|
603 | doctest that doesn't care about the exception detail yet continues
|
---|
604 | to pass under Python releases prior to 2.4 (doctest directives
|
---|
605 | appear to be comments to them). For example,
|
---|
606 |
|
---|
607 | \begin{verbatim}
|
---|
608 | >>> (1, 2)[3] = 'moo' #doctest: +IGNORE_EXCEPTION_DETAIL
|
---|
609 | Traceback (most recent call last):
|
---|
610 | File "<stdin>", line 1, in ?
|
---|
611 | TypeError: object doesn't support item assignment
|
---|
612 | \end{verbatim}
|
---|
613 |
|
---|
614 | passes under Python 2.4 and Python 2.3. The detail changed in 2.4,
|
---|
615 | to say "does not" instead of "doesn't".
|
---|
616 |
|
---|
617 | \end{datadesc}
|
---|
618 |
|
---|
619 | \begin{datadesc}{SKIP}
|
---|
620 |
|
---|
621 | When specified, do not run the example at all. This can be useful
|
---|
622 | in contexts where doctest examples serve as both documentation and
|
---|
623 | test cases, and an example should be included for documentation
|
---|
624 | purposes, but should not be checked. E.g., the example's output
|
---|
625 | might be random; or the example might depend on resources which
|
---|
626 | would be unavailable to the test driver.
|
---|
627 |
|
---|
628 | The SKIP flag can also be used for temporarily "commenting out"
|
---|
629 | examples.
|
---|
630 |
|
---|
631 | \end{datadesc}
|
---|
632 |
|
---|
633 | \begin{datadesc}{COMPARISON_FLAGS}
|
---|
634 | A bitmask or'ing together all the comparison flags above.
|
---|
635 | \end{datadesc}
|
---|
636 |
|
---|
637 | The second group of options controls how test failures are reported:
|
---|
638 |
|
---|
639 | \begin{datadesc}{REPORT_UDIFF}
|
---|
640 | When specified, failures that involve multi-line expected and
|
---|
641 | actual outputs are displayed using a unified diff.
|
---|
642 | \end{datadesc}
|
---|
643 |
|
---|
644 | \begin{datadesc}{REPORT_CDIFF}
|
---|
645 | When specified, failures that involve multi-line expected and
|
---|
646 | actual outputs will be displayed using a context diff.
|
---|
647 | \end{datadesc}
|
---|
648 |
|
---|
649 | \begin{datadesc}{REPORT_NDIFF}
|
---|
650 | When specified, differences are computed by \code{difflib.Differ},
|
---|
651 | using the same algorithm as the popular \file{ndiff.py} utility.
|
---|
652 | This is the only method that marks differences within lines as
|
---|
653 | well as across lines. For example, if a line of expected output
|
---|
654 | contains digit \code{1} where actual output contains letter \code{l},
|
---|
655 | a line is inserted with a caret marking the mismatching column
|
---|
656 | positions.
|
---|
657 | \end{datadesc}
|
---|
658 |
|
---|
659 | \begin{datadesc}{REPORT_ONLY_FIRST_FAILURE}
|
---|
660 | When specified, display the first failing example in each doctest,
|
---|
661 | but suppress output for all remaining examples. This will prevent
|
---|
662 | doctest from reporting correct examples that break because of
|
---|
663 | earlier failures; but it might also hide incorrect examples that
|
---|
664 | fail independently of the first failure. When
|
---|
665 | \constant{REPORT_ONLY_FIRST_FAILURE} is specified, the remaining
|
---|
666 | examples are still run, and still count towards the total number of
|
---|
667 | failures reported; only the output is suppressed.
|
---|
668 | \end{datadesc}
|
---|
669 |
|
---|
670 | \begin{datadesc}{REPORTING_FLAGS}
|
---|
671 | A bitmask or'ing together all the reporting flags above.
|
---|
672 | \end{datadesc}
|
---|
673 |
|
---|
674 | "Doctest directives" may be used to modify the option flags for
|
---|
675 | individual examples. Doctest directives are expressed as a special
|
---|
676 | Python comment following an example's source code:
|
---|
677 |
|
---|
678 | \begin{productionlist}[doctest]
|
---|
679 | \production{directive}
|
---|
680 | {"\#" "doctest:" \token{directive_options}}
|
---|
681 | \production{directive_options}
|
---|
682 | {\token{directive_option} ("," \token{directive_option})*}
|
---|
683 | \production{directive_option}
|
---|
684 | {\token{on_or_off} \token{directive_option_name}}
|
---|
685 | \production{on_or_off}
|
---|
686 | {"+" | "-"}
|
---|
687 | \production{directive_option_name}
|
---|
688 | {"DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...}
|
---|
689 | \end{productionlist}
|
---|
690 |
|
---|
691 | Whitespace is not allowed between the \code{+} or \code{-} and the
|
---|
692 | directive option name. The directive option name can be any of the
|
---|
693 | option flag names explained above.
|
---|
694 |
|
---|
695 | An example's doctest directives modify doctest's behavior for that
|
---|
696 | single example. Use \code{+} to enable the named behavior, or
|
---|
697 | \code{-} to disable it.
|
---|
698 |
|
---|
699 | For example, this test passes:
|
---|
700 |
|
---|
701 | \begin{verbatim}
|
---|
702 | >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
|
---|
703 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
|
---|
704 | 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
|
---|
705 | \end{verbatim}
|
---|
706 |
|
---|
707 | Without the directive it would fail, both because the actual output
|
---|
708 | doesn't have two blanks before the single-digit list elements, and
|
---|
709 | because the actual output is on a single line. This test also passes,
|
---|
710 | and also requires a directive to do so:
|
---|
711 |
|
---|
712 | \begin{verbatim}
|
---|
713 | >>> print range(20) # doctest:+ELLIPSIS
|
---|
714 | [0, 1, ..., 18, 19]
|
---|
715 | \end{verbatim}
|
---|
716 |
|
---|
717 | Multiple directives can be used on a single physical line, separated
|
---|
718 | by commas:
|
---|
719 |
|
---|
720 | \begin{verbatim}
|
---|
721 | >>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
|
---|
722 | [0, 1, ..., 18, 19]
|
---|
723 | \end{verbatim}
|
---|
724 |
|
---|
725 | If multiple directive comments are used for a single example, then
|
---|
726 | they are combined:
|
---|
727 |
|
---|
728 | \begin{verbatim}
|
---|
729 | >>> print range(20) # doctest: +ELLIPSIS
|
---|
730 | ... # doctest: +NORMALIZE_WHITESPACE
|
---|
731 | [0, 1, ..., 18, 19]
|
---|
732 | \end{verbatim}
|
---|
733 |
|
---|
734 | As the previous example shows, you can add \samp{...} lines to your
|
---|
735 | example containing only directives. This can be useful when an
|
---|
736 | example is too long for a directive to comfortably fit on the same
|
---|
737 | line:
|
---|
738 |
|
---|
739 | \begin{verbatim}
|
---|
740 | >>> print range(5) + range(10,20) + range(30,40) + range(50,60)
|
---|
741 | ... # doctest: +ELLIPSIS
|
---|
742 | [0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
|
---|
743 | \end{verbatim}
|
---|
744 |
|
---|
745 | Note that since all options are disabled by default, and directives apply
|
---|
746 | only to the example they appear in, enabling options (via \code{+} in a
|
---|
747 | directive) is usually the only meaningful choice. However, option flags
|
---|
748 | can also be passed to functions that run doctests, establishing different
|
---|
749 | defaults. In such cases, disabling an option via \code{-} in a directive
|
---|
750 | can be useful.
|
---|
751 |
|
---|
752 | \versionchanged[Constants \constant{DONT_ACCEPT_BLANKLINE},
|
---|
753 | \constant{NORMALIZE_WHITESPACE}, \constant{ELLIPSIS},
|
---|
754 | \constant{IGNORE_EXCEPTION_DETAIL},
|
---|
755 | \constant{REPORT_UDIFF}, \constant{REPORT_CDIFF},
|
---|
756 | \constant{REPORT_NDIFF}, \constant{REPORT_ONLY_FIRST_FAILURE},
|
---|
757 | \constant{COMPARISON_FLAGS} and \constant{REPORTING_FLAGS}
|
---|
758 | were added; by default \code{<BLANKLINE>} in expected output
|
---|
759 | matches an empty line in actual output; and doctest directives
|
---|
760 | were added]{2.4}
|
---|
761 | \versionchanged[Constant \constant{SKIP} was added]{2.5}
|
---|
762 |
|
---|
763 | There's also a way to register new option flag names, although this
|
---|
764 | isn't useful unless you intend to extend \refmodule{doctest} internals
|
---|
765 | via subclassing:
|
---|
766 |
|
---|
767 | \begin{funcdesc}{register_optionflag}{name}
|
---|
768 | Create a new option flag with a given name, and return the new
|
---|
769 | flag's integer value. \function{register_optionflag()} can be
|
---|
770 | used when subclassing \class{OutputChecker} or
|
---|
771 | \class{DocTestRunner} to create new options that are supported by
|
---|
772 | your subclasses. \function{register_optionflag} should always be
|
---|
773 | called using the following idiom:
|
---|
774 |
|
---|
775 | \begin{verbatim}
|
---|
776 | MY_FLAG = register_optionflag('MY_FLAG')
|
---|
777 | \end{verbatim}
|
---|
778 |
|
---|
779 | \versionadded{2.4}
|
---|
780 | \end{funcdesc}
|
---|
781 |
|
---|
782 | \subsubsection{Warnings\label{doctest-warnings}}
|
---|
783 |
|
---|
784 | \refmodule{doctest} is serious about requiring exact matches in expected
|
---|
785 | output. If even a single character doesn't match, the test fails. This
|
---|
786 | will probably surprise you a few times, as you learn exactly what Python
|
---|
787 | does and doesn't guarantee about output. For example, when printing a
|
---|
788 | dict, Python doesn't guarantee that the key-value pairs will be printed
|
---|
789 | in any particular order, so a test like
|
---|
790 |
|
---|
791 | % Hey! What happened to Monty Python examples?
|
---|
792 | % Tim: ask Guido -- it's his example!
|
---|
793 | \begin{verbatim}
|
---|
794 | >>> foo()
|
---|
795 | {"Hermione": "hippogryph", "Harry": "broomstick"}
|
---|
796 | \end{verbatim}
|
---|
797 |
|
---|
798 | is vulnerable! One workaround is to do
|
---|
799 |
|
---|
800 | \begin{verbatim}
|
---|
801 | >>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
|
---|
802 | True
|
---|
803 | \end{verbatim}
|
---|
804 |
|
---|
805 | instead. Another is to do
|
---|
806 |
|
---|
807 | \begin{verbatim}
|
---|
808 | >>> d = foo().items()
|
---|
809 | >>> d.sort()
|
---|
810 | >>> d
|
---|
811 | [('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
|
---|
812 | \end{verbatim}
|
---|
813 |
|
---|
814 | There are others, but you get the idea.
|
---|
815 |
|
---|
816 | Another bad idea is to print things that embed an object address, like
|
---|
817 |
|
---|
818 | \begin{verbatim}
|
---|
819 | >>> id(1.0) # certain to fail some of the time
|
---|
820 | 7948648
|
---|
821 | >>> class C: pass
|
---|
822 | >>> C() # the default repr() for instances embeds an address
|
---|
823 | <__main__.C instance at 0x00AC18F0>
|
---|
824 | \end{verbatim}
|
---|
825 |
|
---|
826 | The \constant{ELLIPSIS} directive gives a nice approach for the last
|
---|
827 | example:
|
---|
828 |
|
---|
829 | \begin{verbatim}
|
---|
830 | >>> C() #doctest: +ELLIPSIS
|
---|
831 | <__main__.C instance at 0x...>
|
---|
832 | \end{verbatim}
|
---|
833 |
|
---|
834 | Floating-point numbers are also subject to small output variations across
|
---|
835 | platforms, because Python defers to the platform C library for float
|
---|
836 | formatting, and C libraries vary widely in quality here.
|
---|
837 |
|
---|
838 | \begin{verbatim}
|
---|
839 | >>> 1./7 # risky
|
---|
840 | 0.14285714285714285
|
---|
841 | >>> print 1./7 # safer
|
---|
842 | 0.142857142857
|
---|
843 | >>> print round(1./7, 6) # much safer
|
---|
844 | 0.142857
|
---|
845 | \end{verbatim}
|
---|
846 |
|
---|
847 | Numbers of the form \code{I/2.**J} are safe across all platforms, and I
|
---|
848 | often contrive doctest examples to produce numbers of that form:
|
---|
849 |
|
---|
850 | \begin{verbatim}
|
---|
851 | >>> 3./4 # utterly safe
|
---|
852 | 0.75
|
---|
853 | \end{verbatim}
|
---|
854 |
|
---|
855 | Simple fractions are also easier for people to understand, and that makes
|
---|
856 | for better documentation.
|
---|
857 |
|
---|
858 | \subsection{Basic API\label{doctest-basic-api}}
|
---|
859 |
|
---|
860 | The functions \function{testmod()} and \function{testfile()} provide a
|
---|
861 | simple interface to doctest that should be sufficient for most basic
|
---|
862 | uses. For a less formal introduction to these two functions, see
|
---|
863 | sections \ref{doctest-simple-testmod} and
|
---|
864 | \ref{doctest-simple-testfile}.
|
---|
865 |
|
---|
866 | \begin{funcdesc}{testfile}{filename\optional{, module_relative}\optional{,
|
---|
867 | name}\optional{, package}\optional{,
|
---|
868 | globs}\optional{, verbose}\optional{,
|
---|
869 | report}\optional{, optionflags}\optional{,
|
---|
870 | extraglobs}\optional{, raise_on_error}\optional{,
|
---|
871 | parser}\optional{, encoding}}
|
---|
872 |
|
---|
873 | All arguments except \var{filename} are optional, and should be
|
---|
874 | specified in keyword form.
|
---|
875 |
|
---|
876 | Test examples in the file named \var{filename}. Return
|
---|
877 | \samp{(\var{failure_count}, \var{test_count})}.
|
---|
878 |
|
---|
879 | Optional argument \var{module_relative} specifies how the filename
|
---|
880 | should be interpreted:
|
---|
881 |
|
---|
882 | \begin{itemize}
|
---|
883 | \item If \var{module_relative} is \code{True} (the default), then
|
---|
884 | \var{filename} specifies an OS-independent module-relative
|
---|
885 | path. By default, this path is relative to the calling
|
---|
886 | module's directory; but if the \var{package} argument is
|
---|
887 | specified, then it is relative to that package. To ensure
|
---|
888 | OS-independence, \var{filename} should use \code{/} characters
|
---|
889 | to separate path segments, and may not be an absolute path
|
---|
890 | (i.e., it may not begin with \code{/}).
|
---|
891 | \item If \var{module_relative} is \code{False}, then \var{filename}
|
---|
892 | specifies an OS-specific path. The path may be absolute or
|
---|
893 | relative; relative paths are resolved with respect to the
|
---|
894 | current working directory.
|
---|
895 | \end{itemize}
|
---|
896 |
|
---|
897 | Optional argument \var{name} gives the name of the test; by default,
|
---|
898 | or if \code{None}, \code{os.path.basename(\var{filename})} is used.
|
---|
899 |
|
---|
900 | Optional argument \var{package} is a Python package or the name of a
|
---|
901 | Python package whose directory should be used as the base directory
|
---|
902 | for a module-relative filename. If no package is specified, then
|
---|
903 | the calling module's directory is used as the base directory for
|
---|
904 | module-relative filenames. It is an error to specify \var{package}
|
---|
905 | if \var{module_relative} is \code{False}.
|
---|
906 |
|
---|
907 | Optional argument \var{globs} gives a dict to be used as the globals
|
---|
908 | when executing examples. A new shallow copy of this dict is
|
---|
909 | created for the doctest, so its examples start with a clean slate.
|
---|
910 | By default, or if \code{None}, a new empty dict is used.
|
---|
911 |
|
---|
912 | Optional argument \var{extraglobs} gives a dict merged into the
|
---|
913 | globals used to execute examples. This works like
|
---|
914 | \method{dict.update()}: if \var{globs} and \var{extraglobs} have a
|
---|
915 | common key, the associated value in \var{extraglobs} appears in the
|
---|
916 | combined dict. By default, or if \code{None}, no extra globals are
|
---|
917 | used. This is an advanced feature that allows parameterization of
|
---|
918 | doctests. For example, a doctest can be written for a base class, using
|
---|
919 | a generic name for the class, then reused to test any number of
|
---|
920 | subclasses by passing an \var{extraglobs} dict mapping the generic
|
---|
921 | name to the subclass to be tested.
|
---|
922 |
|
---|
923 | Optional argument \var{verbose} prints lots of stuff if true, and prints
|
---|
924 | only failures if false; by default, or if \code{None}, it's true
|
---|
925 | if and only if \code{'-v'} is in \code{sys.argv}.
|
---|
926 |
|
---|
927 | Optional argument \var{report} prints a summary at the end when true,
|
---|
928 | else prints nothing at the end. In verbose mode, the summary is
|
---|
929 | detailed, else the summary is very brief (in fact, empty if all tests
|
---|
930 | passed).
|
---|
931 |
|
---|
932 | Optional argument \var{optionflags} or's together option flags. See
|
---|
933 | section~\ref{doctest-options}.
|
---|
934 |
|
---|
935 | Optional argument \var{raise_on_error} defaults to false. If true,
|
---|
936 | an exception is raised upon the first failure or unexpected exception
|
---|
937 | in an example. This allows failures to be post-mortem debugged.
|
---|
938 | Default behavior is to continue running examples.
|
---|
939 |
|
---|
940 | Optional argument \var{parser} specifies a \class{DocTestParser} (or
|
---|
941 | subclass) that should be used to extract tests from the files. It
|
---|
942 | defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
|
---|
943 |
|
---|
944 | Optional argument \var{encoding} specifies an encoding that should
|
---|
945 | be used to convert the file to unicode.
|
---|
946 |
|
---|
947 | \versionadded{2.4}
|
---|
948 |
|
---|
949 | \versionchanged[The parameter \var{encoding} was added]{2.5}
|
---|
950 |
|
---|
951 | \end{funcdesc}
|
---|
952 |
|
---|
953 | \begin{funcdesc}{testmod}{\optional{m}\optional{, name}\optional{,
|
---|
954 | globs}\optional{, verbose}\optional{,
|
---|
955 | report}\optional{,
|
---|
956 | optionflags}\optional{, extraglobs}\optional{,
|
---|
957 | raise_on_error}\optional{, exclude_empty}}
|
---|
958 |
|
---|
959 | All arguments are optional, and all except for \var{m} should be
|
---|
960 | specified in keyword form.
|
---|
961 |
|
---|
962 | Test examples in docstrings in functions and classes reachable
|
---|
963 | from module \var{m} (or module \module{__main__} if \var{m} is not
|
---|
964 | supplied or is \code{None}), starting with \code{\var{m}.__doc__}.
|
---|
965 |
|
---|
966 | Also test examples reachable from dict \code{\var{m}.__test__}, if it
|
---|
967 | exists and is not \code{None}. \code{\var{m}.__test__} maps
|
---|
968 | names (strings) to functions, classes and strings; function and class
|
---|
969 | docstrings are searched for examples; strings are searched directly,
|
---|
970 | as if they were docstrings.
|
---|
971 |
|
---|
972 | Only docstrings attached to objects belonging to module \var{m} are
|
---|
973 | searched.
|
---|
974 |
|
---|
975 | Return \samp{(\var{failure_count}, \var{test_count})}.
|
---|
976 |
|
---|
977 | Optional argument \var{name} gives the name of the module; by default,
|
---|
978 | or if \code{None}, \code{\var{m}.__name__} is used.
|
---|
979 |
|
---|
980 | Optional argument \var{exclude_empty} defaults to false. If true,
|
---|
981 | objects for which no doctests are found are excluded from consideration.
|
---|
982 | The default is a backward compatibility hack, so that code still
|
---|
983 | using \method{doctest.master.summarize()} in conjunction with
|
---|
984 | \function{testmod()} continues to get output for objects with no tests.
|
---|
985 | The \var{exclude_empty} argument to the newer \class{DocTestFinder}
|
---|
986 | constructor defaults to true.
|
---|
987 |
|
---|
988 | Optional arguments \var{extraglobs}, \var{verbose}, \var{report},
|
---|
989 | \var{optionflags}, \var{raise_on_error}, and \var{globs} are the same as
|
---|
990 | for function \function{testfile()} above, except that \var{globs}
|
---|
991 | defaults to \code{\var{m}.__dict__}.
|
---|
992 |
|
---|
993 | \versionchanged[The parameter \var{optionflags} was added]{2.3}
|
---|
994 |
|
---|
995 | \versionchanged[The parameters \var{extraglobs}, \var{raise_on_error}
|
---|
996 | and \var{exclude_empty} were added]{2.4}
|
---|
997 |
|
---|
998 | \versionchanged[The optional argument \var{isprivate}, deprecated
|
---|
999 | in 2.4, was removed]{2.5}
|
---|
1000 |
|
---|
1001 | \end{funcdesc}
|
---|
1002 |
|
---|
1003 | There's also a function to run the doctests associated with a single object.
|
---|
1004 | This function is provided for backward compatibility. There are no plans
|
---|
1005 | to deprecate it, but it's rarely useful:
|
---|
1006 |
|
---|
1007 | \begin{funcdesc}{run_docstring_examples}{f, globs\optional{,
|
---|
1008 | verbose}\optional{, name}\optional{,
|
---|
1009 | compileflags}\optional{, optionflags}}
|
---|
1010 |
|
---|
1011 | Test examples associated with object \var{f}; for example, \var{f} may
|
---|
1012 | be a module, function, or class object.
|
---|
1013 |
|
---|
1014 | A shallow copy of dictionary argument \var{globs} is used for the
|
---|
1015 | execution context.
|
---|
1016 |
|
---|
1017 | Optional argument \var{name} is used in failure messages, and defaults
|
---|
1018 | to \code{"NoName"}.
|
---|
1019 |
|
---|
1020 | If optional argument \var{verbose} is true, output is generated even
|
---|
1021 | if there are no failures. By default, output is generated only in case
|
---|
1022 | of an example failure.
|
---|
1023 |
|
---|
1024 | Optional argument \var{compileflags} gives the set of flags that should
|
---|
1025 | be used by the Python compiler when running the examples. By default, or
|
---|
1026 | if \code{None}, flags are deduced corresponding to the set of future
|
---|
1027 | features found in \var{globs}.
|
---|
1028 |
|
---|
1029 | Optional argument \var{optionflags} works as for function
|
---|
1030 | \function{testfile()} above.
|
---|
1031 | \end{funcdesc}
|
---|
1032 |
|
---|
1033 | \subsection{Unittest API\label{doctest-unittest-api}}
|
---|
1034 |
|
---|
1035 | As your collection of doctest'ed modules grows, you'll want a way to run
|
---|
1036 | all their doctests systematically. Prior to Python 2.4, \refmodule{doctest}
|
---|
1037 | had a barely documented \class{Tester} class that supplied a rudimentary
|
---|
1038 | way to combine doctests from multiple modules. \class{Tester} was feeble,
|
---|
1039 | and in practice most serious Python testing frameworks build on the
|
---|
1040 | \refmodule{unittest} module, which supplies many flexible ways to combine
|
---|
1041 | tests from multiple sources. So, in Python 2.4, \refmodule{doctest}'s
|
---|
1042 | \class{Tester} class is deprecated, and \refmodule{doctest} provides two
|
---|
1043 | functions that can be used to create \refmodule{unittest} test suites from
|
---|
1044 | modules and text files containing doctests. These test suites can then be
|
---|
1045 | run using \refmodule{unittest} test runners:
|
---|
1046 |
|
---|
1047 | \begin{verbatim}
|
---|
1048 | import unittest
|
---|
1049 | import doctest
|
---|
1050 | import my_module_with_doctests, and_another
|
---|
1051 |
|
---|
1052 | suite = unittest.TestSuite()
|
---|
1053 | for mod in my_module_with_doctests, and_another:
|
---|
1054 | suite.addTest(doctest.DocTestSuite(mod))
|
---|
1055 | runner = unittest.TextTestRunner()
|
---|
1056 | runner.run(suite)
|
---|
1057 | \end{verbatim}
|
---|
1058 |
|
---|
1059 | There are two main functions for creating \class{\refmodule{unittest}.TestSuite}
|
---|
1060 | instances from text files and modules with doctests:
|
---|
1061 |
|
---|
1062 | \begin{funcdesc}{DocFileSuite}{\optional{module_relative}\optional{,
|
---|
1063 | package}\optional{, setUp}\optional{,
|
---|
1064 | tearDown}\optional{, globs}\optional{,
|
---|
1065 | optionflags}\optional{, parser}\optional{,
|
---|
1066 | encoding}}
|
---|
1067 |
|
---|
1068 | Convert doctest tests from one or more text files to a
|
---|
1069 | \class{\refmodule{unittest}.TestSuite}.
|
---|
1070 |
|
---|
1071 | The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
|
---|
1072 | unittest framework and runs the interactive examples in each file. If an
|
---|
1073 | example in any file fails, then the synthesized unit test fails, and a
|
---|
1074 | \exception{failureException} exception is raised showing the name of the
|
---|
1075 | file containing the test and a (sometimes approximate) line number.
|
---|
1076 |
|
---|
1077 | Pass one or more paths (as strings) to text files to be examined.
|
---|
1078 |
|
---|
1079 | Options may be provided as keyword arguments:
|
---|
1080 |
|
---|
1081 | Optional argument \var{module_relative} specifies how
|
---|
1082 | the filenames in \var{paths} should be interpreted:
|
---|
1083 |
|
---|
1084 | \begin{itemize}
|
---|
1085 | \item If \var{module_relative} is \code{True} (the default), then
|
---|
1086 | each filename specifies an OS-independent module-relative
|
---|
1087 | path. By default, this path is relative to the calling
|
---|
1088 | module's directory; but if the \var{package} argument is
|
---|
1089 | specified, then it is relative to that package. To ensure
|
---|
1090 | OS-independence, each filename should use \code{/} characters
|
---|
1091 | to separate path segments, and may not be an absolute path
|
---|
1092 | (i.e., it may not begin with \code{/}).
|
---|
1093 | \item If \var{module_relative} is \code{False}, then each filename
|
---|
1094 | specifies an OS-specific path. The path may be absolute or
|
---|
1095 | relative; relative paths are resolved with respect to the
|
---|
1096 | current working directory.
|
---|
1097 | \end{itemize}
|
---|
1098 |
|
---|
1099 | Optional argument \var{package} is a Python package or the name
|
---|
1100 | of a Python package whose directory should be used as the base
|
---|
1101 | directory for module-relative filenames. If no package is
|
---|
1102 | specified, then the calling module's directory is used as the base
|
---|
1103 | directory for module-relative filenames. It is an error to specify
|
---|
1104 | \var{package} if \var{module_relative} is \code{False}.
|
---|
1105 |
|
---|
1106 | Optional argument \var{setUp} specifies a set-up function for
|
---|
1107 | the test suite. This is called before running the tests in each
|
---|
1108 | file. The \var{setUp} function will be passed a \class{DocTest}
|
---|
1109 | object. The setUp function can access the test globals as the
|
---|
1110 | \var{globs} attribute of the test passed.
|
---|
1111 |
|
---|
1112 | Optional argument \var{tearDown} specifies a tear-down function
|
---|
1113 | for the test suite. This is called after running the tests in each
|
---|
1114 | file. The \var{tearDown} function will be passed a \class{DocTest}
|
---|
1115 | object. The setUp function can access the test globals as the
|
---|
1116 | \var{globs} attribute of the test passed.
|
---|
1117 |
|
---|
1118 | Optional argument \var{globs} is a dictionary containing the
|
---|
1119 | initial global variables for the tests. A new copy of this
|
---|
1120 | dictionary is created for each test. By default, \var{globs} is
|
---|
1121 | a new empty dictionary.
|
---|
1122 |
|
---|
1123 | Optional argument \var{optionflags} specifies the default
|
---|
1124 | doctest options for the tests, created by or-ing together
|
---|
1125 | individual option flags. See section~\ref{doctest-options}.
|
---|
1126 | See function \function{set_unittest_reportflags()} below for
|
---|
1127 | a better way to set reporting options.
|
---|
1128 |
|
---|
1129 | Optional argument \var{parser} specifies a \class{DocTestParser} (or
|
---|
1130 | subclass) that should be used to extract tests from the files. It
|
---|
1131 | defaults to a normal parser (i.e., \code{\class{DocTestParser}()}).
|
---|
1132 |
|
---|
1133 | Optional argument \var{encoding} specifies an encoding that should
|
---|
1134 | be used to convert the file to unicode.
|
---|
1135 |
|
---|
1136 | \versionadded{2.4}
|
---|
1137 |
|
---|
1138 | \versionchanged[The global \code{__file__} was added to the
|
---|
1139 | globals provided to doctests loaded from a text file using
|
---|
1140 | \function{DocFileSuite()}]{2.5}
|
---|
1141 |
|
---|
1142 | \versionchanged[The parameter \var{encoding} was added]{2.5}
|
---|
1143 |
|
---|
1144 | \end{funcdesc}
|
---|
1145 |
|
---|
1146 | \begin{funcdesc}{DocTestSuite}{\optional{module}\optional{,
|
---|
1147 | globs}\optional{, extraglobs}\optional{,
|
---|
1148 | test_finder}\optional{, setUp}\optional{,
|
---|
1149 | tearDown}\optional{, checker}}
|
---|
1150 | Convert doctest tests for a module to a
|
---|
1151 | \class{\refmodule{unittest}.TestSuite}.
|
---|
1152 |
|
---|
1153 | The returned \class{\refmodule{unittest}.TestSuite} is to be run by the
|
---|
1154 | unittest framework and runs each doctest in the module. If any of the
|
---|
1155 | doctests fail, then the synthesized unit test fails, and a
|
---|
1156 | \exception{failureException} exception is raised showing the name of the
|
---|
1157 | file containing the test and a (sometimes approximate) line number.
|
---|
1158 |
|
---|
1159 | Optional argument \var{module} provides the module to be tested. It
|
---|
1160 | can be a module object or a (possibly dotted) module name. If not
|
---|
1161 | specified, the module calling this function is used.
|
---|
1162 |
|
---|
1163 | Optional argument \var{globs} is a dictionary containing the
|
---|
1164 | initial global variables for the tests. A new copy of this
|
---|
1165 | dictionary is created for each test. By default, \var{globs} is
|
---|
1166 | a new empty dictionary.
|
---|
1167 |
|
---|
1168 | Optional argument \var{extraglobs} specifies an extra set of
|
---|
1169 | global variables, which is merged into \var{globs}. By default, no
|
---|
1170 | extra globals are used.
|
---|
1171 |
|
---|
1172 | Optional argument \var{test_finder} is the \class{DocTestFinder}
|
---|
1173 | object (or a drop-in replacement) that is used to extract doctests
|
---|
1174 | from the module.
|
---|
1175 |
|
---|
1176 | Optional arguments \var{setUp}, \var{tearDown}, and \var{optionflags}
|
---|
1177 | are the same as for function \function{DocFileSuite()} above.
|
---|
1178 |
|
---|
1179 | \versionadded{2.3}
|
---|
1180 |
|
---|
1181 | \versionchanged[The parameters \var{globs}, \var{extraglobs},
|
---|
1182 | \var{test_finder}, \var{setUp}, \var{tearDown}, and
|
---|
1183 | \var{optionflags} were added; this function now uses the same search
|
---|
1184 | technique as \function{testmod()}]{2.4}
|
---|
1185 | \end{funcdesc}
|
---|
1186 |
|
---|
1187 | Under the covers, \function{DocTestSuite()} creates a
|
---|
1188 | \class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocTestCase}
|
---|
1189 | instances, and \class{DocTestCase} is a subclass of
|
---|
1190 | \class{\refmodule{unittest}.TestCase}. \class{DocTestCase} isn't documented
|
---|
1191 | here (it's an internal detail), but studying its code can answer questions
|
---|
1192 | about the exact details of \refmodule{unittest} integration.
|
---|
1193 |
|
---|
1194 | Similarly, \function{DocFileSuite()} creates a
|
---|
1195 | \class{\refmodule{unittest}.TestSuite} out of \class{doctest.DocFileCase}
|
---|
1196 | instances, and \class{DocFileCase} is a subclass of \class{DocTestCase}.
|
---|
1197 |
|
---|
1198 | So both ways of creating a \class{\refmodule{unittest}.TestSuite} run
|
---|
1199 | instances of \class{DocTestCase}. This is important for a subtle reason:
|
---|
1200 | when you run \refmodule{doctest} functions yourself, you can control the
|
---|
1201 | \refmodule{doctest} options in use directly, by passing option flags to
|
---|
1202 | \refmodule{doctest} functions. However, if you're writing a
|
---|
1203 | \refmodule{unittest} framework, \refmodule{unittest} ultimately controls
|
---|
1204 | when and how tests get run. The framework author typically wants to
|
---|
1205 | control \refmodule{doctest} reporting options (perhaps, e.g., specified by
|
---|
1206 | command line options), but there's no way to pass options through
|
---|
1207 | \refmodule{unittest} to \refmodule{doctest} test runners.
|
---|
1208 |
|
---|
1209 | For this reason, \refmodule{doctest} also supports a notion of
|
---|
1210 | \refmodule{doctest} reporting flags specific to \refmodule{unittest}
|
---|
1211 | support, via this function:
|
---|
1212 |
|
---|
1213 | \begin{funcdesc}{set_unittest_reportflags}{flags}
|
---|
1214 | Set the \refmodule{doctest} reporting flags to use.
|
---|
1215 |
|
---|
1216 | Argument \var{flags} or's together option flags. See
|
---|
1217 | section~\ref{doctest-options}. Only "reporting flags" can be used.
|
---|
1218 |
|
---|
1219 | This is a module-global setting, and affects all future doctests run by
|
---|
1220 | module \refmodule{unittest}: the \method{runTest()} method of
|
---|
1221 | \class{DocTestCase} looks at the option flags specified for the test case
|
---|
1222 | when the \class{DocTestCase} instance was constructed. If no reporting
|
---|
1223 | flags were specified (which is the typical and expected case),
|
---|
1224 | \refmodule{doctest}'s \refmodule{unittest} reporting flags are or'ed into
|
---|
1225 | the option flags, and the option flags so augmented are passed to the
|
---|
1226 | \class{DocTestRunner} instance created to run the doctest. If any
|
---|
1227 | reporting flags were specified when the \class{DocTestCase} instance was
|
---|
1228 | constructed, \refmodule{doctest}'s \refmodule{unittest} reporting flags
|
---|
1229 | are ignored.
|
---|
1230 |
|
---|
1231 | The value of the \refmodule{unittest} reporting flags in effect before the
|
---|
1232 | function was called is returned by the function.
|
---|
1233 |
|
---|
1234 | \versionadded{2.4}
|
---|
1235 | \end{funcdesc}
|
---|
1236 |
|
---|
1237 |
|
---|
1238 | \subsection{Advanced API\label{doctest-advanced-api}}
|
---|
1239 |
|
---|
1240 | The basic API is a simple wrapper that's intended to make doctest easy
|
---|
1241 | to use. It is fairly flexible, and should meet most users' needs;
|
---|
1242 | however, if you require more fine-grained control over testing, or
|
---|
1243 | wish to extend doctest's capabilities, then you should use the
|
---|
1244 | advanced API.
|
---|
1245 |
|
---|
1246 | The advanced API revolves around two container classes, which are used
|
---|
1247 | to store the interactive examples extracted from doctest cases:
|
---|
1248 |
|
---|
1249 | \begin{itemize}
|
---|
1250 | \item \class{Example}: A single python statement, paired with its
|
---|
1251 | expected output.
|
---|
1252 | \item \class{DocTest}: A collection of \class{Example}s, typically
|
---|
1253 | extracted from a single docstring or text file.
|
---|
1254 | \end{itemize}
|
---|
1255 |
|
---|
1256 | Additional processing classes are defined to find, parse, and run, and
|
---|
1257 | check doctest examples:
|
---|
1258 |
|
---|
1259 | \begin{itemize}
|
---|
1260 | \item \class{DocTestFinder}: Finds all docstrings in a given module,
|
---|
1261 | and uses a \class{DocTestParser} to create a \class{DocTest}
|
---|
1262 | from every docstring that contains interactive examples.
|
---|
1263 | \item \class{DocTestParser}: Creates a \class{DocTest} object from
|
---|
1264 | a string (such as an object's docstring).
|
---|
1265 | \item \class{DocTestRunner}: Executes the examples in a
|
---|
1266 | \class{DocTest}, and uses an \class{OutputChecker} to verify
|
---|
1267 | their output.
|
---|
1268 | \item \class{OutputChecker}: Compares the actual output from a
|
---|
1269 | doctest example with the expected output, and decides whether
|
---|
1270 | they match.
|
---|
1271 | \end{itemize}
|
---|
1272 |
|
---|
1273 | The relationships among these processing classes are summarized in the
|
---|
1274 | following diagram:
|
---|
1275 |
|
---|
1276 | \begin{verbatim}
|
---|
1277 | list of:
|
---|
1278 | +------+ +---------+
|
---|
1279 | |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
|
---|
1280 | +------+ | ^ +---------+ | ^ (printed)
|
---|
1281 | | | | Example | | |
|
---|
1282 | v | | ... | v |
|
---|
1283 | DocTestParser | Example | OutputChecker
|
---|
1284 | +---------+
|
---|
1285 | \end{verbatim}
|
---|
1286 |
|
---|
1287 | \subsubsection{DocTest Objects\label{doctest-DocTest}}
|
---|
1288 | \begin{classdesc}{DocTest}{examples, globs, name, filename, lineno,
|
---|
1289 | docstring}
|
---|
1290 | A collection of doctest examples that should be run in a single
|
---|
1291 | namespace. The constructor arguments are used to initialize the
|
---|
1292 | member variables of the same names.
|
---|
1293 | \versionadded{2.4}
|
---|
1294 | \end{classdesc}
|
---|
1295 |
|
---|
1296 | \class{DocTest} defines the following member variables. They are
|
---|
1297 | initialized by the constructor, and should not be modified directly.
|
---|
1298 |
|
---|
1299 | \begin{memberdesc}{examples}
|
---|
1300 | A list of \class{Example} objects encoding the individual
|
---|
1301 | interactive Python examples that should be run by this test.
|
---|
1302 | \end{memberdesc}
|
---|
1303 |
|
---|
1304 | \begin{memberdesc}{globs}
|
---|
1305 | The namespace (aka globals) that the examples should be run in.
|
---|
1306 | This is a dictionary mapping names to values. Any changes to the
|
---|
1307 | namespace made by the examples (such as binding new variables)
|
---|
1308 | will be reflected in \member{globs} after the test is run.
|
---|
1309 | \end{memberdesc}
|
---|
1310 |
|
---|
1311 | \begin{memberdesc}{name}
|
---|
1312 | A string name identifying the \class{DocTest}. Typically, this is
|
---|
1313 | the name of the object or file that the test was extracted from.
|
---|
1314 | \end{memberdesc}
|
---|
1315 |
|
---|
1316 | \begin{memberdesc}{filename}
|
---|
1317 | The name of the file that this \class{DocTest} was extracted from;
|
---|
1318 | or \code{None} if the filename is unknown, or if the
|
---|
1319 | \class{DocTest} was not extracted from a file.
|
---|
1320 | \end{memberdesc}
|
---|
1321 |
|
---|
1322 | \begin{memberdesc}{lineno}
|
---|
1323 | The line number within \member{filename} where this
|
---|
1324 | \class{DocTest} begins, or \code{None} if the line number is
|
---|
1325 | unavailable. This line number is zero-based with respect to the
|
---|
1326 | beginning of the file.
|
---|
1327 | \end{memberdesc}
|
---|
1328 |
|
---|
1329 | \begin{memberdesc}{docstring}
|
---|
1330 | The string that the test was extracted from, or `None` if the
|
---|
1331 | string is unavailable, or if the test was not extracted from a
|
---|
1332 | string.
|
---|
1333 | \end{memberdesc}
|
---|
1334 |
|
---|
1335 | \subsubsection{Example Objects\label{doctest-Example}}
|
---|
1336 | \begin{classdesc}{Example}{source, want\optional{,
|
---|
1337 | exc_msg}\optional{, lineno}\optional{,
|
---|
1338 | indent}\optional{, options}}
|
---|
1339 | A single interactive example, consisting of a Python statement and
|
---|
1340 | its expected output. The constructor arguments are used to
|
---|
1341 | initialize the member variables of the same names.
|
---|
1342 | \versionadded{2.4}
|
---|
1343 | \end{classdesc}
|
---|
1344 |
|
---|
1345 | \class{Example} defines the following member variables. They are
|
---|
1346 | initialized by the constructor, and should not be modified directly.
|
---|
1347 |
|
---|
1348 | \begin{memberdesc}{source}
|
---|
1349 | A string containing the example's source code. This source code
|
---|
1350 | consists of a single Python statement, and always ends with a
|
---|
1351 | newline; the constructor adds a newline when necessary.
|
---|
1352 | \end{memberdesc}
|
---|
1353 |
|
---|
1354 | \begin{memberdesc}{want}
|
---|
1355 | The expected output from running the example's source code (either
|
---|
1356 | from stdout, or a traceback in case of exception). \member{want}
|
---|
1357 | ends with a newline unless no output is expected, in which case
|
---|
1358 | it's an empty string. The constructor adds a newline when
|
---|
1359 | necessary.
|
---|
1360 | \end{memberdesc}
|
---|
1361 |
|
---|
1362 | \begin{memberdesc}{exc_msg}
|
---|
1363 | The exception message generated by the example, if the example is
|
---|
1364 | expected to generate an exception; or \code{None} if it is not
|
---|
1365 | expected to generate an exception. This exception message is
|
---|
1366 | compared against the return value of
|
---|
1367 | \function{traceback.format_exception_only()}. \member{exc_msg}
|
---|
1368 | ends with a newline unless it's \code{None}. The constructor adds
|
---|
1369 | a newline if needed.
|
---|
1370 | \end{memberdesc}
|
---|
1371 |
|
---|
1372 | \begin{memberdesc}{lineno}
|
---|
1373 | The line number within the string containing this example where
|
---|
1374 | the example begins. This line number is zero-based with respect
|
---|
1375 | to the beginning of the containing string.
|
---|
1376 | \end{memberdesc}
|
---|
1377 |
|
---|
1378 | \begin{memberdesc}{indent}
|
---|
1379 | The example's indentation in the containing string, i.e., the
|
---|
1380 | number of space characters that precede the example's first
|
---|
1381 | prompt.
|
---|
1382 | \end{memberdesc}
|
---|
1383 |
|
---|
1384 | \begin{memberdesc}{options}
|
---|
1385 | A dictionary mapping from option flags to \code{True} or
|
---|
1386 | \code{False}, which is used to override default options for this
|
---|
1387 | example. Any option flags not contained in this dictionary are
|
---|
1388 | left at their default value (as specified by the
|
---|
1389 | \class{DocTestRunner}'s \member{optionflags}).
|
---|
1390 | By default, no options are set.
|
---|
1391 | \end{memberdesc}
|
---|
1392 |
|
---|
1393 | \subsubsection{DocTestFinder objects\label{doctest-DocTestFinder}}
|
---|
1394 | \begin{classdesc}{DocTestFinder}{\optional{verbose}\optional{,
|
---|
1395 | parser}\optional{, recurse}\optional{,
|
---|
1396 | exclude_empty}}
|
---|
1397 | A processing class used to extract the \class{DocTest}s that are
|
---|
1398 | relevant to a given object, from its docstring and the docstrings
|
---|
1399 | of its contained objects. \class{DocTest}s can currently be
|
---|
1400 | extracted from the following object types: modules, functions,
|
---|
1401 | classes, methods, staticmethods, classmethods, and properties.
|
---|
1402 |
|
---|
1403 | The optional argument \var{verbose} can be used to display the
|
---|
1404 | objects searched by the finder. It defaults to \code{False} (no
|
---|
1405 | output).
|
---|
1406 |
|
---|
1407 | The optional argument \var{parser} specifies the
|
---|
1408 | \class{DocTestParser} object (or a drop-in replacement) that is
|
---|
1409 | used to extract doctests from docstrings.
|
---|
1410 |
|
---|
1411 | If the optional argument \var{recurse} is false, then
|
---|
1412 | \method{DocTestFinder.find()} will only examine the given object,
|
---|
1413 | and not any contained objects.
|
---|
1414 |
|
---|
1415 | If the optional argument \var{exclude_empty} is false, then
|
---|
1416 | \method{DocTestFinder.find()} will include tests for objects with
|
---|
1417 | empty docstrings.
|
---|
1418 |
|
---|
1419 | \versionadded{2.4}
|
---|
1420 | \end{classdesc}
|
---|
1421 |
|
---|
1422 | \class{DocTestFinder} defines the following method:
|
---|
1423 |
|
---|
1424 | \begin{methoddesc}{find}{obj\optional{, name}\optional{,
|
---|
1425 | module}\optional{, globs}\optional{, extraglobs}}
|
---|
1426 | Return a list of the \class{DocTest}s that are defined by
|
---|
1427 | \var{obj}'s docstring, or by any of its contained objects'
|
---|
1428 | docstrings.
|
---|
1429 |
|
---|
1430 | The optional argument \var{name} specifies the object's name; this
|
---|
1431 | name will be used to construct names for the returned
|
---|
1432 | \class{DocTest}s. If \var{name} is not specified, then
|
---|
1433 | \code{\var{obj}.__name__} is used.
|
---|
1434 |
|
---|
1435 | The optional parameter \var{module} is the module that contains
|
---|
1436 | the given object. If the module is not specified or is None, then
|
---|
1437 | the test finder will attempt to automatically determine the
|
---|
1438 | correct module. The object's module is used:
|
---|
1439 |
|
---|
1440 | \begin{itemize}
|
---|
1441 | \item As a default namespace, if \var{globs} is not specified.
|
---|
1442 | \item To prevent the DocTestFinder from extracting DocTests
|
---|
1443 | from objects that are imported from other modules. (Contained
|
---|
1444 | objects with modules other than \var{module} are ignored.)
|
---|
1445 | \item To find the name of the file containing the object.
|
---|
1446 | \item To help find the line number of the object within its file.
|
---|
1447 | \end{itemize}
|
---|
1448 |
|
---|
1449 | If \var{module} is \code{False}, no attempt to find the module
|
---|
1450 | will be made. This is obscure, of use mostly in testing doctest
|
---|
1451 | itself: if \var{module} is \code{False}, or is \code{None} but
|
---|
1452 | cannot be found automatically, then all objects are considered to
|
---|
1453 | belong to the (non-existent) module, so all contained objects will
|
---|
1454 | (recursively) be searched for doctests.
|
---|
1455 |
|
---|
1456 | The globals for each \class{DocTest} is formed by combining
|
---|
1457 | \var{globs} and \var{extraglobs} (bindings in \var{extraglobs}
|
---|
1458 | override bindings in \var{globs}). A new shallow copy of the globals
|
---|
1459 | dictionary is created for each \class{DocTest}. If \var{globs} is
|
---|
1460 | not specified, then it defaults to the module's \var{__dict__}, if
|
---|
1461 | specified, or \code{\{\}} otherwise. If \var{extraglobs} is not
|
---|
1462 | specified, then it defaults to \code{\{\}}.
|
---|
1463 | \end{methoddesc}
|
---|
1464 |
|
---|
1465 | \subsubsection{DocTestParser objects\label{doctest-DocTestParser}}
|
---|
1466 | \begin{classdesc}{DocTestParser}{}
|
---|
1467 | A processing class used to extract interactive examples from a
|
---|
1468 | string, and use them to create a \class{DocTest} object.
|
---|
1469 | \versionadded{2.4}
|
---|
1470 | \end{classdesc}
|
---|
1471 |
|
---|
1472 | \class{DocTestParser} defines the following methods:
|
---|
1473 |
|
---|
1474 | \begin{methoddesc}{get_doctest}{string, globs, name, filename, lineno}
|
---|
1475 | Extract all doctest examples from the given string, and collect
|
---|
1476 | them into a \class{DocTest} object.
|
---|
1477 |
|
---|
1478 | \var{globs}, \var{name}, \var{filename}, and \var{lineno} are
|
---|
1479 | attributes for the new \class{DocTest} object. See the
|
---|
1480 | documentation for \class{DocTest} for more information.
|
---|
1481 | \end{methoddesc}
|
---|
1482 |
|
---|
1483 | \begin{methoddesc}{get_examples}{string\optional{, name}}
|
---|
1484 | Extract all doctest examples from the given string, and return
|
---|
1485 | them as a list of \class{Example} objects. Line numbers are
|
---|
1486 | 0-based. The optional argument \var{name} is a name identifying
|
---|
1487 | this string, and is only used for error messages.
|
---|
1488 | \end{methoddesc}
|
---|
1489 |
|
---|
1490 | \begin{methoddesc}{parse}{string\optional{, name}}
|
---|
1491 | Divide the given string into examples and intervening text, and
|
---|
1492 | return them as a list of alternating \class{Example}s and strings.
|
---|
1493 | Line numbers for the \class{Example}s are 0-based. The optional
|
---|
1494 | argument \var{name} is a name identifying this string, and is only
|
---|
1495 | used for error messages.
|
---|
1496 | \end{methoddesc}
|
---|
1497 |
|
---|
1498 | \subsubsection{DocTestRunner objects\label{doctest-DocTestRunner}}
|
---|
1499 | \begin{classdesc}{DocTestRunner}{\optional{checker}\optional{,
|
---|
1500 | verbose}\optional{, optionflags}}
|
---|
1501 | A processing class used to execute and verify the interactive
|
---|
1502 | examples in a \class{DocTest}.
|
---|
1503 |
|
---|
1504 | The comparison between expected outputs and actual outputs is done
|
---|
1505 | by an \class{OutputChecker}. This comparison may be customized
|
---|
1506 | with a number of option flags; see section~\ref{doctest-options}
|
---|
1507 | for more information. If the option flags are insufficient, then
|
---|
1508 | the comparison may also be customized by passing a subclass of
|
---|
1509 | \class{OutputChecker} to the constructor.
|
---|
1510 |
|
---|
1511 | The test runner's display output can be controlled in two ways.
|
---|
1512 | First, an output function can be passed to
|
---|
1513 | \method{TestRunner.run()}; this function will be called with
|
---|
1514 | strings that should be displayed. It defaults to
|
---|
1515 | \code{sys.stdout.write}. If capturing the output is not
|
---|
1516 | sufficient, then the display output can be also customized by
|
---|
1517 | subclassing DocTestRunner, and overriding the methods
|
---|
1518 | \method{report_start}, \method{report_success},
|
---|
1519 | \method{report_unexpected_exception}, and \method{report_failure}.
|
---|
1520 |
|
---|
1521 | The optional keyword argument \var{checker} specifies the
|
---|
1522 | \class{OutputChecker} object (or drop-in replacement) that should
|
---|
1523 | be used to compare the expected outputs to the actual outputs of
|
---|
1524 | doctest examples.
|
---|
1525 |
|
---|
1526 | The optional keyword argument \var{verbose} controls the
|
---|
1527 | \class{DocTestRunner}'s verbosity. If \var{verbose} is
|
---|
1528 | \code{True}, then information is printed about each example, as it
|
---|
1529 | is run. If \var{verbose} is \code{False}, then only failures are
|
---|
1530 | printed. If \var{verbose} is unspecified, or \code{None}, then
|
---|
1531 | verbose output is used iff the command-line switch \programopt{-v}
|
---|
1532 | is used.
|
---|
1533 |
|
---|
1534 | The optional keyword argument \var{optionflags} can be used to
|
---|
1535 | control how the test runner compares expected output to actual
|
---|
1536 | output, and how it displays failures. For more information, see
|
---|
1537 | section~\ref{doctest-options}.
|
---|
1538 |
|
---|
1539 | \versionadded{2.4}
|
---|
1540 | \end{classdesc}
|
---|
1541 |
|
---|
1542 | \class{DocTestParser} defines the following methods:
|
---|
1543 |
|
---|
1544 | \begin{methoddesc}{report_start}{out, test, example}
|
---|
1545 | Report that the test runner is about to process the given example.
|
---|
1546 | This method is provided to allow subclasses of
|
---|
1547 | \class{DocTestRunner} to customize their output; it should not be
|
---|
1548 | called directly.
|
---|
1549 |
|
---|
1550 | \var{example} is the example about to be processed. \var{test} is
|
---|
1551 | the test containing \var{example}. \var{out} is the output
|
---|
1552 | function that was passed to \method{DocTestRunner.run()}.
|
---|
1553 | \end{methoddesc}
|
---|
1554 |
|
---|
1555 | \begin{methoddesc}{report_success}{out, test, example, got}
|
---|
1556 | Report that the given example ran successfully. This method is
|
---|
1557 | provided to allow subclasses of \class{DocTestRunner} to customize
|
---|
1558 | their output; it should not be called directly.
|
---|
1559 |
|
---|
1560 | \var{example} is the example about to be processed. \var{got} is
|
---|
1561 | the actual output from the example. \var{test} is the test
|
---|
1562 | containing \var{example}. \var{out} is the output function that
|
---|
1563 | was passed to \method{DocTestRunner.run()}.
|
---|
1564 | \end{methoddesc}
|
---|
1565 |
|
---|
1566 | \begin{methoddesc}{report_failure}{out, test, example, got}
|
---|
1567 | Report that the given example failed. This method is provided to
|
---|
1568 | allow subclasses of \class{DocTestRunner} to customize their
|
---|
1569 | output; it should not be called directly.
|
---|
1570 |
|
---|
1571 | \var{example} is the example about to be processed. \var{got} is
|
---|
1572 | the actual output from the example. \var{test} is the test
|
---|
1573 | containing \var{example}. \var{out} is the output function that
|
---|
1574 | was passed to \method{DocTestRunner.run()}.
|
---|
1575 | \end{methoddesc}
|
---|
1576 |
|
---|
1577 | \begin{methoddesc}{report_unexpected_exception}{out, test, example, exc_info}
|
---|
1578 | Report that the given example raised an unexpected exception.
|
---|
1579 | This method is provided to allow subclasses of
|
---|
1580 | \class{DocTestRunner} to customize their output; it should not be
|
---|
1581 | called directly.
|
---|
1582 |
|
---|
1583 | \var{example} is the example about to be processed.
|
---|
1584 | \var{exc_info} is a tuple containing information about the
|
---|
1585 | unexpected exception (as returned by \function{sys.exc_info()}).
|
---|
1586 | \var{test} is the test containing \var{example}. \var{out} is the
|
---|
1587 | output function that was passed to \method{DocTestRunner.run()}.
|
---|
1588 | \end{methoddesc}
|
---|
1589 |
|
---|
1590 | \begin{methoddesc}{run}{test\optional{, compileflags}\optional{,
|
---|
1591 | out}\optional{, clear_globs}}
|
---|
1592 | Run the examples in \var{test} (a \class{DocTest} object), and
|
---|
1593 | display the results using the writer function \var{out}.
|
---|
1594 |
|
---|
1595 | The examples are run in the namespace \code{test.globs}. If
|
---|
1596 | \var{clear_globs} is true (the default), then this namespace will
|
---|
1597 | be cleared after the test runs, to help with garbage collection.
|
---|
1598 | If you would like to examine the namespace after the test
|
---|
1599 | completes, then use \var{clear_globs=False}.
|
---|
1600 |
|
---|
1601 | \var{compileflags} gives the set of flags that should be used by
|
---|
1602 | the Python compiler when running the examples. If not specified,
|
---|
1603 | then it will default to the set of future-import flags that apply
|
---|
1604 | to \var{globs}.
|
---|
1605 |
|
---|
1606 | The output of each example is checked using the
|
---|
1607 | \class{DocTestRunner}'s output checker, and the results are
|
---|
1608 | formatted by the \method{DocTestRunner.report_*} methods.
|
---|
1609 | \end{methoddesc}
|
---|
1610 |
|
---|
1611 | \begin{methoddesc}{summarize}{\optional{verbose}}
|
---|
1612 | Print a summary of all the test cases that have been run by this
|
---|
1613 | DocTestRunner, and return a tuple \samp{(\var{failure_count},
|
---|
1614 | \var{test_count})}.
|
---|
1615 |
|
---|
1616 | The optional \var{verbose} argument controls how detailed the
|
---|
1617 | summary is. If the verbosity is not specified, then the
|
---|
1618 | \class{DocTestRunner}'s verbosity is used.
|
---|
1619 | \end{methoddesc}
|
---|
1620 |
|
---|
1621 | \subsubsection{OutputChecker objects\label{doctest-OutputChecker}}
|
---|
1622 |
|
---|
1623 | \begin{classdesc}{OutputChecker}{}
|
---|
1624 | A class used to check the whether the actual output from a doctest
|
---|
1625 | example matches the expected output. \class{OutputChecker}
|
---|
1626 | defines two methods: \method{check_output}, which compares a given
|
---|
1627 | pair of outputs, and returns true if they match; and
|
---|
1628 | \method{output_difference}, which returns a string describing the
|
---|
1629 | differences between two outputs.
|
---|
1630 | \versionadded{2.4}
|
---|
1631 | \end{classdesc}
|
---|
1632 |
|
---|
1633 | \class{OutputChecker} defines the following methods:
|
---|
1634 |
|
---|
1635 | \begin{methoddesc}{check_output}{want, got, optionflags}
|
---|
1636 | Return \code{True} iff the actual output from an example
|
---|
1637 | (\var{got}) matches the expected output (\var{want}). These
|
---|
1638 | strings are always considered to match if they are identical; but
|
---|
1639 | depending on what option flags the test runner is using, several
|
---|
1640 | non-exact match types are also possible. See
|
---|
1641 | section~\ref{doctest-options} for more information about option
|
---|
1642 | flags.
|
---|
1643 | \end{methoddesc}
|
---|
1644 |
|
---|
1645 | \begin{methoddesc}{output_difference}{example, got, optionflags}
|
---|
1646 | Return a string describing the differences between the expected
|
---|
1647 | output for a given example (\var{example}) and the actual output
|
---|
1648 | (\var{got}). \var{optionflags} is the set of option flags used to
|
---|
1649 | compare \var{want} and \var{got}.
|
---|
1650 | \end{methoddesc}
|
---|
1651 |
|
---|
1652 | \subsection{Debugging\label{doctest-debugging}}
|
---|
1653 |
|
---|
1654 | Doctest provides several mechanisms for debugging doctest examples:
|
---|
1655 |
|
---|
1656 | \begin{itemize}
|
---|
1657 | \item Several functions convert doctests to executable Python
|
---|
1658 | programs, which can be run under the Python debugger, \refmodule{pdb}.
|
---|
1659 | \item The \class{DebugRunner} class is a subclass of
|
---|
1660 | \class{DocTestRunner} that raises an exception for the first
|
---|
1661 | failing example, containing information about that example.
|
---|
1662 | This information can be used to perform post-mortem debugging on
|
---|
1663 | the example.
|
---|
1664 | \item The \refmodule{unittest} cases generated by \function{DocTestSuite()}
|
---|
1665 | support the \method{debug()} method defined by
|
---|
1666 | \class{\refmodule{unittest}.TestCase}.
|
---|
1667 | \item You can add a call to \function{\refmodule{pdb}.set_trace()} in a
|
---|
1668 | doctest example, and you'll drop into the Python debugger when that
|
---|
1669 | line is executed. Then you can inspect current values of variables,
|
---|
1670 | and so on. For example, suppose \file{a.py} contains just this
|
---|
1671 | module docstring:
|
---|
1672 |
|
---|
1673 | \begin{verbatim}
|
---|
1674 | """
|
---|
1675 | >>> def f(x):
|
---|
1676 | ... g(x*2)
|
---|
1677 | >>> def g(x):
|
---|
1678 | ... print x+3
|
---|
1679 | ... import pdb; pdb.set_trace()
|
---|
1680 | >>> f(3)
|
---|
1681 | 9
|
---|
1682 | """
|
---|
1683 | \end{verbatim}
|
---|
1684 |
|
---|
1685 | Then an interactive Python session may look like this:
|
---|
1686 |
|
---|
1687 | \begin{verbatim}
|
---|
1688 | >>> import a, doctest
|
---|
1689 | >>> doctest.testmod(a)
|
---|
1690 | --Return--
|
---|
1691 | > <doctest a[1]>(3)g()->None
|
---|
1692 | -> import pdb; pdb.set_trace()
|
---|
1693 | (Pdb) list
|
---|
1694 | 1 def g(x):
|
---|
1695 | 2 print x+3
|
---|
1696 | 3 -> import pdb; pdb.set_trace()
|
---|
1697 | [EOF]
|
---|
1698 | (Pdb) print x
|
---|
1699 | 6
|
---|
1700 | (Pdb) step
|
---|
1701 | --Return--
|
---|
1702 | > <doctest a[0]>(2)f()->None
|
---|
1703 | -> g(x*2)
|
---|
1704 | (Pdb) list
|
---|
1705 | 1 def f(x):
|
---|
1706 | 2 -> g(x*2)
|
---|
1707 | [EOF]
|
---|
1708 | (Pdb) print x
|
---|
1709 | 3
|
---|
1710 | (Pdb) step
|
---|
1711 | --Return--
|
---|
1712 | > <doctest a[2]>(1)?()->None
|
---|
1713 | -> f(3)
|
---|
1714 | (Pdb) cont
|
---|
1715 | (0, 3)
|
---|
1716 | >>>
|
---|
1717 | \end{verbatim}
|
---|
1718 |
|
---|
1719 | \versionchanged[The ability to use \code{\refmodule{pdb}.set_trace()}
|
---|
1720 | usefully inside doctests was added]{2.4}
|
---|
1721 | \end{itemize}
|
---|
1722 |
|
---|
1723 | Functions that convert doctests to Python code, and possibly run
|
---|
1724 | the synthesized code under the debugger:
|
---|
1725 |
|
---|
1726 | \begin{funcdesc}{script_from_examples}{s}
|
---|
1727 | Convert text with examples to a script.
|
---|
1728 |
|
---|
1729 | Argument \var{s} is a string containing doctest examples. The string
|
---|
1730 | is converted to a Python script, where doctest examples in \var{s}
|
---|
1731 | are converted to regular code, and everything else is converted to
|
---|
1732 | Python comments. The generated script is returned as a string.
|
---|
1733 | For example,
|
---|
1734 |
|
---|
1735 | \begin{verbatim}
|
---|
1736 | import doctest
|
---|
1737 | print doctest.script_from_examples(r"""
|
---|
1738 | Set x and y to 1 and 2.
|
---|
1739 | >>> x, y = 1, 2
|
---|
1740 |
|
---|
1741 | Print their sum:
|
---|
1742 | >>> print x+y
|
---|
1743 | 3
|
---|
1744 | """)
|
---|
1745 | \end{verbatim}
|
---|
1746 |
|
---|
1747 | displays:
|
---|
1748 |
|
---|
1749 | \begin{verbatim}
|
---|
1750 | # Set x and y to 1 and 2.
|
---|
1751 | x, y = 1, 2
|
---|
1752 | #
|
---|
1753 | # Print their sum:
|
---|
1754 | print x+y
|
---|
1755 | # Expected:
|
---|
1756 | ## 3
|
---|
1757 | \end{verbatim}
|
---|
1758 |
|
---|
1759 | This function is used internally by other functions (see below), but
|
---|
1760 | can also be useful when you want to transform an interactive Python
|
---|
1761 | session into a Python script.
|
---|
1762 |
|
---|
1763 | \versionadded{2.4}
|
---|
1764 | \end{funcdesc}
|
---|
1765 |
|
---|
1766 | \begin{funcdesc}{testsource}{module, name}
|
---|
1767 | Convert the doctest for an object to a script.
|
---|
1768 |
|
---|
1769 | Argument \var{module} is a module object, or dotted name of a module,
|
---|
1770 | containing the object whose doctests are of interest. Argument
|
---|
1771 | \var{name} is the name (within the module) of the object with the
|
---|
1772 | doctests of interest. The result is a string, containing the
|
---|
1773 | object's docstring converted to a Python script, as described for
|
---|
1774 | \function{script_from_examples()} above. For example, if module
|
---|
1775 | \file{a.py} contains a top-level function \function{f()}, then
|
---|
1776 |
|
---|
1777 | \begin{verbatim}
|
---|
1778 | import a, doctest
|
---|
1779 | print doctest.testsource(a, "a.f")
|
---|
1780 | \end{verbatim}
|
---|
1781 |
|
---|
1782 | prints a script version of function \function{f()}'s docstring,
|
---|
1783 | with doctests converted to code, and the rest placed in comments.
|
---|
1784 |
|
---|
1785 | \versionadded{2.3}
|
---|
1786 | \end{funcdesc}
|
---|
1787 |
|
---|
1788 | \begin{funcdesc}{debug}{module, name\optional{, pm}}
|
---|
1789 | Debug the doctests for an object.
|
---|
1790 |
|
---|
1791 | The \var{module} and \var{name} arguments are the same as for function
|
---|
1792 | \function{testsource()} above. The synthesized Python script for the
|
---|
1793 | named object's docstring is written to a temporary file, and then that
|
---|
1794 | file is run under the control of the Python debugger, \refmodule{pdb}.
|
---|
1795 |
|
---|
1796 | A shallow copy of \code{\var{module}.__dict__} is used for both local
|
---|
1797 | and global execution context.
|
---|
1798 |
|
---|
1799 | Optional argument \var{pm} controls whether post-mortem debugging is
|
---|
1800 | used. If \var{pm} has a true value, the script file is run directly, and
|
---|
1801 | the debugger gets involved only if the script terminates via raising an
|
---|
1802 | unhandled exception. If it does, then post-mortem debugging is invoked,
|
---|
1803 | via \code{\refmodule{pdb}.post_mortem()}, passing the traceback object
|
---|
1804 | from the unhandled exception. If \var{pm} is not specified, or is false,
|
---|
1805 | the script is run under the debugger from the start, via passing an
|
---|
1806 | appropriate \function{execfile()} call to \code{\refmodule{pdb}.run()}.
|
---|
1807 |
|
---|
1808 | \versionadded{2.3}
|
---|
1809 |
|
---|
1810 | \versionchanged[The \var{pm} argument was added]{2.4}
|
---|
1811 | \end{funcdesc}
|
---|
1812 |
|
---|
1813 | \begin{funcdesc}{debug_src}{src\optional{, pm}\optional{, globs}}
|
---|
1814 | Debug the doctests in a string.
|
---|
1815 |
|
---|
1816 | This is like function \function{debug()} above, except that
|
---|
1817 | a string containing doctest examples is specified directly, via
|
---|
1818 | the \var{src} argument.
|
---|
1819 |
|
---|
1820 | Optional argument \var{pm} has the same meaning as in function
|
---|
1821 | \function{debug()} above.
|
---|
1822 |
|
---|
1823 | Optional argument \var{globs} gives a dictionary to use as both
|
---|
1824 | local and global execution context. If not specified, or \code{None},
|
---|
1825 | an empty dictionary is used. If specified, a shallow copy of the
|
---|
1826 | dictionary is used.
|
---|
1827 |
|
---|
1828 | \versionadded{2.4}
|
---|
1829 | \end{funcdesc}
|
---|
1830 |
|
---|
1831 | The \class{DebugRunner} class, and the special exceptions it may raise,
|
---|
1832 | are of most interest to testing framework authors, and will only be
|
---|
1833 | sketched here. See the source code, and especially \class{DebugRunner}'s
|
---|
1834 | docstring (which is a doctest!) for more details:
|
---|
1835 |
|
---|
1836 | \begin{classdesc}{DebugRunner}{\optional{checker}\optional{,
|
---|
1837 | verbose}\optional{, optionflags}}
|
---|
1838 |
|
---|
1839 | A subclass of \class{DocTestRunner} that raises an exception as
|
---|
1840 | soon as a failure is encountered. If an unexpected exception
|
---|
1841 | occurs, an \exception{UnexpectedException} exception is raised,
|
---|
1842 | containing the test, the example, and the original exception. If
|
---|
1843 | the output doesn't match, then a \exception{DocTestFailure}
|
---|
1844 | exception is raised, containing the test, the example, and the
|
---|
1845 | actual output.
|
---|
1846 |
|
---|
1847 | For information about the constructor parameters and methods, see
|
---|
1848 | the documentation for \class{DocTestRunner} in
|
---|
1849 | section~\ref{doctest-advanced-api}.
|
---|
1850 | \end{classdesc}
|
---|
1851 |
|
---|
1852 | There are two exceptions that may be raised by \class{DebugRunner}
|
---|
1853 | instances:
|
---|
1854 |
|
---|
1855 | \begin{excclassdesc}{DocTestFailure}{test, example, got}
|
---|
1856 | An exception thrown by \class{DocTestRunner} to signal that a
|
---|
1857 | doctest example's actual output did not match its expected output.
|
---|
1858 | The constructor arguments are used to initialize the member
|
---|
1859 | variables of the same names.
|
---|
1860 | \end{excclassdesc}
|
---|
1861 | \exception{DocTestFailure} defines the following member variables:
|
---|
1862 | \begin{memberdesc}{test}
|
---|
1863 | The \class{DocTest} object that was being run when the example failed.
|
---|
1864 | \end{memberdesc}
|
---|
1865 | \begin{memberdesc}{example}
|
---|
1866 | The \class{Example} that failed.
|
---|
1867 | \end{memberdesc}
|
---|
1868 | \begin{memberdesc}{got}
|
---|
1869 | The example's actual output.
|
---|
1870 | \end{memberdesc}
|
---|
1871 |
|
---|
1872 | \begin{excclassdesc}{UnexpectedException}{test, example, exc_info}
|
---|
1873 | An exception thrown by \class{DocTestRunner} to signal that a
|
---|
1874 | doctest example raised an unexpected exception. The constructor
|
---|
1875 | arguments are used to initialize the member variables of the same
|
---|
1876 | names.
|
---|
1877 | \end{excclassdesc}
|
---|
1878 | \exception{UnexpectedException} defines the following member variables:
|
---|
1879 | \begin{memberdesc}{test}
|
---|
1880 | The \class{DocTest} object that was being run when the example failed.
|
---|
1881 | \end{memberdesc}
|
---|
1882 | \begin{memberdesc}{example}
|
---|
1883 | The \class{Example} that failed.
|
---|
1884 | \end{memberdesc}
|
---|
1885 | \begin{memberdesc}{exc_info}
|
---|
1886 | A tuple containing information about the unexpected exception, as
|
---|
1887 | returned by \function{sys.exc_info()}.
|
---|
1888 | \end{memberdesc}
|
---|
1889 |
|
---|
1890 | \subsection{Soapbox\label{doctest-soapbox}}
|
---|
1891 |
|
---|
1892 | As mentioned in the introduction, \refmodule{doctest} has grown to have
|
---|
1893 | three primary uses:
|
---|
1894 |
|
---|
1895 | \begin{enumerate}
|
---|
1896 | \item Checking examples in docstrings.
|
---|
1897 | \item Regression testing.
|
---|
1898 | \item Executable documentation / literate testing.
|
---|
1899 | \end{enumerate}
|
---|
1900 |
|
---|
1901 | These uses have different requirements, and it is important to
|
---|
1902 | distinguish them. In particular, filling your docstrings with obscure
|
---|
1903 | test cases makes for bad documentation.
|
---|
1904 |
|
---|
1905 | When writing a docstring, choose docstring examples with care.
|
---|
1906 | There's an art to this that needs to be learned---it may not be
|
---|
1907 | natural at first. Examples should add genuine value to the
|
---|
1908 | documentation. A good example can often be worth many words.
|
---|
1909 | If done with care, the examples will be invaluable for your users, and
|
---|
1910 | will pay back the time it takes to collect them many times over as the
|
---|
1911 | years go by and things change. I'm still amazed at how often one of
|
---|
1912 | my \refmodule{doctest} examples stops working after a "harmless"
|
---|
1913 | change.
|
---|
1914 |
|
---|
1915 | Doctest also makes an excellent tool for regression testing, especially if
|
---|
1916 | you don't skimp on explanatory text. By interleaving prose and examples,
|
---|
1917 | it becomes much easier to keep track of what's actually being tested, and
|
---|
1918 | why. When a test fails, good prose can make it much easier to figure out
|
---|
1919 | what the problem is, and how it should be fixed. It's true that you could
|
---|
1920 | write extensive comments in code-based testing, but few programmers do.
|
---|
1921 | Many have found that using doctest approaches instead leads to much clearer
|
---|
1922 | tests. Perhaps this is simply because doctest makes writing prose a little
|
---|
1923 | easier than writing code, while writing comments in code is a little
|
---|
1924 | harder. I think it goes deeper than just that: the natural attitude
|
---|
1925 | when writing a doctest-based test is that you want to explain the fine
|
---|
1926 | points of your software, and illustrate them with examples. This in
|
---|
1927 | turn naturally leads to test files that start with the simplest features,
|
---|
1928 | and logically progress to complications and edge cases. A coherent
|
---|
1929 | narrative is the result, instead of a collection of isolated functions
|
---|
1930 | that test isolated bits of functionality seemingly at random. It's
|
---|
1931 | a different attitude, and produces different results, blurring the
|
---|
1932 | distinction between testing and explaining.
|
---|
1933 |
|
---|
1934 | Regression testing is best confined to dedicated objects or files. There
|
---|
1935 | are several options for organizing tests:
|
---|
1936 |
|
---|
1937 | \begin{itemize}
|
---|
1938 | \item Write text files containing test cases as interactive examples,
|
---|
1939 | and test the files using \function{testfile()} or
|
---|
1940 | \function{DocFileSuite()}. This is recommended, although is
|
---|
1941 | easiest to do for new projects, designed from the start to use
|
---|
1942 | doctest.
|
---|
1943 | \item Define functions named \code{_regrtest_\textit{topic}} that
|
---|
1944 | consist of single docstrings, containing test cases for the
|
---|
1945 | named topics. These functions can be included in the same file
|
---|
1946 | as the module, or separated out into a separate test file.
|
---|
1947 | \item Define a \code{__test__} dictionary mapping from regression test
|
---|
1948 | topics to docstrings containing test cases.
|
---|
1949 | \end{itemize}
|
---|