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). |
| 3 | # Significant enhancements by: |
| 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 | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 299 | 'DocTestTestCase', |
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 | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 308 | import sys, traceback, inspect, linecache, re, types |
| 309 | import unittest, difflib, tempfile |
| 310 | from StringIO import StringIO |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 311 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 312 | # Option constants. |
| 313 | DONT_ACCEPT_TRUE_FOR_1 = 1 << 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 314 | DONT_ACCEPT_BLANKLINE = 1 << 1 |
| 315 | NORMALIZE_WHITESPACE = 1 << 2 |
| 316 | ELLIPSIS = 1 << 3 |
| 317 | UNIFIED_DIFF = 1 << 4 |
| 318 | CONTEXT_DIFF = 1 << 5 |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 319 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 320 | OPTIONFLAGS_BY_NAME = { |
| 321 | 'DONT_ACCEPT_TRUE_FOR_1': DONT_ACCEPT_TRUE_FOR_1, |
| 322 | 'DONT_ACCEPT_BLANKLINE': DONT_ACCEPT_BLANKLINE, |
| 323 | 'NORMALIZE_WHITESPACE': NORMALIZE_WHITESPACE, |
| 324 | 'ELLIPSIS': ELLIPSIS, |
| 325 | 'UNIFIED_DIFF': UNIFIED_DIFF, |
| 326 | 'CONTEXT_DIFF': CONTEXT_DIFF, |
| 327 | } |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 328 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 329 | # Special string markers for use in `want` strings: |
| 330 | BLANKLINE_MARKER = '<BLANKLINE>' |
| 331 | ELLIPSIS_MARKER = '...' |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 332 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 333 | ###################################################################### |
| 334 | ## Table of Contents |
| 335 | ###################################################################### |
| 336 | # 1. Utility Functions |
| 337 | # 2. Example & DocTest -- store test cases |
| 338 | # 3. DocTest Finder -- extracts test cases from objects |
| 339 | # 4. DocTest Runner -- runs test cases |
| 340 | # 5. Test Functions -- convenient wrappers for testing |
| 341 | # 6. Tester Class -- for backwards compatibility |
| 342 | # 7. Unittest Support |
| 343 | # 8. Debugging Support |
| 344 | # 9. Example Usage |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 345 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 346 | ###################################################################### |
| 347 | ## 1. Utility Functions |
| 348 | ###################################################################### |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 349 | |
| 350 | def is_private(prefix, base): |
| 351 | """prefix, base -> true iff name prefix + "." + base is "private". |
| 352 | |
| 353 | Prefix may be an empty string, and base does not contain a period. |
| 354 | Prefix is ignored (although functions you write conforming to this |
| 355 | protocol may make use of it). |
| 356 | Return true iff base begins with an (at least one) underscore, but |
| 357 | does not both begin and end with (at least) two underscores. |
| 358 | |
| 359 | >>> is_private("a.b", "my_func") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 360 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 361 | >>> is_private("____", "_my_func") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 362 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 363 | >>> is_private("someclass", "__init__") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 364 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 365 | >>> is_private("sometypo", "__init_") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 366 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 367 | >>> is_private("x.y.z", "_") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 368 | True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 369 | >>> is_private("_x.y.z", "__") |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 370 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 371 | >>> is_private("", "") # senseless but consistent |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 372 | False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 373 | """ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 374 | return base[:1] == "_" and not base[:2] == "__" == base[-2:] |
| 375 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 376 | def _extract_future_flags(globs): |
| 377 | """ |
| 378 | Return the compiler-flags associated with the future features that |
| 379 | have been imported into the given namespace (globs). |
| 380 | """ |
| 381 | flags = 0 |
| 382 | for fname in __future__.all_feature_names: |
| 383 | feature = globs.get(fname, None) |
| 384 | if feature is getattr(__future__, fname): |
| 385 | flags |= feature.compiler_flag |
| 386 | return flags |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 387 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 388 | def _normalize_module(module, depth=2): |
| 389 | """ |
| 390 | Return the module specified by `module`. In particular: |
| 391 | - If `module` is a module, then return module. |
| 392 | - If `module` is a string, then import and return the |
| 393 | module with that name. |
| 394 | - If `module` is None, then return the calling module. |
| 395 | The calling module is assumed to be the module of |
| 396 | the stack frame at the given depth in the call stack. |
| 397 | """ |
| 398 | if inspect.ismodule(module): |
| 399 | return module |
| 400 | elif isinstance(module, (str, unicode)): |
| 401 | return __import__(module, globals(), locals(), ["*"]) |
| 402 | elif module is None: |
| 403 | return sys.modules[sys._getframe(depth).f_globals['__name__']] |
| 404 | else: |
| 405 | raise TypeError("Expected a module, string, or None") |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 406 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 407 | def _tag_msg(tag, msg, indent_msg=True): |
| 408 | """ |
| 409 | Return a string that displays a tag-and-message pair nicely, |
| 410 | keeping the tag and its message on the same line when that |
| 411 | makes sense. If `indent_msg` is true, then messages that are |
| 412 | put on separate lines will be indented. |
| 413 | """ |
| 414 | # What string should we use to indent contents? |
| 415 | INDENT = ' ' |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 416 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 417 | # If the message doesn't end in a newline, then add one. |
| 418 | if msg[-1:] != '\n': |
| 419 | msg += '\n' |
| 420 | # If the message is short enough, and contains no internal |
| 421 | # newlines, then display it on the same line as the tag. |
| 422 | # Otherwise, display the tag on its own line. |
| 423 | if (len(tag) + len(msg) < 75 and |
| 424 | msg.find('\n', 0, len(msg)-1) == -1): |
| 425 | return '%s: %s' % (tag, msg) |
| 426 | else: |
| 427 | if indent_msg: |
| 428 | msg = '\n'.join([INDENT+l for l in msg.split('\n')]) |
| 429 | msg = msg[:-len(INDENT)] |
| 430 | return '%s:\n%s' % (tag, msg) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 431 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 432 | # Override some StringIO methods. |
| 433 | class _SpoofOut(StringIO): |
| 434 | def getvalue(self): |
| 435 | result = StringIO.getvalue(self) |
| 436 | # If anything at all was written, make sure there's a trailing |
| 437 | # newline. There's no way for the expected output to indicate |
| 438 | # that a trailing newline is missing. |
| 439 | if result and not result.endswith("\n"): |
| 440 | result += "\n" |
| 441 | # Prevent softspace from screwing up the next test case, in |
| 442 | # case they used print with a trailing comma in an example. |
| 443 | if hasattr(self, "softspace"): |
| 444 | del self.softspace |
| 445 | return result |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 446 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 447 | def truncate(self, size=None): |
| 448 | StringIO.truncate(self, size) |
| 449 | if hasattr(self, "softspace"): |
| 450 | del self.softspace |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 451 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 452 | ###################################################################### |
| 453 | ## 2. Example & DocTest |
| 454 | ###################################################################### |
| 455 | ## - An "example" is a <source, want> pair, where "source" is a |
| 456 | ## fragment of source code, and "want" is the expected output for |
| 457 | ## "source." The Example class also includes information about |
| 458 | ## where the example was extracted from. |
| 459 | ## |
| 460 | ## - A "doctest" is a collection of examples extracted from a string |
| 461 | ## (such as an object's docstring). The DocTest class also includes |
| 462 | ## information about where the string was extracted from. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 463 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 464 | class Example: |
| 465 | """ |
| 466 | A single doctest example, consisting of source code and expected |
| 467 | output. Example defines the following attributes: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 468 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 469 | - source: The source code that should be run. It ends with a |
| 470 | newline iff the source spans more than one line. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 471 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 472 | - want: The expected output from running the source code. If |
| 473 | not empty, then this string ends with a newline. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 474 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 475 | - lineno: The line number within the DocTest string containing |
| 476 | this Example where the Example begins. This line number is |
| 477 | zero-based, with respect to the beginning of the DocTest. |
| 478 | """ |
| 479 | def __init__(self, source, want, lineno): |
| 480 | # Check invariants. |
| 481 | assert (source[-1:] == '\n') == ('\n' in source[:-1]) |
| 482 | assert want == '' or want[-1] == '\n' |
| 483 | # Store properties. |
| 484 | self.source = source |
| 485 | self.want = want |
| 486 | self.lineno = lineno |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 487 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 488 | class DocTest: |
| 489 | """ |
| 490 | A collection of doctest examples that should be run in a single |
| 491 | namespace. Each DocTest defines the following attributes: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 492 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 493 | - examples: the list of examples. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 494 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 495 | - globs: The namespace (aka globals) that the examples should |
| 496 | be run in. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 497 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 498 | - name: A name identifying the DocTest (typically, the name of |
| 499 | the object whose docstring this DocTest was extracted from). |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 500 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 501 | - filename: The name of the file that this DocTest was extracted |
| 502 | from. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 503 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 504 | - lineno: The line number within filename where this DocTest |
| 505 | begins. This line number is zero-based, with respect to the |
| 506 | beginning of the file. |
| 507 | """ |
| 508 | def __init__(self, docstring, globs, name, filename, lineno): |
| 509 | """ |
| 510 | Create a new DocTest, by extracting examples from `docstring`. |
| 511 | The DocTest's globals are initialized with a copy of `globs`. |
| 512 | """ |
| 513 | # Store a copy of the globals |
| 514 | self.globs = globs.copy() |
| 515 | # Store identifying information |
| 516 | self.name = name |
| 517 | self.filename = filename |
| 518 | self.lineno = lineno |
| 519 | # Parse the docstring. |
| 520 | self.examples = self._parse(docstring) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 521 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 522 | _PS1 = ">>>" |
| 523 | _PS2 = "..." |
| 524 | _isPS1 = re.compile(r"(\s*)" + re.escape(_PS1)).match |
| 525 | _isPS2 = re.compile(r"(\s*)" + re.escape(_PS2)).match |
| 526 | _isEmpty = re.compile(r"\s*$").match |
| 527 | _isComment = re.compile(r"\s*#").match |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 528 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 529 | def _parse(self, string): |
| 530 | if not string.endswith('\n'): |
| 531 | string += '\n' |
| 532 | examples = [] |
| 533 | isPS1, isPS2 = self._isPS1, self._isPS2 |
| 534 | isEmpty, isComment = self._isEmpty, self._isComment |
| 535 | lines = string.split("\n") |
| 536 | i, n = 0, len(lines) |
| 537 | while i < n: |
| 538 | # Search for an example (a PS1 line). |
| 539 | line = lines[i] |
| 540 | i += 1 |
| 541 | m = isPS1(line) |
| 542 | if m is None: |
| 543 | continue |
| 544 | # line is a PS1 line. |
| 545 | j = m.end(0) # beyond the prompt |
| 546 | if isEmpty(line, j) or isComment(line, j): |
| 547 | # a bare prompt or comment -- not interesting |
| 548 | continue |
| 549 | # line is a non-trivial PS1 line. |
| 550 | lineno = i - 1 |
| 551 | if line[j] != " ": |
| 552 | raise ValueError('line %r of the docstring for %s lacks ' |
| 553 | 'blank after %s: %r' % |
| 554 | (lineno, self.name, self._PS1, line)) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 555 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 556 | j += 1 |
| 557 | blanks = m.group(1) |
| 558 | nblanks = len(blanks) |
| 559 | # suck up this and following PS2 lines |
| 560 | source = [] |
| 561 | while 1: |
| 562 | source.append(line[j:]) |
| 563 | line = lines[i] |
| 564 | m = isPS2(line) |
| 565 | if m: |
| 566 | if m.group(1) != blanks: |
| 567 | raise ValueError('line %r of the docstring for %s ' |
| 568 | 'has inconsistent leading whitespace: %r' % |
| 569 | (i, self.name, line)) |
| 570 | i += 1 |
| 571 | else: |
| 572 | break |
| 573 | # get rid of useless null line from trailing empty "..." |
| 574 | if source[-1] == "": |
| 575 | assert len(source) > 1 |
| 576 | del source[-1] |
| 577 | if len(source) == 1: |
| 578 | source = source[0] |
| 579 | else: |
| 580 | source = "\n".join(source) + "\n" |
| 581 | # suck up response |
| 582 | if isPS1(line) or isEmpty(line): |
| 583 | want = "" |
| 584 | else: |
| 585 | want = [] |
| 586 | while 1: |
| 587 | if line[:nblanks] != blanks: |
| 588 | raise ValueError('line %r of the docstring for %s ' |
| 589 | 'has inconsistent leading whitespace: %r' % |
| 590 | (i, self.name, line)) |
| 591 | want.append(line[nblanks:]) |
| 592 | i += 1 |
| 593 | line = lines[i] |
| 594 | if isPS1(line) or isEmpty(line): |
| 595 | break |
| 596 | want = "\n".join(want) + "\n" |
| 597 | examples.append(Example(source, want, lineno)) |
| 598 | return examples |
| 599 | |
| 600 | def __repr__(self): |
| 601 | if len(self.examples) == 0: |
| 602 | examples = 'no examples' |
| 603 | elif len(self.examples) == 1: |
| 604 | examples = '1 example' |
| 605 | else: |
| 606 | examples = '%d examples' % len(self.examples) |
| 607 | return ('<DocTest %s from %s:%s (%s)>' % |
| 608 | (self.name, self.filename, self.lineno, examples)) |
| 609 | |
| 610 | |
| 611 | # This lets us sort tests by name: |
| 612 | def __cmp__(self, other): |
| 613 | if not isinstance(other, DocTest): |
| 614 | return -1 |
| 615 | return cmp((self.name, self.filename, self.lineno, id(self)), |
| 616 | (other.name, other.filename, other.lineno, id(other))) |
| 617 | |
| 618 | ###################################################################### |
| 619 | ## 3. DocTest Finder |
| 620 | ###################################################################### |
| 621 | |
| 622 | class DocTestFinder: |
| 623 | """ |
| 624 | A class used to extract the DocTests that are relevant to a given |
| 625 | object, from its docstring and the docstrings of its contained |
| 626 | objects. Doctests can currently be extracted from the following |
| 627 | object types: modules, functions, classes, methods, staticmethods, |
| 628 | classmethods, and properties. |
| 629 | |
| 630 | An optional name filter and an optional object filter may be |
| 631 | passed to the constructor, to restrict which contained objects are |
| 632 | examined by the doctest finder: |
| 633 | |
| 634 | - The name filter is a function `f(prefix, base)`, that returns |
| 635 | true if an object named `prefix.base` should be ignored. |
| 636 | - The object filter is a function `f(obj)` that returns true |
| 637 | if the given object should be ignored. |
| 638 | |
| 639 | Each object is ignored if either filter function returns true for |
| 640 | that object. These filter functions are applied when examining |
| 641 | the contents of a module or of a class, but not when examining a |
| 642 | module's `__test__` dictionary. By default, no objects are |
| 643 | ignored. |
| 644 | """ |
| 645 | |
| 646 | def __init__(self, verbose=False, namefilter=None, objfilter=None, |
| 647 | recurse=True): |
| 648 | """ |
| 649 | Create a new doctest finder. |
| 650 | |
| 651 | If the optional argument `recurse` is false, then `find` will |
| 652 | only examine the given object, and not any contained objects. |
| 653 | """ |
| 654 | self._verbose = verbose |
| 655 | self._namefilter = namefilter |
| 656 | self._objfilter = objfilter |
| 657 | self._recurse = recurse |
| 658 | |
| 659 | def find(self, obj, name=None, module=None, globs=None, |
| 660 | extraglobs=None, ignore_imports=True): |
| 661 | """ |
| 662 | Return a list of the DocTests that are defined by the given |
| 663 | object's docstring, or by any of its contained objects' |
| 664 | docstrings. |
| 665 | |
| 666 | The optional parameter `module` is the module that contains |
| 667 | the given object. If the module is not specified, then the |
| 668 | test finder will attempt to automatically determine the |
| 669 | correct module. The object's module is used: |
| 670 | |
| 671 | - As a default namespace, if `globs` is not specified. |
| 672 | - To prevent the DocTestFinder from extracting DocTests |
| 673 | from objects that are imported from other modules |
| 674 | (as long as `ignore_imports` is true). |
| 675 | - To find the name of the file containing the object. |
| 676 | - To help find the line number of the object within its |
| 677 | file. |
| 678 | |
| 679 | The globals for each DocTest is formed by combining `globs` |
| 680 | and `extraglobs` (bindings in `extraglobs` override bindings |
| 681 | in `globs`). A new copy of the globals dictionary is created |
| 682 | for each DocTest. If `globs` is not specified, then it |
| 683 | defaults to the module's `__dict__`, if specified, or {} |
| 684 | otherwise. If `extraglobs` is not specified, then it defaults |
| 685 | to {}. |
| 686 | |
| 687 | If the optional flag `ignore_imports` is true, then the |
| 688 | doctest finder will ignore any contained objects whose module |
| 689 | does not match `module`. Otherwise, it will extract tests |
| 690 | from all contained objects, including imported objects. |
| 691 | """ |
| 692 | # If name was not specified, then extract it from the object. |
| 693 | if name is None: |
| 694 | name = getattr(obj, '__name__', None) |
| 695 | if name is None: |
| 696 | raise ValueError("DocTestFinder.find: name must be given " |
| 697 | "when obj.__name__ doesn't exist: %r" % |
| 698 | (type(obj),)) |
| 699 | |
| 700 | # Find the module that contains the given object (if obj is |
| 701 | # a module, then module=obj.). Note: this may fail, in which |
| 702 | # case module will be None. |
| 703 | if module is None: |
| 704 | module = inspect.getmodule(obj) |
| 705 | |
| 706 | # Read the module's source code. This is used by |
| 707 | # DocTestFinder._find_lineno to find the line number for a |
| 708 | # given object's docstring. |
| 709 | try: |
| 710 | file = inspect.getsourcefile(obj) or inspect.getfile(obj) |
| 711 | source_lines = linecache.getlines(file) |
| 712 | if not source_lines: |
| 713 | source_lines = None |
| 714 | except TypeError: |
| 715 | source_lines = None |
| 716 | |
| 717 | # Initialize globals, and merge in extraglobs. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 718 | if globs is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 719 | if module is None: |
| 720 | globs = {} |
| 721 | else: |
| 722 | globs = module.__dict__.copy() |
| 723 | else: |
| 724 | globs = globs.copy() |
| 725 | if extraglobs is not None: |
| 726 | globs.update(extraglobs) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 727 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 728 | # Recursively expore `obj`, extracting DocTests. |
| 729 | tests = [] |
| 730 | self._find(tests, obj, name, module, source_lines, |
| 731 | globs, ignore_imports, {}) |
| 732 | return tests |
| 733 | |
| 734 | def _filter(self, obj, prefix, base): |
| 735 | """ |
| 736 | Return true if the given object should not be examined. |
| 737 | """ |
| 738 | return ((self._namefilter is not None and |
| 739 | self._namefilter(prefix, base)) or |
| 740 | (self._objfilter is not None and |
| 741 | self._objfilter(obj))) |
| 742 | |
| 743 | def _from_module(self, module, object): |
| 744 | """ |
| 745 | Return true if the given object is defined in the given |
| 746 | module. |
| 747 | """ |
| 748 | if module is None: |
| 749 | return True |
| 750 | elif inspect.isfunction(object): |
| 751 | return module.__dict__ is object.func_globals |
| 752 | elif inspect.isclass(object): |
| 753 | return module.__name__ == object.__module__ |
| 754 | elif inspect.getmodule(object) is not None: |
| 755 | return module is inspect.getmodule(object) |
| 756 | elif hasattr(object, '__module__'): |
| 757 | return module.__name__ == object.__module__ |
| 758 | elif isinstance(object, property): |
| 759 | return True # [XX] no way not be sure. |
| 760 | else: |
| 761 | raise ValueError("object must be a class or function") |
| 762 | |
| 763 | def _find(self, tests, obj, name, module, source_lines, |
| 764 | globs, ignore_imports, seen): |
| 765 | """ |
| 766 | Find tests for the given object and any contained objects, and |
| 767 | add them to `tests`. |
| 768 | """ |
| 769 | if self._verbose: |
| 770 | print 'Finding tests in %s' % name |
| 771 | |
| 772 | # If we've already processed this object, then ignore it. |
| 773 | if id(obj) in seen: |
| 774 | return |
| 775 | seen[id(obj)] = 1 |
| 776 | |
| 777 | # Find a test for this object, and add it to the list of tests. |
| 778 | test = self._get_test(obj, name, module, globs, source_lines) |
| 779 | if test is not None: |
| 780 | tests.append(test) |
| 781 | |
| 782 | # Look for tests in a module's contained objects. |
| 783 | if inspect.ismodule(obj) and self._recurse: |
| 784 | for valname, val in obj.__dict__.items(): |
| 785 | # Check if this contained object should be ignored. |
| 786 | if self._filter(val, name, valname): |
| 787 | continue |
| 788 | valname = '%s.%s' % (name, valname) |
| 789 | # Recurse to functions & classes. |
| 790 | if ((inspect.isfunction(val) or inspect.isclass(val)) and |
| 791 | (self._from_module(module, val) or not ignore_imports)): |
| 792 | self._find(tests, val, valname, module, source_lines, |
| 793 | globs, ignore_imports, seen) |
| 794 | |
| 795 | # Look for tests in a module's __test__ dictionary. |
| 796 | if inspect.ismodule(obj) and self._recurse: |
| 797 | for valname, val in getattr(obj, '__test__', {}).items(): |
| 798 | if not isinstance(valname, basestring): |
| 799 | raise ValueError("DocTestFinder.find: __test__ keys " |
| 800 | "must be strings: %r" % |
| 801 | (type(valname),)) |
| 802 | if not (inspect.isfunction(val) or inspect.isclass(val) or |
| 803 | inspect.ismethod(val) or inspect.ismodule(val) or |
| 804 | isinstance(val, basestring)): |
| 805 | raise ValueError("DocTestFinder.find: __test__ values " |
| 806 | "must be strings, functions, methods, " |
| 807 | "classes, or modules: %r" % |
| 808 | (type(val),)) |
| 809 | valname = '%s.%s' % (name, valname) |
| 810 | self._find(tests, val, valname, module, source_lines, |
| 811 | globs, ignore_imports, seen) |
| 812 | |
| 813 | # Look for tests in a class's contained objects. |
| 814 | if inspect.isclass(obj) and self._recurse: |
| 815 | for valname, val in obj.__dict__.items(): |
| 816 | # Check if this contained object should be ignored. |
| 817 | if self._filter(val, name, valname): |
| 818 | continue |
| 819 | # Special handling for staticmethod/classmethod. |
| 820 | if isinstance(val, staticmethod): |
| 821 | val = getattr(obj, valname) |
| 822 | if isinstance(val, classmethod): |
| 823 | val = getattr(obj, valname).im_func |
| 824 | |
| 825 | # Recurse to methods, properties, and nested classes. |
| 826 | if ((inspect.isfunction(val) or inspect.isclass(val) or |
| 827 | isinstance(val, property)) and |
| 828 | (self._from_module(module, val) or not ignore_imports)): |
| 829 | valname = '%s.%s' % (name, valname) |
| 830 | self._find(tests, val, valname, module, source_lines, |
| 831 | globs, ignore_imports, seen) |
| 832 | |
| 833 | def _get_test(self, obj, name, module, globs, source_lines): |
| 834 | """ |
| 835 | Return a DocTest for the given object, if it defines a docstring; |
| 836 | otherwise, return None. |
| 837 | """ |
| 838 | # Extract the object's docstring. If it doesn't have one, |
| 839 | # then return None (no test for this object). |
| 840 | if isinstance(obj, basestring): |
| 841 | docstring = obj |
| 842 | else: |
| 843 | try: |
| 844 | if obj.__doc__ is None: |
| 845 | return None |
| 846 | docstring = str(obj.__doc__) |
| 847 | except (TypeError, AttributeError): |
| 848 | return None |
| 849 | |
| 850 | # Don't bother if the docstring is empty. |
| 851 | if not docstring: |
| 852 | return None |
| 853 | |
| 854 | # Find the docstring's location in the file. |
| 855 | lineno = self._find_lineno(obj, source_lines) |
| 856 | |
| 857 | # Return a DocTest for this object. |
| 858 | if module is None: |
| 859 | filename = None |
| 860 | else: |
| 861 | filename = getattr(module, '__file__', module.__name__) |
| 862 | return DocTest(docstring, globs, name, filename, lineno) |
| 863 | |
| 864 | def _find_lineno(self, obj, source_lines): |
| 865 | """ |
| 866 | Return a line number of the given object's docstring. Note: |
| 867 | this method assumes that the object has a docstring. |
| 868 | """ |
| 869 | lineno = None |
| 870 | |
| 871 | # Find the line number for modules. |
| 872 | if inspect.ismodule(obj): |
| 873 | lineno = 0 |
| 874 | |
| 875 | # Find the line number for classes. |
| 876 | # Note: this could be fooled if a class is defined multiple |
| 877 | # times in a single file. |
| 878 | if inspect.isclass(obj): |
| 879 | if source_lines is None: |
| 880 | return None |
| 881 | pat = re.compile(r'^\s*class\s*%s\b' % |
| 882 | getattr(obj, '__name__', '-')) |
| 883 | for i, line in enumerate(source_lines): |
| 884 | if pat.match(line): |
| 885 | lineno = i |
| 886 | break |
| 887 | |
| 888 | # Find the line number for functions & methods. |
| 889 | if inspect.ismethod(obj): obj = obj.im_func |
| 890 | if inspect.isfunction(obj): obj = obj.func_code |
| 891 | if inspect.istraceback(obj): obj = obj.tb_frame |
| 892 | if inspect.isframe(obj): obj = obj.f_code |
| 893 | if inspect.iscode(obj): |
| 894 | lineno = getattr(obj, 'co_firstlineno', None)-1 |
| 895 | |
| 896 | # Find the line number where the docstring starts. Assume |
| 897 | # that it's the first line that begins with a quote mark. |
| 898 | # Note: this could be fooled by a multiline function |
| 899 | # signature, where a continuation line begins with a quote |
| 900 | # mark. |
| 901 | if lineno is not None: |
| 902 | if source_lines is None: |
| 903 | return lineno+1 |
| 904 | pat = re.compile('(^|.*:)\s*\w*("|\')') |
| 905 | for lineno in range(lineno, len(source_lines)): |
| 906 | if pat.match(source_lines[lineno]): |
| 907 | return lineno |
| 908 | |
| 909 | # We couldn't find the line number. |
| 910 | return None |
| 911 | |
| 912 | ###################################################################### |
| 913 | ## 4. DocTest Runner |
| 914 | ###################################################################### |
| 915 | |
| 916 | # [XX] Should overridable methods (eg DocTestRunner.check_output) be |
| 917 | # named with a leading underscore? |
| 918 | |
| 919 | class DocTestRunner: |
| 920 | """ |
| 921 | A class used to run DocTest test cases, and accumulate statistics. |
| 922 | The `run` method is used to process a single DocTest case. It |
| 923 | returns a tuple `(f, t)`, where `t` is the number of test cases |
| 924 | tried, and `f` is the number of test cases that failed. |
| 925 | |
| 926 | >>> tests = DocTestFinder().find(_TestClass) |
| 927 | >>> runner = DocTestRunner(verbose=False) |
| 928 | >>> for test in tests: |
| 929 | ... print runner.run(test) |
| 930 | (0, 2) |
| 931 | (0, 1) |
| 932 | (0, 2) |
| 933 | (0, 2) |
| 934 | |
| 935 | The `summarize` method prints a summary of all the test cases that |
| 936 | have been run by the runner, and returns an aggregated `(f, t)` |
| 937 | tuple: |
| 938 | |
| 939 | >>> runner.summarize(verbose=1) |
| 940 | 4 items passed all tests: |
| 941 | 2 tests in _TestClass |
| 942 | 2 tests in _TestClass.__init__ |
| 943 | 2 tests in _TestClass.get |
| 944 | 1 tests in _TestClass.square |
| 945 | 7 tests in 4 items. |
| 946 | 7 passed and 0 failed. |
| 947 | Test passed. |
| 948 | (0, 7) |
| 949 | |
| 950 | The aggregated number of tried examples and failed examples is |
| 951 | also available via the `tries` and `failures` attributes: |
| 952 | |
| 953 | >>> runner.tries |
| 954 | 7 |
| 955 | >>> runner.failures |
| 956 | 0 |
| 957 | |
| 958 | The comparison between expected outputs and actual outputs is done |
| 959 | by the `check_output` method. This comparison may be customized |
| 960 | with a number of option flags; see the documentation for `testmod` |
| 961 | for more information. If the option flags are insufficient, then |
| 962 | the comparison may also be customized by subclassing |
| 963 | DocTestRunner, and overriding the methods `check_output` and |
| 964 | `output_difference`. |
| 965 | |
| 966 | The test runner's display output can be controlled in two ways. |
| 967 | First, an output function (`out) can be passed to |
| 968 | `TestRunner.run`; this function will be called with strings that |
| 969 | should be displayed. It defaults to `sys.stdout.write`. If |
| 970 | capturing the output is not sufficient, then the display output |
| 971 | can be also customized by subclassing DocTestRunner, and |
| 972 | overriding the methods `report_start`, `report_success`, |
| 973 | `report_unexpected_exception`, and `report_failure`. |
| 974 | """ |
| 975 | # This divider string is used to separate failure messages, and to |
| 976 | # separate sections of the summary. |
| 977 | DIVIDER = "*" * 70 |
| 978 | |
| 979 | def __init__(self, verbose=None, optionflags=0): |
| 980 | """ |
| 981 | Create a new test runner. |
| 982 | |
| 983 | Optional keyword arg 'verbose' prints lots of stuff if true, |
| 984 | only failures if false; by default, it's true iff '-v' is in |
| 985 | sys.argv. |
| 986 | |
| 987 | Optional argument `optionflags` can be used to control how the |
| 988 | test runner compares expected output to actual output, and how |
| 989 | it displays failures. See the documentation for `testmod` for |
| 990 | more information. |
| 991 | """ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 992 | if verbose is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 993 | verbose = '-v' in sys.argv |
| 994 | self._verbose = verbose |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 995 | self.optionflags = optionflags |
| 996 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 997 | # Keep track of the examples we've run. |
| 998 | self.tries = 0 |
| 999 | self.failures = 0 |
| 1000 | self._name2ft = {} |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1001 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1002 | # Create a fake output target for capturing doctest output. |
| 1003 | self._fakeout = _SpoofOut() |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 1004 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1005 | #///////////////////////////////////////////////////////////////// |
| 1006 | # Output verification methods |
| 1007 | #///////////////////////////////////////////////////////////////// |
| 1008 | # These two methods should be updated together, since the |
| 1009 | # output_difference method needs to know what should be considered |
| 1010 | # to match by check_output. |
| 1011 | |
| 1012 | def check_output(self, want, got): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1013 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1014 | Return True iff the actual output (`got`) matches the expected |
| 1015 | output (`want`). These strings are always considered to match |
| 1016 | if they are identical; but depending on what option flags the |
| 1017 | test runner is using, several non-exact match types are also |
| 1018 | possible. See the documentation for `TestRunner` for more |
| 1019 | information about option flags. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1020 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1021 | # Handle the common case first, for efficiency: |
| 1022 | # if they're string-identical, always return true. |
| 1023 | if got == want: |
| 1024 | return True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1025 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1026 | # The values True and False replaced 1 and 0 as the return |
| 1027 | # value for boolean comparisons in Python 2.3. |
| 1028 | if not (self.optionflags & DONT_ACCEPT_TRUE_FOR_1): |
| 1029 | if (got,want) == ("True\n", "1\n"): |
| 1030 | return True |
| 1031 | if (got,want) == ("False\n", "0\n"): |
| 1032 | return True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1033 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1034 | # <BLANKLINE> can be used as a special sequence to signify a |
| 1035 | # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. |
| 1036 | if not (self.optionflags & DONT_ACCEPT_BLANKLINE): |
| 1037 | # Replace <BLANKLINE> in want with a blank line. |
| 1038 | want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER), |
| 1039 | '', want) |
| 1040 | # If a line in got contains only spaces, then remove the |
| 1041 | # spaces. |
| 1042 | got = re.sub('(?m)^\s*?$', '', got) |
| 1043 | if got == want: |
| 1044 | return True |
| 1045 | |
| 1046 | # This flag causes doctest to ignore any differences in the |
| 1047 | # contents of whitespace strings. Note that this can be used |
| 1048 | # in conjunction with the ELLISPIS flag. |
| 1049 | if (self.optionflags & NORMALIZE_WHITESPACE): |
| 1050 | got = ' '.join(got.split()) |
| 1051 | want = ' '.join(want.split()) |
| 1052 | if got == want: |
| 1053 | return True |
| 1054 | |
| 1055 | # The ELLIPSIS flag says to let the sequence "..." in `want` |
| 1056 | # match any substring in `got`. We implement this by |
| 1057 | # transforming `want` into a regular expression. |
| 1058 | if (self.optionflags & ELLIPSIS): |
| 1059 | # Escape any special regexp characters |
| 1060 | want_re = re.escape(want) |
| 1061 | # Replace ellipsis markers ('...') with .* |
| 1062 | want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*') |
| 1063 | # Require that it matches the entire string; and set the |
| 1064 | # re.DOTALL flag (with '(?s)'). |
| 1065 | want_re = '(?s)^%s$' % want_re |
| 1066 | # Check if the `want_re` regexp matches got. |
| 1067 | if re.match(want_re, got): |
| 1068 | return True |
| 1069 | |
| 1070 | # We didn't find any match; return false. |
| 1071 | return False |
| 1072 | |
| 1073 | def output_difference(self, want, got): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1074 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1075 | Return a string describing the differences between the |
| 1076 | expected output (`want`) and the actual output (`got`). |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1077 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1078 | # If <BLANKLINE>s are being used, then replace <BLANKLINE> |
| 1079 | # with blank lines in the expected output string. |
| 1080 | if not (self.optionflags & DONT_ACCEPT_BLANKLINE): |
| 1081 | want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1082 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1083 | # Check if we should use diff. Don't use diff if the actual |
| 1084 | # or expected outputs are too short, or if the expected output |
| 1085 | # contains an ellipsis marker. |
| 1086 | if ((self.optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and |
| 1087 | want.count('\n') > 2 and got.count('\n') > 2 and |
| 1088 | not (self.optionflags & ELLIPSIS and '...' in want)): |
| 1089 | # Split want & got into lines. |
| 1090 | want_lines = [l+'\n' for l in want.split('\n')] |
| 1091 | got_lines = [l+'\n' for l in got.split('\n')] |
| 1092 | # Use difflib to find their differences. |
| 1093 | if self.optionflags & UNIFIED_DIFF: |
| 1094 | diff = difflib.unified_diff(want_lines, got_lines, n=2, |
| 1095 | fromfile='Expected', tofile='Got') |
| 1096 | kind = 'unified' |
| 1097 | elif self.optionflags & CONTEXT_DIFF: |
| 1098 | diff = difflib.context_diff(want_lines, got_lines, n=2, |
| 1099 | fromfile='Expected', tofile='Got') |
| 1100 | kind = 'context' |
| 1101 | else: |
| 1102 | assert 0, 'Bad diff option' |
| 1103 | # Remove trailing whitespace on diff output. |
| 1104 | diff = [line.rstrip() + '\n' for line in diff] |
| 1105 | return _tag_msg("Differences (" + kind + " diff)", |
| 1106 | ''.join(diff)) |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 1107 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1108 | # If we're not using diff, then simply list the expected |
| 1109 | # output followed by the actual output. |
| 1110 | return (_tag_msg("Expected", want or "Nothing") + |
| 1111 | _tag_msg("Got", got)) |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 1112 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1113 | #///////////////////////////////////////////////////////////////// |
| 1114 | # Reporting methods |
| 1115 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 1116 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1117 | def report_start(self, out, test, example): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1118 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1119 | Report that the test runner is about to process the given |
| 1120 | example. (Only displays a message if verbose=True) |
| 1121 | """ |
| 1122 | if self._verbose: |
| 1123 | out(_tag_msg("Trying", example.source) + |
| 1124 | _tag_msg("Expecting", example.want or "nothing")) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1125 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1126 | def report_success(self, out, test, example, got): |
| 1127 | """ |
| 1128 | Report that the given example ran successfully. (Only |
| 1129 | displays a message if verbose=True) |
| 1130 | """ |
| 1131 | if self._verbose: |
| 1132 | out("ok\n") |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1133 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1134 | def report_failure(self, out, test, example, got): |
| 1135 | """ |
| 1136 | Report that the given example failed. |
| 1137 | """ |
| 1138 | # Print an error message. |
| 1139 | out(self.__failure_header(test, example) + |
| 1140 | self.output_difference(example.want, got)) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1141 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1142 | def report_unexpected_exception(self, out, test, example, exc_info): |
| 1143 | """ |
| 1144 | Report that the given example raised an unexpected exception. |
| 1145 | """ |
| 1146 | # Get a traceback message. |
| 1147 | excout = StringIO() |
| 1148 | exc_type, exc_val, exc_tb = exc_info |
| 1149 | traceback.print_exception(exc_type, exc_val, exc_tb, file=excout) |
| 1150 | exception_tb = excout.getvalue() |
| 1151 | # Print an error message. |
| 1152 | out(self.__failure_header(test, example) + |
| 1153 | _tag_msg("Exception raised", exception_tb)) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1154 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1155 | def __failure_header(self, test, example): |
| 1156 | s = (self.DIVIDER + "\n" + |
| 1157 | _tag_msg("Failure in example", example.source)) |
| 1158 | if test.filename is None: |
| 1159 | # [XX] I'm not putting +1 here, to give the same output |
| 1160 | # as the old version. But I think it *should* go here. |
| 1161 | return s + ("from line #%s of %s\n" % |
| 1162 | (example.lineno, test.name)) |
| 1163 | elif test.lineno is None: |
| 1164 | return s + ("from line #%s of %s in %s\n" % |
| 1165 | (example.lineno+1, test.name, test.filename)) |
| 1166 | else: |
| 1167 | lineno = test.lineno+example.lineno+1 |
| 1168 | return s + ("from line #%s of %s (%s)\n" % |
| 1169 | (lineno, test.filename, test.name)) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1170 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1171 | #///////////////////////////////////////////////////////////////// |
| 1172 | # DocTest Running |
| 1173 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1174 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1175 | # A regular expression for handling `want` strings that contain |
| 1176 | # expected exceptions. It divides `want` into two pieces: the |
| 1177 | # pre-exception output (`out`) and the exception message (`exc`), |
| 1178 | # as generated by traceback.format_exception_only(). (I assume |
| 1179 | # that the exception_only message is the first non-indented line |
| 1180 | # starting with word characters after the "Traceback ...".) |
| 1181 | _EXCEPTION_RE = re.compile(('^(?P<out>.*)' |
| 1182 | '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?' |
| 1183 | '^(?P<exc>\w+.*)') % |
| 1184 | ('most recent call last', 'innermost last'), |
| 1185 | re.MULTILINE | re.DOTALL) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1186 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1187 | _OPTION_DIRECTIVE_RE = re.compile('\s*doctest:\s*(?P<flags>[^#\n]*)') |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1188 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1189 | def __handle_directive(self, example): |
| 1190 | """ |
| 1191 | Check if the given example is actually a directive to doctest |
| 1192 | (to turn an optionflag on or off); and if it is, then handle |
| 1193 | the directive. |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1194 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1195 | Return true iff the example is actually a directive (and so |
| 1196 | should not be executed). |
Tim Peters | 4a9ac4a | 2001-10-02 22:47:08 +0000 | [diff] [blame] | 1197 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1198 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1199 | m = self._OPTION_DIRECTIVE_RE.match(example.source) |
| 1200 | if m is None: |
| 1201 | return False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1202 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1203 | for flag in m.group('flags').upper().split(): |
| 1204 | if (flag[:1] not in '+-' or |
| 1205 | flag[1:] not in OPTIONFLAGS_BY_NAME): |
| 1206 | raise ValueError('Bad doctest option directive: '+flag) |
| 1207 | if flag[0] == '+': |
| 1208 | self.optionflags |= OPTIONFLAGS_BY_NAME[flag[1:]] |
| 1209 | else: |
| 1210 | self.optionflags &= ~OPTIONFLAGS_BY_NAME[flag[1:]] |
| 1211 | return True |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1212 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1213 | def __run(self, test, compileflags, out): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1214 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1215 | Run the examples in `test`. Write the outcome of each example |
| 1216 | with one of the `DocTestRunner.report_*` methods, using the |
| 1217 | writer function `out`. `compileflags` is the set of compiler |
| 1218 | flags that should be used to execute examples. Return a tuple |
| 1219 | `(f, t)`, where `t` is the number of examples tried, and `f` |
| 1220 | is the number of examples that failed. The examples are run |
| 1221 | in the namespace `test.globs`. |
| 1222 | """ |
| 1223 | # Keep track of the number of failures and tries. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1224 | failures = tries = 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1225 | |
| 1226 | # Save the option flags (since option directives can be used |
| 1227 | # to modify them). |
| 1228 | original_optionflags = self.optionflags |
| 1229 | |
| 1230 | # Process each example. |
| 1231 | for example in test.examples: |
| 1232 | # Check if it's an option directive. If it is, then handle |
| 1233 | # it, and go on to the next example. |
| 1234 | if self.__handle_directive(example): |
| 1235 | continue |
| 1236 | |
| 1237 | # Record that we started this example. |
| 1238 | tries += 1 |
| 1239 | self.report_start(out, test, example) |
| 1240 | |
| 1241 | # Run the example in the given context (globs), and record |
| 1242 | # any exception that gets raised. (But don't intercept |
| 1243 | # keyboard interrupts.) |
| 1244 | try: |
| 1245 | # If the example is a compound statement on one line, |
| 1246 | # like "if 1: print 2", then compile() requires a |
| 1247 | # trailing newline. Rather than analyze that, always |
| 1248 | # append one (it never hurts). |
| 1249 | exec compile(example.source + '\n', "<string>", "single", |
| 1250 | compileflags, 1) in test.globs |
| 1251 | exception = None |
| 1252 | except KeyboardInterrupt: |
| 1253 | raise |
| 1254 | except: |
| 1255 | exception = sys.exc_info() |
| 1256 | |
| 1257 | # Extract the example's actual output from fakeout, and |
| 1258 | # write it to `got`. Add a terminating newline if it |
| 1259 | # doesn't have already one. |
| 1260 | got = self._fakeout.getvalue() |
| 1261 | self._fakeout.truncate(0) |
| 1262 | |
| 1263 | # If the example executed without raising any exceptions, |
| 1264 | # then verify its output and report its outcome. |
| 1265 | if exception is None: |
| 1266 | if self.check_output(example.want, got): |
| 1267 | self.report_success(out, test, example, got) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1268 | else: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1269 | self.report_failure(out, test, example, got) |
| 1270 | failures += 1 |
| 1271 | |
| 1272 | # If the example raised an exception, then check if it was |
| 1273 | # expected. |
| 1274 | else: |
| 1275 | exc_info = sys.exc_info() |
| 1276 | exc_msg = traceback.format_exception_only(*exc_info[:2])[-1] |
| 1277 | |
| 1278 | # Search the `want` string for an exception. If we don't |
| 1279 | # find one, then report an unexpected exception. |
| 1280 | m = self._EXCEPTION_RE.match(example.want) |
| 1281 | if m is None: |
| 1282 | self.report_unexpected_exception(out, test, example, |
| 1283 | exc_info) |
| 1284 | failures += 1 |
| 1285 | else: |
| 1286 | exc_hdr = m.group('hdr')+'\n' # Exception header |
| 1287 | # The test passes iff the pre-exception output and |
| 1288 | # the exception description match the values given |
| 1289 | # in `want`. |
| 1290 | if (self.check_output(m.group('out'), got) and |
| 1291 | self.check_output(m.group('exc'), exc_msg)): |
| 1292 | # Is +exc_msg the right thing here?? |
| 1293 | self.report_success(out, test, example, |
| 1294 | got+exc_hdr+exc_msg) |
| 1295 | else: |
| 1296 | self.report_failure(out, test, example, |
| 1297 | got+exc_hdr+exc_msg) |
| 1298 | failures += 1 |
| 1299 | |
| 1300 | # Restore the option flags (in case they were modified) |
| 1301 | self.optionflags = original_optionflags |
| 1302 | |
| 1303 | # Record and return the number of failures and tries. |
| 1304 | self.__record_outcome(test, failures, tries) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1305 | return failures, tries |
| 1306 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1307 | def __record_outcome(self, test, f, t): |
| 1308 | """ |
| 1309 | Record the fact that the given DocTest (`test`) generated `f` |
| 1310 | failures out of `t` tried examples. |
| 1311 | """ |
| 1312 | f2, t2 = self._name2ft.get(test.name, (0,0)) |
| 1313 | self._name2ft[test.name] = (f+f2, t+t2) |
| 1314 | self.failures += f |
| 1315 | self.tries += t |
| 1316 | |
| 1317 | def run(self, test, compileflags=None, out=None, clear_globs=True): |
| 1318 | """ |
| 1319 | Run the examples in `test`, and display the results using the |
| 1320 | writer function `out`. |
| 1321 | |
| 1322 | The examples are run in the namespace `test.globs`. If |
| 1323 | `clear_globs` is true (the default), then this namespace will |
| 1324 | be cleared after the test runs, to help with garbage |
| 1325 | collection. If you would like to examine the namespace after |
| 1326 | the test completes, then use `clear_globs=False`. |
| 1327 | |
| 1328 | `compileflags` gives the set of flags that should be used by |
| 1329 | the Python compiler when running the examples. If not |
| 1330 | specified, then it will default to the set of future-import |
| 1331 | flags that apply to `globs`. |
| 1332 | |
| 1333 | The output of each example is checked using |
| 1334 | `DocTestRunner.check_output`, and the results are formatted by |
| 1335 | the `DocTestRunner.report_*` methods. |
| 1336 | """ |
| 1337 | if compileflags is None: |
| 1338 | compileflags = _extract_future_flags(test.globs) |
| 1339 | if out is None: |
| 1340 | out = sys.stdout.write |
| 1341 | saveout = sys.stdout |
| 1342 | |
| 1343 | try: |
| 1344 | sys.stdout = self._fakeout |
| 1345 | return self.__run(test, compileflags, out) |
| 1346 | finally: |
| 1347 | sys.stdout = saveout |
| 1348 | # While Python gc can clean up most cycles on its own, it doesn't |
| 1349 | # chase frame objects. This is especially irksome when running |
| 1350 | # generator tests that raise exceptions, because a named generator- |
| 1351 | # iterator gets an entry in globs, and the generator-iterator |
| 1352 | # object's frame's traceback info points back to globs. This is |
| 1353 | # easy to break just by clearing the namespace. This can also |
| 1354 | # help to break other kinds of cycles, and even for cycles that |
| 1355 | # gc can break itself it's better to break them ASAP. |
| 1356 | if clear_globs: |
| 1357 | test.globs.clear() |
| 1358 | |
| 1359 | #///////////////////////////////////////////////////////////////// |
| 1360 | # Summarization |
| 1361 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1362 | def summarize(self, verbose=None): |
| 1363 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1364 | Print a summary of all the test cases that have been run by |
| 1365 | this DocTestRunner, and return a tuple `(f, t)`, where `f` is |
| 1366 | the total number of failed examples, and `t` is the total |
| 1367 | number of tried examples. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1368 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1369 | The optional `verbose` argument controls how detailed the |
| 1370 | summary is. If the verbosity is not specified, then the |
| 1371 | DocTestRunner's verbosity is used. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1372 | """ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1373 | if verbose is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1374 | verbose = self._verbose |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1375 | notests = [] |
| 1376 | passed = [] |
| 1377 | failed = [] |
| 1378 | totalt = totalf = 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1379 | for x in self._name2ft.items(): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1380 | name, (f, t) = x |
| 1381 | assert f <= t |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1382 | totalt += t |
| 1383 | totalf += f |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1384 | if t == 0: |
| 1385 | notests.append(name) |
| 1386 | elif f == 0: |
| 1387 | passed.append( (name, t) ) |
| 1388 | else: |
| 1389 | failed.append(x) |
| 1390 | if verbose: |
| 1391 | if notests: |
| 1392 | print len(notests), "items had no tests:" |
| 1393 | notests.sort() |
| 1394 | for thing in notests: |
| 1395 | print " ", thing |
| 1396 | if passed: |
| 1397 | print len(passed), "items passed all tests:" |
| 1398 | passed.sort() |
| 1399 | for thing, count in passed: |
| 1400 | print " %3d tests in %s" % (count, thing) |
| 1401 | if failed: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1402 | print self.DIVIDER |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1403 | print len(failed), "items had failures:" |
| 1404 | failed.sort() |
| 1405 | for thing, (f, t) in failed: |
| 1406 | print " %3d of %3d in %s" % (f, t, thing) |
| 1407 | if verbose: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1408 | print totalt, "tests in", len(self._name2ft), "items." |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1409 | print totalt - totalf, "passed and", totalf, "failed." |
| 1410 | if totalf: |
| 1411 | print "***Test Failed***", totalf, "failures." |
| 1412 | elif verbose: |
| 1413 | print "Test passed." |
| 1414 | return totalf, totalt |
| 1415 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1416 | ###################################################################### |
| 1417 | ## 5. Test Functions |
| 1418 | ###################################################################### |
| 1419 | # These should be backwards compatible. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1420 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1421 | def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1422 | report=True, optionflags=0, extraglobs=None): |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1423 | """m=None, name=None, globs=None, verbose=None, isprivate=None, |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1424 | report=True, optionflags=0, extraglobs=None |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1425 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1426 | Test examples in docstrings in functions and classes reachable |
| 1427 | 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] | 1428 | with m.__doc__. Unless isprivate is specified, private names |
| 1429 | are not skipped. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1430 | |
| 1431 | Also test examples reachable from dict m.__test__ if it exists and is |
| 1432 | not None. m.__dict__ maps names to functions, classes and strings; |
| 1433 | function and class docstrings are tested even if the name is private; |
| 1434 | strings are tested directly, as if they were docstrings. |
| 1435 | |
| 1436 | Return (#failures, #tests). |
| 1437 | |
| 1438 | See doctest.__doc__ for an overview. |
| 1439 | |
| 1440 | Optional keyword arg "name" gives the name of the module; by default |
| 1441 | use m.__name__. |
| 1442 | |
| 1443 | Optional keyword arg "globs" gives a dict to be used as the globals |
| 1444 | when executing examples; by default, use m.__dict__. A copy of this |
| 1445 | dict is actually used for each docstring, so that each docstring's |
| 1446 | examples start with a clean slate. |
| 1447 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1448 | Optional keyword arg "extraglobs" gives a dictionary that should be |
| 1449 | merged into the globals that are used to execute examples. By |
| 1450 | default, no extra globals are used. This is new in 2.4. |
| 1451 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1452 | Optional keyword arg "verbose" prints lots of stuff if true, prints |
| 1453 | only failures if false; by default, it's true iff "-v" is in sys.argv. |
| 1454 | |
| 1455 | Optional keyword arg "isprivate" specifies a function used to |
| 1456 | determine whether a name is private. The default function is |
Raymond Hettinger | 71adf7e | 2003-07-16 19:25:22 +0000 | [diff] [blame] | 1457 | treat all functions as public. Optionally, "isprivate" can be |
| 1458 | set to doctest.is_private to skip over functions marked as private |
| 1459 | using the underscore naming convention; see its docs for details. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1460 | |
| 1461 | Optional keyword arg "report" prints a summary at the end when true, |
| 1462 | else prints nothing at the end. In verbose mode, the summary is |
| 1463 | detailed, else very brief (in fact, empty if all tests passed). |
| 1464 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1465 | Optional keyword arg "optionflags" or's together module constants, |
| 1466 | and defaults to 0. This is new in 2.3. Possible values: |
| 1467 | |
| 1468 | DONT_ACCEPT_TRUE_FOR_1 |
| 1469 | By default, if an expected output block contains just "1", |
| 1470 | an actual output block containing just "True" is considered |
| 1471 | to be a match, and similarly for "0" versus "False". When |
| 1472 | DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution |
| 1473 | is allowed. |
| 1474 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1475 | DONT_ACCEPT_BLANKLINE |
| 1476 | By default, if an expected output block contains a line |
| 1477 | containing only the string "<BLANKLINE>", then that line |
| 1478 | will match a blank line in the actual output. When |
| 1479 | DONT_ACCEPT_BLANKLINE is specified, this substitution is |
| 1480 | not allowed. |
| 1481 | |
| 1482 | NORMALIZE_WHITESPACE |
| 1483 | When NORMALIZE_WHITESPACE is specified, all sequences of |
| 1484 | whitespace are treated as equal. I.e., any sequence of |
| 1485 | whitespace within the expected output will match any |
| 1486 | sequence of whitespace within the actual output. |
| 1487 | |
| 1488 | ELLIPSIS |
| 1489 | When ELLIPSIS is specified, then an ellipsis marker |
| 1490 | ("...") in the expected output can match any substring in |
| 1491 | the actual output. |
| 1492 | |
| 1493 | UNIFIED_DIFF |
| 1494 | When UNIFIED_DIFF is specified, failures that involve |
| 1495 | multi-line expected and actual outputs will be displayed |
| 1496 | using a unified diff. |
| 1497 | |
| 1498 | CONTEXT_DIFF |
| 1499 | When CONTEXT_DIFF is specified, failures that involve |
| 1500 | multi-line expected and actual outputs will be displayed |
| 1501 | using a context diff. |
| 1502 | """ |
| 1503 | |
| 1504 | """ [XX] This is no longer true: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1505 | Advanced tomfoolery: testmod runs methods of a local instance of |
| 1506 | class doctest.Tester, then merges the results into (or creates) |
| 1507 | global Tester instance doctest.master. Methods of doctest.master |
| 1508 | can be called directly too, if you want to do something unusual. |
| 1509 | Passing report=0 to testmod is especially useful then, to delay |
| 1510 | displaying a summary. Invoke doctest.master.summarize(verbose) |
| 1511 | when you're done fiddling. |
| 1512 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1513 | # If no module was given, then use __main__. |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1514 | if m is None: |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1515 | # DWA - m will still be None if this wasn't invoked from the command |
| 1516 | # line, in which case the following TypeError is about as good an error |
| 1517 | # as we should expect |
| 1518 | m = sys.modules.get('__main__') |
| 1519 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1520 | # Check that we were actually given a module. |
| 1521 | if not inspect.ismodule(m): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 1522 | raise TypeError("testmod: module required; %r" % (m,)) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1523 | |
| 1524 | # If no name was given, then use the module's name. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1525 | if name is None: |
| 1526 | name = m.__name__ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1527 | |
| 1528 | # Find, parse, and run all tests in the given module. |
| 1529 | finder = DocTestFinder(namefilter=isprivate) |
| 1530 | runner = DocTestRunner(verbose=verbose, optionflags=optionflags) |
| 1531 | for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): |
| 1532 | runner.run(test) |
| 1533 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1534 | if report: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1535 | runner.summarize() |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1536 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1537 | return runner.failures, runner.tries |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1538 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1539 | def run_docstring_examples(f, globs, verbose=False, name="NoName", |
| 1540 | compileflags=None, optionflags=0): |
| 1541 | """ |
| 1542 | Test examples in the given object's docstring (`f`), using `globs` |
| 1543 | as globals. Optional argument `name` is used in failure messages. |
| 1544 | If the optional argument `verbose` is true, then generate output |
| 1545 | even if there are no failures. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1546 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1547 | `compileflags` gives the set of flags that should be used by the |
| 1548 | Python compiler when running the examples. If not specified, then |
| 1549 | it will default to the set of future-import flags that apply to |
| 1550 | `globs`. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1551 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1552 | Optional keyword arg `optionflags` specifies options for the |
| 1553 | testing and output. See the documentation for `testmod` for more |
| 1554 | information. |
| 1555 | """ |
| 1556 | # Find, parse, and run all tests in the given module. |
| 1557 | finder = DocTestFinder(verbose=verbose, recurse=False) |
| 1558 | runner = DocTestRunner(verbose=verbose, optionflags=optionflags) |
| 1559 | for test in finder.find(f, name, globs=globs): |
| 1560 | runner.run(test, compileflags=compileflags) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1561 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1562 | ###################################################################### |
| 1563 | ## 6. Tester |
| 1564 | ###################################################################### |
| 1565 | # This is provided only for backwards compatibility. It's not |
| 1566 | # actually used in any way. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1567 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1568 | class Tester: |
| 1569 | def __init__(self, mod=None, globs=None, verbose=None, |
| 1570 | isprivate=None, optionflags=0): |
| 1571 | if mod is None and globs is None: |
| 1572 | raise TypeError("Tester.__init__: must specify mod or globs") |
| 1573 | if mod is not None and not _ismodule(mod): |
| 1574 | raise TypeError("Tester.__init__: mod must be a module; %r" % |
| 1575 | (mod,)) |
| 1576 | if globs is None: |
| 1577 | globs = mod.__dict__ |
| 1578 | self.globs = globs |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1579 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1580 | self.verbose = verbose |
| 1581 | self.isprivate = isprivate |
| 1582 | self.optionflags = optionflags |
| 1583 | self.testfinder = DocTestFinder(namefilter=isprivate) |
| 1584 | self.testrunner = DocTestRunner(verbose=verbose, |
| 1585 | optionflags=optionflags) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1586 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1587 | def runstring(self, s, name): |
| 1588 | test = DocTest(s, self.globs, name, None, None) |
| 1589 | if self.verbose: |
| 1590 | print "Running string", name |
| 1591 | (f,t) = self.testrunner.run(test) |
| 1592 | if self.verbose: |
| 1593 | print f, "of", t, "examples failed in string", name |
| 1594 | return (f,t) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1595 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1596 | def rundoc(self, object, name=None, module=None, ignore_imports=True): |
| 1597 | f = t = 0 |
| 1598 | tests = self.testfinder.find(object, name, module=module, |
| 1599 | globs=self.globs, |
| 1600 | ignore_imports=ignore_imports) |
| 1601 | for test in tests: |
| 1602 | (f2, t2) = self.testrunner.run(test) |
| 1603 | (f,t) = (f+f2, t+t2) |
| 1604 | return (f,t) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1605 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1606 | def rundict(self, d, name, module=None): |
| 1607 | import new |
| 1608 | m = new.module(name) |
| 1609 | m.__dict__.update(d) |
| 1610 | ignore_imports = (module is not None) |
| 1611 | return self.rundoc(m, name, module, ignore_imports) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1612 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1613 | def run__test__(self, d, name): |
| 1614 | import new |
| 1615 | m = new.module(name) |
| 1616 | m.__test__ = d |
| 1617 | return self.rundoc(m, name, module) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1618 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1619 | def summarize(self, verbose=None): |
| 1620 | return self.testrunner.summarize(verbose) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1621 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1622 | def merge(self, other): |
| 1623 | d = self.testrunner._name2ft |
| 1624 | for name, (f, t) in other.testrunner._name2ft.items(): |
| 1625 | if name in d: |
| 1626 | print "*** Tester.merge: '" + name + "' in both" \ |
| 1627 | " testers; summing outcomes." |
| 1628 | f2, t2 = d[name] |
| 1629 | f = f + f2 |
| 1630 | t = t + t2 |
| 1631 | d[name] = f, t |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1632 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1633 | ###################################################################### |
| 1634 | ## 7. Unittest Support |
| 1635 | ###################################################################### |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1636 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1637 | class DocTestTestCase(unittest.TestCase): |
| 1638 | """A test case that wraps a test function. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1639 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1640 | This is useful for slipping pre-existing test functions into the |
| 1641 | PyUnit framework. Optionally, set-up and tidy-up functions can be |
| 1642 | supplied. As with TestCase, the tidy-up ('tearDown') function will |
| 1643 | always be called if the set-up ('setUp') function ran successfully. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1644 | """ |
| 1645 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1646 | def __init__(self, test_runner, test, |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1647 | setUp=None, tearDown=None): |
| 1648 | unittest.TestCase.__init__(self) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1649 | self.__test_runner = test_runner |
| 1650 | self.__test = test |
| 1651 | self.__setUp = setUp |
| 1652 | self.__tearDown = tearDown |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1653 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1654 | def setUp(self): |
| 1655 | if self.__setUp is not None: |
| 1656 | self.__setUp() |
| 1657 | |
| 1658 | def tearDown(self): |
| 1659 | if self.__tearDown is not None: |
| 1660 | self.__tearDown() |
| 1661 | |
| 1662 | def runTest(self): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1663 | test = self.__test |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1664 | old = sys.stdout |
| 1665 | new = StringIO() |
| 1666 | try: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1667 | self.__test_runner.DIVIDER = "-"*70 |
| 1668 | failures, tries = self.__test_runner.run(test, out=new.write) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1669 | finally: |
| 1670 | sys.stdout = old |
| 1671 | |
| 1672 | if failures: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1673 | lname = '.'.join(test.name.split('.')[-1:]) |
| 1674 | if test.lineno is None: |
| 1675 | lineno = 'unknown line number' |
| 1676 | else: |
| 1677 | lineno = 'line %s' % test.lineno |
| 1678 | err = new.getvalue() |
| 1679 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1680 | raise self.failureException( |
| 1681 | 'Failed doctest test for %s\n' |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1682 | ' File "%s", %s, in %s\n\n%s' |
| 1683 | % (test.name, test.filename, lineno, lname, err)) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1684 | |
| 1685 | def id(self): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1686 | return self.__test.name |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1687 | |
| 1688 | def __repr__(self): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1689 | name = self.__test.name.split('.') |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1690 | return "%s (%s)" % (name[-1], '.'.join(name[:-1])) |
| 1691 | |
| 1692 | __str__ = __repr__ |
| 1693 | |
| 1694 | def shortDescription(self): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1695 | return "Doctest: " + self.__test.name |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1696 | |
| 1697 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1698 | def DocTestSuite(module=None, filename=None, globs=None, extraglobs=None, |
| 1699 | optionflags=0, |
| 1700 | test_finder=None, test_runner=None, |
| 1701 | setUp=lambda: None, tearDown=lambda: None): |
| 1702 | """ |
| 1703 | Convert doctest tests for a mudule to a unittest test suite |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1704 | |
| 1705 | This tests convers each documentation string in a module that |
| 1706 | contains doctest tests to a unittest test case. If any of the |
| 1707 | tests in a doc string fail, then the test case fails. An error is |
| 1708 | raised showing the name of the file containing the test and a |
| 1709 | (sometimes approximate) line number. |
| 1710 | |
| 1711 | A module argument provides the module to be tested. The argument |
| 1712 | can be either a module or a module name. |
| 1713 | |
| 1714 | If no argument is given, the calling module is used. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1715 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1716 | if module is not None and filename is not None: |
| 1717 | raise ValueError('Specify module or filename, not both.') |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1718 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1719 | if test_finder is None: |
| 1720 | test_finder = DocTestFinder() |
| 1721 | if test_runner is None: |
| 1722 | test_runner = DocTestRunner(optionflags=optionflags) |
| 1723 | |
| 1724 | if filename is not None: |
| 1725 | name = os.path.basename(filename) |
| 1726 | test = Test(open(filename).read(),name,filename,0) |
| 1727 | if globs is None: |
| 1728 | globs = {} |
| 1729 | else: |
| 1730 | module = _normalize_module(module) |
| 1731 | tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) |
| 1732 | if globs is None: |
| 1733 | globs = module.__dict__ |
| 1734 | if not tests: # [XX] why do we want to do this? |
| 1735 | raise ValueError(module, "has no tests") |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1736 | |
| 1737 | tests.sort() |
| 1738 | suite = unittest.TestSuite() |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1739 | for test in tests: |
| 1740 | if len(test.examples) == 0: continue |
| 1741 | if not test.filename: |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1742 | filename = module.__file__ |
| 1743 | if filename.endswith(".pyc"): |
| 1744 | filename = filename[:-1] |
| 1745 | elif filename.endswith(".pyo"): |
| 1746 | filename = filename[:-1] |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1747 | test.filename = filename |
| 1748 | suite.addTest(DocTestTestCase(test_runner, test, |
| 1749 | setUp, tearDown)) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1750 | |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1751 | return suite |
| 1752 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1753 | ###################################################################### |
| 1754 | ## 8. Debugging Support |
| 1755 | ###################################################################### |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1756 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1757 | def _want_comment(example): |
| 1758 | """ |
| 1759 | Return a comment containing the expected output for the given |
| 1760 | example. |
| 1761 | """ |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1762 | # Return the expected output, if any |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1763 | want = example.want |
| 1764 | if want: |
| 1765 | if want[-1] == '\n': want = want[:-1] |
| 1766 | want = "\n# ".join(want.split("\n")) |
| 1767 | want = "\n# Expected:\n# %s" % want |
| 1768 | return want |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1769 | |
| 1770 | def testsource(module, name): |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1771 | """Extract the test sources from a doctest test docstring as a script |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1772 | |
| 1773 | Provide the module (or dotted name of the module) containing the |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1774 | test to be debugged and the name (within the module) of the object |
| 1775 | with the doc string with tests to be debugged. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1776 | |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1777 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1778 | module = _normalize_module(module) |
| 1779 | tests = DocTestFinder().find(module) |
| 1780 | test = [t for t in tests if t.name == name] |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1781 | if not test: |
| 1782 | raise ValueError(name, "not found in tests") |
| 1783 | test = test[0] |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1784 | testsrc = '\n'.join([ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1785 | "%s%s" % (example.source, _want_comment(example)) |
| 1786 | for example in test.examples |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1787 | ]) |
| 1788 | return testsrc |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1789 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1790 | def debug_src(src, pm=False, globs=None): |
| 1791 | """Debug a single doctest test doc string |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1792 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1793 | The string is provided directly |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1794 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1795 | test = DocTest(src, globs or {}, 'debug', None, None) |
| 1796 | |
| 1797 | testsrc = '\n'.join([ |
| 1798 | "%s%s" % (example.source, _want_comment(example)) |
| 1799 | for example in test.examples |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1800 | ]) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1801 | debug_script(testsrc, pm, globs) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1802 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1803 | def debug_script(src, pm=False, globs=None): |
| 1804 | "Debug a test script" |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1805 | import pdb |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1806 | |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1807 | srcfilename = tempfile.mktemp("doctestdebug.py") |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1808 | f = open(srcfilename, 'w') |
| 1809 | f.write(src) |
| 1810 | f.close() |
| 1811 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1812 | if globs: |
| 1813 | globs = globs.copy() |
| 1814 | else: |
| 1815 | globs = {} |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1816 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1817 | if pm: |
| 1818 | try: |
| 1819 | execfile(srcfilename, globs, globs) |
| 1820 | except: |
| 1821 | print sys.exc_info()[1] |
| 1822 | pdb.post_mortem(sys.exc_info()[2]) |
| 1823 | else: |
| 1824 | # Note that %r is vital here. '%s' instead can, e.g., cause |
| 1825 | # backslashes to get treated as metacharacters on Windows. |
| 1826 | pdb.run("execfile(%r)" % srcfilename, globs, globs) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1827 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1828 | def debug(module, name, pm=False): |
| 1829 | """Debug a single doctest test doc string |
| 1830 | |
| 1831 | Provide the module (or dotted name of the module) containing the |
| 1832 | test to be debugged and the name (within the module) of the object |
| 1833 | with the doc string with tests to be debugged. |
| 1834 | |
| 1835 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1836 | module = _normalize_module(module) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 1837 | testsrc = testsource(module, name) |
| 1838 | debug_script(testsrc, pm, module.__dict__) |
| 1839 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1840 | ###################################################################### |
| 1841 | ## 9. Example Usage |
| 1842 | ###################################################################### |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1843 | class _TestClass: |
| 1844 | """ |
| 1845 | A pointless class, for sanity-checking of docstring testing. |
| 1846 | |
| 1847 | Methods: |
| 1848 | square() |
| 1849 | get() |
| 1850 | |
| 1851 | >>> _TestClass(13).get() + _TestClass(-12).get() |
| 1852 | 1 |
| 1853 | >>> hex(_TestClass(13).square().get()) |
| 1854 | '0xa9' |
| 1855 | """ |
| 1856 | |
| 1857 | def __init__(self, val): |
| 1858 | """val -> _TestClass object with associated value val. |
| 1859 | |
| 1860 | >>> t = _TestClass(123) |
| 1861 | >>> print t.get() |
| 1862 | 123 |
| 1863 | """ |
| 1864 | |
| 1865 | self.val = val |
| 1866 | |
| 1867 | def square(self): |
| 1868 | """square() -> square TestClass's associated value |
| 1869 | |
| 1870 | >>> _TestClass(13).square().get() |
| 1871 | 169 |
| 1872 | """ |
| 1873 | |
| 1874 | self.val = self.val ** 2 |
| 1875 | return self |
| 1876 | |
| 1877 | def get(self): |
| 1878 | """get() -> return TestClass's associated value. |
| 1879 | |
| 1880 | >>> x = _TestClass(-42) |
| 1881 | >>> print x.get() |
| 1882 | -42 |
| 1883 | """ |
| 1884 | |
| 1885 | return self.val |
| 1886 | |
| 1887 | __test__ = {"_TestClass": _TestClass, |
| 1888 | "string": r""" |
| 1889 | Example of a string object, searched as-is. |
| 1890 | >>> x = 1; y = 2 |
| 1891 | >>> x + y, x * y |
| 1892 | (3, 2) |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1893 | """, |
| 1894 | "bool-int equivalence": r""" |
| 1895 | In 2.2, boolean expressions displayed |
| 1896 | 0 or 1. By default, we still accept |
| 1897 | them. This can be disabled by passing |
| 1898 | DONT_ACCEPT_TRUE_FOR_1 to the new |
| 1899 | optionflags argument. |
| 1900 | >>> 4 == 4 |
| 1901 | 1 |
| 1902 | >>> 4 == 4 |
| 1903 | True |
| 1904 | >>> 4 > 4 |
| 1905 | 0 |
| 1906 | >>> 4 > 4 |
| 1907 | False |
| 1908 | """, |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 1909 | "blank lines": r""" |
| 1910 | Blank lines can be marked with <BLANKLINE>: |
| 1911 | >>> print 'foo\n\nbar\n' |
| 1912 | foo |
| 1913 | <BLANKLINE> |
| 1914 | bar |
| 1915 | <BLANKLINE> |
| 1916 | """, |
| 1917 | } |
| 1918 | # "ellipsis": r""" |
| 1919 | # If the ellipsis flag is used, then '...' can be used to |
| 1920 | # elide substrings in the desired output: |
| 1921 | # >>> print range(1000) |
| 1922 | # [0, 1, 2, ..., 999] |
| 1923 | # """, |
| 1924 | # "whitespace normalization": r""" |
| 1925 | # If the whitespace normalization flag is used, then |
| 1926 | # differences in whitespace are ignored. |
| 1927 | # >>> print range(30) |
| 1928 | # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, |
| 1929 | # 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, |
| 1930 | # 27, 28, 29] |
| 1931 | # """, |
| 1932 | # } |
| 1933 | |
| 1934 | def test1(): r""" |
| 1935 | >>> from doctest import Tester |
| 1936 | >>> t = Tester(globs={'x': 42}, verbose=0) |
| 1937 | >>> t.runstring(r''' |
| 1938 | ... >>> x = x * 2 |
| 1939 | ... >>> print x |
| 1940 | ... 42 |
| 1941 | ... ''', 'XYZ') |
| 1942 | ********************************************************************** |
| 1943 | Failure in example: print x |
| 1944 | from line #2 of XYZ |
| 1945 | Expected: 42 |
| 1946 | Got: 84 |
| 1947 | (1, 2) |
| 1948 | >>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2') |
| 1949 | (0, 2) |
| 1950 | >>> t.summarize() |
| 1951 | ********************************************************************** |
| 1952 | 1 items had failures: |
| 1953 | 1 of 2 in XYZ |
| 1954 | ***Test Failed*** 1 failures. |
| 1955 | (1, 4) |
| 1956 | >>> t.summarize(verbose=1) |
| 1957 | 1 items passed all tests: |
| 1958 | 2 tests in example2 |
| 1959 | ********************************************************************** |
| 1960 | 1 items had failures: |
| 1961 | 1 of 2 in XYZ |
| 1962 | 4 tests in 2 items. |
| 1963 | 3 passed and 1 failed. |
| 1964 | ***Test Failed*** 1 failures. |
| 1965 | (1, 4) |
| 1966 | """ |
| 1967 | |
| 1968 | def test2(): r""" |
| 1969 | >>> t = Tester(globs={}, verbose=1) |
| 1970 | >>> test = r''' |
| 1971 | ... # just an example |
| 1972 | ... >>> x = 1 + 2 |
| 1973 | ... >>> x |
| 1974 | ... 3 |
| 1975 | ... ''' |
| 1976 | >>> t.runstring(test, "Example") |
| 1977 | Running string Example |
| 1978 | Trying: x = 1 + 2 |
| 1979 | Expecting: nothing |
| 1980 | ok |
| 1981 | Trying: x |
| 1982 | Expecting: 3 |
| 1983 | ok |
| 1984 | 0 of 2 examples failed in string Example |
| 1985 | (0, 2) |
| 1986 | """ |
| 1987 | def test3(): r""" |
| 1988 | >>> t = Tester(globs={}, verbose=0) |
| 1989 | >>> def _f(): |
| 1990 | ... '''Trivial docstring example. |
| 1991 | ... >>> assert 2 == 2 |
| 1992 | ... ''' |
| 1993 | ... return 32 |
| 1994 | ... |
| 1995 | >>> t.rundoc(_f) # expect 0 failures in 1 example |
| 1996 | (0, 1) |
| 1997 | """ |
| 1998 | def test4(): """ |
| 1999 | >>> import new |
| 2000 | >>> m1 = new.module('_m1') |
| 2001 | >>> m2 = new.module('_m2') |
| 2002 | >>> test_data = \""" |
| 2003 | ... def _f(): |
| 2004 | ... '''>>> assert 1 == 1 |
| 2005 | ... ''' |
| 2006 | ... def g(): |
| 2007 | ... '''>>> assert 2 != 1 |
| 2008 | ... ''' |
| 2009 | ... class H: |
| 2010 | ... '''>>> assert 2 > 1 |
| 2011 | ... ''' |
| 2012 | ... def bar(self): |
| 2013 | ... '''>>> assert 1 < 2 |
| 2014 | ... ''' |
| 2015 | ... \""" |
| 2016 | >>> exec test_data in m1.__dict__ |
| 2017 | >>> exec test_data in m2.__dict__ |
| 2018 | >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H}) |
| 2019 | |
| 2020 | Tests that objects outside m1 are excluded: |
| 2021 | |
| 2022 | >>> t = Tester(globs={}, verbose=0, isprivate=is_private) |
| 2023 | >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped |
| 2024 | (0, 3) |
| 2025 | |
| 2026 | Again, but with the default isprivate function allowing _f: |
| 2027 | |
| 2028 | >>> t = Tester(globs={}, verbose=0) |
| 2029 | >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped |
| 2030 | (0, 4) |
| 2031 | |
| 2032 | And once more, not excluding stuff outside m1: |
| 2033 | |
| 2034 | >>> t = Tester(globs={}, verbose=0) |
| 2035 | >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped. |
| 2036 | (0, 8) |
| 2037 | |
| 2038 | The exclusion of objects from outside the designated module is |
| 2039 | meant to be invoked automagically by testmod. |
| 2040 | |
| 2041 | >>> testmod(m1, isprivate=is_private, verbose=False) |
| 2042 | (0, 3) |
| 2043 | """ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2044 | |
| 2045 | def _test(): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame^] | 2046 | #import doctest |
| 2047 | #doctest.testmod(doctest, verbose=False, |
| 2048 | # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE | |
| 2049 | # UNIFIED_DIFF) |
| 2050 | #print '~'*70 |
| 2051 | r = unittest.TextTestRunner() |
| 2052 | r.run(DocTestSuite()) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2053 | |
| 2054 | if __name__ == "__main__": |
| 2055 | _test() |