Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 1 | # Module doctest. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2 | # Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org). |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 3 | # Major enhancements and refactoring by: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 4 | # Jim Fulton |
| 5 | # Edward Loper |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 6 | |
| 7 | # Provided as-is; use at your own risk; no warranty; no promises; enjoy! |
| 8 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 9 | # [XX] This docstring is out-of-date: |
Martin v. Löwis | 92816de | 2004-05-31 19:01:00 +0000 | [diff] [blame] | 10 | r"""Module doctest -- a framework for running examples in docstrings. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 11 | |
| 12 | NORMAL USAGE |
| 13 | |
| 14 | In normal use, end each module M with: |
| 15 | |
| 16 | def _test(): |
| 17 | import doctest, M # replace M with your module's name |
| 18 | return doctest.testmod(M) # ditto |
| 19 | |
| 20 | if __name__ == "__main__": |
| 21 | _test() |
| 22 | |
| 23 | Then running the module as a script will cause the examples in the |
| 24 | docstrings to get executed and verified: |
| 25 | |
| 26 | python M.py |
| 27 | |
| 28 | This won't display anything unless an example fails, in which case the |
| 29 | failing example(s) and the cause(s) of the failure(s) are printed to stdout |
| 30 | (why not stderr? because stderr is a lame hack <0.2 wink>), and the final |
| 31 | line of output is "Test failed.". |
| 32 | |
| 33 | Run it with the -v switch instead: |
| 34 | |
| 35 | python M.py -v |
| 36 | |
| 37 | and a detailed report of all examples tried is printed to stdout, along |
| 38 | with assorted summaries at the end. |
| 39 | |
| 40 | You can force verbose mode by passing "verbose=1" to testmod, or prohibit |
| 41 | it by passing "verbose=0". In either of those cases, sys.argv is not |
| 42 | examined by testmod. |
| 43 | |
| 44 | In any case, testmod returns a 2-tuple of ints (f, t), where f is the |
| 45 | number of docstring examples that failed and t is the total number of |
| 46 | docstring examples attempted. |
| 47 | |
| 48 | |
| 49 | WHICH DOCSTRINGS ARE EXAMINED? |
| 50 | |
| 51 | + M.__doc__. |
| 52 | |
| 53 | + f.__doc__ for all functions f in M.__dict__.values(), except those |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 54 | defined in other modules. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 55 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 56 | + C.__doc__ for all classes C in M.__dict__.values(), except those |
| 57 | defined in other modules. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 58 | |
| 59 | + If M.__test__ exists and "is true", it must be a dict, and |
| 60 | each entry maps a (string) name to a function object, class object, or |
| 61 | string. Function and class object docstrings found from M.__test__ |
| 62 | are searched even if the name is private, and strings are searched |
| 63 | directly as if they were docstrings. In output, a key K in M.__test__ |
| 64 | appears with name |
| 65 | <name of M>.__test__.K |
| 66 | |
| 67 | Any classes found are recursively searched similarly, to test docstrings in |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 68 | their contained methods and nested classes. All names reached from |
| 69 | M.__test__ are searched. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 70 | |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 71 | Optionally, functions with private names can be skipped (unless listed in |
| 72 | M.__test__) by supplying a function to the "isprivate" argument that will |
| 73 | identify private functions. For convenience, one such function is |
| 74 | supplied. docttest.is_private considers a name to be private if it begins |
| 75 | with an underscore (like "_my_func") but doesn't both begin and end with |
| 76 | (at least) two underscores (like "__init__"). By supplying this function |
| 77 | or your own "isprivate" function to testmod, the behavior can be customized. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 78 | |
| 79 | If you want to test docstrings in objects with private names too, stuff |
| 80 | them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your |
| 81 | own isprivate function to Tester's constructor, or call the rundoc method |
| 82 | of a Tester instance). |
| 83 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 84 | WHAT'S THE EXECUTION CONTEXT? |
| 85 | |
| 86 | By default, each time testmod finds a docstring to test, it uses a *copy* |
| 87 | of M's globals (so that running tests on a module doesn't change the |
| 88 | module's real globals, and so that one test in M can't leave behind crumbs |
| 89 | that accidentally allow another test to work). This means examples can |
| 90 | freely use any names defined at top-level in M. It also means that sloppy |
| 91 | imports (see above) can cause examples in external docstrings to use |
| 92 | globals inappropriate for them. |
| 93 | |
| 94 | You can force use of your own dict as the execution context by passing |
| 95 | "globs=your_dict" to testmod instead. Presumably this would be a copy of |
| 96 | M.__dict__ merged with the globals from other imported modules. |
| 97 | |
| 98 | |
| 99 | WHAT IF I WANT TO TEST A WHOLE PACKAGE? |
| 100 | |
| 101 | Piece o' cake, provided the modules do their testing from docstrings. |
| 102 | Here's the test.py I use for the world's most elaborate Rational/ |
| 103 | floating-base-conversion pkg (which I'll distribute some day): |
| 104 | |
| 105 | from Rational import Cvt |
| 106 | from Rational import Format |
| 107 | from Rational import machprec |
| 108 | from Rational import Rat |
| 109 | from Rational import Round |
| 110 | from Rational import utils |
| 111 | |
| 112 | modules = (Cvt, |
| 113 | Format, |
| 114 | machprec, |
| 115 | Rat, |
| 116 | Round, |
| 117 | utils) |
| 118 | |
| 119 | def _test(): |
| 120 | import doctest |
| 121 | import sys |
| 122 | verbose = "-v" in sys.argv |
| 123 | for mod in modules: |
| 124 | doctest.testmod(mod, verbose=verbose, report=0) |
| 125 | doctest.master.summarize() |
| 126 | |
| 127 | if __name__ == "__main__": |
| 128 | _test() |
| 129 | |
| 130 | IOW, it just runs testmod on all the pkg modules. testmod remembers the |
| 131 | names and outcomes (# of failures, # of tries) for each item it's seen, and |
| 132 | passing "report=0" prevents it from printing a summary in verbose mode. |
| 133 | Instead, the summary is delayed until all modules have been tested, and |
| 134 | then "doctest.master.summarize()" forces the summary at the end. |
| 135 | |
| 136 | So this is very nice in practice: each module can be tested individually |
| 137 | with almost no work beyond writing up docstring examples, and collections |
| 138 | of modules can be tested too as a unit with no more work than the above. |
| 139 | |
| 140 | |
| 141 | WHAT ABOUT EXCEPTIONS? |
| 142 | |
| 143 | No problem, as long as the only output generated by the example is the |
| 144 | traceback itself. For example: |
| 145 | |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 146 | >>> [1, 2, 3].remove(42) |
Tim Peters | ea4f931 | 2001-02-13 20:54:42 +0000 | [diff] [blame] | 147 | Traceback (most recent call last): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 148 | File "<stdin>", line 1, in ? |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 149 | ValueError: list.remove(x): x not in list |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 150 | >>> |
| 151 | |
| 152 | Note that only the exception type and value are compared (specifically, |
| 153 | only the last line in the traceback). |
| 154 | |
| 155 | |
| 156 | ADVANCED USAGE |
| 157 | |
| 158 | doctest.testmod() captures the testing policy I find most useful most |
| 159 | often. You may want other policies. |
| 160 | |
| 161 | testmod() actually creates a local instance of class doctest.Tester, runs |
| 162 | appropriate methods of that class, and merges the results into global |
| 163 | Tester instance doctest.master. |
| 164 | |
| 165 | You can create your own instances of doctest.Tester, and so build your own |
| 166 | policies, or even run methods of doctest.master directly. See |
| 167 | doctest.Tester.__doc__ for details. |
| 168 | |
| 169 | |
| 170 | SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!? |
| 171 | |
| 172 | Oh ya. It's easy! In most cases a copy-and-paste of an interactive |
| 173 | console session works fine -- just make sure the leading whitespace is |
| 174 | rigidly consistent (you can mix tabs and spaces if you're too lazy to do it |
| 175 | right, but doctest is not in the business of guessing what you think a tab |
| 176 | means). |
| 177 | |
| 178 | >>> # comments are ignored |
| 179 | >>> x = 12 |
| 180 | >>> x |
| 181 | 12 |
| 182 | >>> if x == 13: |
| 183 | ... print "yes" |
| 184 | ... else: |
| 185 | ... print "no" |
| 186 | ... print "NO" |
| 187 | ... print "NO!!!" |
| 188 | ... |
| 189 | no |
| 190 | NO |
| 191 | NO!!! |
| 192 | >>> |
| 193 | |
| 194 | Any expected output must immediately follow the final ">>>" or "..." line |
| 195 | containing the code, and the expected output (if any) extends to the next |
| 196 | ">>>" or all-whitespace line. That's it. |
| 197 | |
| 198 | Bummers: |
| 199 | |
| 200 | + Expected output cannot contain an all-whitespace line, since such a line |
| 201 | is taken to signal the end of expected output. |
| 202 | |
| 203 | + Output to stdout is captured, but not output to stderr (exception |
| 204 | tracebacks are captured via a different means). |
| 205 | |
Martin v. Löwis | 92816de | 2004-05-31 19:01:00 +0000 | [diff] [blame] | 206 | + If you continue a line via backslashing in an interactive session, |
| 207 | or for any other reason use a backslash, you should use a raw |
| 208 | docstring, which will preserve your backslahses exactly as you type |
| 209 | them: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 210 | |
Tim Peters | 4e0e1b6 | 2004-07-07 20:54:48 +0000 | [diff] [blame] | 211 | >>> def f(x): |
Martin v. Löwis | 92816de | 2004-05-31 19:01:00 +0000 | [diff] [blame] | 212 | ... r'''Backslashes in a raw docstring: m\n''' |
| 213 | >>> print f.__doc__ |
| 214 | Backslashes in a raw docstring: m\n |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 215 | |
Martin v. Löwis | 92816de | 2004-05-31 19:01:00 +0000 | [diff] [blame] | 216 | Otherwise, the backslash will be interpreted as part of the string. |
| 217 | E.g., the "\n" above would be interpreted as a newline character. |
| 218 | Alternatively, you can double each backslash in the doctest version |
| 219 | (and not use a raw string): |
| 220 | |
Tim Peters | 4e0e1b6 | 2004-07-07 20:54:48 +0000 | [diff] [blame] | 221 | >>> def f(x): |
Martin v. Löwis | 92816de | 2004-05-31 19:01:00 +0000 | [diff] [blame] | 222 | ... '''Backslashes in a raw docstring: m\\n''' |
| 223 | >>> print f.__doc__ |
| 224 | Backslashes in a raw docstring: m\n |
Tim Peters | 4e0e1b6 | 2004-07-07 20:54:48 +0000 | [diff] [blame] | 225 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 226 | The starting column doesn't matter: |
| 227 | |
| 228 | >>> assert "Easy!" |
| 229 | >>> import math |
| 230 | >>> math.floor(1.9) |
| 231 | 1.0 |
| 232 | |
| 233 | and as many leading whitespace characters are stripped from the expected |
| 234 | output as appeared in the initial ">>>" line that triggered it. |
| 235 | |
| 236 | If you execute this very file, the examples above will be found and |
| 237 | executed, leading to this output in verbose mode: |
| 238 | |
| 239 | Running doctest.__doc__ |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 240 | Trying: [1, 2, 3].remove(42) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 241 | Expecting: |
Tim Peters | ea4f931 | 2001-02-13 20:54:42 +0000 | [diff] [blame] | 242 | Traceback (most recent call last): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 243 | File "<stdin>", line 1, in ? |
Tim Peters | 60e23f4 | 2001-02-14 00:43:21 +0000 | [diff] [blame] | 244 | ValueError: list.remove(x): x not in list |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 245 | ok |
| 246 | Trying: x = 12 |
| 247 | Expecting: nothing |
| 248 | ok |
| 249 | Trying: x |
| 250 | Expecting: 12 |
| 251 | ok |
| 252 | Trying: |
| 253 | if x == 13: |
| 254 | print "yes" |
| 255 | else: |
| 256 | print "no" |
| 257 | print "NO" |
| 258 | print "NO!!!" |
| 259 | Expecting: |
| 260 | no |
| 261 | NO |
| 262 | NO!!! |
| 263 | ok |
| 264 | ... and a bunch more like that, with this summary at the end: |
| 265 | |
| 266 | 5 items had no tests: |
| 267 | doctest.Tester.__init__ |
| 268 | doctest.Tester.run__test__ |
| 269 | doctest.Tester.summarize |
| 270 | doctest.run_docstring_examples |
| 271 | doctest.testmod |
| 272 | 12 items passed all tests: |
| 273 | 8 tests in doctest |
| 274 | 6 tests in doctest.Tester |
| 275 | 10 tests in doctest.Tester.merge |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 276 | 14 tests in doctest.Tester.rundict |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 277 | 3 tests in doctest.Tester.rundoc |
| 278 | 3 tests in doctest.Tester.runstring |
| 279 | 2 tests in doctest.__test__._TestClass |
| 280 | 2 tests in doctest.__test__._TestClass.__init__ |
| 281 | 2 tests in doctest.__test__._TestClass.get |
| 282 | 1 tests in doctest.__test__._TestClass.square |
| 283 | 2 tests in doctest.__test__.string |
| 284 | 7 tests in doctest.is_private |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 285 | 60 tests in 17 items. |
| 286 | 60 passed and 0 failed. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 287 | Test passed. |
| 288 | """ |
| 289 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 290 | __all__ = [ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 291 | 'is_private', |
| 292 | 'Example', |
| 293 | 'DocTest', |
| 294 | 'DocTestFinder', |
| 295 | 'DocTestRunner', |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 296 | 'testmod', |
| 297 | 'run_docstring_examples', |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 298 | 'Tester', |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 299 | 'DocTestCase', |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 300 | 'DocTestSuite', |
| 301 | 'testsource', |
| 302 | 'debug', |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 303 | # 'master', |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 304 | ] |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 305 | |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 306 | import __future__ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 307 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 308 | import sys, traceback, inspect, linecache, os, re, types |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 309 | import unittest, difflib, tempfile |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 310 | import warnings |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 311 | from StringIO import StringIO |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 312 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 313 | # Option constants. |
| 314 | DONT_ACCEPT_TRUE_FOR_1 = 1 << 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 315 | DONT_ACCEPT_BLANKLINE = 1 << 1 |
| 316 | NORMALIZE_WHITESPACE = 1 << 2 |
| 317 | ELLIPSIS = 1 << 3 |
| 318 | UNIFIED_DIFF = 1 << 4 |
| 319 | CONTEXT_DIFF = 1 << 5 |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 320 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 321 | OPTIONFLAGS_BY_NAME = { |
| 322 | 'DONT_ACCEPT_TRUE_FOR_1': DONT_ACCEPT_TRUE_FOR_1, |
| 323 | 'DONT_ACCEPT_BLANKLINE': DONT_ACCEPT_BLANKLINE, |
| 324 | 'NORMALIZE_WHITESPACE': NORMALIZE_WHITESPACE, |
| 325 | 'ELLIPSIS': ELLIPSIS, |
| 326 | 'UNIFIED_DIFF': UNIFIED_DIFF, |
| 327 | 'CONTEXT_DIFF': CONTEXT_DIFF, |
| 328 | } |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 329 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 330 | # Special string markers for use in `want` strings: |
| 331 | BLANKLINE_MARKER = '<BLANKLINE>' |
| 332 | ELLIPSIS_MARKER = '...' |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 333 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 334 | |
| 335 | # There are 4 basic classes: |
| 336 | # - Example: a <source, want> pair, plus an intra-docstring line number. |
| 337 | # - DocTest: a collection of examples, parsed from a docstring, plus |
| 338 | # info about where the docstring came from (name, filename, lineno). |
| 339 | # - DocTestFinder: extracts DocTests from a given object's docstring and |
| 340 | # its contained objects' docstrings. |
| 341 | # - DocTestRunner: runs DocTest cases, and accumulates statistics. |
| 342 | # |
| 343 | # So the basic picture is: |
| 344 | # |
| 345 | # list of: |
| 346 | # +------+ +---------+ +-------+ |
| 347 | # |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results| |
| 348 | # +------+ +---------+ +-------+ |
| 349 | # | Example | |
| 350 | # | ... | |
| 351 | # | Example | |
| 352 | # +---------+ |
| 353 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 354 | ###################################################################### |
| 355 | ## Table of Contents |
| 356 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 357 | # 1. Utility Functions |
| 358 | # 2. Example & DocTest -- store test cases |
| 359 | # 3. DocTest Parser -- extracts examples from strings |
| 360 | # 4. DocTest Finder -- extracts test cases from objects |
| 361 | # 5. DocTest Runner -- runs test cases |
| 362 | # 6. Test Functions -- convenient wrappers for testing |
| 363 | # 7. Tester Class -- for backwards compatibility |
| 364 | # 8. Unittest Support |
| 365 | # 9. Debugging Support |
| 366 | # 10. Example Usage |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 367 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 368 | ###################################################################### |
| 369 | ## 1. Utility Functions |
| 370 | ###################################################################### |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 371 | |
| 372 | def is_private(prefix, base): |
| 373 | """prefix, base -> true iff name prefix + "." + base is "private". |
| 374 | |
| 375 | Prefix may be an empty string, and base does not contain a period. |
| 376 | Prefix is ignored (although functions you write conforming to this |
| 377 | protocol may make use of it). |
| 378 | Return true iff base begins with an (at least one) underscore, but |
| 379 | does not both begin and end with (at least) two underscores. |
| 380 | |
Tim Peters | bafb1fe | 2004-08-08 01:52:57 +0000 | [diff] [blame] | 381 | >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning, |
| 382 | ... "doctest", 0) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 383 | >>> is_private("a.b", "my_func") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 384 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 385 | >>> is_private("____", "_my_func") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 386 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 387 | >>> is_private("someclass", "__init__") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 388 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 389 | >>> is_private("sometypo", "__init_") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 390 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 391 | >>> is_private("x.y.z", "_") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 392 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 393 | >>> is_private("_x.y.z", "__") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 394 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 395 | >>> is_private("", "") # senseless but consistent |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 396 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 397 | """ |
Tim Peters | bafb1fe | 2004-08-08 01:52:57 +0000 | [diff] [blame] | 398 | warnings.warn("is_private is deprecated; it wasn't useful; " |
| 399 | "examine DocTestFinder.find() lists instead", |
Tim Peters | 3ddd60a | 2004-08-08 02:43:33 +0000 | [diff] [blame] | 400 | DeprecationWarning, stacklevel=2) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 401 | return base[:1] == "_" and not base[:2] == "__" == base[-2:] |
| 402 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 403 | def _extract_future_flags(globs): |
| 404 | """ |
| 405 | Return the compiler-flags associated with the future features that |
| 406 | have been imported into the given namespace (globs). |
| 407 | """ |
| 408 | flags = 0 |
| 409 | for fname in __future__.all_feature_names: |
| 410 | feature = globs.get(fname, None) |
| 411 | if feature is getattr(__future__, fname): |
| 412 | flags |= feature.compiler_flag |
| 413 | return flags |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 414 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 415 | def _normalize_module(module, depth=2): |
| 416 | """ |
| 417 | Return the module specified by `module`. In particular: |
| 418 | - If `module` is a module, then return module. |
| 419 | - If `module` is a string, then import and return the |
| 420 | module with that name. |
| 421 | - If `module` is None, then return the calling module. |
| 422 | The calling module is assumed to be the module of |
| 423 | the stack frame at the given depth in the call stack. |
| 424 | """ |
| 425 | if inspect.ismodule(module): |
| 426 | return module |
| 427 | elif isinstance(module, (str, unicode)): |
| 428 | return __import__(module, globals(), locals(), ["*"]) |
| 429 | elif module is None: |
| 430 | return sys.modules[sys._getframe(depth).f_globals['__name__']] |
| 431 | else: |
| 432 | raise TypeError("Expected a module, string, or None") |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 433 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 434 | def _tag_msg(tag, msg, indent_msg=True): |
| 435 | """ |
| 436 | Return a string that displays a tag-and-message pair nicely, |
| 437 | keeping the tag and its message on the same line when that |
| 438 | makes sense. If `indent_msg` is true, then messages that are |
| 439 | put on separate lines will be indented. |
| 440 | """ |
| 441 | # What string should we use to indent contents? |
| 442 | INDENT = ' ' |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 443 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 444 | # If the message doesn't end in a newline, then add one. |
| 445 | if msg[-1:] != '\n': |
| 446 | msg += '\n' |
| 447 | # If the message is short enough, and contains no internal |
| 448 | # newlines, then display it on the same line as the tag. |
| 449 | # Otherwise, display the tag on its own line. |
| 450 | if (len(tag) + len(msg) < 75 and |
| 451 | msg.find('\n', 0, len(msg)-1) == -1): |
| 452 | return '%s: %s' % (tag, msg) |
| 453 | else: |
| 454 | if indent_msg: |
| 455 | msg = '\n'.join([INDENT+l for l in msg.split('\n')]) |
| 456 | msg = msg[:-len(INDENT)] |
| 457 | return '%s:\n%s' % (tag, msg) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 458 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 459 | # Override some StringIO methods. |
| 460 | class _SpoofOut(StringIO): |
| 461 | def getvalue(self): |
| 462 | result = StringIO.getvalue(self) |
| 463 | # If anything at all was written, make sure there's a trailing |
| 464 | # newline. There's no way for the expected output to indicate |
| 465 | # that a trailing newline is missing. |
| 466 | if result and not result.endswith("\n"): |
| 467 | result += "\n" |
| 468 | # Prevent softspace from screwing up the next test case, in |
| 469 | # case they used print with a trailing comma in an example. |
| 470 | if hasattr(self, "softspace"): |
| 471 | del self.softspace |
| 472 | return result |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 473 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 474 | def truncate(self, size=None): |
| 475 | StringIO.truncate(self, size) |
| 476 | if hasattr(self, "softspace"): |
| 477 | del self.softspace |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 478 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 479 | ###################################################################### |
| 480 | ## 2. Example & DocTest |
| 481 | ###################################################################### |
| 482 | ## - An "example" is a <source, want> pair, where "source" is a |
| 483 | ## fragment of source code, and "want" is the expected output for |
| 484 | ## "source." The Example class also includes information about |
| 485 | ## where the example was extracted from. |
| 486 | ## |
| 487 | ## - A "doctest" is a collection of examples extracted from a string |
| 488 | ## (such as an object's docstring). The DocTest class also includes |
| 489 | ## information about where the string was extracted from. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 490 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 491 | class Example: |
| 492 | """ |
| 493 | A single doctest example, consisting of source code and expected |
| 494 | output. Example defines the following attributes: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 495 | |
Edward Loper | 78b58f3 | 2004-08-09 02:56:02 +0000 | [diff] [blame^] | 496 | - source: A single python statement, ending in a newline iff the |
| 497 | statement spans more than one line. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 498 | |
Edward Loper | 78b58f3 | 2004-08-09 02:56:02 +0000 | [diff] [blame^] | 499 | - want: The expected output from running the source code (either |
| 500 | from stdout, or a traceback in case of exception). `want` |
| 501 | should always end with a newline, unless no output is expected, |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 502 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 503 | - lineno: The line number within the DocTest string containing |
| 504 | this Example where the Example begins. This line number is |
| 505 | zero-based, with respect to the beginning of the DocTest. |
| 506 | """ |
| 507 | def __init__(self, source, want, lineno): |
| 508 | # Check invariants. |
Tim Peters | 9b625d3 | 2004-08-04 20:04:32 +0000 | [diff] [blame] | 509 | if (source[-1:] == '\n') != ('\n' in source[:-1]): |
| 510 | raise AssertionError("source must end with newline iff " |
| 511 | "source contains more than one line") |
| 512 | if want and want[-1] != '\n': |
| 513 | raise AssertionError("non-empty want must end with newline") |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 514 | # Store properties. |
| 515 | self.source = source |
| 516 | self.want = want |
| 517 | self.lineno = lineno |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 518 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 519 | class DocTest: |
| 520 | """ |
| 521 | A collection of doctest examples that should be run in a single |
| 522 | namespace. Each DocTest defines the following attributes: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 523 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 524 | - examples: the list of examples. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 525 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 526 | - globs: The namespace (aka globals) that the examples should |
| 527 | be run in. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 528 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 529 | - name: A name identifying the DocTest (typically, the name of |
| 530 | the object whose docstring this DocTest was extracted from). |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 531 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 532 | - docstring: The docstring being tested |
| 533 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 534 | - filename: The name of the file that this DocTest was extracted |
| 535 | from. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 536 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 537 | - lineno: The line number within filename where this DocTest |
| 538 | begins. This line number is zero-based, with respect to the |
| 539 | beginning of the file. |
| 540 | """ |
| 541 | def __init__(self, docstring, globs, name, filename, lineno): |
| 542 | """ |
| 543 | Create a new DocTest, by extracting examples from `docstring`. |
| 544 | The DocTest's globals are initialized with a copy of `globs`. |
| 545 | """ |
| 546 | # Store a copy of the globals |
| 547 | self.globs = globs.copy() |
| 548 | # Store identifying information |
| 549 | self.name = name |
| 550 | self.filename = filename |
| 551 | self.lineno = lineno |
| 552 | # Parse the docstring. |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 553 | self.docstring = docstring |
Edward Loper | 78b58f3 | 2004-08-09 02:56:02 +0000 | [diff] [blame^] | 554 | self.examples = Parser(name, docstring).get_examples() |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 555 | |
| 556 | def __repr__(self): |
| 557 | if len(self.examples) == 0: |
| 558 | examples = 'no examples' |
| 559 | elif len(self.examples) == 1: |
| 560 | examples = '1 example' |
| 561 | else: |
| 562 | examples = '%d examples' % len(self.examples) |
| 563 | return ('<DocTest %s from %s:%s (%s)>' % |
| 564 | (self.name, self.filename, self.lineno, examples)) |
| 565 | |
| 566 | |
| 567 | # This lets us sort tests by name: |
| 568 | def __cmp__(self, other): |
| 569 | if not isinstance(other, DocTest): |
| 570 | return -1 |
| 571 | return cmp((self.name, self.filename, self.lineno, id(self)), |
| 572 | (other.name, other.filename, other.lineno, id(other))) |
| 573 | |
| 574 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 575 | ## 2. Example Parser |
| 576 | ###################################################################### |
| 577 | |
| 578 | class Parser: |
| 579 | """ |
| 580 | Extract doctests from a string. |
| 581 | """ |
| 582 | def __init__(self, name, string): |
| 583 | """ |
| 584 | Prepare to extract doctests from string `string`. |
| 585 | |
| 586 | `name` is an arbitrary (string) name associated with the string, |
| 587 | and is used only in error messages. |
| 588 | """ |
| 589 | self.name = name |
| 590 | self.string = string.expandtabs() |
| 591 | |
| 592 | _EXAMPLE_RE = re.compile(r''' |
| 593 | # Source consists of a PS1 line followed by zero or more PS2 lines. |
| 594 | (?P<source> |
| 595 | (?:^(?P<indent> [ ]*) >>> .*) # PS1 line |
| 596 | (?:\n [ ]* \.\.\. .*)*) # PS2 lines |
| 597 | \n? |
| 598 | # Want consists of any non-blank lines that do not start with PS1. |
| 599 | (?P<want> (?:(?![ ]*$) # Not a blank line |
| 600 | (?![ ]*>>>) # Not a line starting with PS1 |
| 601 | .*$\n? # But any other line |
| 602 | )*) |
| 603 | ''', re.MULTILINE | re.VERBOSE) |
| 604 | _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$') |
| 605 | |
| 606 | def get_examples(self): |
| 607 | """ |
Edward Loper | 78b58f3 | 2004-08-09 02:56:02 +0000 | [diff] [blame^] | 608 | Extract all doctest examples, from the string, and return them |
| 609 | as a list of `Example` objects. Line numbers are 0-based, |
| 610 | because it's most common in doctests that nothing interesting |
| 611 | appears on the same line as opening triple-quote, and so the |
| 612 | first interesting line is called \"line 1\" then. |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 613 | |
| 614 | >>> text = ''' |
| 615 | ... >>> x, y = 2, 3 # no output expected |
| 616 | ... >>> if 1: |
| 617 | ... ... print x |
| 618 | ... ... print y |
| 619 | ... 2 |
| 620 | ... 3 |
| 621 | ... |
| 622 | ... Some text. |
| 623 | ... >>> x+y |
| 624 | ... 5 |
| 625 | ... ''' |
| 626 | >>> for x in Parser('<string>', text).get_examples(): |
Edward Loper | 78b58f3 | 2004-08-09 02:56:02 +0000 | [diff] [blame^] | 627 | ... print (x.source, x.want, x.lineno) |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 628 | ('x, y = 2, 3 # no output expected', '', 1) |
| 629 | ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2) |
| 630 | ('x+y', '5\\n', 9) |
| 631 | """ |
| 632 | examples = [] |
| 633 | charno, lineno = 0, 0 |
| 634 | # Find all doctest examples in the string: |
| 635 | for m in self._EXAMPLE_RE.finditer(self.string): |
| 636 | # Update lineno (lines before this example) |
| 637 | lineno += self.string.count('\n', charno, m.start()) |
| 638 | |
| 639 | # Extract source/want from the regexp match. |
| 640 | (source, want) = self._parse_example(m, lineno) |
| 641 | if self._IS_BLANK_OR_COMMENT.match(source): |
| 642 | continue |
Edward Loper | 78b58f3 | 2004-08-09 02:56:02 +0000 | [diff] [blame^] | 643 | examples.append( Example(source, want, lineno) ) |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 644 | |
| 645 | # Update lineno (lines inside this example) |
| 646 | lineno += self.string.count('\n', m.start(), m.end()) |
| 647 | # Update charno. |
| 648 | charno = m.end() |
| 649 | return examples |
| 650 | |
| 651 | def get_program(self): |
| 652 | """ |
| 653 | Return an executable program from the string, as a string. |
| 654 | |
| 655 | The format of this isn't rigidly defined. In general, doctest |
| 656 | examples become the executable statements in the result, and |
| 657 | their expected outputs become comments, preceded by an \"#Expected:\" |
| 658 | comment. Everything else (text, comments, everything not part of |
| 659 | a doctest test) is also placed in comments. |
| 660 | |
| 661 | >>> text = ''' |
| 662 | ... >>> x, y = 2, 3 # no output expected |
| 663 | ... >>> if 1: |
| 664 | ... ... print x |
| 665 | ... ... print y |
| 666 | ... 2 |
| 667 | ... 3 |
| 668 | ... |
| 669 | ... Some text. |
| 670 | ... >>> x+y |
| 671 | ... 5 |
| 672 | ... ''' |
| 673 | >>> print Parser('<string>', text).get_program() |
| 674 | x, y = 2, 3 # no output expected |
| 675 | if 1: |
| 676 | print x |
| 677 | print y |
| 678 | # Expected: |
| 679 | # 2 |
| 680 | # 3 |
| 681 | # |
| 682 | # Some text. |
| 683 | x+y |
| 684 | # Expected: |
| 685 | # 5 |
| 686 | """ |
| 687 | output = [] |
| 688 | charnum, lineno = 0, 0 |
| 689 | # Find all doctest examples in the string: |
| 690 | for m in self._EXAMPLE_RE.finditer(self.string): |
| 691 | # Add any text before this example, as a comment. |
| 692 | if m.start() > charnum: |
| 693 | lines = self.string[charnum:m.start()-1].split('\n') |
| 694 | output.extend([self._comment_line(l) for l in lines]) |
| 695 | lineno += len(lines) |
| 696 | |
| 697 | # Extract source/want from the regexp match. |
| 698 | (source, want) = self._parse_example(m, lineno, False) |
| 699 | # Display the source |
| 700 | output.append(source) |
| 701 | # Display the expected output, if any |
| 702 | if want: |
| 703 | output.append('# Expected:') |
| 704 | output.extend(['# '+l for l in want.split('\n')]) |
| 705 | |
| 706 | # Update the line number & char number. |
| 707 | lineno += self.string.count('\n', m.start(), m.end()) |
| 708 | charnum = m.end() |
| 709 | # Add any remaining text, as comments. |
| 710 | output.extend([self._comment_line(l) |
| 711 | for l in self.string[charnum:].split('\n')]) |
| 712 | # Trim junk on both ends. |
| 713 | while output and output[-1] == '#': |
| 714 | output.pop() |
| 715 | while output and output[0] == '#': |
| 716 | output.pop(0) |
| 717 | # Combine the output, and return it. |
| 718 | return '\n'.join(output) |
| 719 | |
| 720 | def _parse_example(self, m, lineno, add_newlines=True): |
| 721 | # Get the example's indentation level. |
| 722 | indent = len(m.group('indent')) |
| 723 | |
| 724 | # Divide source into lines; check that they're properly |
| 725 | # indented; and then strip their indentation & prompts. |
| 726 | source_lines = m.group('source').split('\n') |
| 727 | self._check_prompt_blank(source_lines, indent, lineno) |
| 728 | self._check_prefix(source_lines[1:], ' '*indent+'.', lineno) |
| 729 | source = '\n'.join([sl[indent+4:] for sl in source_lines]) |
| 730 | if len(source_lines) > 1 and add_newlines: |
| 731 | source += '\n' |
| 732 | |
| 733 | # Divide want into lines; check that it's properly |
| 734 | # indented; and then strip the indentation. |
| 735 | want_lines = m.group('want').rstrip().split('\n') |
| 736 | self._check_prefix(want_lines, ' '*indent, |
| 737 | lineno+len(source_lines)) |
| 738 | want = '\n'.join([wl[indent:] for wl in want_lines]) |
| 739 | if len(want) > 0 and add_newlines: |
| 740 | want += '\n' |
| 741 | |
| 742 | return source, want |
| 743 | |
| 744 | def _comment_line(self, line): |
| 745 | line = line.rstrip() |
| 746 | if line: return '# '+line |
| 747 | else: return '#' |
| 748 | |
| 749 | def _check_prompt_blank(self, lines, indent, lineno): |
| 750 | for i, line in enumerate(lines): |
| 751 | if len(line) >= indent+4 and line[indent+3] != ' ': |
| 752 | raise ValueError('line %r of the docstring for %s ' |
| 753 | 'lacks blank after %s: %r' % |
| 754 | (lineno+i+1, self.name, |
| 755 | line[indent:indent+3], line)) |
| 756 | |
| 757 | def _check_prefix(self, lines, prefix, lineno): |
| 758 | for i, line in enumerate(lines): |
| 759 | if line and not line.startswith(prefix): |
| 760 | raise ValueError('line %r of the docstring for %s has ' |
| 761 | 'inconsistent leading whitespace: %r' % |
| 762 | (lineno+i+1, self.name, line)) |
| 763 | |
| 764 | |
| 765 | ###################################################################### |
| 766 | ## 4. DocTest Finder |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 767 | ###################################################################### |
| 768 | |
| 769 | class DocTestFinder: |
| 770 | """ |
| 771 | A class used to extract the DocTests that are relevant to a given |
| 772 | object, from its docstring and the docstrings of its contained |
| 773 | objects. Doctests can currently be extracted from the following |
| 774 | object types: modules, functions, classes, methods, staticmethods, |
| 775 | classmethods, and properties. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 776 | """ |
| 777 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 778 | def __init__(self, verbose=False, doctest_factory=DocTest, |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 779 | recurse=True, _namefilter=None): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 780 | """ |
| 781 | Create a new doctest finder. |
| 782 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 783 | The optional argument `doctest_factory` specifies a class or |
| 784 | function that should be used to create new DocTest objects (or |
Tim Peters | 161c963 | 2004-08-08 03:38:33 +0000 | [diff] [blame] | 785 | objects that implement the same interface as DocTest). The |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 786 | signature for this factory function should match the signature |
| 787 | of the DocTest constructor. |
| 788 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 789 | If the optional argument `recurse` is false, then `find` will |
| 790 | only examine the given object, and not any contained objects. |
| 791 | """ |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 792 | self._doctest_factory = doctest_factory |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 793 | self._verbose = verbose |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 794 | self._recurse = recurse |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 795 | # _namefilter is undocumented, and exists only for temporary backward- |
| 796 | # compatibility support of testmod's deprecated isprivate mess. |
| 797 | self._namefilter = _namefilter |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 798 | |
| 799 | def find(self, obj, name=None, module=None, globs=None, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 800 | extraglobs=None): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 801 | """ |
| 802 | Return a list of the DocTests that are defined by the given |
| 803 | object's docstring, or by any of its contained objects' |
| 804 | docstrings. |
| 805 | |
| 806 | The optional parameter `module` is the module that contains |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 807 | the given object. If the module is not specified or is None, then |
| 808 | the test finder will attempt to automatically determine the |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 809 | correct module. The object's module is used: |
| 810 | |
| 811 | - As a default namespace, if `globs` is not specified. |
| 812 | - To prevent the DocTestFinder from extracting DocTests |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 813 | from objects that are imported from other modules. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 814 | - To find the name of the file containing the object. |
| 815 | - To help find the line number of the object within its |
| 816 | file. |
| 817 | |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 818 | Contained objects whose module does not match `module` are ignored. |
| 819 | |
| 820 | If `module` is False, no attempt to find the module will be made. |
| 821 | This is obscure, of use mostly in tests: if `module` is False, or |
| 822 | is None but cannot be found automatically, then all objects are |
| 823 | considered to belong to the (non-existent) module, so all contained |
| 824 | objects will (recursively) be searched for doctests. |
| 825 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 826 | The globals for each DocTest is formed by combining `globs` |
| 827 | and `extraglobs` (bindings in `extraglobs` override bindings |
| 828 | in `globs`). A new copy of the globals dictionary is created |
| 829 | for each DocTest. If `globs` is not specified, then it |
| 830 | defaults to the module's `__dict__`, if specified, or {} |
| 831 | otherwise. If `extraglobs` is not specified, then it defaults |
| 832 | to {}. |
| 833 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 834 | """ |
| 835 | # If name was not specified, then extract it from the object. |
| 836 | if name is None: |
| 837 | name = getattr(obj, '__name__', None) |
| 838 | if name is None: |
| 839 | raise ValueError("DocTestFinder.find: name must be given " |
| 840 | "when obj.__name__ doesn't exist: %r" % |
| 841 | (type(obj),)) |
| 842 | |
| 843 | # Find the module that contains the given object (if obj is |
| 844 | # a module, then module=obj.). Note: this may fail, in which |
| 845 | # case module will be None. |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 846 | if module is False: |
| 847 | module = None |
| 848 | elif module is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 849 | module = inspect.getmodule(obj) |
| 850 | |
| 851 | # Read the module's source code. This is used by |
| 852 | # DocTestFinder._find_lineno to find the line number for a |
| 853 | # given object's docstring. |
| 854 | try: |
| 855 | file = inspect.getsourcefile(obj) or inspect.getfile(obj) |
| 856 | source_lines = linecache.getlines(file) |
| 857 | if not source_lines: |
| 858 | source_lines = None |
| 859 | except TypeError: |
| 860 | source_lines = None |
| 861 | |
| 862 | # Initialize globals, and merge in extraglobs. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 863 | if globs is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 864 | if module is None: |
| 865 | globs = {} |
| 866 | else: |
| 867 | globs = module.__dict__.copy() |
| 868 | else: |
| 869 | globs = globs.copy() |
| 870 | if extraglobs is not None: |
| 871 | globs.update(extraglobs) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 872 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 873 | # Recursively expore `obj`, extracting DocTests. |
| 874 | tests = [] |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 875 | self._find(tests, obj, name, module, source_lines, globs, {}) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 876 | return tests |
| 877 | |
| 878 | def _filter(self, obj, prefix, base): |
| 879 | """ |
| 880 | Return true if the given object should not be examined. |
| 881 | """ |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 882 | return (self._namefilter is not None and |
| 883 | self._namefilter(prefix, base)) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 884 | |
| 885 | def _from_module(self, module, object): |
| 886 | """ |
| 887 | Return true if the given object is defined in the given |
| 888 | module. |
| 889 | """ |
| 890 | if module is None: |
| 891 | return True |
| 892 | elif inspect.isfunction(object): |
| 893 | return module.__dict__ is object.func_globals |
| 894 | elif inspect.isclass(object): |
| 895 | return module.__name__ == object.__module__ |
| 896 | elif inspect.getmodule(object) is not None: |
| 897 | return module is inspect.getmodule(object) |
| 898 | elif hasattr(object, '__module__'): |
| 899 | return module.__name__ == object.__module__ |
| 900 | elif isinstance(object, property): |
| 901 | return True # [XX] no way not be sure. |
| 902 | else: |
| 903 | raise ValueError("object must be a class or function") |
| 904 | |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 905 | def _find(self, tests, obj, name, module, source_lines, globs, seen): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 906 | """ |
| 907 | Find tests for the given object and any contained objects, and |
| 908 | add them to `tests`. |
| 909 | """ |
| 910 | if self._verbose: |
| 911 | print 'Finding tests in %s' % name |
| 912 | |
| 913 | # If we've already processed this object, then ignore it. |
| 914 | if id(obj) in seen: |
| 915 | return |
| 916 | seen[id(obj)] = 1 |
| 917 | |
| 918 | # Find a test for this object, and add it to the list of tests. |
| 919 | test = self._get_test(obj, name, module, globs, source_lines) |
| 920 | if test is not None: |
| 921 | tests.append(test) |
| 922 | |
| 923 | # Look for tests in a module's contained objects. |
| 924 | if inspect.ismodule(obj) and self._recurse: |
| 925 | for valname, val in obj.__dict__.items(): |
| 926 | # Check if this contained object should be ignored. |
| 927 | if self._filter(val, name, valname): |
| 928 | continue |
| 929 | valname = '%s.%s' % (name, valname) |
| 930 | # Recurse to functions & classes. |
| 931 | if ((inspect.isfunction(val) or inspect.isclass(val)) and |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 932 | self._from_module(module, val)): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 933 | self._find(tests, val, valname, module, source_lines, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 934 | globs, seen) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 935 | |
| 936 | # Look for tests in a module's __test__ dictionary. |
| 937 | if inspect.ismodule(obj) and self._recurse: |
| 938 | for valname, val in getattr(obj, '__test__', {}).items(): |
| 939 | if not isinstance(valname, basestring): |
| 940 | raise ValueError("DocTestFinder.find: __test__ keys " |
| 941 | "must be strings: %r" % |
| 942 | (type(valname),)) |
| 943 | if not (inspect.isfunction(val) or inspect.isclass(val) or |
| 944 | inspect.ismethod(val) or inspect.ismodule(val) or |
| 945 | isinstance(val, basestring)): |
| 946 | raise ValueError("DocTestFinder.find: __test__ values " |
| 947 | "must be strings, functions, methods, " |
| 948 | "classes, or modules: %r" % |
| 949 | (type(val),)) |
| 950 | valname = '%s.%s' % (name, valname) |
| 951 | self._find(tests, val, valname, module, source_lines, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 952 | globs, seen) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 953 | |
| 954 | # Look for tests in a class's contained objects. |
| 955 | if inspect.isclass(obj) and self._recurse: |
| 956 | for valname, val in obj.__dict__.items(): |
| 957 | # Check if this contained object should be ignored. |
| 958 | if self._filter(val, name, valname): |
| 959 | continue |
| 960 | # Special handling for staticmethod/classmethod. |
| 961 | if isinstance(val, staticmethod): |
| 962 | val = getattr(obj, valname) |
| 963 | if isinstance(val, classmethod): |
| 964 | val = getattr(obj, valname).im_func |
| 965 | |
| 966 | # Recurse to methods, properties, and nested classes. |
| 967 | if ((inspect.isfunction(val) or inspect.isclass(val) or |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 968 | isinstance(val, property)) and |
| 969 | self._from_module(module, val)): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 970 | valname = '%s.%s' % (name, valname) |
| 971 | self._find(tests, val, valname, module, source_lines, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 972 | globs, seen) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 973 | |
| 974 | def _get_test(self, obj, name, module, globs, source_lines): |
| 975 | """ |
| 976 | Return a DocTest for the given object, if it defines a docstring; |
| 977 | otherwise, return None. |
| 978 | """ |
| 979 | # Extract the object's docstring. If it doesn't have one, |
| 980 | # then return None (no test for this object). |
| 981 | if isinstance(obj, basestring): |
| 982 | docstring = obj |
| 983 | else: |
| 984 | try: |
| 985 | if obj.__doc__ is None: |
| 986 | return None |
| 987 | docstring = str(obj.__doc__) |
| 988 | except (TypeError, AttributeError): |
| 989 | return None |
| 990 | |
| 991 | # Don't bother if the docstring is empty. |
| 992 | if not docstring: |
| 993 | return None |
| 994 | |
| 995 | # Find the docstring's location in the file. |
| 996 | lineno = self._find_lineno(obj, source_lines) |
| 997 | |
| 998 | # Return a DocTest for this object. |
| 999 | if module is None: |
| 1000 | filename = None |
| 1001 | else: |
| 1002 | filename = getattr(module, '__file__', module.__name__) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1003 | return self._doctest_factory(docstring, globs, name, filename, lineno) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1004 | |
| 1005 | def _find_lineno(self, obj, source_lines): |
| 1006 | """ |
| 1007 | Return a line number of the given object's docstring. Note: |
| 1008 | this method assumes that the object has a docstring. |
| 1009 | """ |
| 1010 | lineno = None |
| 1011 | |
| 1012 | # Find the line number for modules. |
| 1013 | if inspect.ismodule(obj): |
| 1014 | lineno = 0 |
| 1015 | |
| 1016 | # Find the line number for classes. |
| 1017 | # Note: this could be fooled if a class is defined multiple |
| 1018 | # times in a single file. |
| 1019 | if inspect.isclass(obj): |
| 1020 | if source_lines is None: |
| 1021 | return None |
| 1022 | pat = re.compile(r'^\s*class\s*%s\b' % |
| 1023 | getattr(obj, '__name__', '-')) |
| 1024 | for i, line in enumerate(source_lines): |
| 1025 | if pat.match(line): |
| 1026 | lineno = i |
| 1027 | break |
| 1028 | |
| 1029 | # Find the line number for functions & methods. |
| 1030 | if inspect.ismethod(obj): obj = obj.im_func |
| 1031 | if inspect.isfunction(obj): obj = obj.func_code |
| 1032 | if inspect.istraceback(obj): obj = obj.tb_frame |
| 1033 | if inspect.isframe(obj): obj = obj.f_code |
| 1034 | if inspect.iscode(obj): |
| 1035 | lineno = getattr(obj, 'co_firstlineno', None)-1 |
| 1036 | |
| 1037 | # Find the line number where the docstring starts. Assume |
| 1038 | # that it's the first line that begins with a quote mark. |
| 1039 | # Note: this could be fooled by a multiline function |
| 1040 | # signature, where a continuation line begins with a quote |
| 1041 | # mark. |
| 1042 | if lineno is not None: |
| 1043 | if source_lines is None: |
| 1044 | return lineno+1 |
| 1045 | pat = re.compile('(^|.*:)\s*\w*("|\')') |
| 1046 | for lineno in range(lineno, len(source_lines)): |
| 1047 | if pat.match(source_lines[lineno]): |
| 1048 | return lineno |
| 1049 | |
| 1050 | # We couldn't find the line number. |
| 1051 | return None |
| 1052 | |
| 1053 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 1054 | ## 5. DocTest Runner |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1055 | ###################################################################### |
| 1056 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1057 | class DocTestRunner: |
| 1058 | """ |
| 1059 | A class used to run DocTest test cases, and accumulate statistics. |
| 1060 | The `run` method is used to process a single DocTest case. It |
| 1061 | returns a tuple `(f, t)`, where `t` is the number of test cases |
| 1062 | tried, and `f` is the number of test cases that failed. |
| 1063 | |
| 1064 | >>> tests = DocTestFinder().find(_TestClass) |
| 1065 | >>> runner = DocTestRunner(verbose=False) |
| 1066 | >>> for test in tests: |
| 1067 | ... print runner.run(test) |
| 1068 | (0, 2) |
| 1069 | (0, 1) |
| 1070 | (0, 2) |
| 1071 | (0, 2) |
| 1072 | |
| 1073 | The `summarize` method prints a summary of all the test cases that |
| 1074 | have been run by the runner, and returns an aggregated `(f, t)` |
| 1075 | tuple: |
| 1076 | |
| 1077 | >>> runner.summarize(verbose=1) |
| 1078 | 4 items passed all tests: |
| 1079 | 2 tests in _TestClass |
| 1080 | 2 tests in _TestClass.__init__ |
| 1081 | 2 tests in _TestClass.get |
| 1082 | 1 tests in _TestClass.square |
| 1083 | 7 tests in 4 items. |
| 1084 | 7 passed and 0 failed. |
| 1085 | Test passed. |
| 1086 | (0, 7) |
| 1087 | |
| 1088 | The aggregated number of tried examples and failed examples is |
| 1089 | also available via the `tries` and `failures` attributes: |
| 1090 | |
| 1091 | >>> runner.tries |
| 1092 | 7 |
| 1093 | >>> runner.failures |
| 1094 | 0 |
| 1095 | |
| 1096 | The comparison between expected outputs and actual outputs is done |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1097 | by an `OutputChecker`. This comparison may be customized with a |
| 1098 | number of option flags; see the documentation for `testmod` for |
| 1099 | more information. If the option flags are insufficient, then the |
| 1100 | comparison may also be customized by passing a subclass of |
| 1101 | `OutputChecker` to the constructor. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1102 | |
| 1103 | The test runner's display output can be controlled in two ways. |
| 1104 | First, an output function (`out) can be passed to |
| 1105 | `TestRunner.run`; this function will be called with strings that |
| 1106 | should be displayed. It defaults to `sys.stdout.write`. If |
| 1107 | capturing the output is not sufficient, then the display output |
| 1108 | can be also customized by subclassing DocTestRunner, and |
| 1109 | overriding the methods `report_start`, `report_success`, |
| 1110 | `report_unexpected_exception`, and `report_failure`. |
| 1111 | """ |
| 1112 | # This divider string is used to separate failure messages, and to |
| 1113 | # separate sections of the summary. |
| 1114 | DIVIDER = "*" * 70 |
| 1115 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1116 | def __init__(self, checker=None, verbose=None, optionflags=0): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1117 | """ |
| 1118 | Create a new test runner. |
| 1119 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1120 | Optional keyword arg `checker` is the `OutputChecker` that |
| 1121 | should be used to compare the expected outputs and actual |
| 1122 | outputs of doctest examples. |
| 1123 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1124 | Optional keyword arg 'verbose' prints lots of stuff if true, |
| 1125 | only failures if false; by default, it's true iff '-v' is in |
| 1126 | sys.argv. |
| 1127 | |
| 1128 | Optional argument `optionflags` can be used to control how the |
| 1129 | test runner compares expected output to actual output, and how |
| 1130 | it displays failures. See the documentation for `testmod` for |
| 1131 | more information. |
| 1132 | """ |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1133 | self._checker = checker or OutputChecker() |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1134 | if verbose is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1135 | verbose = '-v' in sys.argv |
| 1136 | self._verbose = verbose |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1137 | self.optionflags = optionflags |
| 1138 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1139 | # Keep track of the examples we've run. |
| 1140 | self.tries = 0 |
| 1141 | self.failures = 0 |
| 1142 | self._name2ft = {} |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1143 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1144 | # Create a fake output target for capturing doctest output. |
| 1145 | self._fakeout = _SpoofOut() |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 1146 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1147 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1148 | # Reporting methods |
| 1149 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 1150 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1151 | def report_start(self, out, test, example): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1152 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1153 | Report that the test runner is about to process the given |
| 1154 | example. (Only displays a message if verbose=True) |
| 1155 | """ |
| 1156 | if self._verbose: |
| 1157 | out(_tag_msg("Trying", example.source) + |
| 1158 | _tag_msg("Expecting", example.want or "nothing")) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1159 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1160 | def report_success(self, out, test, example, got): |
| 1161 | """ |
| 1162 | Report that the given example ran successfully. (Only |
| 1163 | displays a message if verbose=True) |
| 1164 | """ |
| 1165 | if self._verbose: |
| 1166 | out("ok\n") |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1167 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1168 | def report_failure(self, out, test, example, got): |
| 1169 | """ |
| 1170 | Report that the given example failed. |
| 1171 | """ |
| 1172 | # Print an error message. |
| 1173 | out(self.__failure_header(test, example) + |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1174 | self._checker.output_difference(example.want, got, |
| 1175 | self.optionflags)) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1176 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1177 | def report_unexpected_exception(self, out, test, example, exc_info): |
| 1178 | """ |
| 1179 | Report that the given example raised an unexpected exception. |
| 1180 | """ |
| 1181 | # Get a traceback message. |
| 1182 | excout = StringIO() |
| 1183 | exc_type, exc_val, exc_tb = exc_info |
| 1184 | traceback.print_exception(exc_type, exc_val, exc_tb, file=excout) |
| 1185 | exception_tb = excout.getvalue() |
| 1186 | # Print an error message. |
| 1187 | out(self.__failure_header(test, example) + |
| 1188 | _tag_msg("Exception raised", exception_tb)) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1189 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1190 | def __failure_header(self, test, example): |
| 1191 | s = (self.DIVIDER + "\n" + |
| 1192 | _tag_msg("Failure in example", example.source)) |
| 1193 | if test.filename is None: |
| 1194 | # [XX] I'm not putting +1 here, to give the same output |
| 1195 | # as the old version. But I think it *should* go here. |
| 1196 | return s + ("from line #%s of %s\n" % |
| 1197 | (example.lineno, test.name)) |
| 1198 | elif test.lineno is None: |
| 1199 | return s + ("from line #%s of %s in %s\n" % |
| 1200 | (example.lineno+1, test.name, test.filename)) |
| 1201 | else: |
| 1202 | lineno = test.lineno+example.lineno+1 |
| 1203 | return s + ("from line #%s of %s (%s)\n" % |
| 1204 | (lineno, test.filename, test.name)) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1205 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1206 | #///////////////////////////////////////////////////////////////// |
| 1207 | # DocTest Running |
| 1208 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1209 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1210 | # A regular expression for handling `want` strings that contain |
| 1211 | # expected exceptions. It divides `want` into two pieces: the |
| 1212 | # pre-exception output (`out`) and the exception message (`exc`), |
| 1213 | # as generated by traceback.format_exception_only(). (I assume |
| 1214 | # that the exception_only message is the first non-indented line |
| 1215 | # starting with word characters after the "Traceback ...".) |
| 1216 | _EXCEPTION_RE = re.compile(('^(?P<out>.*)' |
| 1217 | '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?' |
| 1218 | '^(?P<exc>\w+.*)') % |
| 1219 | ('most recent call last', 'innermost last'), |
| 1220 | re.MULTILINE | re.DOTALL) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1221 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1222 | _OPTION_DIRECTIVE_RE = re.compile('\s*doctest:\s*(?P<flags>[^#\n]*)') |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1223 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1224 | def __handle_directive(self, example): |
| 1225 | """ |
| 1226 | Check if the given example is actually a directive to doctest |
| 1227 | (to turn an optionflag on or off); and if it is, then handle |
| 1228 | the directive. |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1229 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1230 | Return true iff the example is actually a directive (and so |
| 1231 | should not be executed). |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 1232 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1233 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1234 | m = self._OPTION_DIRECTIVE_RE.match(example.source) |
| 1235 | if m is None: |
| 1236 | return False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1237 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1238 | for flag in m.group('flags').upper().split(): |
| 1239 | if (flag[:1] not in '+-' or |
| 1240 | flag[1:] not in OPTIONFLAGS_BY_NAME): |
| 1241 | raise ValueError('Bad doctest option directive: '+flag) |
| 1242 | if flag[0] == '+': |
| 1243 | self.optionflags |= OPTIONFLAGS_BY_NAME[flag[1:]] |
| 1244 | else: |
| 1245 | self.optionflags &= ~OPTIONFLAGS_BY_NAME[flag[1:]] |
| 1246 | return True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1247 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1248 | def __run(self, test, compileflags, out): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1249 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1250 | Run the examples in `test`. Write the outcome of each example |
| 1251 | with one of the `DocTestRunner.report_*` methods, using the |
| 1252 | writer function `out`. `compileflags` is the set of compiler |
| 1253 | flags that should be used to execute examples. Return a tuple |
| 1254 | `(f, t)`, where `t` is the number of examples tried, and `f` |
| 1255 | is the number of examples that failed. The examples are run |
| 1256 | in the namespace `test.globs`. |
| 1257 | """ |
| 1258 | # Keep track of the number of failures and tries. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1259 | failures = tries = 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1260 | |
| 1261 | # Save the option flags (since option directives can be used |
| 1262 | # to modify them). |
| 1263 | original_optionflags = self.optionflags |
| 1264 | |
| 1265 | # Process each example. |
| 1266 | for example in test.examples: |
| 1267 | # Check if it's an option directive. If it is, then handle |
| 1268 | # it, and go on to the next example. |
| 1269 | if self.__handle_directive(example): |
| 1270 | continue |
| 1271 | |
| 1272 | # Record that we started this example. |
| 1273 | tries += 1 |
| 1274 | self.report_start(out, test, example) |
| 1275 | |
| 1276 | # Run the example in the given context (globs), and record |
| 1277 | # any exception that gets raised. (But don't intercept |
| 1278 | # keyboard interrupts.) |
| 1279 | try: |
| 1280 | # If the example is a compound statement on one line, |
| 1281 | # like "if 1: print 2", then compile() requires a |
| 1282 | # trailing newline. Rather than analyze that, always |
| 1283 | # append one (it never hurts). |
| 1284 | exec compile(example.source + '\n', "<string>", "single", |
| 1285 | compileflags, 1) in test.globs |
| 1286 | exception = None |
| 1287 | except KeyboardInterrupt: |
| 1288 | raise |
| 1289 | except: |
| 1290 | exception = sys.exc_info() |
| 1291 | |
| 1292 | # Extract the example's actual output from fakeout, and |
| 1293 | # write it to `got`. Add a terminating newline if it |
| 1294 | # doesn't have already one. |
| 1295 | got = self._fakeout.getvalue() |
| 1296 | self._fakeout.truncate(0) |
| 1297 | |
| 1298 | # If the example executed without raising any exceptions, |
| 1299 | # then verify its output and report its outcome. |
| 1300 | if exception is None: |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1301 | if self._checker.check_output(example.want, got, |
| 1302 | self.optionflags): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1303 | self.report_success(out, test, example, got) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1304 | else: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1305 | self.report_failure(out, test, example, got) |
| 1306 | failures += 1 |
| 1307 | |
| 1308 | # If the example raised an exception, then check if it was |
| 1309 | # expected. |
| 1310 | else: |
| 1311 | exc_info = sys.exc_info() |
| 1312 | exc_msg = traceback.format_exception_only(*exc_info[:2])[-1] |
| 1313 | |
| 1314 | # Search the `want` string for an exception. If we don't |
| 1315 | # find one, then report an unexpected exception. |
| 1316 | m = self._EXCEPTION_RE.match(example.want) |
| 1317 | if m is None: |
| 1318 | self.report_unexpected_exception(out, test, example, |
| 1319 | exc_info) |
| 1320 | failures += 1 |
| 1321 | else: |
| 1322 | exc_hdr = m.group('hdr')+'\n' # Exception header |
| 1323 | # The test passes iff the pre-exception output and |
| 1324 | # the exception description match the values given |
| 1325 | # in `want`. |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1326 | if (self._checker.check_output(m.group('out'), got, |
| 1327 | self.optionflags) and |
| 1328 | self._checker.check_output(m.group('exc'), exc_msg, |
| 1329 | self.optionflags)): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1330 | # Is +exc_msg the right thing here?? |
| 1331 | self.report_success(out, test, example, |
| 1332 | got+exc_hdr+exc_msg) |
| 1333 | else: |
| 1334 | self.report_failure(out, test, example, |
| 1335 | got+exc_hdr+exc_msg) |
| 1336 | failures += 1 |
| 1337 | |
| 1338 | # Restore the option flags (in case they were modified) |
| 1339 | self.optionflags = original_optionflags |
| 1340 | |
| 1341 | # Record and return the number of failures and tries. |
| 1342 | self.__record_outcome(test, failures, tries) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1343 | return failures, tries |
| 1344 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1345 | def __record_outcome(self, test, f, t): |
| 1346 | """ |
| 1347 | Record the fact that the given DocTest (`test`) generated `f` |
| 1348 | failures out of `t` tried examples. |
| 1349 | """ |
| 1350 | f2, t2 = self._name2ft.get(test.name, (0,0)) |
| 1351 | self._name2ft[test.name] = (f+f2, t+t2) |
| 1352 | self.failures += f |
| 1353 | self.tries += t |
| 1354 | |
| 1355 | def run(self, test, compileflags=None, out=None, clear_globs=True): |
| 1356 | """ |
| 1357 | Run the examples in `test`, and display the results using the |
| 1358 | writer function `out`. |
| 1359 | |
| 1360 | The examples are run in the namespace `test.globs`. If |
| 1361 | `clear_globs` is true (the default), then this namespace will |
| 1362 | be cleared after the test runs, to help with garbage |
| 1363 | collection. If you would like to examine the namespace after |
| 1364 | the test completes, then use `clear_globs=False`. |
| 1365 | |
| 1366 | `compileflags` gives the set of flags that should be used by |
| 1367 | the Python compiler when running the examples. If not |
| 1368 | specified, then it will default to the set of future-import |
| 1369 | flags that apply to `globs`. |
| 1370 | |
| 1371 | The output of each example is checked using |
| 1372 | `DocTestRunner.check_output`, and the results are formatted by |
| 1373 | the `DocTestRunner.report_*` methods. |
| 1374 | """ |
| 1375 | if compileflags is None: |
| 1376 | compileflags = _extract_future_flags(test.globs) |
| 1377 | if out is None: |
| 1378 | out = sys.stdout.write |
| 1379 | saveout = sys.stdout |
| 1380 | |
| 1381 | try: |
| 1382 | sys.stdout = self._fakeout |
| 1383 | return self.__run(test, compileflags, out) |
| 1384 | finally: |
| 1385 | sys.stdout = saveout |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1386 | if clear_globs: |
| 1387 | test.globs.clear() |
| 1388 | |
| 1389 | #///////////////////////////////////////////////////////////////// |
| 1390 | # Summarization |
| 1391 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1392 | def summarize(self, verbose=None): |
| 1393 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1394 | Print a summary of all the test cases that have been run by |
| 1395 | this DocTestRunner, and return a tuple `(f, t)`, where `f` is |
| 1396 | the total number of failed examples, and `t` is the total |
| 1397 | number of tried examples. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1398 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1399 | The optional `verbose` argument controls how detailed the |
| 1400 | summary is. If the verbosity is not specified, then the |
| 1401 | DocTestRunner's verbosity is used. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1402 | """ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1403 | if verbose is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1404 | verbose = self._verbose |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1405 | notests = [] |
| 1406 | passed = [] |
| 1407 | failed = [] |
| 1408 | totalt = totalf = 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1409 | for x in self._name2ft.items(): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1410 | name, (f, t) = x |
| 1411 | assert f <= t |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1412 | totalt += t |
| 1413 | totalf += f |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1414 | if t == 0: |
| 1415 | notests.append(name) |
| 1416 | elif f == 0: |
| 1417 | passed.append( (name, t) ) |
| 1418 | else: |
| 1419 | failed.append(x) |
| 1420 | if verbose: |
| 1421 | if notests: |
| 1422 | print len(notests), "items had no tests:" |
| 1423 | notests.sort() |
| 1424 | for thing in notests: |
| 1425 | print " ", thing |
| 1426 | if passed: |
| 1427 | print len(passed), "items passed all tests:" |
| 1428 | passed.sort() |
| 1429 | for thing, count in passed: |
| 1430 | print " %3d tests in %s" % (count, thing) |
| 1431 | if failed: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1432 | print self.DIVIDER |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1433 | print len(failed), "items had failures:" |
| 1434 | failed.sort() |
| 1435 | for thing, (f, t) in failed: |
| 1436 | print " %3d of %3d in %s" % (f, t, thing) |
| 1437 | if verbose: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1438 | print totalt, "tests in", len(self._name2ft), "items." |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1439 | print totalt - totalf, "passed and", totalf, "failed." |
| 1440 | if totalf: |
| 1441 | print "***Test Failed***", totalf, "failures." |
| 1442 | elif verbose: |
| 1443 | print "Test passed." |
| 1444 | return totalf, totalt |
| 1445 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1446 | class OutputChecker: |
| 1447 | """ |
| 1448 | A class used to check the whether the actual output from a doctest |
| 1449 | example matches the expected output. `OutputChecker` defines two |
| 1450 | methods: `check_output`, which compares a given pair of outputs, |
| 1451 | and returns true if they match; and `output_difference`, which |
| 1452 | returns a string describing the differences between two outputs. |
| 1453 | """ |
| 1454 | def check_output(self, want, got, optionflags): |
| 1455 | """ |
| 1456 | Return True iff the actual output (`got`) matches the expected |
| 1457 | output (`want`). These strings are always considered to match |
| 1458 | if they are identical; but depending on what option flags the |
| 1459 | test runner is using, several non-exact match types are also |
| 1460 | possible. See the documentation for `TestRunner` for more |
| 1461 | information about option flags. |
| 1462 | """ |
| 1463 | # Handle the common case first, for efficiency: |
| 1464 | # if they're string-identical, always return true. |
| 1465 | if got == want: |
| 1466 | return True |
| 1467 | |
| 1468 | # The values True and False replaced 1 and 0 as the return |
| 1469 | # value for boolean comparisons in Python 2.3. |
| 1470 | if not (optionflags & DONT_ACCEPT_TRUE_FOR_1): |
| 1471 | if (got,want) == ("True\n", "1\n"): |
| 1472 | return True |
| 1473 | if (got,want) == ("False\n", "0\n"): |
| 1474 | return True |
| 1475 | |
| 1476 | # <BLANKLINE> can be used as a special sequence to signify a |
| 1477 | # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. |
| 1478 | if not (optionflags & DONT_ACCEPT_BLANKLINE): |
| 1479 | # Replace <BLANKLINE> in want with a blank line. |
| 1480 | want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER), |
| 1481 | '', want) |
| 1482 | # If a line in got contains only spaces, then remove the |
| 1483 | # spaces. |
| 1484 | got = re.sub('(?m)^\s*?$', '', got) |
| 1485 | if got == want: |
| 1486 | return True |
| 1487 | |
| 1488 | # This flag causes doctest to ignore any differences in the |
| 1489 | # contents of whitespace strings. Note that this can be used |
| 1490 | # in conjunction with the ELLISPIS flag. |
| 1491 | if (optionflags & NORMALIZE_WHITESPACE): |
| 1492 | got = ' '.join(got.split()) |
| 1493 | want = ' '.join(want.split()) |
| 1494 | if got == want: |
| 1495 | return True |
| 1496 | |
| 1497 | # The ELLIPSIS flag says to let the sequence "..." in `want` |
| 1498 | # match any substring in `got`. We implement this by |
| 1499 | # transforming `want` into a regular expression. |
| 1500 | if (optionflags & ELLIPSIS): |
| 1501 | # Escape any special regexp characters |
| 1502 | want_re = re.escape(want) |
| 1503 | # Replace ellipsis markers ('...') with .* |
| 1504 | want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*') |
| 1505 | # Require that it matches the entire string; and set the |
| 1506 | # re.DOTALL flag (with '(?s)'). |
| 1507 | want_re = '(?s)^%s$' % want_re |
| 1508 | # Check if the `want_re` regexp matches got. |
| 1509 | if re.match(want_re, got): |
| 1510 | return True |
| 1511 | |
| 1512 | # We didn't find any match; return false. |
| 1513 | return False |
| 1514 | |
| 1515 | def output_difference(self, want, got, optionflags): |
| 1516 | """ |
| 1517 | Return a string describing the differences between the |
| 1518 | expected output (`want`) and the actual output (`got`). |
| 1519 | """ |
| 1520 | # If <BLANKLINE>s are being used, then replace <BLANKLINE> |
| 1521 | # with blank lines in the expected output string. |
| 1522 | if not (optionflags & DONT_ACCEPT_BLANKLINE): |
| 1523 | want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want) |
| 1524 | |
| 1525 | # Check if we should use diff. Don't use diff if the actual |
| 1526 | # or expected outputs are too short, or if the expected output |
| 1527 | # contains an ellipsis marker. |
| 1528 | if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and |
| 1529 | want.count('\n') > 2 and got.count('\n') > 2 and |
| 1530 | not (optionflags & ELLIPSIS and '...' in want)): |
| 1531 | # Split want & got into lines. |
| 1532 | want_lines = [l+'\n' for l in want.split('\n')] |
| 1533 | got_lines = [l+'\n' for l in got.split('\n')] |
| 1534 | # Use difflib to find their differences. |
| 1535 | if optionflags & UNIFIED_DIFF: |
| 1536 | diff = difflib.unified_diff(want_lines, got_lines, n=2, |
| 1537 | fromfile='Expected', tofile='Got') |
| 1538 | kind = 'unified' |
| 1539 | elif optionflags & CONTEXT_DIFF: |
| 1540 | diff = difflib.context_diff(want_lines, got_lines, n=2, |
| 1541 | fromfile='Expected', tofile='Got') |
| 1542 | kind = 'context' |
| 1543 | else: |
| 1544 | assert 0, 'Bad diff option' |
| 1545 | # Remove trailing whitespace on diff output. |
| 1546 | diff = [line.rstrip() + '\n' for line in diff] |
| 1547 | return _tag_msg("Differences (" + kind + " diff)", |
| 1548 | ''.join(diff)) |
| 1549 | |
| 1550 | # If we're not using diff, then simply list the expected |
| 1551 | # output followed by the actual output. |
| 1552 | return (_tag_msg("Expected", want or "Nothing") + |
| 1553 | _tag_msg("Got", got)) |
| 1554 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1555 | class DocTestFailure(Exception): |
| 1556 | """A DocTest example has failed in debugging mode. |
| 1557 | |
| 1558 | The exception instance has variables: |
| 1559 | |
| 1560 | - test: the DocTest object being run |
| 1561 | |
| 1562 | - excample: the Example object that failed |
| 1563 | |
| 1564 | - got: the actual output |
| 1565 | """ |
| 1566 | def __init__(self, test, example, got): |
| 1567 | self.test = test |
| 1568 | self.example = example |
| 1569 | self.got = got |
| 1570 | |
| 1571 | def __str__(self): |
| 1572 | return str(self.test) |
| 1573 | |
| 1574 | class UnexpectedException(Exception): |
| 1575 | """A DocTest example has encountered an unexpected exception |
| 1576 | |
| 1577 | The exception instance has variables: |
| 1578 | |
| 1579 | - test: the DocTest object being run |
| 1580 | |
| 1581 | - excample: the Example object that failed |
| 1582 | |
| 1583 | - exc_info: the exception info |
| 1584 | """ |
| 1585 | def __init__(self, test, example, exc_info): |
| 1586 | self.test = test |
| 1587 | self.example = example |
| 1588 | self.exc_info = exc_info |
| 1589 | |
| 1590 | def __str__(self): |
| 1591 | return str(self.test) |
Tim Peters | d1b7827 | 2004-08-07 06:03:09 +0000 | [diff] [blame] | 1592 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1593 | class DebugRunner(DocTestRunner): |
| 1594 | r"""Run doc tests but raise an exception as soon as there is a failure. |
| 1595 | |
| 1596 | If an unexpected exception occurs, an UnexpectedException is raised. |
| 1597 | It contains the test, the example, and the original exception: |
| 1598 | |
| 1599 | >>> runner = DebugRunner(verbose=False) |
| 1600 | >>> test = DocTest('>>> raise KeyError\n42', {}, 'foo', 'foo.py', 0) |
| 1601 | >>> try: |
| 1602 | ... runner.run(test) |
| 1603 | ... except UnexpectedException, failure: |
| 1604 | ... pass |
| 1605 | |
| 1606 | >>> failure.test is test |
| 1607 | True |
| 1608 | |
| 1609 | >>> failure.example.want |
| 1610 | '42\n' |
| 1611 | |
| 1612 | >>> exc_info = failure.exc_info |
| 1613 | >>> raise exc_info[0], exc_info[1], exc_info[2] |
| 1614 | Traceback (most recent call last): |
| 1615 | ... |
| 1616 | KeyError |
| 1617 | |
| 1618 | We wrap the original exception to give the calling application |
| 1619 | access to the test and example information. |
| 1620 | |
| 1621 | If the output doesn't match, then a DocTestFailure is raised: |
| 1622 | |
| 1623 | >>> test = DocTest(''' |
| 1624 | ... >>> x = 1 |
| 1625 | ... >>> x |
| 1626 | ... 2 |
| 1627 | ... ''', {}, 'foo', 'foo.py', 0) |
| 1628 | |
| 1629 | >>> try: |
| 1630 | ... runner.run(test) |
| 1631 | ... except DocTestFailure, failure: |
| 1632 | ... pass |
| 1633 | |
| 1634 | DocTestFailure objects provide access to the test: |
| 1635 | |
| 1636 | >>> failure.test is test |
| 1637 | True |
| 1638 | |
| 1639 | As well as to the example: |
| 1640 | |
| 1641 | >>> failure.example.want |
| 1642 | '2\n' |
| 1643 | |
| 1644 | and the actual output: |
| 1645 | |
| 1646 | >>> failure.got |
| 1647 | '1\n' |
| 1648 | |
| 1649 | If a failure or error occurs, the globals are left intact: |
| 1650 | |
| 1651 | >>> del test.globs['__builtins__'] |
| 1652 | >>> test.globs |
| 1653 | {'x': 1} |
| 1654 | |
| 1655 | >>> test = DocTest(''' |
| 1656 | ... >>> x = 2 |
| 1657 | ... >>> raise KeyError |
| 1658 | ... ''', {}, 'foo', 'foo.py', 0) |
| 1659 | |
| 1660 | >>> runner.run(test) |
| 1661 | Traceback (most recent call last): |
| 1662 | ... |
| 1663 | UnexpectedException: <DocTest foo from foo.py:0 (2 examples)> |
Tim Peters | d1b7827 | 2004-08-07 06:03:09 +0000 | [diff] [blame] | 1664 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1665 | >>> del test.globs['__builtins__'] |
| 1666 | >>> test.globs |
| 1667 | {'x': 2} |
| 1668 | |
| 1669 | But the globals are cleared if there is no error: |
| 1670 | |
| 1671 | >>> test = DocTest(''' |
| 1672 | ... >>> x = 2 |
| 1673 | ... ''', {}, 'foo', 'foo.py', 0) |
| 1674 | |
| 1675 | >>> runner.run(test) |
| 1676 | (0, 1) |
| 1677 | |
| 1678 | >>> test.globs |
| 1679 | {} |
| 1680 | |
| 1681 | """ |
| 1682 | |
| 1683 | def run(self, test, compileflags=None, out=None, clear_globs=True): |
| 1684 | r = DocTestRunner.run(self, test, compileflags, out, False) |
| 1685 | if clear_globs: |
| 1686 | test.globs.clear() |
| 1687 | return r |
| 1688 | |
| 1689 | def report_unexpected_exception(self, out, test, example, exc_info): |
| 1690 | raise UnexpectedException(test, example, exc_info) |
| 1691 | |
| 1692 | def report_failure(self, out, test, example, got): |
| 1693 | raise DocTestFailure(test, example, got) |
| 1694 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1695 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 1696 | ## 6. Test Functions |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1697 | ###################################################################### |
| 1698 | # These should be backwards compatible. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1699 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1700 | def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1701 | report=True, optionflags=0, extraglobs=None, |
| 1702 | raise_on_error=False): |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1703 | """m=None, name=None, globs=None, verbose=None, isprivate=None, |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1704 | report=True, optionflags=0, extraglobs=None |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1705 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1706 | Test examples in docstrings in functions and classes reachable |
| 1707 | 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] | 1708 | with m.__doc__. Unless isprivate is specified, private names |
| 1709 | are not skipped. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1710 | |
| 1711 | Also test examples reachable from dict m.__test__ if it exists and is |
| 1712 | not None. m.__dict__ maps names to functions, classes and strings; |
| 1713 | function and class docstrings are tested even if the name is private; |
| 1714 | strings are tested directly, as if they were docstrings. |
| 1715 | |
| 1716 | Return (#failures, #tests). |
| 1717 | |
| 1718 | See doctest.__doc__ for an overview. |
| 1719 | |
| 1720 | Optional keyword arg "name" gives the name of the module; by default |
| 1721 | use m.__name__. |
| 1722 | |
| 1723 | Optional keyword arg "globs" gives a dict to be used as the globals |
| 1724 | when executing examples; by default, use m.__dict__. A copy of this |
| 1725 | dict is actually used for each docstring, so that each docstring's |
| 1726 | examples start with a clean slate. |
| 1727 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1728 | Optional keyword arg "extraglobs" gives a dictionary that should be |
| 1729 | merged into the globals that are used to execute examples. By |
| 1730 | default, no extra globals are used. This is new in 2.4. |
| 1731 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1732 | Optional keyword arg "verbose" prints lots of stuff if true, prints |
| 1733 | only failures if false; by default, it's true iff "-v" is in sys.argv. |
| 1734 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1735 | Optional keyword arg "report" prints a summary at the end when true, |
| 1736 | else prints nothing at the end. In verbose mode, the summary is |
| 1737 | detailed, else very brief (in fact, empty if all tests passed). |
| 1738 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1739 | Optional keyword arg "optionflags" or's together module constants, |
| 1740 | and defaults to 0. This is new in 2.3. Possible values: |
| 1741 | |
| 1742 | DONT_ACCEPT_TRUE_FOR_1 |
| 1743 | By default, if an expected output block contains just "1", |
| 1744 | an actual output block containing just "True" is considered |
| 1745 | to be a match, and similarly for "0" versus "False". When |
| 1746 | DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution |
| 1747 | is allowed. |
| 1748 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1749 | DONT_ACCEPT_BLANKLINE |
| 1750 | By default, if an expected output block contains a line |
| 1751 | containing only the string "<BLANKLINE>", then that line |
| 1752 | will match a blank line in the actual output. When |
| 1753 | DONT_ACCEPT_BLANKLINE is specified, this substitution is |
| 1754 | not allowed. |
| 1755 | |
| 1756 | NORMALIZE_WHITESPACE |
| 1757 | When NORMALIZE_WHITESPACE is specified, all sequences of |
| 1758 | whitespace are treated as equal. I.e., any sequence of |
| 1759 | whitespace within the expected output will match any |
| 1760 | sequence of whitespace within the actual output. |
| 1761 | |
| 1762 | ELLIPSIS |
| 1763 | When ELLIPSIS is specified, then an ellipsis marker |
| 1764 | ("...") in the expected output can match any substring in |
| 1765 | the actual output. |
| 1766 | |
| 1767 | UNIFIED_DIFF |
| 1768 | When UNIFIED_DIFF is specified, failures that involve |
| 1769 | multi-line expected and actual outputs will be displayed |
| 1770 | using a unified diff. |
| 1771 | |
| 1772 | CONTEXT_DIFF |
| 1773 | When CONTEXT_DIFF is specified, failures that involve |
| 1774 | multi-line expected and actual outputs will be displayed |
| 1775 | using a context diff. |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1776 | |
| 1777 | Optional keyword arg "raise_on_error" raises an exception on the |
| 1778 | first unexpected exception or failure. This allows failures to be |
| 1779 | post-mortem debugged. |
| 1780 | |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 1781 | Deprecated in Python 2.4: |
| 1782 | Optional keyword arg "isprivate" specifies a function used to |
| 1783 | determine whether a name is private. The default function is |
| 1784 | treat all functions as public. Optionally, "isprivate" can be |
| 1785 | set to doctest.is_private to skip over functions marked as private |
| 1786 | using the underscore naming convention; see its docs for details. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1787 | """ |
| 1788 | |
| 1789 | """ [XX] This is no longer true: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1790 | Advanced tomfoolery: testmod runs methods of a local instance of |
| 1791 | class doctest.Tester, then merges the results into (or creates) |
| 1792 | global Tester instance doctest.master. Methods of doctest.master |
| 1793 | can be called directly too, if you want to do something unusual. |
| 1794 | Passing report=0 to testmod is especially useful then, to delay |
| 1795 | displaying a summary. Invoke doctest.master.summarize(verbose) |
| 1796 | when you're done fiddling. |
| 1797 | """ |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 1798 | if isprivate is not None: |
| 1799 | warnings.warn("the isprivate argument is deprecated; " |
| 1800 | "examine DocTestFinder.find() lists instead", |
| 1801 | DeprecationWarning) |
| 1802 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1803 | # If no module was given, then use __main__. |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1804 | if m is None: |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1805 | # DWA - m will still be None if this wasn't invoked from the command |
| 1806 | # line, in which case the following TypeError is about as good an error |
| 1807 | # as we should expect |
| 1808 | m = sys.modules.get('__main__') |
| 1809 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1810 | # Check that we were actually given a module. |
| 1811 | if not inspect.ismodule(m): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 1812 | raise TypeError("testmod: module required; %r" % (m,)) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1813 | |
| 1814 | # If no name was given, then use the module's name. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1815 | if name is None: |
| 1816 | name = m.__name__ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1817 | |
| 1818 | # Find, parse, and run all tests in the given module. |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 1819 | finder = DocTestFinder(_namefilter=isprivate) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1820 | |
| 1821 | if raise_on_error: |
| 1822 | runner = DebugRunner(verbose=verbose, optionflags=optionflags) |
| 1823 | else: |
| 1824 | runner = DocTestRunner(verbose=verbose, optionflags=optionflags) |
| 1825 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1826 | for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): |
| 1827 | runner.run(test) |
| 1828 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1829 | if report: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1830 | runner.summarize() |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1831 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1832 | return runner.failures, runner.tries |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1833 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1834 | def run_docstring_examples(f, globs, verbose=False, name="NoName", |
| 1835 | compileflags=None, optionflags=0): |
| 1836 | """ |
| 1837 | Test examples in the given object's docstring (`f`), using `globs` |
| 1838 | as globals. Optional argument `name` is used in failure messages. |
| 1839 | If the optional argument `verbose` is true, then generate output |
| 1840 | even if there are no failures. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1841 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1842 | `compileflags` gives the set of flags that should be used by the |
| 1843 | Python compiler when running the examples. If not specified, then |
| 1844 | it will default to the set of future-import flags that apply to |
| 1845 | `globs`. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1846 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1847 | Optional keyword arg `optionflags` specifies options for the |
| 1848 | testing and output. See the documentation for `testmod` for more |
| 1849 | information. |
| 1850 | """ |
| 1851 | # Find, parse, and run all tests in the given module. |
| 1852 | finder = DocTestFinder(verbose=verbose, recurse=False) |
| 1853 | runner = DocTestRunner(verbose=verbose, optionflags=optionflags) |
| 1854 | for test in finder.find(f, name, globs=globs): |
| 1855 | runner.run(test, compileflags=compileflags) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1856 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1857 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 1858 | ## 7. Tester |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1859 | ###################################################################### |
| 1860 | # This is provided only for backwards compatibility. It's not |
| 1861 | # actually used in any way. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1862 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1863 | class Tester: |
| 1864 | def __init__(self, mod=None, globs=None, verbose=None, |
| 1865 | isprivate=None, optionflags=0): |
Tim Peters | 3ddd60a | 2004-08-08 02:43:33 +0000 | [diff] [blame] | 1866 | |
| 1867 | warnings.warn("class Tester is deprecated; " |
| 1868 | "use class doctest.DocTestRunner instead", |
| 1869 | DeprecationWarning, stacklevel=2) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1870 | if mod is None and globs is None: |
| 1871 | raise TypeError("Tester.__init__: must specify mod or globs") |
| 1872 | if mod is not None and not _ismodule(mod): |
| 1873 | raise TypeError("Tester.__init__: mod must be a module; %r" % |
| 1874 | (mod,)) |
| 1875 | if globs is None: |
| 1876 | globs = mod.__dict__ |
| 1877 | self.globs = globs |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1878 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1879 | self.verbose = verbose |
| 1880 | self.isprivate = isprivate |
| 1881 | self.optionflags = optionflags |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 1882 | self.testfinder = DocTestFinder(_namefilter=isprivate) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1883 | self.testrunner = DocTestRunner(verbose=verbose, |
| 1884 | optionflags=optionflags) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1885 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1886 | def runstring(self, s, name): |
| 1887 | test = DocTest(s, self.globs, name, None, None) |
| 1888 | if self.verbose: |
| 1889 | print "Running string", name |
| 1890 | (f,t) = self.testrunner.run(test) |
| 1891 | if self.verbose: |
| 1892 | print f, "of", t, "examples failed in string", name |
| 1893 | return (f,t) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1894 | |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1895 | def rundoc(self, object, name=None, module=None): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1896 | f = t = 0 |
| 1897 | tests = self.testfinder.find(object, name, module=module, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1898 | globs=self.globs) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1899 | for test in tests: |
| 1900 | (f2, t2) = self.testrunner.run(test) |
| 1901 | (f,t) = (f+f2, t+t2) |
| 1902 | return (f,t) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1903 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1904 | def rundict(self, d, name, module=None): |
| 1905 | import new |
| 1906 | m = new.module(name) |
| 1907 | m.__dict__.update(d) |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1908 | if module is None: |
| 1909 | module = False |
| 1910 | return self.rundoc(m, name, module) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1911 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1912 | def run__test__(self, d, name): |
| 1913 | import new |
| 1914 | m = new.module(name) |
| 1915 | m.__test__ = d |
| 1916 | return self.rundoc(m, name, module) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1917 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1918 | def summarize(self, verbose=None): |
| 1919 | return self.testrunner.summarize(verbose) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1920 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1921 | def merge(self, other): |
| 1922 | d = self.testrunner._name2ft |
| 1923 | for name, (f, t) in other.testrunner._name2ft.items(): |
| 1924 | if name in d: |
| 1925 | print "*** Tester.merge: '" + name + "' in both" \ |
| 1926 | " testers; summing outcomes." |
| 1927 | f2, t2 = d[name] |
| 1928 | f = f + f2 |
| 1929 | t = t + t2 |
| 1930 | d[name] = f, t |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1931 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1932 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 1933 | ## 8. Unittest Support |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1934 | ###################################################################### |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1935 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1936 | class DocTestCase(unittest.TestCase): |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1937 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1938 | def __init__(self, test, optionflags=0, setUp=None, tearDown=None, |
| 1939 | checker=None): |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1940 | unittest.TestCase.__init__(self) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1941 | self._dt_optionflags = optionflags |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1942 | self._dt_checker = checker |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1943 | self._dt_test = test |
| 1944 | self._dt_setUp = setUp |
| 1945 | self._dt_tearDown = tearDown |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1946 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1947 | def setUp(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1948 | if self._dt_setUp is not None: |
| 1949 | self._dt_setUp() |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1950 | |
| 1951 | def tearDown(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1952 | if self._dt_tearDown is not None: |
| 1953 | self._dt_tearDown() |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1954 | |
| 1955 | def runTest(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1956 | test = self._dt_test |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1957 | old = sys.stdout |
| 1958 | new = StringIO() |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1959 | runner = DocTestRunner(optionflags=self._dt_optionflags, |
| 1960 | checker=self._dt_checker, verbose=False) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1961 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1962 | try: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1963 | runner.DIVIDER = "-"*70 |
| 1964 | failures, tries = runner.run(test, out=new.write) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1965 | finally: |
| 1966 | sys.stdout = old |
| 1967 | |
| 1968 | if failures: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1969 | raise self.failureException(self.format_failure(new.getvalue())) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1970 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1971 | def format_failure(self, err): |
| 1972 | test = self._dt_test |
| 1973 | if test.lineno is None: |
| 1974 | lineno = 'unknown line number' |
| 1975 | else: |
| 1976 | lineno = 'line %s' % test.lineno |
| 1977 | lname = '.'.join(test.name.split('.')[-1:]) |
| 1978 | return ('Failed doctest test for %s\n' |
| 1979 | ' File "%s", line %s, in %s\n\n%s' |
| 1980 | % (test.name, test.filename, lineno, lname, err) |
| 1981 | ) |
| 1982 | |
| 1983 | def debug(self): |
| 1984 | r"""Run the test case without results and without catching exceptions |
| 1985 | |
| 1986 | The unit test framework includes a debug method on test cases |
| 1987 | and test suites to support post-mortem debugging. The test code |
| 1988 | is run in such a way that errors are not caught. This way a |
| 1989 | caller can catch the errors and initiate post-mortem debugging. |
| 1990 | |
| 1991 | The DocTestCase provides a debug method that raises |
| 1992 | UnexpectedException errors if there is an unexepcted |
| 1993 | exception: |
| 1994 | |
| 1995 | >>> test = DocTest('>>> raise KeyError\n42', |
| 1996 | ... {}, 'foo', 'foo.py', 0) |
| 1997 | >>> case = DocTestCase(test) |
| 1998 | >>> try: |
| 1999 | ... case.debug() |
| 2000 | ... except UnexpectedException, failure: |
| 2001 | ... pass |
| 2002 | |
| 2003 | The UnexpectedException contains the test, the example, and |
| 2004 | the original exception: |
| 2005 | |
| 2006 | >>> failure.test is test |
| 2007 | True |
| 2008 | |
| 2009 | >>> failure.example.want |
| 2010 | '42\n' |
| 2011 | |
| 2012 | >>> exc_info = failure.exc_info |
| 2013 | >>> raise exc_info[0], exc_info[1], exc_info[2] |
| 2014 | Traceback (most recent call last): |
| 2015 | ... |
| 2016 | KeyError |
| 2017 | |
| 2018 | If the output doesn't match, then a DocTestFailure is raised: |
| 2019 | |
| 2020 | >>> test = DocTest(''' |
| 2021 | ... >>> x = 1 |
| 2022 | ... >>> x |
| 2023 | ... 2 |
| 2024 | ... ''', {}, 'foo', 'foo.py', 0) |
| 2025 | >>> case = DocTestCase(test) |
| 2026 | |
| 2027 | >>> try: |
| 2028 | ... case.debug() |
| 2029 | ... except DocTestFailure, failure: |
| 2030 | ... pass |
| 2031 | |
| 2032 | DocTestFailure objects provide access to the test: |
| 2033 | |
| 2034 | >>> failure.test is test |
| 2035 | True |
| 2036 | |
| 2037 | As well as to the example: |
| 2038 | |
| 2039 | >>> failure.example.want |
| 2040 | '2\n' |
| 2041 | |
| 2042 | and the actual output: |
| 2043 | |
| 2044 | >>> failure.got |
| 2045 | '1\n' |
| 2046 | |
| 2047 | """ |
| 2048 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 2049 | runner = DebugRunner(optionflags=self._dt_optionflags, |
| 2050 | checker=self._dt_checker, verbose=False) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2051 | runner.run(self._dt_test, out=nooutput) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2052 | |
| 2053 | def id(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2054 | return self._dt_test.name |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2055 | |
| 2056 | def __repr__(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2057 | name = self._dt_test.name.split('.') |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2058 | return "%s (%s)" % (name[-1], '.'.join(name[:-1])) |
| 2059 | |
| 2060 | __str__ = __repr__ |
| 2061 | |
| 2062 | def shortDescription(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2063 | return "Doctest: " + self._dt_test.name |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2064 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2065 | def nooutput(*args): |
| 2066 | pass |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2067 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2068 | def DocTestSuite(module=None, globs=None, extraglobs=None, |
| 2069 | optionflags=0, test_finder=None, |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 2070 | setUp=lambda: None, tearDown=lambda: None, |
| 2071 | checker=None): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2072 | """ |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2073 | Convert doctest tests for a mudule to a unittest test suite. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2074 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2075 | This converts each documentation string in a module that |
| 2076 | contains doctest tests to a unittest test case. If any of the |
| 2077 | tests in a doc string fail, then the test case fails. An exception |
| 2078 | is raised showing the name of the file containing the test and a |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2079 | (sometimes approximate) line number. |
| 2080 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2081 | The `module` argument provides the module to be tested. The argument |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2082 | can be either a module or a module name. |
| 2083 | |
| 2084 | If no argument is given, the calling module is used. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2085 | """ |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2086 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2087 | if test_finder is None: |
| 2088 | test_finder = DocTestFinder() |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2089 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2090 | module = _normalize_module(module) |
| 2091 | tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) |
| 2092 | if globs is None: |
| 2093 | globs = module.__dict__ |
| 2094 | if not tests: # [XX] why do we want to do this? |
| 2095 | raise ValueError(module, "has no tests") |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2096 | |
| 2097 | tests.sort() |
| 2098 | suite = unittest.TestSuite() |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2099 | for test in tests: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2100 | if len(test.examples) == 0: |
| 2101 | continue |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2102 | if not test.filename: |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2103 | filename = module.__file__ |
| 2104 | if filename.endswith(".pyc"): |
| 2105 | filename = filename[:-1] |
| 2106 | elif filename.endswith(".pyo"): |
| 2107 | filename = filename[:-1] |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2108 | test.filename = filename |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 2109 | suite.addTest(DocTestCase(test, optionflags, setUp, tearDown, |
| 2110 | checker)) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2111 | |
| 2112 | return suite |
| 2113 | |
| 2114 | class DocFileCase(DocTestCase): |
| 2115 | |
| 2116 | def id(self): |
| 2117 | return '_'.join(self._dt_test.name.split('.')) |
| 2118 | |
| 2119 | def __repr__(self): |
| 2120 | return self._dt_test.filename |
| 2121 | __str__ = __repr__ |
| 2122 | |
| 2123 | def format_failure(self, err): |
| 2124 | return ('Failed doctest test for %s\n File "%s", line 0\n\n%s' |
| 2125 | % (self._dt_test.name, self._dt_test.filename, err) |
| 2126 | ) |
| 2127 | |
| 2128 | def DocFileTest(path, package=None, globs=None, |
| 2129 | setUp=None, tearDown=None, |
| 2130 | optionflags=0): |
| 2131 | package = _normalize_module(package) |
| 2132 | name = path.split('/')[-1] |
| 2133 | dir = os.path.split(package.__file__)[0] |
| 2134 | path = os.path.join(dir, *(path.split('/'))) |
| 2135 | doc = open(path).read() |
| 2136 | |
| 2137 | if globs is None: |
| 2138 | globs = {} |
| 2139 | |
| 2140 | test = DocTest(doc, globs, name, path, 0) |
| 2141 | |
| 2142 | return DocFileCase(test, optionflags, setUp, tearDown) |
| 2143 | |
| 2144 | def DocFileSuite(*paths, **kw): |
| 2145 | """Creates a suite of doctest files. |
| 2146 | |
| 2147 | One or more text file paths are given as strings. These should |
| 2148 | use "/" characters to separate path segments. Paths are relative |
| 2149 | to the directory of the calling module, or relative to the package |
| 2150 | passed as a keyword argument. |
| 2151 | |
| 2152 | A number of options may be provided as keyword arguments: |
| 2153 | |
| 2154 | package |
| 2155 | The name of a Python package. Text-file paths will be |
| 2156 | interpreted relative to the directory containing this package. |
| 2157 | The package may be supplied as a package object or as a dotted |
| 2158 | package name. |
| 2159 | |
| 2160 | setUp |
| 2161 | The name of a set-up function. This is called before running the |
| 2162 | tests in each file. |
| 2163 | |
| 2164 | tearDown |
| 2165 | The name of a tear-down function. This is called after running the |
| 2166 | tests in each file. |
| 2167 | |
| 2168 | globs |
| 2169 | A dictionary containing initial global variables for the tests. |
| 2170 | """ |
| 2171 | suite = unittest.TestSuite() |
| 2172 | |
| 2173 | # We do this here so that _normalize_module is called at the right |
| 2174 | # level. If it were called in DocFileTest, then this function |
| 2175 | # would be the caller and we might guess the package incorrectly. |
| 2176 | kw['package'] = _normalize_module(kw.get('package')) |
| 2177 | |
| 2178 | for path in paths: |
| 2179 | suite.addTest(DocFileTest(path, **kw)) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2180 | |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2181 | return suite |
| 2182 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2183 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 2184 | ## 9. Debugging Support |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2185 | ###################################################################### |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2186 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2187 | def script_from_examples(s): |
| 2188 | r"""Extract script from text with examples. |
| 2189 | |
| 2190 | Converts text with examples to a Python script. Example input is |
| 2191 | converted to regular code. Example output and all other words |
| 2192 | are converted to comments: |
| 2193 | |
| 2194 | >>> text = ''' |
| 2195 | ... Here are examples of simple math. |
| 2196 | ... |
| 2197 | ... Python has super accurate integer addition |
| 2198 | ... |
| 2199 | ... >>> 2 + 2 |
| 2200 | ... 5 |
| 2201 | ... |
| 2202 | ... And very friendly error messages: |
| 2203 | ... |
| 2204 | ... >>> 1/0 |
| 2205 | ... To Infinity |
| 2206 | ... And |
| 2207 | ... Beyond |
| 2208 | ... |
| 2209 | ... You can use logic if you want: |
| 2210 | ... |
| 2211 | ... >>> if 0: |
| 2212 | ... ... blah |
| 2213 | ... ... blah |
| 2214 | ... ... |
| 2215 | ... |
| 2216 | ... Ho hum |
| 2217 | ... ''' |
| 2218 | |
| 2219 | >>> print script_from_examples(text) |
| 2220 | # Here are examples of simple math. |
| 2221 | # |
| 2222 | # Python has super accurate integer addition |
| 2223 | # |
| 2224 | 2 + 2 |
| 2225 | # Expected: |
| 2226 | # 5 |
| 2227 | # |
| 2228 | # And very friendly error messages: |
| 2229 | # |
| 2230 | 1/0 |
| 2231 | # Expected: |
| 2232 | # To Infinity |
| 2233 | # And |
| 2234 | # Beyond |
| 2235 | # |
| 2236 | # You can use logic if you want: |
| 2237 | # |
| 2238 | if 0: |
| 2239 | blah |
| 2240 | blah |
| 2241 | <BLANKLINE> |
| 2242 | # |
| 2243 | # Ho hum |
| 2244 | """ |
| 2245 | |
| 2246 | return Parser('<string>', s).get_program() |
| 2247 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2248 | def _want_comment(example): |
| 2249 | """ |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2250 | Return a comment containing the expected output for the given example. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2251 | """ |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2252 | # Return the expected output, if any |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2253 | want = example.want |
| 2254 | if want: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2255 | if want[-1] == '\n': |
| 2256 | want = want[:-1] |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2257 | want = "\n# ".join(want.split("\n")) |
| 2258 | want = "\n# Expected:\n# %s" % want |
| 2259 | return want |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2260 | |
| 2261 | def testsource(module, name): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2262 | """Extract the test sources from a doctest docstring as a script. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2263 | |
| 2264 | Provide the module (or dotted name of the module) containing the |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2265 | test to be debugged and the name (within the module) of the object |
| 2266 | with the doc string with tests to be debugged. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2267 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2268 | module = _normalize_module(module) |
| 2269 | tests = DocTestFinder().find(module) |
| 2270 | test = [t for t in tests if t.name == name] |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2271 | if not test: |
| 2272 | raise ValueError(name, "not found in tests") |
| 2273 | test = test[0] |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2274 | testsrc = script_from_examples(test.docstring) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2275 | return testsrc |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2276 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2277 | def debug_src(src, pm=False, globs=None): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2278 | """Debug a single doctest docstring, in argument `src`'""" |
| 2279 | testsrc = script_from_examples(src) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2280 | debug_script(testsrc, pm, globs) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2281 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2282 | def debug_script(src, pm=False, globs=None): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2283 | "Debug a test script. `src` is the script, as a string." |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2284 | import pdb |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2285 | |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2286 | srcfilename = tempfile.mktemp("doctestdebug.py") |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2287 | f = open(srcfilename, 'w') |
| 2288 | f.write(src) |
| 2289 | f.close() |
| 2290 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2291 | if globs: |
| 2292 | globs = globs.copy() |
| 2293 | else: |
| 2294 | globs = {} |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2295 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2296 | if pm: |
| 2297 | try: |
| 2298 | execfile(srcfilename, globs, globs) |
| 2299 | except: |
| 2300 | print sys.exc_info()[1] |
| 2301 | pdb.post_mortem(sys.exc_info()[2]) |
| 2302 | else: |
| 2303 | # Note that %r is vital here. '%s' instead can, e.g., cause |
| 2304 | # backslashes to get treated as metacharacters on Windows. |
| 2305 | pdb.run("execfile(%r)" % srcfilename, globs, globs) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2306 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2307 | def debug(module, name, pm=False): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2308 | """Debug a single doctest docstring. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2309 | |
| 2310 | Provide the module (or dotted name of the module) containing the |
| 2311 | test to be debugged and the name (within the module) of the object |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2312 | with the docstring with tests to be debugged. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2313 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2314 | module = _normalize_module(module) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2315 | testsrc = testsource(module, name) |
| 2316 | debug_script(testsrc, pm, module.__dict__) |
| 2317 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2318 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 2319 | ## 10. Example Usage |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2320 | ###################################################################### |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2321 | class _TestClass: |
| 2322 | """ |
| 2323 | A pointless class, for sanity-checking of docstring testing. |
| 2324 | |
| 2325 | Methods: |
| 2326 | square() |
| 2327 | get() |
| 2328 | |
| 2329 | >>> _TestClass(13).get() + _TestClass(-12).get() |
| 2330 | 1 |
| 2331 | >>> hex(_TestClass(13).square().get()) |
| 2332 | '0xa9' |
| 2333 | """ |
| 2334 | |
| 2335 | def __init__(self, val): |
| 2336 | """val -> _TestClass object with associated value val. |
| 2337 | |
| 2338 | >>> t = _TestClass(123) |
| 2339 | >>> print t.get() |
| 2340 | 123 |
| 2341 | """ |
| 2342 | |
| 2343 | self.val = val |
| 2344 | |
| 2345 | def square(self): |
| 2346 | """square() -> square TestClass's associated value |
| 2347 | |
| 2348 | >>> _TestClass(13).square().get() |
| 2349 | 169 |
| 2350 | """ |
| 2351 | |
| 2352 | self.val = self.val ** 2 |
| 2353 | return self |
| 2354 | |
| 2355 | def get(self): |
| 2356 | """get() -> return TestClass's associated value. |
| 2357 | |
| 2358 | >>> x = _TestClass(-42) |
| 2359 | >>> print x.get() |
| 2360 | -42 |
| 2361 | """ |
| 2362 | |
| 2363 | return self.val |
| 2364 | |
| 2365 | __test__ = {"_TestClass": _TestClass, |
| 2366 | "string": r""" |
| 2367 | Example of a string object, searched as-is. |
| 2368 | >>> x = 1; y = 2 |
| 2369 | >>> x + y, x * y |
| 2370 | (3, 2) |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 2371 | """, |
| 2372 | "bool-int equivalence": r""" |
| 2373 | In 2.2, boolean expressions displayed |
| 2374 | 0 or 1. By default, we still accept |
| 2375 | them. This can be disabled by passing |
| 2376 | DONT_ACCEPT_TRUE_FOR_1 to the new |
| 2377 | optionflags argument. |
| 2378 | >>> 4 == 4 |
| 2379 | 1 |
| 2380 | >>> 4 == 4 |
| 2381 | True |
| 2382 | >>> 4 > 4 |
| 2383 | 0 |
| 2384 | >>> 4 > 4 |
| 2385 | False |
| 2386 | """, |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2387 | "blank lines": r""" |
| 2388 | Blank lines can be marked with <BLANKLINE>: |
| 2389 | >>> print 'foo\n\nbar\n' |
| 2390 | foo |
| 2391 | <BLANKLINE> |
| 2392 | bar |
| 2393 | <BLANKLINE> |
| 2394 | """, |
| 2395 | } |
| 2396 | # "ellipsis": r""" |
| 2397 | # If the ellipsis flag is used, then '...' can be used to |
| 2398 | # elide substrings in the desired output: |
| 2399 | # >>> print range(1000) |
| 2400 | # [0, 1, 2, ..., 999] |
| 2401 | # """, |
| 2402 | # "whitespace normalization": r""" |
| 2403 | # If the whitespace normalization flag is used, then |
| 2404 | # differences in whitespace are ignored. |
| 2405 | # >>> print range(30) |
| 2406 | # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, |
| 2407 | # 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, |
| 2408 | # 27, 28, 29] |
| 2409 | # """, |
| 2410 | # } |
| 2411 | |
| 2412 | def test1(): r""" |
Tim Peters | 3ddd60a | 2004-08-08 02:43:33 +0000 | [diff] [blame] | 2413 | >>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning, |
| 2414 | ... "doctest", 0) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2415 | >>> from doctest import Tester |
| 2416 | >>> t = Tester(globs={'x': 42}, verbose=0) |
| 2417 | >>> t.runstring(r''' |
| 2418 | ... >>> x = x * 2 |
| 2419 | ... >>> print x |
| 2420 | ... 42 |
| 2421 | ... ''', 'XYZ') |
| 2422 | ********************************************************************** |
| 2423 | Failure in example: print x |
| 2424 | from line #2 of XYZ |
| 2425 | Expected: 42 |
| 2426 | Got: 84 |
| 2427 | (1, 2) |
| 2428 | >>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2') |
| 2429 | (0, 2) |
| 2430 | >>> t.summarize() |
| 2431 | ********************************************************************** |
| 2432 | 1 items had failures: |
| 2433 | 1 of 2 in XYZ |
| 2434 | ***Test Failed*** 1 failures. |
| 2435 | (1, 4) |
| 2436 | >>> t.summarize(verbose=1) |
| 2437 | 1 items passed all tests: |
| 2438 | 2 tests in example2 |
| 2439 | ********************************************************************** |
| 2440 | 1 items had failures: |
| 2441 | 1 of 2 in XYZ |
| 2442 | 4 tests in 2 items. |
| 2443 | 3 passed and 1 failed. |
| 2444 | ***Test Failed*** 1 failures. |
| 2445 | (1, 4) |
| 2446 | """ |
| 2447 | |
| 2448 | def test2(): r""" |
Tim Peters | 3ddd60a | 2004-08-08 02:43:33 +0000 | [diff] [blame] | 2449 | >>> warnings.filterwarnings("ignore", "class Tester", |
| 2450 | ... DeprecationWarning, "doctest", 0) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2451 | >>> t = Tester(globs={}, verbose=1) |
| 2452 | >>> test = r''' |
| 2453 | ... # just an example |
| 2454 | ... >>> x = 1 + 2 |
| 2455 | ... >>> x |
| 2456 | ... 3 |
| 2457 | ... ''' |
| 2458 | >>> t.runstring(test, "Example") |
| 2459 | Running string Example |
| 2460 | Trying: x = 1 + 2 |
| 2461 | Expecting: nothing |
| 2462 | ok |
| 2463 | Trying: x |
| 2464 | Expecting: 3 |
| 2465 | ok |
| 2466 | 0 of 2 examples failed in string Example |
| 2467 | (0, 2) |
| 2468 | """ |
| 2469 | def test3(): r""" |
Tim Peters | 3ddd60a | 2004-08-08 02:43:33 +0000 | [diff] [blame] | 2470 | >>> warnings.filterwarnings("ignore", "class Tester", |
| 2471 | ... DeprecationWarning, "doctest", 0) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2472 | >>> t = Tester(globs={}, verbose=0) |
| 2473 | >>> def _f(): |
| 2474 | ... '''Trivial docstring example. |
| 2475 | ... >>> assert 2 == 2 |
| 2476 | ... ''' |
| 2477 | ... return 32 |
| 2478 | ... |
| 2479 | >>> t.rundoc(_f) # expect 0 failures in 1 example |
| 2480 | (0, 1) |
| 2481 | """ |
| 2482 | def test4(): """ |
| 2483 | >>> import new |
| 2484 | >>> m1 = new.module('_m1') |
| 2485 | >>> m2 = new.module('_m2') |
| 2486 | >>> test_data = \""" |
| 2487 | ... def _f(): |
| 2488 | ... '''>>> assert 1 == 1 |
| 2489 | ... ''' |
| 2490 | ... def g(): |
| 2491 | ... '''>>> assert 2 != 1 |
| 2492 | ... ''' |
| 2493 | ... class H: |
| 2494 | ... '''>>> assert 2 > 1 |
| 2495 | ... ''' |
| 2496 | ... def bar(self): |
| 2497 | ... '''>>> assert 1 < 2 |
| 2498 | ... ''' |
| 2499 | ... \""" |
| 2500 | >>> exec test_data in m1.__dict__ |
| 2501 | >>> exec test_data in m2.__dict__ |
| 2502 | >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H}) |
| 2503 | |
| 2504 | Tests that objects outside m1 are excluded: |
| 2505 | |
Tim Peters | 3ddd60a | 2004-08-08 02:43:33 +0000 | [diff] [blame] | 2506 | >>> warnings.filterwarnings("ignore", "class Tester", |
| 2507 | ... DeprecationWarning, "doctest", 0) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2508 | >>> t = Tester(globs={}, verbose=0) |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 2509 | >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2510 | (0, 4) |
| 2511 | |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 2512 | Once more, not excluding stuff outside m1: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2513 | |
| 2514 | >>> t = Tester(globs={}, verbose=0) |
| 2515 | >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped. |
| 2516 | (0, 8) |
| 2517 | |
| 2518 | The exclusion of objects from outside the designated module is |
| 2519 | meant to be invoked automagically by testmod. |
| 2520 | |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 2521 | >>> testmod(m1, verbose=False) |
| 2522 | (0, 4) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2523 | """ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2524 | |
| 2525 | def _test(): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2526 | #import doctest |
| 2527 | #doctest.testmod(doctest, verbose=False, |
| 2528 | # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE | |
| 2529 | # UNIFIED_DIFF) |
| 2530 | #print '~'*70 |
| 2531 | r = unittest.TextTestRunner() |
| 2532 | r.run(DocTestSuite()) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2533 | |
| 2534 | if __name__ == "__main__": |
| 2535 | _test() |