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