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