Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 1 | # Module doctest. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2 | # Released to the public domain 16-Jan-2001, |
| 3 | # by Tim Peters (tim.one@home.com). |
| 4 | |
| 5 | # Provided as-is; use at your own risk; no warranty; no promises; enjoy! |
| 6 | |
| 7 | """Module doctest -- a framework for running examples in docstrings. |
| 8 | |
| 9 | NORMAL USAGE |
| 10 | |
| 11 | In normal use, end each module M with: |
| 12 | |
| 13 | def _test(): |
| 14 | import doctest, M # replace M with your module's name |
| 15 | return doctest.testmod(M) # ditto |
| 16 | |
| 17 | if __name__ == "__main__": |
| 18 | _test() |
| 19 | |
| 20 | Then running the module as a script will cause the examples in the |
| 21 | docstrings to get executed and verified: |
| 22 | |
| 23 | python M.py |
| 24 | |
| 25 | This won't display anything unless an example fails, in which case the |
| 26 | failing example(s) and the cause(s) of the failure(s) are printed to stdout |
| 27 | (why not stderr? because stderr is a lame hack <0.2 wink>), and the final |
| 28 | line of output is "Test failed.". |
| 29 | |
| 30 | Run it with the -v switch instead: |
| 31 | |
| 32 | python M.py -v |
| 33 | |
| 34 | and a detailed report of all examples tried is printed to stdout, along |
| 35 | with assorted summaries at the end. |
| 36 | |
| 37 | You can force verbose mode by passing "verbose=1" to testmod, or prohibit |
| 38 | it by passing "verbose=0". In either of those cases, sys.argv is not |
| 39 | examined by testmod. |
| 40 | |
| 41 | In any case, testmod returns a 2-tuple of ints (f, t), where f is the |
| 42 | number of docstring examples that failed and t is the total number of |
| 43 | docstring examples attempted. |
| 44 | |
| 45 | |
| 46 | WHICH DOCSTRINGS ARE EXAMINED? |
| 47 | |
| 48 | + M.__doc__. |
| 49 | |
| 50 | + f.__doc__ for all functions f in M.__dict__.values(), except those |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 51 | defined in other modules. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 52 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 53 | + C.__doc__ for all classes C in M.__dict__.values(), except those |
| 54 | defined in other modules. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 55 | |
| 56 | + If M.__test__ exists and "is true", it must be a dict, and |
| 57 | each entry maps a (string) name to a function object, class object, or |
| 58 | string. Function and class object docstrings found from M.__test__ |
| 59 | are searched even if the name is private, and strings are searched |
| 60 | directly as if they were docstrings. In output, a key K in M.__test__ |
| 61 | appears with name |
| 62 | <name of M>.__test__.K |
| 63 | |
| 64 | Any classes found are recursively searched similarly, to test docstrings in |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 65 | their contained methods and nested classes. All names reached from |
| 66 | M.__test__ are searched. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 67 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 68 | Optionally, functions with private names can be skipped (unless listed in |
| 69 | M.__test__) by supplying a function to the "isprivate" argument that will |
| 70 | identify private functions. For convenience, one such function is |
| 71 | supplied. docttest.is_private considers a name to be private if it begins |
| 72 | with an underscore (like "_my_func") but doesn't both begin and end with |
| 73 | (at least) two underscores (like "__init__"). By supplying this function |
| 74 | or your own "isprivate" function to testmod, the behavior can be customized. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 75 | |
| 76 | If you want to test docstrings in objects with private names too, stuff |
| 77 | them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your |
| 78 | own isprivate function to Tester's constructor, or call the rundoc method |
| 79 | of a Tester instance). |
| 80 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 81 | WHAT'S THE EXECUTION CONTEXT? |
| 82 | |
| 83 | By default, each time testmod finds a docstring to test, it uses a *copy* |
| 84 | of M's globals (so that running tests on a module doesn't change the |
| 85 | module's real globals, and so that one test in M can't leave behind crumbs |
| 86 | that accidentally allow another test to work). This means examples can |
| 87 | freely use any names defined at top-level in M. It also means that sloppy |
| 88 | imports (see above) can cause examples in external docstrings to use |
| 89 | globals inappropriate for them. |
| 90 | |
| 91 | You can force use of your own dict as the execution context by passing |
| 92 | "globs=your_dict" to testmod instead. Presumably this would be a copy of |
| 93 | M.__dict__ merged with the globals from other imported modules. |
| 94 | |
| 95 | |
| 96 | WHAT IF I WANT TO TEST A WHOLE PACKAGE? |
| 97 | |
| 98 | Piece o' cake, provided the modules do their testing from docstrings. |
| 99 | Here's the test.py I use for the world's most elaborate Rational/ |
| 100 | floating-base-conversion pkg (which I'll distribute some day): |
| 101 | |
| 102 | from Rational import Cvt |
| 103 | from Rational import Format |
| 104 | from Rational import machprec |
| 105 | from Rational import Rat |
| 106 | from Rational import Round |
| 107 | from Rational import utils |
| 108 | |
| 109 | modules = (Cvt, |
| 110 | Format, |
| 111 | machprec, |
| 112 | Rat, |
| 113 | Round, |
| 114 | utils) |
| 115 | |
| 116 | def _test(): |
| 117 | import doctest |
| 118 | import sys |
| 119 | verbose = "-v" in sys.argv |
| 120 | for mod in modules: |
| 121 | doctest.testmod(mod, verbose=verbose, report=0) |
| 122 | doctest.master.summarize() |
| 123 | |
| 124 | if __name__ == "__main__": |
| 125 | _test() |
| 126 | |
| 127 | IOW, it just runs testmod on all the pkg modules. testmod remembers the |
| 128 | names and outcomes (# of failures, # of tries) for each item it's seen, and |
| 129 | passing "report=0" prevents it from printing a summary in verbose mode. |
| 130 | Instead, the summary is delayed until all modules have been tested, and |
| 131 | then "doctest.master.summarize()" forces the summary at the end. |
| 132 | |
| 133 | So this is very nice in practice: each module can be tested individually |
| 134 | with almost no work beyond writing up docstring examples, and collections |
| 135 | of modules can be tested too as a unit with no more work than the above. |
| 136 | |
| 137 | |
| 138 | WHAT ABOUT EXCEPTIONS? |
| 139 | |
| 140 | No problem, as long as the only output generated by the example is the |
| 141 | traceback itself. For example: |
| 142 | |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 143 | >>> [1, 2, 3].remove(42) |
Tim Peters | ea4f931 | 2001-02-13 20:54:42 +0000 | [diff] [blame] | 144 | Traceback (most recent call last): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 145 | File "<stdin>", line 1, in ? |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 146 | ValueError: list.remove(x): x not in list |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 147 | >>> |
| 148 | |
| 149 | Note that only the exception type and value are compared (specifically, |
| 150 | only the last line in the traceback). |
| 151 | |
| 152 | |
| 153 | ADVANCED USAGE |
| 154 | |
| 155 | doctest.testmod() captures the testing policy I find most useful most |
| 156 | often. You may want other policies. |
| 157 | |
| 158 | testmod() actually creates a local instance of class doctest.Tester, runs |
| 159 | appropriate methods of that class, and merges the results into global |
| 160 | Tester instance doctest.master. |
| 161 | |
| 162 | You can create your own instances of doctest.Tester, and so build your own |
| 163 | policies, or even run methods of doctest.master directly. See |
| 164 | doctest.Tester.__doc__ for details. |
| 165 | |
| 166 | |
| 167 | SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!? |
| 168 | |
| 169 | Oh ya. It's easy! In most cases a copy-and-paste of an interactive |
| 170 | console session works fine -- just make sure the leading whitespace is |
| 171 | rigidly consistent (you can mix tabs and spaces if you're too lazy to do it |
| 172 | right, but doctest is not in the business of guessing what you think a tab |
| 173 | means). |
| 174 | |
| 175 | >>> # comments are ignored |
| 176 | >>> x = 12 |
| 177 | >>> x |
| 178 | 12 |
| 179 | >>> if x == 13: |
| 180 | ... print "yes" |
| 181 | ... else: |
| 182 | ... print "no" |
| 183 | ... print "NO" |
| 184 | ... print "NO!!!" |
| 185 | ... |
| 186 | no |
| 187 | NO |
| 188 | NO!!! |
| 189 | >>> |
| 190 | |
| 191 | Any expected output must immediately follow the final ">>>" or "..." line |
| 192 | containing the code, and the expected output (if any) extends to the next |
| 193 | ">>>" or all-whitespace line. That's it. |
| 194 | |
| 195 | Bummers: |
| 196 | |
| 197 | + Expected output cannot contain an all-whitespace line, since such a line |
| 198 | is taken to signal the end of expected output. |
| 199 | |
| 200 | + Output to stdout is captured, but not output to stderr (exception |
| 201 | tracebacks are captured via a different means). |
| 202 | |
| 203 | + If you continue a line via backslashing in an interactive session, or for |
| 204 | any other reason use a backslash, you need to double the backslash in the |
| 205 | docstring version. This is simply because you're in a string, and so the |
| 206 | backslash must be escaped for it to survive intact. Like: |
| 207 | |
| 208 | >>> if "yes" == \\ |
| 209 | ... "y" + \\ |
| 210 | ... "es": # in the source code you'll see the doubled backslashes |
| 211 | ... print 'yes' |
| 212 | yes |
| 213 | |
| 214 | The starting column doesn't matter: |
| 215 | |
| 216 | >>> assert "Easy!" |
| 217 | >>> import math |
| 218 | >>> math.floor(1.9) |
| 219 | 1.0 |
| 220 | |
| 221 | and as many leading whitespace characters are stripped from the expected |
| 222 | output as appeared in the initial ">>>" line that triggered it. |
| 223 | |
| 224 | If you execute this very file, the examples above will be found and |
| 225 | executed, leading to this output in verbose mode: |
| 226 | |
| 227 | Running doctest.__doc__ |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 228 | Trying: [1, 2, 3].remove(42) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 229 | Expecting: |
Tim Peters | ea4f931 | 2001-02-13 20:54:42 +0000 | [diff] [blame] | 230 | Traceback (most recent call last): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 231 | File "<stdin>", line 1, in ? |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 232 | ValueError: list.remove(x): x not in list |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 233 | ok |
| 234 | Trying: x = 12 |
| 235 | Expecting: nothing |
| 236 | ok |
| 237 | Trying: x |
| 238 | Expecting: 12 |
| 239 | ok |
| 240 | Trying: |
| 241 | if x == 13: |
| 242 | print "yes" |
| 243 | else: |
| 244 | print "no" |
| 245 | print "NO" |
| 246 | print "NO!!!" |
| 247 | Expecting: |
| 248 | no |
| 249 | NO |
| 250 | NO!!! |
| 251 | ok |
| 252 | ... and a bunch more like that, with this summary at the end: |
| 253 | |
| 254 | 5 items had no tests: |
| 255 | doctest.Tester.__init__ |
| 256 | doctest.Tester.run__test__ |
| 257 | doctest.Tester.summarize |
| 258 | doctest.run_docstring_examples |
| 259 | doctest.testmod |
| 260 | 12 items passed all tests: |
| 261 | 8 tests in doctest |
| 262 | 6 tests in doctest.Tester |
| 263 | 10 tests in doctest.Tester.merge |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 264 | 14 tests in doctest.Tester.rundict |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 265 | 3 tests in doctest.Tester.rundoc |
| 266 | 3 tests in doctest.Tester.runstring |
| 267 | 2 tests in doctest.__test__._TestClass |
| 268 | 2 tests in doctest.__test__._TestClass.__init__ |
| 269 | 2 tests in doctest.__test__._TestClass.get |
| 270 | 1 tests in doctest.__test__._TestClass.square |
| 271 | 2 tests in doctest.__test__.string |
| 272 | 7 tests in doctest.is_private |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 273 | 60 tests in 17 items. |
| 274 | 60 passed and 0 failed. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 275 | Test passed. |
| 276 | """ |
| 277 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 278 | __all__ = [ |
| 279 | 'testmod', |
| 280 | 'run_docstring_examples', |
| 281 | 'is_private', |
| 282 | 'Tester', |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 283 | 'DocTestTestFailure', |
| 284 | 'DocTestSuite', |
| 285 | 'testsource', |
| 286 | 'debug', |
Raymond Hettinger | cc39a13 | 2003-07-11 22:36:52 +0000 | [diff] [blame] | 287 | 'master', |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 288 | ] |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 289 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 290 | import __future__ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 291 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 292 | import re |
| 293 | PS1 = ">>>" |
| 294 | PS2 = "..." |
| 295 | _isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match |
| 296 | _isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match |
| 297 | _isEmpty = re.compile(r"\s*$").match |
| 298 | _isComment = re.compile(r"\s*#").match |
| 299 | del re |
| 300 | |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 301 | from types import StringTypes as _StringTypes |
| 302 | |
| 303 | from inspect import isclass as _isclass |
| 304 | from inspect import isfunction as _isfunction |
Raymond Hettinger | 5f8b0b1 | 2003-09-02 02:09:05 +0000 | [diff] [blame] | 305 | from inspect import ismethod as _ismethod |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 306 | from inspect import ismodule as _ismodule |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 307 | from inspect import classify_class_attrs as _classify_class_attrs |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 308 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 309 | # Option constants. |
| 310 | DONT_ACCEPT_TRUE_FOR_1 = 1 << 0 |
| 311 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 312 | # Extract interactive examples from a string. Return a list of triples, |
| 313 | # (source, outcome, lineno). "source" is the source code, and ends |
| 314 | # with a newline iff the source spans more than one line. "outcome" is |
| 315 | # the expected output if any, else an empty string. When not empty, |
| 316 | # outcome always ends with a newline. "lineno" is the line number, |
| 317 | # 0-based wrt the start of the string, of the first source line. |
| 318 | |
| 319 | def _extract_examples(s): |
| 320 | isPS1, isPS2 = _isPS1, _isPS2 |
| 321 | isEmpty, isComment = _isEmpty, _isComment |
| 322 | examples = [] |
Eric S. Raymond | 630e69c | 2001-02-09 08:33:43 +0000 | [diff] [blame] | 323 | lines = s.split("\n") |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 324 | i, n = 0, len(lines) |
| 325 | while i < n: |
| 326 | line = lines[i] |
| 327 | i = i + 1 |
| 328 | m = isPS1(line) |
| 329 | if m is None: |
| 330 | continue |
| 331 | j = m.end(0) # beyond the prompt |
| 332 | if isEmpty(line, j) or isComment(line, j): |
| 333 | # a bare prompt or comment -- not interesting |
| 334 | continue |
| 335 | lineno = i - 1 |
| 336 | if line[j] != " ": |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 337 | raise ValueError("line %r of docstring lacks blank after %s: %s" % |
| 338 | (lineno, PS1, line)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 339 | j = j + 1 |
| 340 | blanks = m.group(1) |
| 341 | nblanks = len(blanks) |
| 342 | # suck up this and following PS2 lines |
| 343 | source = [] |
| 344 | while 1: |
| 345 | source.append(line[j:]) |
| 346 | line = lines[i] |
| 347 | m = isPS2(line) |
| 348 | if m: |
| 349 | if m.group(1) != blanks: |
| 350 | raise ValueError("inconsistent leading whitespace " |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 351 | "in line %r of docstring: %s" % (i, line)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 352 | i = i + 1 |
| 353 | else: |
| 354 | break |
| 355 | if len(source) == 1: |
| 356 | source = source[0] |
| 357 | else: |
| 358 | # get rid of useless null line from trailing empty "..." |
| 359 | if source[-1] == "": |
| 360 | del source[-1] |
Eric S. Raymond | 630e69c | 2001-02-09 08:33:43 +0000 | [diff] [blame] | 361 | source = "\n".join(source) + "\n" |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 362 | # suck up response |
| 363 | if isPS1(line) or isEmpty(line): |
| 364 | expect = "" |
| 365 | else: |
| 366 | expect = [] |
| 367 | while 1: |
| 368 | if line[:nblanks] != blanks: |
| 369 | raise ValueError("inconsistent leading whitespace " |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 370 | "in line %r of docstring: %s" % (i, line)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 371 | expect.append(line[nblanks:]) |
| 372 | i = i + 1 |
| 373 | line = lines[i] |
| 374 | if isPS1(line) or isEmpty(line): |
| 375 | break |
Eric S. Raymond | 630e69c | 2001-02-09 08:33:43 +0000 | [diff] [blame] | 376 | expect = "\n".join(expect) + "\n" |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 377 | examples.append( (source, expect, lineno) ) |
| 378 | return examples |
| 379 | |
| 380 | # Capture stdout when running examples. |
| 381 | |
| 382 | class _SpoofOut: |
| 383 | def __init__(self): |
| 384 | self.clear() |
| 385 | def write(self, s): |
| 386 | self.buf.append(s) |
| 387 | def get(self): |
Tim Peters | f9bb496 | 2001-02-14 06:35:35 +0000 | [diff] [blame] | 388 | guts = "".join(self.buf) |
| 389 | # If anything at all was written, make sure there's a trailing |
| 390 | # newline. There's no way for the expected output to indicate |
| 391 | # that a trailing newline is missing. |
| 392 | if guts and not guts.endswith("\n"): |
| 393 | guts = guts + "\n" |
Tim Peters | c77db34 | 2001-10-23 02:21:52 +0000 | [diff] [blame] | 394 | # Prevent softspace from screwing up the next test case, in |
| 395 | # case they used print with a trailing comma in an example. |
| 396 | if hasattr(self, "softspace"): |
| 397 | del self.softspace |
Tim Peters | f9bb496 | 2001-02-14 06:35:35 +0000 | [diff] [blame] | 398 | return guts |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 399 | def clear(self): |
| 400 | self.buf = [] |
Tim Peters | c77db34 | 2001-10-23 02:21:52 +0000 | [diff] [blame] | 401 | if hasattr(self, "softspace"): |
| 402 | del self.softspace |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 403 | def flush(self): |
| 404 | # JPython calls flush |
| 405 | pass |
| 406 | |
| 407 | # Display some tag-and-msg pairs nicely, keeping the tag and its msg |
| 408 | # on the same line when that makes sense. |
| 409 | |
| 410 | def _tag_out(printer, *tag_msg_pairs): |
| 411 | for tag, msg in tag_msg_pairs: |
| 412 | printer(tag + ":") |
| 413 | msg_has_nl = msg[-1:] == "\n" |
| 414 | msg_has_two_nl = msg_has_nl and \ |
Eric S. Raymond | 630e69c | 2001-02-09 08:33:43 +0000 | [diff] [blame] | 415 | msg.find("\n") < len(msg) - 1 |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 416 | if len(tag) + len(msg) < 76 and not msg_has_two_nl: |
| 417 | printer(" ") |
| 418 | else: |
| 419 | printer("\n") |
| 420 | printer(msg) |
| 421 | if not msg_has_nl: |
| 422 | printer("\n") |
| 423 | |
| 424 | # Run list of examples, in context globs. "out" can be used to display |
| 425 | # stuff to "the real" stdout, and fakeout is an instance of _SpoofOut |
| 426 | # that captures the examples' std output. Return (#failures, #tries). |
| 427 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 428 | def _run_examples_inner(out, fakeout, examples, globs, verbose, name, |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 429 | compileflags, optionflags): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 430 | import sys, traceback |
| 431 | OK, BOOM, FAIL = range(3) |
| 432 | NADA = "nothing" |
| 433 | stderr = _SpoofOut() |
| 434 | failures = 0 |
| 435 | for source, want, lineno in examples: |
| 436 | if verbose: |
| 437 | _tag_out(out, ("Trying", source), |
| 438 | ("Expecting", want or NADA)) |
| 439 | fakeout.clear() |
| 440 | try: |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 441 | exec compile(source, "<string>", "single", |
| 442 | compileflags, 1) in globs |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 443 | got = fakeout.get() |
| 444 | state = OK |
Tim Peters | bcc2c12 | 2002-03-20 19:32:03 +0000 | [diff] [blame] | 445 | except KeyboardInterrupt: |
| 446 | raise |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 447 | except: |
| 448 | # See whether the exception was expected. |
Tim Peters | ea4f931 | 2001-02-13 20:54:42 +0000 | [diff] [blame] | 449 | if want.find("Traceback (innermost last):\n") == 0 or \ |
| 450 | want.find("Traceback (most recent call last):\n") == 0: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 451 | # Only compare exception type and value - the rest of |
| 452 | # the traceback isn't necessary. |
Eric S. Raymond | 630e69c | 2001-02-09 08:33:43 +0000 | [diff] [blame] | 453 | want = want.split('\n')[-2] + '\n' |
Tim Peters | 77f2d50 | 2001-06-24 18:59:01 +0000 | [diff] [blame] | 454 | exc_type, exc_val = sys.exc_info()[:2] |
Tim Peters | 08bba95 | 2001-06-24 06:46:58 +0000 | [diff] [blame] | 455 | got = traceback.format_exception_only(exc_type, exc_val)[-1] |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 456 | state = OK |
| 457 | else: |
| 458 | # unexpected exception |
| 459 | stderr.clear() |
| 460 | traceback.print_exc(file=stderr) |
| 461 | state = BOOM |
| 462 | |
| 463 | if state == OK: |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 464 | if (got == want or |
| 465 | (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and |
| 466 | (got, want) in (("True\n", "1\n"), ("False\n", "0\n")) |
| 467 | ) |
| 468 | ): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 469 | if verbose: |
| 470 | out("ok\n") |
| 471 | continue |
| 472 | state = FAIL |
| 473 | |
| 474 | assert state in (FAIL, BOOM) |
| 475 | failures = failures + 1 |
| 476 | out("*" * 65 + "\n") |
| 477 | _tag_out(out, ("Failure in example", source)) |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 478 | out("from line #%r of %s\n" % (lineno, name)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 479 | if state == FAIL: |
| 480 | _tag_out(out, ("Expected", want or NADA), ("Got", got)) |
| 481 | else: |
| 482 | assert state == BOOM |
| 483 | _tag_out(out, ("Exception raised", stderr.get())) |
| 484 | |
| 485 | return failures, len(examples) |
| 486 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 487 | # Get the future-flags associated with the future features that have been |
| 488 | # imported into globs. |
| 489 | |
| 490 | def _extract_future_flags(globs): |
| 491 | flags = 0 |
| 492 | for fname in __future__.all_feature_names: |
| 493 | feature = globs.get(fname, None) |
| 494 | if feature is getattr(__future__, fname): |
| 495 | flags |= feature.compiler_flag |
| 496 | return flags |
| 497 | |
Tim Peters | d4ad59e | 2001-06-24 20:02:47 +0000 | [diff] [blame] | 498 | # Run list of examples, in a shallow copy of context (dict) globs. |
| 499 | # Return (#failures, #tries). |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 500 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 501 | def _run_examples(examples, globs, verbose, name, compileflags, |
| 502 | optionflags): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 503 | import sys |
| 504 | saveout = sys.stdout |
Tim Peters | d4ad59e | 2001-06-24 20:02:47 +0000 | [diff] [blame] | 505 | globs = globs.copy() |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 506 | try: |
| 507 | sys.stdout = fakeout = _SpoofOut() |
| 508 | x = _run_examples_inner(saveout.write, fakeout, examples, |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 509 | globs, verbose, name, compileflags, |
| 510 | optionflags) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 511 | finally: |
| 512 | sys.stdout = saveout |
Tim Peters | d4ad59e | 2001-06-24 20:02:47 +0000 | [diff] [blame] | 513 | # While Python gc can clean up most cycles on its own, it doesn't |
| 514 | # chase frame objects. This is especially irksome when running |
| 515 | # generator tests that raise exceptions, because a named generator- |
| 516 | # iterator gets an entry in globs, and the generator-iterator |
| 517 | # object's frame's traceback info points back to globs. This is |
Tim Peters | fee69d0 | 2001-06-24 20:24:16 +0000 | [diff] [blame] | 518 | # easy to break just by clearing the namespace. This can also |
| 519 | # help to break other kinds of cycles, and even for cycles that |
| 520 | # gc can break itself it's better to break them ASAP. |
Tim Peters | d4ad59e | 2001-06-24 20:02:47 +0000 | [diff] [blame] | 521 | globs.clear() |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 522 | return x |
| 523 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 524 | def run_docstring_examples(f, globs, verbose=0, name="NoName", |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 525 | compileflags=None, optionflags=0): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 526 | """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__. |
| 527 | |
Tim Peters | d4ad59e | 2001-06-24 20:02:47 +0000 | [diff] [blame] | 528 | Use (a shallow copy of) dict globs as the globals for execution. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 529 | Return (#failures, #tries). |
| 530 | |
| 531 | If optional arg verbose is true, print stuff even if there are no |
| 532 | failures. |
| 533 | Use string name in failure msgs. |
| 534 | """ |
| 535 | |
| 536 | try: |
| 537 | doc = f.__doc__ |
| 538 | if not doc: |
| 539 | # docstring empty or None |
| 540 | return 0, 0 |
| 541 | # just in case CT invents a doc object that has to be forced |
| 542 | # to look like a string <0.9 wink> |
| 543 | doc = str(doc) |
Tim Peters | bcc2c12 | 2002-03-20 19:32:03 +0000 | [diff] [blame] | 544 | except KeyboardInterrupt: |
| 545 | raise |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 546 | except: |
| 547 | return 0, 0 |
| 548 | |
| 549 | e = _extract_examples(doc) |
| 550 | if not e: |
| 551 | return 0, 0 |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 552 | if compileflags is None: |
| 553 | compileflags = _extract_future_flags(globs) |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 554 | return _run_examples(e, globs, verbose, name, compileflags, optionflags) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 555 | |
| 556 | def is_private(prefix, base): |
| 557 | """prefix, base -> true iff name prefix + "." + base is "private". |
| 558 | |
| 559 | Prefix may be an empty string, and base does not contain a period. |
| 560 | Prefix is ignored (although functions you write conforming to this |
| 561 | protocol may make use of it). |
| 562 | Return true iff base begins with an (at least one) underscore, but |
| 563 | does not both begin and end with (at least) two underscores. |
| 564 | |
| 565 | >>> is_private("a.b", "my_func") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 566 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 567 | >>> is_private("____", "_my_func") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 568 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 569 | >>> is_private("someclass", "__init__") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 570 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 571 | >>> is_private("sometypo", "__init_") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 572 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 573 | >>> is_private("x.y.z", "_") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 574 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 575 | >>> is_private("_x.y.z", "__") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 576 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 577 | >>> is_private("", "") # senseless but consistent |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 578 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 579 | """ |
| 580 | |
| 581 | return base[:1] == "_" and not base[:2] == "__" == base[-2:] |
| 582 | |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 583 | # Determine if a class of function was defined in the given module. |
| 584 | |
| 585 | def _from_module(module, object): |
| 586 | if _isfunction(object): |
| 587 | return module.__dict__ is object.func_globals |
| 588 | if _isclass(object): |
| 589 | return module.__name__ == object.__module__ |
| 590 | raise ValueError("object must be a class or function") |
| 591 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 592 | class Tester: |
| 593 | """Class Tester -- runs docstring examples and accumulates stats. |
| 594 | |
| 595 | In normal use, function doctest.testmod() hides all this from you, |
| 596 | so use that if you can. Create your own instances of Tester to do |
| 597 | fancier things. |
| 598 | |
| 599 | Methods: |
| 600 | runstring(s, name) |
| 601 | Search string s for examples to run; use name for logging. |
| 602 | Return (#failures, #tries). |
| 603 | |
| 604 | rundoc(object, name=None) |
| 605 | Search object.__doc__ for examples to run; use name (or |
| 606 | object.__name__) for logging. Return (#failures, #tries). |
| 607 | |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 608 | rundict(d, name, module=None) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 609 | Search for examples in docstrings in all of d.values(); use name |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 610 | for logging. Exclude functions and classes not defined in module |
| 611 | if specified. Return (#failures, #tries). |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 612 | |
| 613 | run__test__(d, name) |
| 614 | Treat dict d like module.__test__. Return (#failures, #tries). |
| 615 | |
| 616 | summarize(verbose=None) |
| 617 | Display summary of testing results, to stdout. Return |
| 618 | (#failures, #tries). |
| 619 | |
| 620 | merge(other) |
| 621 | Merge in the test results from Tester instance "other". |
| 622 | |
| 623 | >>> from doctest import Tester |
| 624 | >>> t = Tester(globs={'x': 42}, verbose=0) |
| 625 | >>> t.runstring(r''' |
| 626 | ... >>> x = x * 2 |
| 627 | ... >>> print x |
| 628 | ... 42 |
| 629 | ... ''', 'XYZ') |
| 630 | ***************************************************************** |
| 631 | Failure in example: print x |
| 632 | from line #2 of XYZ |
| 633 | Expected: 42 |
| 634 | Got: 84 |
| 635 | (1, 2) |
| 636 | >>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2') |
| 637 | (0, 2) |
| 638 | >>> t.summarize() |
Guido van Rossum | 261d91a | 2001-03-18 17:05:58 +0000 | [diff] [blame] | 639 | ***************************************************************** |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 640 | 1 items had failures: |
| 641 | 1 of 2 in XYZ |
| 642 | ***Test Failed*** 1 failures. |
| 643 | (1, 4) |
| 644 | >>> t.summarize(verbose=1) |
| 645 | 1 items passed all tests: |
| 646 | 2 tests in example2 |
Guido van Rossum | 261d91a | 2001-03-18 17:05:58 +0000 | [diff] [blame] | 647 | ***************************************************************** |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 648 | 1 items had failures: |
| 649 | 1 of 2 in XYZ |
| 650 | 4 tests in 2 items. |
| 651 | 3 passed and 1 failed. |
| 652 | ***Test Failed*** 1 failures. |
| 653 | (1, 4) |
| 654 | >>> |
| 655 | """ |
| 656 | |
| 657 | def __init__(self, mod=None, globs=None, verbose=None, |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 658 | isprivate=None, optionflags=0): |
| 659 | """mod=None, globs=None, verbose=None, isprivate=None, |
| 660 | optionflags=0 |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 661 | |
| 662 | See doctest.__doc__ for an overview. |
| 663 | |
| 664 | Optional keyword arg "mod" is a module, whose globals are used for |
| 665 | executing examples. If not specified, globs must be specified. |
| 666 | |
| 667 | Optional keyword arg "globs" gives a dict to be used as the globals |
| 668 | when executing examples; if not specified, use the globals from |
| 669 | module mod. |
| 670 | |
| 671 | In either case, a copy of the dict is used for each docstring |
| 672 | examined. |
| 673 | |
| 674 | Optional keyword arg "verbose" prints lots of stuff if true, only |
| 675 | failures if false; by default, it's true iff "-v" is in sys.argv. |
| 676 | |
| 677 | Optional keyword arg "isprivate" specifies a function used to determine |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 678 | whether a name is private. The default function is to assume that |
| 679 | no functions are private. The "isprivate" arg may be set to |
| 680 | doctest.is_private in order to skip over functions marked as private |
| 681 | using an underscore naming convention; see its docs for details. |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 682 | |
| 683 | See doctest.testmod docs for the meaning of optionflags. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 684 | """ |
| 685 | |
| 686 | if mod is None and globs is None: |
| 687 | raise TypeError("Tester.__init__: must specify mod or globs") |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 688 | if mod is not None and not _ismodule(mod): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 689 | raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 690 | if globs is None: |
| 691 | globs = mod.__dict__ |
| 692 | self.globs = globs |
| 693 | |
| 694 | if verbose is None: |
| 695 | import sys |
| 696 | verbose = "-v" in sys.argv |
| 697 | self.verbose = verbose |
| 698 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 699 | # By default, assume that nothing is private |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 700 | if isprivate is None: |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 701 | isprivate = lambda prefix, base: 0 |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 702 | self.isprivate = isprivate |
| 703 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 704 | self.optionflags = optionflags |
| 705 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 706 | self.name2ft = {} # map name to (#failures, #trials) pair |
| 707 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 708 | self.compileflags = _extract_future_flags(globs) |
| 709 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 710 | def runstring(self, s, name): |
| 711 | """ |
| 712 | s, name -> search string s for examples to run, logging as name. |
| 713 | |
| 714 | Use string name as the key for logging the outcome. |
| 715 | Return (#failures, #examples). |
| 716 | |
| 717 | >>> t = Tester(globs={}, verbose=1) |
| 718 | >>> test = r''' |
| 719 | ... # just an example |
| 720 | ... >>> x = 1 + 2 |
| 721 | ... >>> x |
| 722 | ... 3 |
| 723 | ... ''' |
| 724 | >>> t.runstring(test, "Example") |
| 725 | Running string Example |
| 726 | Trying: x = 1 + 2 |
| 727 | Expecting: nothing |
| 728 | ok |
| 729 | Trying: x |
| 730 | Expecting: 3 |
| 731 | ok |
| 732 | 0 of 2 examples failed in string Example |
| 733 | (0, 2) |
| 734 | """ |
| 735 | |
| 736 | if self.verbose: |
| 737 | print "Running string", name |
| 738 | f = t = 0 |
| 739 | e = _extract_examples(s) |
| 740 | if e: |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 741 | f, t = _run_examples(e, self.globs, self.verbose, name, |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 742 | self.compileflags, self.optionflags) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 743 | if self.verbose: |
| 744 | print f, "of", t, "examples failed in string", name |
| 745 | self.__record_outcome(name, f, t) |
| 746 | return f, t |
| 747 | |
| 748 | def rundoc(self, object, name=None): |
| 749 | """ |
| 750 | object, name=None -> search object.__doc__ for examples to run. |
| 751 | |
| 752 | Use optional string name as the key for logging the outcome; |
| 753 | by default use object.__name__. |
| 754 | Return (#failures, #examples). |
| 755 | If object is a class object, search recursively for method |
| 756 | docstrings too. |
| 757 | object.__doc__ is examined regardless of name, but if object is |
| 758 | a class, whether private names reached from object are searched |
| 759 | depends on the constructor's "isprivate" argument. |
| 760 | |
| 761 | >>> t = Tester(globs={}, verbose=0) |
| 762 | >>> def _f(): |
| 763 | ... '''Trivial docstring example. |
| 764 | ... >>> assert 2 == 2 |
| 765 | ... ''' |
| 766 | ... return 32 |
| 767 | ... |
| 768 | >>> t.rundoc(_f) # expect 0 failures in 1 example |
| 769 | (0, 1) |
| 770 | """ |
| 771 | |
| 772 | if name is None: |
| 773 | try: |
| 774 | name = object.__name__ |
| 775 | except AttributeError: |
| 776 | raise ValueError("Tester.rundoc: name must be given " |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 777 | "when object.__name__ doesn't exist; %r" % (object,)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 778 | if self.verbose: |
| 779 | print "Running", name + ".__doc__" |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 780 | f, t = run_docstring_examples(object, self.globs, self.verbose, name, |
Tim Peters | 275abbd | 2003-06-29 03:11:20 +0000 | [diff] [blame] | 781 | self.compileflags, self.optionflags) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 782 | if self.verbose: |
| 783 | print f, "of", t, "examples failed in", name + ".__doc__" |
| 784 | self.__record_outcome(name, f, t) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 785 | if _isclass(object): |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 786 | # In 2.2, class and static methods complicate life. Build |
| 787 | # a dict "that works", by hook or by crook. |
| 788 | d = {} |
| 789 | for tag, kind, homecls, value in _classify_class_attrs(object): |
| 790 | |
| 791 | if homecls is not object: |
| 792 | # Only look at names defined immediately by the class. |
| 793 | continue |
| 794 | |
| 795 | elif self.isprivate(name, tag): |
| 796 | continue |
| 797 | |
| 798 | elif kind == "method": |
| 799 | # value is already a function |
| 800 | d[tag] = value |
| 801 | |
| 802 | elif kind == "static method": |
| 803 | # value isn't a function, but getattr reveals one |
| 804 | d[tag] = getattr(object, tag) |
| 805 | |
| 806 | elif kind == "class method": |
| 807 | # Hmm. A classmethod object doesn't seem to reveal |
| 808 | # enough. But getattr turns it into a bound method, |
| 809 | # and from there .im_func retrieves the underlying |
| 810 | # function. |
| 811 | d[tag] = getattr(object, tag).im_func |
| 812 | |
| 813 | elif kind == "property": |
| 814 | # The methods implementing the property have their |
| 815 | # own docstrings -- but the property may have one too. |
| 816 | if value.__doc__ is not None: |
| 817 | d[tag] = str(value.__doc__) |
| 818 | |
| 819 | elif kind == "data": |
| 820 | # Grab nested classes. |
| 821 | if _isclass(value): |
| 822 | d[tag] = value |
| 823 | |
| 824 | else: |
| 825 | raise ValueError("teach doctest about %r" % kind) |
| 826 | |
| 827 | f2, t2 = self.run__test__(d, name) |
| 828 | f += f2 |
| 829 | t += t2 |
| 830 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 831 | return f, t |
| 832 | |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 833 | def rundict(self, d, name, module=None): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 834 | """ |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 835 | d, name, module=None -> search for docstring examples in d.values(). |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 836 | |
| 837 | For k, v in d.items() such that v is a function or class, |
| 838 | do self.rundoc(v, name + "." + k). Whether this includes |
| 839 | objects with private names depends on the constructor's |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 840 | "isprivate" argument. If module is specified, functions and |
| 841 | classes that are not defined in module are excluded. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 842 | Return aggregate (#failures, #examples). |
| 843 | |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 844 | Build and populate two modules with sample functions to test that |
| 845 | exclusion of external functions and classes works. |
| 846 | |
| 847 | >>> import new |
| 848 | >>> m1 = new.module('_m1') |
| 849 | >>> m2 = new.module('_m2') |
| 850 | >>> test_data = \""" |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 851 | ... def _f(): |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 852 | ... '''>>> assert 1 == 1 |
| 853 | ... ''' |
| 854 | ... def g(): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 855 | ... '''>>> assert 2 != 1 |
| 856 | ... ''' |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 857 | ... class H: |
| 858 | ... '''>>> assert 2 > 1 |
| 859 | ... ''' |
| 860 | ... def bar(self): |
| 861 | ... '''>>> assert 1 < 2 |
| 862 | ... ''' |
| 863 | ... \""" |
| 864 | >>> exec test_data in m1.__dict__ |
| 865 | >>> exec test_data in m2.__dict__ |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 866 | >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H}) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 867 | |
| 868 | Tests that objects outside m1 are excluded: |
| 869 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 870 | >>> t = Tester(globs={}, verbose=0, isprivate=is_private) |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 871 | >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 872 | (0, 3) |
| 873 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 874 | Again, but with the default isprivate function allowing _f: |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 875 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 876 | >>> t = Tester(globs={}, verbose=0) |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 877 | >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 878 | (0, 4) |
| 879 | |
| 880 | And once more, not excluding stuff outside m1: |
| 881 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 882 | >>> t = Tester(globs={}, verbose=0) |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 883 | >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped. |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 884 | (0, 8) |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 885 | |
| 886 | The exclusion of objects from outside the designated module is |
| 887 | meant to be invoked automagically by testmod. |
| 888 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 889 | >>> testmod(m1, isprivate=is_private) |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 890 | (0, 3) |
| 891 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 892 | """ |
| 893 | |
| 894 | if not hasattr(d, "items"): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 895 | raise TypeError("Tester.rundict: d must support .items(); %r" % (d,)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 896 | f = t = 0 |
Tim Peters | 24a4191 | 2001-03-21 23:07:59 +0000 | [diff] [blame] | 897 | # Run the tests by alpha order of names, for consistency in |
| 898 | # verbose-mode output. |
| 899 | names = d.keys() |
| 900 | names.sort() |
| 901 | for thisname in names: |
| 902 | value = d[thisname] |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 903 | if _isfunction(value) or _isclass(value): |
| 904 | if module and not _from_module(module, value): |
| 905 | continue |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 906 | f2, t2 = self.__runone(value, name + "." + thisname) |
| 907 | f = f + f2 |
| 908 | t = t + t2 |
| 909 | return f, t |
| 910 | |
| 911 | def run__test__(self, d, name): |
| 912 | """d, name -> Treat dict d like module.__test__. |
| 913 | |
| 914 | Return (#failures, #tries). |
| 915 | See testmod.__doc__ for details. |
| 916 | """ |
| 917 | |
| 918 | failures = tries = 0 |
| 919 | prefix = name + "." |
| 920 | savepvt = self.isprivate |
| 921 | try: |
| 922 | self.isprivate = lambda *args: 0 |
Tim Peters | 24a4191 | 2001-03-21 23:07:59 +0000 | [diff] [blame] | 923 | # Run the tests by alpha order of names, for consistency in |
| 924 | # verbose-mode output. |
| 925 | keys = d.keys() |
| 926 | keys.sort() |
| 927 | for k in keys: |
| 928 | v = d[k] |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 929 | thisname = prefix + k |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 930 | if type(v) in _StringTypes: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 931 | f, t = self.runstring(v, thisname) |
Raymond Hettinger | 5f8b0b1 | 2003-09-02 02:09:05 +0000 | [diff] [blame] | 932 | elif _isfunction(v) or _isclass(v) or _ismethod(v): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 933 | f, t = self.rundoc(v, thisname) |
| 934 | else: |
| 935 | raise TypeError("Tester.run__test__: values in " |
Raymond Hettinger | 5f8b0b1 | 2003-09-02 02:09:05 +0000 | [diff] [blame] | 936 | "dict must be strings, functions, methods, " |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 937 | "or classes; %r" % (v,)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 938 | failures = failures + f |
| 939 | tries = tries + t |
| 940 | finally: |
| 941 | self.isprivate = savepvt |
| 942 | return failures, tries |
| 943 | |
| 944 | def summarize(self, verbose=None): |
| 945 | """ |
| 946 | verbose=None -> summarize results, return (#failures, #tests). |
| 947 | |
| 948 | Print summary of test results to stdout. |
| 949 | Optional arg 'verbose' controls how wordy this is. By |
| 950 | default, use the verbose setting established by the |
| 951 | constructor. |
| 952 | """ |
| 953 | |
| 954 | if verbose is None: |
| 955 | verbose = self.verbose |
| 956 | notests = [] |
| 957 | passed = [] |
| 958 | failed = [] |
| 959 | totalt = totalf = 0 |
| 960 | for x in self.name2ft.items(): |
| 961 | name, (f, t) = x |
| 962 | assert f <= t |
| 963 | totalt = totalt + t |
| 964 | totalf = totalf + f |
| 965 | if t == 0: |
| 966 | notests.append(name) |
| 967 | elif f == 0: |
| 968 | passed.append( (name, t) ) |
| 969 | else: |
| 970 | failed.append(x) |
| 971 | if verbose: |
| 972 | if notests: |
| 973 | print len(notests), "items had no tests:" |
| 974 | notests.sort() |
| 975 | for thing in notests: |
| 976 | print " ", thing |
| 977 | if passed: |
| 978 | print len(passed), "items passed all tests:" |
| 979 | passed.sort() |
| 980 | for thing, count in passed: |
| 981 | print " %3d tests in %s" % (count, thing) |
| 982 | if failed: |
Guido van Rossum | af00a46 | 2001-03-18 16:58:44 +0000 | [diff] [blame] | 983 | print "*" * 65 |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 984 | print len(failed), "items had failures:" |
| 985 | failed.sort() |
| 986 | for thing, (f, t) in failed: |
| 987 | print " %3d of %3d in %s" % (f, t, thing) |
| 988 | if verbose: |
| 989 | print totalt, "tests in", len(self.name2ft), "items." |
| 990 | print totalt - totalf, "passed and", totalf, "failed." |
| 991 | if totalf: |
| 992 | print "***Test Failed***", totalf, "failures." |
| 993 | elif verbose: |
| 994 | print "Test passed." |
| 995 | return totalf, totalt |
| 996 | |
| 997 | def merge(self, other): |
| 998 | """ |
| 999 | other -> merge in test results from the other Tester instance. |
| 1000 | |
| 1001 | If self and other both have a test result for something |
| 1002 | with the same name, the (#failures, #tests) results are |
| 1003 | summed, and a warning is printed to stdout. |
| 1004 | |
| 1005 | >>> from doctest import Tester |
| 1006 | >>> t1 = Tester(globs={}, verbose=0) |
| 1007 | >>> t1.runstring(''' |
| 1008 | ... >>> x = 12 |
| 1009 | ... >>> print x |
| 1010 | ... 12 |
| 1011 | ... ''', "t1example") |
| 1012 | (0, 2) |
| 1013 | >>> |
| 1014 | >>> t2 = Tester(globs={}, verbose=0) |
| 1015 | >>> t2.runstring(''' |
| 1016 | ... >>> x = 13 |
| 1017 | ... >>> print x |
| 1018 | ... 13 |
| 1019 | ... ''', "t2example") |
| 1020 | (0, 2) |
| 1021 | >>> common = ">>> assert 1 + 2 == 3\\n" |
| 1022 | >>> t1.runstring(common, "common") |
| 1023 | (0, 1) |
| 1024 | >>> t2.runstring(common, "common") |
| 1025 | (0, 1) |
| 1026 | >>> t1.merge(t2) |
| 1027 | *** Tester.merge: 'common' in both testers; summing outcomes. |
| 1028 | >>> t1.summarize(1) |
| 1029 | 3 items passed all tests: |
| 1030 | 2 tests in common |
| 1031 | 2 tests in t1example |
| 1032 | 2 tests in t2example |
| 1033 | 6 tests in 3 items. |
| 1034 | 6 passed and 0 failed. |
| 1035 | Test passed. |
| 1036 | (0, 6) |
| 1037 | >>> |
| 1038 | """ |
| 1039 | |
| 1040 | d = self.name2ft |
| 1041 | for name, (f, t) in other.name2ft.items(): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 1042 | if name in d: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1043 | print "*** Tester.merge: '" + name + "' in both" \ |
| 1044 | " testers; summing outcomes." |
| 1045 | f2, t2 = d[name] |
| 1046 | f = f + f2 |
| 1047 | t = t + t2 |
| 1048 | d[name] = f, t |
| 1049 | |
| 1050 | def __record_outcome(self, name, f, t): |
Raymond Hettinger | 54f0222 | 2002-06-01 14:18:47 +0000 | [diff] [blame] | 1051 | if name in self.name2ft: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1052 | print "*** Warning: '" + name + "' was tested before;", \ |
| 1053 | "summing outcomes." |
| 1054 | f2, t2 = self.name2ft[name] |
| 1055 | f = f + f2 |
| 1056 | t = t + t2 |
| 1057 | self.name2ft[name] = f, t |
| 1058 | |
| 1059 | def __runone(self, target, name): |
| 1060 | if "." in name: |
Eric S. Raymond | 630e69c | 2001-02-09 08:33:43 +0000 | [diff] [blame] | 1061 | i = name.rindex(".") |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1062 | prefix, base = name[:i], name[i+1:] |
| 1063 | else: |
| 1064 | prefix, base = "", base |
| 1065 | if self.isprivate(prefix, base): |
| 1066 | return 0, 0 |
| 1067 | return self.rundoc(target, name) |
| 1068 | |
| 1069 | master = None |
| 1070 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1071 | def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1072 | report=True, optionflags=0): |
| 1073 | """m=None, name=None, globs=None, verbose=None, isprivate=None, |
| 1074 | report=True, optionflags=0 |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1075 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1076 | Test examples in docstrings in functions and classes reachable |
| 1077 | from module m (or the current module if m is not supplied), starting |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 1078 | with m.__doc__. Unless isprivate is specified, private names |
| 1079 | are not skipped. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1080 | |
| 1081 | Also test examples reachable from dict m.__test__ if it exists and is |
| 1082 | not None. m.__dict__ maps names to functions, classes and strings; |
| 1083 | function and class docstrings are tested even if the name is private; |
| 1084 | strings are tested directly, as if they were docstrings. |
| 1085 | |
| 1086 | Return (#failures, #tests). |
| 1087 | |
| 1088 | See doctest.__doc__ for an overview. |
| 1089 | |
| 1090 | Optional keyword arg "name" gives the name of the module; by default |
| 1091 | use m.__name__. |
| 1092 | |
| 1093 | Optional keyword arg "globs" gives a dict to be used as the globals |
| 1094 | when executing examples; by default, use m.__dict__. A copy of this |
| 1095 | dict is actually used for each docstring, so that each docstring's |
| 1096 | examples start with a clean slate. |
| 1097 | |
| 1098 | Optional keyword arg "verbose" prints lots of stuff if true, prints |
| 1099 | only failures if false; by default, it's true iff "-v" is in sys.argv. |
| 1100 | |
| 1101 | Optional keyword arg "isprivate" specifies a function used to |
| 1102 | determine whether a name is private. The default function is |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 1103 | treat all functions as public. Optionally, "isprivate" can be |
| 1104 | set to doctest.is_private to skip over functions marked as private |
| 1105 | using the underscore naming convention; see its docs for details. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1106 | |
| 1107 | Optional keyword arg "report" prints a summary at the end when true, |
| 1108 | else prints nothing at the end. In verbose mode, the summary is |
| 1109 | detailed, else very brief (in fact, empty if all tests passed). |
| 1110 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1111 | Optional keyword arg "optionflags" or's together module constants, |
| 1112 | and defaults to 0. This is new in 2.3. Possible values: |
| 1113 | |
| 1114 | DONT_ACCEPT_TRUE_FOR_1 |
| 1115 | By default, if an expected output block contains just "1", |
| 1116 | an actual output block containing just "True" is considered |
| 1117 | to be a match, and similarly for "0" versus "False". When |
| 1118 | DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution |
| 1119 | is allowed. |
| 1120 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1121 | Advanced tomfoolery: testmod runs methods of a local instance of |
| 1122 | class doctest.Tester, then merges the results into (or creates) |
| 1123 | global Tester instance doctest.master. Methods of doctest.master |
| 1124 | can be called directly too, if you want to do something unusual. |
| 1125 | Passing report=0 to testmod is especially useful then, to delay |
| 1126 | displaying a summary. Invoke doctest.master.summarize(verbose) |
| 1127 | when you're done fiddling. |
| 1128 | """ |
| 1129 | |
| 1130 | global master |
| 1131 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1132 | if m is None: |
| 1133 | import sys |
| 1134 | # DWA - m will still be None if this wasn't invoked from the command |
| 1135 | # line, in which case the following TypeError is about as good an error |
| 1136 | # as we should expect |
| 1137 | m = sys.modules.get('__main__') |
| 1138 | |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1139 | if not _ismodule(m): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 1140 | raise TypeError("testmod: module required; %r" % (m,)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1141 | if name is None: |
| 1142 | name = m.__name__ |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1143 | tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate, |
| 1144 | optionflags=optionflags) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1145 | failures, tries = tester.rundoc(m, name) |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 1146 | f, t = tester.rundict(m.__dict__, name, m) |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1147 | failures += f |
| 1148 | tries += t |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1149 | if hasattr(m, "__test__"): |
| 1150 | testdict = m.__test__ |
| 1151 | if testdict: |
| 1152 | if not hasattr(testdict, "items"): |
| 1153 | raise TypeError("testmod: module.__test__ must support " |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 1154 | ".items(); %r" % (testdict,)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1155 | f, t = tester.run__test__(testdict, name + ".__test__") |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1156 | failures += f |
| 1157 | tries += t |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1158 | if report: |
| 1159 | tester.summarize() |
| 1160 | if master is None: |
| 1161 | master = tester |
| 1162 | else: |
| 1163 | master.merge(tester) |
| 1164 | return failures, tries |
| 1165 | |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1166 | ########################################################################### |
| 1167 | # Various doctest extensions, to make using doctest with unittest |
| 1168 | # easier, and to help debugging when a doctest goes wrong. Original |
| 1169 | # code by Jim Fulton. |
| 1170 | |
| 1171 | # Utilities. |
| 1172 | |
| 1173 | # If module is None, return the calling module (the module that called |
| 1174 | # the routine that called _normalize_module -- this normally won't be |
| 1175 | # doctest!). If module is a string, it should be the (possibly dotted) |
| 1176 | # name of a module, and the (rightmost) module object is returned. Else |
| 1177 | # module is returned untouched; the intent appears to be that module is |
| 1178 | # already a module object in this case (although this isn't checked). |
| 1179 | |
| 1180 | def _normalize_module(module): |
| 1181 | import sys |
| 1182 | |
| 1183 | if module is None: |
| 1184 | # Get our caller's caller's module. |
| 1185 | module = sys._getframe(2).f_globals['__name__'] |
| 1186 | module = sys.modules[module] |
| 1187 | |
Raymond Hettinger | 7a70ea4 | 2003-09-17 05:50:59 +0000 | [diff] [blame] | 1188 | elif isinstance(module, basestring): |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1189 | # The ["*"] at the end is a mostly meaningless incantation with |
| 1190 | # a crucial property: if, e.g., module is 'a.b.c', it convinces |
| 1191 | # __import__ to return c instead of a. |
| 1192 | module = __import__(module, globals(), locals(), ["*"]) |
| 1193 | |
| 1194 | return module |
| 1195 | |
| 1196 | # tests is a list of (testname, docstring, filename, lineno) tuples. |
| 1197 | # If object has a __doc__ attr, and the __doc__ attr looks like it |
| 1198 | # contains a doctest (specifically, if it contains an instance of '>>>'), |
| 1199 | # then tuple |
| 1200 | # prefix + name, object.__doc__, filename, lineno |
| 1201 | # is appended to tests. Else tests is left alone. |
| 1202 | # There is no return value. |
| 1203 | |
| 1204 | def _get_doctest(name, object, tests, prefix, filename='', lineno=''): |
| 1205 | doc = getattr(object, '__doc__', '') |
| 1206 | if isinstance(doc, basestring) and '>>>' in doc: |
| 1207 | tests.append((prefix + name, doc, filename, lineno)) |
| 1208 | |
| 1209 | # tests is a list of (testname, docstring, filename, lineno) tuples. |
| 1210 | # docstrings containing doctests are appended to tests (if any are found). |
| 1211 | # items is a dict, like a module or class dict, mapping strings to objects. |
| 1212 | # mdict is the global dict of a "home" module -- only objects belonging |
| 1213 | # to this module are searched for docstrings. module is the module to |
| 1214 | # which mdict belongs. |
| 1215 | # prefix is a string to be prepended to an object's name when adding a |
| 1216 | # tuple to tests. |
| 1217 | # The objects (values) in items are examined (recursively), and doctests |
| 1218 | # belonging to functions and classes in the home module are appended to |
| 1219 | # tests. |
| 1220 | # minlineno is a gimmick to try to guess the file-relative line number |
| 1221 | # at which a doctest probably begins. |
| 1222 | |
| 1223 | def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0): |
| 1224 | |
| 1225 | for name, object in items: |
| 1226 | # Only interested in named objects. |
| 1227 | if not hasattr(object, '__name__'): |
| 1228 | continue |
| 1229 | |
| 1230 | elif hasattr(object, 'func_globals'): |
| 1231 | # Looks like a function. |
| 1232 | if object.func_globals is not mdict: |
| 1233 | # Non-local function. |
| 1234 | continue |
| 1235 | code = getattr(object, 'func_code', None) |
| 1236 | filename = getattr(code, 'co_filename', '') |
| 1237 | lineno = getattr(code, 'co_firstlineno', -1) + 1 |
| 1238 | if minlineno: |
| 1239 | minlineno = min(lineno, minlineno) |
| 1240 | else: |
| 1241 | minlineno = lineno |
| 1242 | _get_doctest(name, object, tests, prefix, filename, lineno) |
| 1243 | |
| 1244 | elif hasattr(object, "__module__"): |
| 1245 | # Maybe a class-like thing, in which case we care. |
| 1246 | if object.__module__ != module.__name__: |
| 1247 | # Not the same module. |
| 1248 | continue |
| 1249 | if not (hasattr(object, '__dict__') |
| 1250 | and hasattr(object, '__bases__')): |
| 1251 | # Not a class. |
| 1252 | continue |
| 1253 | |
| 1254 | lineno = _extract_doctests(object.__dict__.items(), |
| 1255 | module, |
| 1256 | mdict, |
| 1257 | tests, |
| 1258 | prefix + name + ".") |
| 1259 | # XXX "-3" is unclear. |
| 1260 | _get_doctest(name, object, tests, prefix, |
| 1261 | lineno="%s (or above)" % (lineno - 3)) |
| 1262 | |
| 1263 | return minlineno |
| 1264 | |
| 1265 | # Find all the doctests belonging to the module object. |
| 1266 | # Return a list of |
| 1267 | # (testname, docstring, filename, lineno) |
| 1268 | # tuples. |
| 1269 | |
| 1270 | def _find_tests(module, prefix=None): |
| 1271 | if prefix is None: |
| 1272 | prefix = module.__name__ |
| 1273 | mdict = module.__dict__ |
| 1274 | tests = [] |
| 1275 | # Get the module-level doctest (if any). |
| 1276 | _get_doctest(prefix, module, tests, '', lineno="1 (or above)") |
| 1277 | # Recursively search the module __dict__ for doctests. |
| 1278 | if prefix: |
| 1279 | prefix += "." |
| 1280 | _extract_doctests(mdict.items(), module, mdict, tests, prefix) |
| 1281 | return tests |
| 1282 | |
| 1283 | # unittest helpers. |
| 1284 | |
| 1285 | # A function passed to unittest, for unittest to drive. |
| 1286 | # tester is doctest Tester instance. doc is the docstring whose |
| 1287 | # doctests are to be run. |
| 1288 | |
| 1289 | def _utest(tester, name, doc, filename, lineno): |
| 1290 | import sys |
| 1291 | from StringIO import StringIO |
| 1292 | |
| 1293 | old = sys.stdout |
| 1294 | sys.stdout = new = StringIO() |
| 1295 | try: |
| 1296 | failures, tries = tester.runstring(doc, name) |
| 1297 | finally: |
| 1298 | sys.stdout = old |
| 1299 | |
| 1300 | if failures: |
| 1301 | msg = new.getvalue() |
| 1302 | lname = '.'.join(name.split('.')[-1:]) |
| 1303 | if not lineno: |
| 1304 | lineno = "0 (don't know line number)" |
| 1305 | # Don't change this format! It was designed so that Emacs can |
| 1306 | # parse it naturally. |
| 1307 | raise DocTestTestFailure('Failed doctest test for %s\n' |
| 1308 | ' File "%s", line %s, in %s\n\n%s' % |
| 1309 | (name, filename, lineno, lname, msg)) |
| 1310 | |
| 1311 | class DocTestTestFailure(Exception): |
| 1312 | """A doctest test failed""" |
| 1313 | |
| 1314 | def DocTestSuite(module=None): |
| 1315 | """Convert doctest tests for a module to a unittest TestSuite. |
| 1316 | |
| 1317 | The returned TestSuite is to be run by the unittest framework, and |
| 1318 | runs each doctest in the module. If any of the doctests fail, |
| 1319 | then the synthesized unit test fails, and an error is raised showing |
| 1320 | the name of the file containing the test and a (sometimes approximate) |
| 1321 | line number. |
| 1322 | |
| 1323 | The optional module argument provides the module to be tested. It |
| 1324 | can be a module object or a (possibly dotted) module name. If not |
| 1325 | specified, the module calling DocTestSuite() is used. |
| 1326 | |
| 1327 | Example (although note that unittest supplies many ways to use the |
| 1328 | TestSuite returned; see the unittest docs): |
| 1329 | |
| 1330 | import unittest |
| 1331 | import doctest |
| 1332 | import my_module_with_doctests |
| 1333 | |
| 1334 | suite = doctest.DocTestSuite(my_module_with_doctests) |
| 1335 | runner = unittest.TextTestRunner() |
| 1336 | runner.run(suite) |
| 1337 | """ |
| 1338 | |
| 1339 | import unittest |
| 1340 | |
| 1341 | module = _normalize_module(module) |
| 1342 | tests = _find_tests(module) |
| 1343 | if not tests: |
| 1344 | raise ValueError(module, "has no tests") |
| 1345 | |
| 1346 | tests.sort() |
| 1347 | suite = unittest.TestSuite() |
| 1348 | tester = Tester(module) |
| 1349 | for name, doc, filename, lineno in tests: |
| 1350 | if not filename: |
| 1351 | filename = module.__file__ |
| 1352 | if filename.endswith(".pyc"): |
| 1353 | filename = filename[:-1] |
| 1354 | elif filename.endswith(".pyo"): |
| 1355 | filename = filename[:-1] |
| 1356 | def runit(name=name, doc=doc, filename=filename, lineno=lineno): |
| 1357 | _utest(tester, name, doc, filename, lineno) |
| 1358 | suite.addTest(unittest.FunctionTestCase( |
| 1359 | runit, |
| 1360 | description="doctest of " + name)) |
| 1361 | return suite |
| 1362 | |
| 1363 | # Debugging support. |
| 1364 | |
| 1365 | def _expect(expect): |
| 1366 | # Return the expected output (if any), formatted as a Python |
| 1367 | # comment block. |
| 1368 | if expect: |
| 1369 | expect = "\n# ".join(expect.split("\n")) |
| 1370 | expect = "\n# Expect:\n# %s" % expect |
| 1371 | return expect |
| 1372 | |
| 1373 | def testsource(module, name): |
| 1374 | """Extract the doctest examples from a docstring. |
| 1375 | |
| 1376 | Provide the module (or dotted name of the module) containing the |
| 1377 | tests to be extracted, and the name (within the module) of the object |
| 1378 | with the docstring containing the tests to be extracted. |
| 1379 | |
| 1380 | The doctest examples are returned as a string containing Python |
| 1381 | code. The expected output blocks in the examples are converted |
| 1382 | to Python comments. |
| 1383 | """ |
| 1384 | |
| 1385 | module = _normalize_module(module) |
| 1386 | tests = _find_tests(module, "") |
| 1387 | test = [doc for (tname, doc, dummy, dummy) in tests |
| 1388 | if tname == name] |
| 1389 | if not test: |
| 1390 | raise ValueError(name, "not found in tests") |
| 1391 | test = test[0] |
| 1392 | examples = [source + _expect(expect) |
| 1393 | for source, expect, dummy in _extract_examples(test)] |
| 1394 | return '\n'.join(examples) |
| 1395 | |
| 1396 | def debug(module, name): |
| 1397 | """Debug a single docstring containing doctests. |
| 1398 | |
| 1399 | Provide the module (or dotted name of the module) containing the |
| 1400 | docstring to be debugged, and the name (within the module) of the |
| 1401 | object with the docstring to be debugged. |
| 1402 | |
| 1403 | The doctest examples are extracted (see function testsource()), |
| 1404 | and written to a temp file. The Python debugger (pdb) is then |
| 1405 | invoked on that file. |
| 1406 | """ |
| 1407 | |
| 1408 | import os |
| 1409 | import pdb |
| 1410 | import tempfile |
| 1411 | |
| 1412 | module = _normalize_module(module) |
| 1413 | testsrc = testsource(module, name) |
| 1414 | srcfilename = tempfile.mktemp("doctestdebug.py") |
| 1415 | f = file(srcfilename, 'w') |
| 1416 | f.write(testsrc) |
| 1417 | f.close() |
| 1418 | |
| 1419 | globs = {} |
| 1420 | globs.update(module.__dict__) |
| 1421 | try: |
| 1422 | # Note that %r is vital here. '%s' instead can, e.g., cause |
| 1423 | # backslashes to get treated as metacharacters on Windows. |
| 1424 | pdb.run("execfile(%r)" % srcfilename, globs, globs) |
| 1425 | finally: |
| 1426 | os.remove(srcfilename) |
| 1427 | |
| 1428 | |
| 1429 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1430 | class _TestClass: |
| 1431 | """ |
| 1432 | A pointless class, for sanity-checking of docstring testing. |
| 1433 | |
| 1434 | Methods: |
| 1435 | square() |
| 1436 | get() |
| 1437 | |
| 1438 | >>> _TestClass(13).get() + _TestClass(-12).get() |
| 1439 | 1 |
| 1440 | >>> hex(_TestClass(13).square().get()) |
| 1441 | '0xa9' |
| 1442 | """ |
| 1443 | |
| 1444 | def __init__(self, val): |
| 1445 | """val -> _TestClass object with associated value val. |
| 1446 | |
| 1447 | >>> t = _TestClass(123) |
| 1448 | >>> print t.get() |
| 1449 | 123 |
| 1450 | """ |
| 1451 | |
| 1452 | self.val = val |
| 1453 | |
| 1454 | def square(self): |
| 1455 | """square() -> square TestClass's associated value |
| 1456 | |
| 1457 | >>> _TestClass(13).square().get() |
| 1458 | 169 |
| 1459 | """ |
| 1460 | |
| 1461 | self.val = self.val ** 2 |
| 1462 | return self |
| 1463 | |
| 1464 | def get(self): |
| 1465 | """get() -> return TestClass's associated value. |
| 1466 | |
| 1467 | >>> x = _TestClass(-42) |
| 1468 | >>> print x.get() |
| 1469 | -42 |
| 1470 | """ |
| 1471 | |
| 1472 | return self.val |
| 1473 | |
| 1474 | __test__ = {"_TestClass": _TestClass, |
| 1475 | "string": r""" |
| 1476 | Example of a string object, searched as-is. |
| 1477 | >>> x = 1; y = 2 |
| 1478 | >>> x + y, x * y |
| 1479 | (3, 2) |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1480 | """, |
| 1481 | "bool-int equivalence": r""" |
| 1482 | In 2.2, boolean expressions displayed |
| 1483 | 0 or 1. By default, we still accept |
| 1484 | them. This can be disabled by passing |
| 1485 | DONT_ACCEPT_TRUE_FOR_1 to the new |
| 1486 | optionflags argument. |
| 1487 | >>> 4 == 4 |
| 1488 | 1 |
| 1489 | >>> 4 == 4 |
| 1490 | True |
| 1491 | >>> 4 > 4 |
| 1492 | 0 |
| 1493 | >>> 4 > 4 |
| 1494 | False |
| 1495 | """, |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1496 | } |
| 1497 | |
| 1498 | def _test(): |
| 1499 | import doctest |
| 1500 | return doctest.testmod(doctest) |
| 1501 | |
| 1502 | if __name__ == "__main__": |
| 1503 | _test() |