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