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