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 | 958cc89 | 2004-09-13 14:53:28 +0000 | [diff] [blame] | 851 | recurse=True, _namefilter=None, exclude_empty=True): |
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. |
Edward Loper | 32ddbf7 | 2004-09-13 05:47:24 +0000 | [diff] [blame] | 863 | |
Tim Peters | 958cc89 | 2004-09-13 14:53:28 +0000 | [diff] [blame] | 864 | If the optional argument `exclude_empty` is false, then `find` |
| 865 | will include tests for objects with empty docstrings. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 866 | """ |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 867 | self._parser = parser |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 868 | self._verbose = verbose |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 869 | self._recurse = recurse |
Edward Loper | 32ddbf7 | 2004-09-13 05:47:24 +0000 | [diff] [blame] | 870 | self._exclude_empty = exclude_empty |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 871 | # _namefilter is undocumented, and exists only for temporary backward- |
| 872 | # compatibility support of testmod's deprecated isprivate mess. |
| 873 | self._namefilter = _namefilter |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 874 | |
| 875 | def find(self, obj, name=None, module=None, globs=None, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 876 | extraglobs=None): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 877 | """ |
| 878 | Return a list of the DocTests that are defined by the given |
| 879 | object's docstring, or by any of its contained objects' |
| 880 | docstrings. |
| 881 | |
| 882 | The optional parameter `module` is the module that contains |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 883 | the given object. If the module is not specified or is None, then |
| 884 | the test finder will attempt to automatically determine the |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 885 | correct module. The object's module is used: |
| 886 | |
| 887 | - As a default namespace, if `globs` is not specified. |
| 888 | - To prevent the DocTestFinder from extracting DocTests |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 889 | from objects that are imported from other modules. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 890 | - To find the name of the file containing the object. |
| 891 | - To help find the line number of the object within its |
| 892 | file. |
| 893 | |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 894 | Contained objects whose module does not match `module` are ignored. |
| 895 | |
| 896 | If `module` is False, no attempt to find the module will be made. |
| 897 | This is obscure, of use mostly in tests: if `module` is False, or |
| 898 | is None but cannot be found automatically, then all objects are |
| 899 | considered to belong to the (non-existent) module, so all contained |
| 900 | objects will (recursively) be searched for doctests. |
| 901 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 902 | The globals for each DocTest is formed by combining `globs` |
| 903 | and `extraglobs` (bindings in `extraglobs` override bindings |
| 904 | in `globs`). A new copy of the globals dictionary is created |
| 905 | for each DocTest. If `globs` is not specified, then it |
| 906 | defaults to the module's `__dict__`, if specified, or {} |
| 907 | otherwise. If `extraglobs` is not specified, then it defaults |
| 908 | to {}. |
| 909 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 910 | """ |
| 911 | # If name was not specified, then extract it from the object. |
| 912 | if name is None: |
| 913 | name = getattr(obj, '__name__', None) |
| 914 | if name is None: |
| 915 | raise ValueError("DocTestFinder.find: name must be given " |
| 916 | "when obj.__name__ doesn't exist: %r" % |
| 917 | (type(obj),)) |
| 918 | |
| 919 | # Find the module that contains the given object (if obj is |
| 920 | # a module, then module=obj.). Note: this may fail, in which |
| 921 | # case module will be None. |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 922 | if module is False: |
| 923 | module = None |
| 924 | elif module is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 925 | module = inspect.getmodule(obj) |
| 926 | |
| 927 | # Read the module's source code. This is used by |
| 928 | # DocTestFinder._find_lineno to find the line number for a |
| 929 | # given object's docstring. |
| 930 | try: |
| 931 | file = inspect.getsourcefile(obj) or inspect.getfile(obj) |
| 932 | source_lines = linecache.getlines(file) |
| 933 | if not source_lines: |
| 934 | source_lines = None |
| 935 | except TypeError: |
| 936 | source_lines = None |
| 937 | |
| 938 | # Initialize globals, and merge in extraglobs. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 939 | if globs is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 940 | if module is None: |
| 941 | globs = {} |
| 942 | else: |
| 943 | globs = module.__dict__.copy() |
| 944 | else: |
| 945 | globs = globs.copy() |
| 946 | if extraglobs is not None: |
| 947 | globs.update(extraglobs) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 948 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 949 | # Recursively expore `obj`, extracting DocTests. |
| 950 | tests = [] |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 951 | self._find(tests, obj, name, module, source_lines, globs, {}) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 952 | return tests |
| 953 | |
| 954 | def _filter(self, obj, prefix, base): |
| 955 | """ |
| 956 | Return true if the given object should not be examined. |
| 957 | """ |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 958 | return (self._namefilter is not None and |
| 959 | self._namefilter(prefix, base)) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 960 | |
| 961 | def _from_module(self, module, object): |
| 962 | """ |
| 963 | Return true if the given object is defined in the given |
| 964 | module. |
| 965 | """ |
| 966 | if module is None: |
| 967 | return True |
| 968 | elif inspect.isfunction(object): |
| 969 | return module.__dict__ is object.func_globals |
| 970 | elif inspect.isclass(object): |
| 971 | return module.__name__ == object.__module__ |
| 972 | elif inspect.getmodule(object) is not None: |
| 973 | return module is inspect.getmodule(object) |
| 974 | elif hasattr(object, '__module__'): |
| 975 | return module.__name__ == object.__module__ |
| 976 | elif isinstance(object, property): |
| 977 | return True # [XX] no way not be sure. |
| 978 | else: |
| 979 | raise ValueError("object must be a class or function") |
| 980 | |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 981 | def _find(self, tests, obj, name, module, source_lines, globs, seen): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 982 | """ |
| 983 | Find tests for the given object and any contained objects, and |
| 984 | add them to `tests`. |
| 985 | """ |
| 986 | if self._verbose: |
| 987 | print 'Finding tests in %s' % name |
| 988 | |
| 989 | # If we've already processed this object, then ignore it. |
| 990 | if id(obj) in seen: |
| 991 | return |
| 992 | seen[id(obj)] = 1 |
| 993 | |
| 994 | # Find a test for this object, and add it to the list of tests. |
| 995 | test = self._get_test(obj, name, module, globs, source_lines) |
| 996 | if test is not None: |
| 997 | tests.append(test) |
| 998 | |
| 999 | # Look for tests in a module's contained objects. |
| 1000 | if inspect.ismodule(obj) and self._recurse: |
| 1001 | for valname, val in obj.__dict__.items(): |
| 1002 | # Check if this contained object should be ignored. |
| 1003 | if self._filter(val, name, valname): |
| 1004 | continue |
| 1005 | valname = '%s.%s' % (name, valname) |
| 1006 | # Recurse to functions & classes. |
| 1007 | if ((inspect.isfunction(val) or inspect.isclass(val)) and |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1008 | self._from_module(module, val)): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1009 | self._find(tests, val, valname, module, source_lines, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1010 | globs, seen) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1011 | |
| 1012 | # Look for tests in a module's __test__ dictionary. |
| 1013 | if inspect.ismodule(obj) and self._recurse: |
| 1014 | for valname, val in getattr(obj, '__test__', {}).items(): |
| 1015 | if not isinstance(valname, basestring): |
| 1016 | raise ValueError("DocTestFinder.find: __test__ keys " |
| 1017 | "must be strings: %r" % |
| 1018 | (type(valname),)) |
| 1019 | if not (inspect.isfunction(val) or inspect.isclass(val) or |
| 1020 | inspect.ismethod(val) or inspect.ismodule(val) or |
| 1021 | isinstance(val, basestring)): |
| 1022 | raise ValueError("DocTestFinder.find: __test__ values " |
| 1023 | "must be strings, functions, methods, " |
| 1024 | "classes, or modules: %r" % |
| 1025 | (type(val),)) |
Tim Peters | c568478 | 2004-09-13 01:07:12 +0000 | [diff] [blame] | 1026 | valname = '%s.__test__.%s' % (name, valname) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1027 | self._find(tests, val, valname, module, source_lines, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1028 | globs, seen) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1029 | |
| 1030 | # Look for tests in a class's contained objects. |
| 1031 | if inspect.isclass(obj) and self._recurse: |
| 1032 | for valname, val in obj.__dict__.items(): |
| 1033 | # Check if this contained object should be ignored. |
| 1034 | if self._filter(val, name, valname): |
| 1035 | continue |
| 1036 | # Special handling for staticmethod/classmethod. |
| 1037 | if isinstance(val, staticmethod): |
| 1038 | val = getattr(obj, valname) |
| 1039 | if isinstance(val, classmethod): |
| 1040 | val = getattr(obj, valname).im_func |
| 1041 | |
| 1042 | # Recurse to methods, properties, and nested classes. |
| 1043 | if ((inspect.isfunction(val) or inspect.isclass(val) or |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1044 | isinstance(val, property)) and |
| 1045 | self._from_module(module, val)): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1046 | valname = '%s.%s' % (name, valname) |
| 1047 | self._find(tests, val, valname, module, source_lines, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 1048 | globs, seen) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1049 | |
| 1050 | def _get_test(self, obj, name, module, globs, source_lines): |
| 1051 | """ |
| 1052 | Return a DocTest for the given object, if it defines a docstring; |
| 1053 | otherwise, return None. |
| 1054 | """ |
| 1055 | # Extract the object's docstring. If it doesn't have one, |
| 1056 | # then return None (no test for this object). |
| 1057 | if isinstance(obj, basestring): |
| 1058 | docstring = obj |
| 1059 | else: |
| 1060 | try: |
| 1061 | if obj.__doc__ is None: |
Edward Loper | 32ddbf7 | 2004-09-13 05:47:24 +0000 | [diff] [blame] | 1062 | docstring = '' |
| 1063 | else: |
| 1064 | docstring = str(obj.__doc__) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1065 | except (TypeError, AttributeError): |
Edward Loper | 32ddbf7 | 2004-09-13 05:47:24 +0000 | [diff] [blame] | 1066 | docstring = '' |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1067 | |
| 1068 | # Find the docstring's location in the file. |
| 1069 | lineno = self._find_lineno(obj, source_lines) |
| 1070 | |
Edward Loper | 32ddbf7 | 2004-09-13 05:47:24 +0000 | [diff] [blame] | 1071 | # Don't bother if the docstring is empty. |
| 1072 | if self._exclude_empty and not docstring: |
| 1073 | return None |
| 1074 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1075 | # Return a DocTest for this object. |
| 1076 | if module is None: |
| 1077 | filename = None |
| 1078 | else: |
| 1079 | filename = getattr(module, '__file__', module.__name__) |
Jim Fulton | 07a349c | 2004-08-22 14:10:00 +0000 | [diff] [blame] | 1080 | if filename[-4:] in (".pyc", ".pyo"): |
| 1081 | filename = filename[:-1] |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 1082 | return self._parser.get_doctest(docstring, globs, name, |
| 1083 | filename, lineno) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1084 | |
| 1085 | def _find_lineno(self, obj, source_lines): |
| 1086 | """ |
| 1087 | Return a line number of the given object's docstring. Note: |
| 1088 | this method assumes that the object has a docstring. |
| 1089 | """ |
| 1090 | lineno = None |
| 1091 | |
| 1092 | # Find the line number for modules. |
| 1093 | if inspect.ismodule(obj): |
| 1094 | lineno = 0 |
| 1095 | |
| 1096 | # Find the line number for classes. |
| 1097 | # Note: this could be fooled if a class is defined multiple |
| 1098 | # times in a single file. |
| 1099 | if inspect.isclass(obj): |
| 1100 | if source_lines is None: |
| 1101 | return None |
| 1102 | pat = re.compile(r'^\s*class\s*%s\b' % |
| 1103 | getattr(obj, '__name__', '-')) |
| 1104 | for i, line in enumerate(source_lines): |
| 1105 | if pat.match(line): |
| 1106 | lineno = i |
| 1107 | break |
| 1108 | |
| 1109 | # Find the line number for functions & methods. |
| 1110 | if inspect.ismethod(obj): obj = obj.im_func |
| 1111 | if inspect.isfunction(obj): obj = obj.func_code |
| 1112 | if inspect.istraceback(obj): obj = obj.tb_frame |
| 1113 | if inspect.isframe(obj): obj = obj.f_code |
| 1114 | if inspect.iscode(obj): |
| 1115 | lineno = getattr(obj, 'co_firstlineno', None)-1 |
| 1116 | |
| 1117 | # Find the line number where the docstring starts. Assume |
| 1118 | # that it's the first line that begins with a quote mark. |
| 1119 | # Note: this could be fooled by a multiline function |
| 1120 | # signature, where a continuation line begins with a quote |
| 1121 | # mark. |
| 1122 | if lineno is not None: |
| 1123 | if source_lines is None: |
| 1124 | return lineno+1 |
| 1125 | pat = re.compile('(^|.*:)\s*\w*("|\')') |
| 1126 | for lineno in range(lineno, len(source_lines)): |
| 1127 | if pat.match(source_lines[lineno]): |
| 1128 | return lineno |
| 1129 | |
| 1130 | # We couldn't find the line number. |
| 1131 | return None |
| 1132 | |
| 1133 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 1134 | ## 5. DocTest Runner |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1135 | ###################################################################### |
| 1136 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1137 | class DocTestRunner: |
| 1138 | """ |
| 1139 | A class used to run DocTest test cases, and accumulate statistics. |
| 1140 | The `run` method is used to process a single DocTest case. It |
| 1141 | returns a tuple `(f, t)`, where `t` is the number of test cases |
| 1142 | tried, and `f` is the number of test cases that failed. |
| 1143 | |
| 1144 | >>> tests = DocTestFinder().find(_TestClass) |
| 1145 | >>> runner = DocTestRunner(verbose=False) |
| 1146 | >>> for test in tests: |
| 1147 | ... print runner.run(test) |
| 1148 | (0, 2) |
| 1149 | (0, 1) |
| 1150 | (0, 2) |
| 1151 | (0, 2) |
| 1152 | |
| 1153 | The `summarize` method prints a summary of all the test cases that |
| 1154 | have been run by the runner, and returns an aggregated `(f, t)` |
| 1155 | tuple: |
| 1156 | |
| 1157 | >>> runner.summarize(verbose=1) |
| 1158 | 4 items passed all tests: |
| 1159 | 2 tests in _TestClass |
| 1160 | 2 tests in _TestClass.__init__ |
| 1161 | 2 tests in _TestClass.get |
| 1162 | 1 tests in _TestClass.square |
| 1163 | 7 tests in 4 items. |
| 1164 | 7 passed and 0 failed. |
| 1165 | Test passed. |
| 1166 | (0, 7) |
| 1167 | |
| 1168 | The aggregated number of tried examples and failed examples is |
| 1169 | also available via the `tries` and `failures` attributes: |
| 1170 | |
| 1171 | >>> runner.tries |
| 1172 | 7 |
| 1173 | >>> runner.failures |
| 1174 | 0 |
| 1175 | |
| 1176 | The comparison between expected outputs and actual outputs is done |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1177 | by an `OutputChecker`. This comparison may be customized with a |
| 1178 | number of option flags; see the documentation for `testmod` for |
| 1179 | more information. If the option flags are insufficient, then the |
| 1180 | comparison may also be customized by passing a subclass of |
| 1181 | `OutputChecker` to the constructor. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1182 | |
| 1183 | The test runner's display output can be controlled in two ways. |
| 1184 | First, an output function (`out) can be passed to |
| 1185 | `TestRunner.run`; this function will be called with strings that |
| 1186 | should be displayed. It defaults to `sys.stdout.write`. If |
| 1187 | capturing the output is not sufficient, then the display output |
| 1188 | can be also customized by subclassing DocTestRunner, and |
| 1189 | overriding the methods `report_start`, `report_success`, |
| 1190 | `report_unexpected_exception`, and `report_failure`. |
| 1191 | """ |
| 1192 | # This divider string is used to separate failure messages, and to |
| 1193 | # separate sections of the summary. |
| 1194 | DIVIDER = "*" * 70 |
| 1195 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1196 | def __init__(self, checker=None, verbose=None, optionflags=0): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1197 | """ |
| 1198 | Create a new test runner. |
| 1199 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1200 | Optional keyword arg `checker` is the `OutputChecker` that |
| 1201 | should be used to compare the expected outputs and actual |
| 1202 | outputs of doctest examples. |
| 1203 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1204 | Optional keyword arg 'verbose' prints lots of stuff if true, |
| 1205 | only failures if false; by default, it's true iff '-v' is in |
| 1206 | sys.argv. |
| 1207 | |
| 1208 | Optional argument `optionflags` can be used to control how the |
| 1209 | test runner compares expected output to actual output, and how |
| 1210 | it displays failures. See the documentation for `testmod` for |
| 1211 | more information. |
| 1212 | """ |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1213 | self._checker = checker or OutputChecker() |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1214 | if verbose is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1215 | verbose = '-v' in sys.argv |
| 1216 | self._verbose = verbose |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1217 | self.optionflags = optionflags |
Jim Fulton | 07a349c | 2004-08-22 14:10:00 +0000 | [diff] [blame] | 1218 | self.original_optionflags = optionflags |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1219 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1220 | # Keep track of the examples we've run. |
| 1221 | self.tries = 0 |
| 1222 | self.failures = 0 |
| 1223 | self._name2ft = {} |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1224 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1225 | # Create a fake output target for capturing doctest output. |
| 1226 | self._fakeout = _SpoofOut() |
Tim Peters | 4fd9e2f | 2001-08-18 00:05:50 +0000 | [diff] [blame] | 1227 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1228 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1229 | # Reporting methods |
| 1230 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 17111f3 | 2001-10-03 04:08:26 +0000 | [diff] [blame] | 1231 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1232 | def report_start(self, out, test, example): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1233 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1234 | Report that the test runner is about to process the given |
| 1235 | example. (Only displays a message if verbose=True) |
| 1236 | """ |
| 1237 | if self._verbose: |
Edward Loper | aacf083 | 2004-08-26 01:19:50 +0000 | [diff] [blame] | 1238 | if example.want: |
| 1239 | out('Trying:\n' + _indent(example.source) + |
| 1240 | 'Expecting:\n' + _indent(example.want)) |
| 1241 | else: |
| 1242 | out('Trying:\n' + _indent(example.source) + |
| 1243 | 'Expecting nothing\n') |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1244 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1245 | def report_success(self, out, test, example, got): |
| 1246 | """ |
| 1247 | Report that the given example ran successfully. (Only |
| 1248 | displays a message if verbose=True) |
| 1249 | """ |
| 1250 | if self._verbose: |
| 1251 | out("ok\n") |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1252 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1253 | def report_failure(self, out, test, example, got): |
| 1254 | """ |
| 1255 | Report that the given example failed. |
| 1256 | """ |
Edward Loper | 8e4a34b | 2004-08-12 02:34:27 +0000 | [diff] [blame] | 1257 | out(self._failure_header(test, example) + |
Edward Loper | ca9111e | 2004-08-26 03:00:24 +0000 | [diff] [blame] | 1258 | self._checker.output_difference(example, got, self.optionflags)) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1259 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1260 | def report_unexpected_exception(self, out, test, example, exc_info): |
| 1261 | """ |
| 1262 | Report that the given example raised an unexpected exception. |
| 1263 | """ |
Edward Loper | 8e4a34b | 2004-08-12 02:34:27 +0000 | [diff] [blame] | 1264 | out(self._failure_header(test, example) + |
Edward Loper | aacf083 | 2004-08-26 01:19:50 +0000 | [diff] [blame] | 1265 | 'Exception raised:\n' + _indent(_exception_traceback(exc_info))) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1266 | |
Edward Loper | 8e4a34b | 2004-08-12 02:34:27 +0000 | [diff] [blame] | 1267 | def _failure_header(self, test, example): |
Jim Fulton | 07a349c | 2004-08-22 14:10:00 +0000 | [diff] [blame] | 1268 | out = [self.DIVIDER] |
| 1269 | if test.filename: |
| 1270 | if test.lineno is not None and example.lineno is not None: |
| 1271 | lineno = test.lineno + example.lineno + 1 |
| 1272 | else: |
| 1273 | lineno = '?' |
| 1274 | out.append('File "%s", line %s, in %s' % |
| 1275 | (test.filename, lineno, test.name)) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1276 | else: |
Jim Fulton | 07a349c | 2004-08-22 14:10:00 +0000 | [diff] [blame] | 1277 | out.append('Line %s, in %s' % (example.lineno+1, test.name)) |
| 1278 | out.append('Failed example:') |
| 1279 | source = example.source |
Edward Loper | aacf083 | 2004-08-26 01:19:50 +0000 | [diff] [blame] | 1280 | out.append(_indent(source)) |
| 1281 | return '\n'.join(out) |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1282 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1283 | #///////////////////////////////////////////////////////////////// |
| 1284 | # DocTest Running |
| 1285 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 7402f79 | 2001-10-02 03:53:41 +0000 | [diff] [blame] | 1286 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1287 | def __run(self, test, compileflags, out): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1288 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1289 | Run the examples in `test`. Write the outcome of each example |
| 1290 | with one of the `DocTestRunner.report_*` methods, using the |
| 1291 | writer function `out`. `compileflags` is the set of compiler |
| 1292 | flags that should be used to execute examples. Return a tuple |
| 1293 | `(f, t)`, where `t` is the number of examples tried, and `f` |
| 1294 | is the number of examples that failed. The examples are run |
| 1295 | in the namespace `test.globs`. |
| 1296 | """ |
| 1297 | # Keep track of the number of failures and tries. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1298 | failures = tries = 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1299 | |
| 1300 | # Save the option flags (since option directives can be used |
| 1301 | # to modify them). |
| 1302 | original_optionflags = self.optionflags |
| 1303 | |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1304 | SUCCESS, FAILURE, BOOM = range(3) # `outcome` state |
| 1305 | |
| 1306 | check = self._checker.check_output |
| 1307 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1308 | # Process each example. |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1309 | for examplenum, example in enumerate(test.examples): |
| 1310 | |
Edward Loper | a89f88d | 2004-08-26 02:45:51 +0000 | [diff] [blame] | 1311 | # If REPORT_ONLY_FIRST_FAILURE is set, then supress |
| 1312 | # reporting after the first failure. |
| 1313 | quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and |
| 1314 | failures > 0) |
| 1315 | |
Edward Loper | 74bca7a | 2004-08-12 02:27:44 +0000 | [diff] [blame] | 1316 | # Merge in the example's options. |
| 1317 | self.optionflags = original_optionflags |
| 1318 | if example.options: |
| 1319 | for (optionflag, val) in example.options.items(): |
| 1320 | if val: |
| 1321 | self.optionflags |= optionflag |
| 1322 | else: |
| 1323 | self.optionflags &= ~optionflag |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1324 | |
| 1325 | # Record that we started this example. |
| 1326 | tries += 1 |
Edward Loper | a89f88d | 2004-08-26 02:45:51 +0000 | [diff] [blame] | 1327 | if not quiet: |
| 1328 | self.report_start(out, test, example) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1329 | |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1330 | # Use a special filename for compile(), so we can retrieve |
| 1331 | # the source code during interactive debugging (see |
| 1332 | # __patched_linecache_getlines). |
| 1333 | filename = '<doctest %s[%d]>' % (test.name, examplenum) |
| 1334 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1335 | # Run the example in the given context (globs), and record |
| 1336 | # any exception that gets raised. (But don't intercept |
| 1337 | # keyboard interrupts.) |
| 1338 | try: |
Tim Peters | 208ca70 | 2004-08-09 04:12:36 +0000 | [diff] [blame] | 1339 | # Don't blink! This is where the user's code gets run. |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1340 | exec compile(example.source, filename, "single", |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1341 | compileflags, 1) in test.globs |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1342 | self.debugger.set_continue() # ==== Example Finished ==== |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1343 | exception = None |
| 1344 | except KeyboardInterrupt: |
| 1345 | raise |
| 1346 | except: |
| 1347 | exception = sys.exc_info() |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1348 | self.debugger.set_continue() # ==== Example Finished ==== |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1349 | |
Tim Peters | 208ca70 | 2004-08-09 04:12:36 +0000 | [diff] [blame] | 1350 | got = self._fakeout.getvalue() # the actual output |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1351 | self._fakeout.truncate(0) |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1352 | outcome = FAILURE # guilty until proved innocent or insane |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1353 | |
| 1354 | # If the example executed without raising any exceptions, |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1355 | # verify its output. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1356 | if exception is None: |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1357 | if check(example.want, got, self.optionflags): |
| 1358 | outcome = SUCCESS |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1359 | |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1360 | # The example raised an exception: check if it was expected. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1361 | else: |
| 1362 | exc_info = sys.exc_info() |
| 1363 | exc_msg = traceback.format_exception_only(*exc_info[:2])[-1] |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1364 | if not quiet: |
| 1365 | got += _exception_traceback(exc_info) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1366 | |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1367 | # If `example.exc_msg` is None, then we weren't expecting |
| 1368 | # an exception. |
Edward Loper | a6b6832 | 2004-08-26 00:05:43 +0000 | [diff] [blame] | 1369 | if example.exc_msg is None: |
Tim Peters | 1fbf9c5 | 2004-09-04 17:21:02 +0000 | [diff] [blame] | 1370 | outcome = BOOM |
| 1371 | |
| 1372 | # We expected an exception: see whether it matches. |
| 1373 | elif check(example.exc_msg, exc_msg, self.optionflags): |
| 1374 | outcome = SUCCESS |
| 1375 | |
| 1376 | # Another chance if they didn't care about the detail. |
| 1377 | elif self.optionflags & IGNORE_EXCEPTION_DETAIL: |
| 1378 | m1 = re.match(r'[^:]*:', example.exc_msg) |
| 1379 | m2 = re.match(r'[^:]*:', exc_msg) |
| 1380 | if m1 and m2 and check(m1.group(0), m2.group(0), |
| 1381 | self.optionflags): |
| 1382 | outcome = SUCCESS |
| 1383 | |
| 1384 | # Report the outcome. |
| 1385 | if outcome is SUCCESS: |
| 1386 | if not quiet: |
| 1387 | self.report_success(out, test, example, got) |
| 1388 | elif outcome is FAILURE: |
| 1389 | if not quiet: |
| 1390 | self.report_failure(out, test, example, got) |
| 1391 | failures += 1 |
| 1392 | elif outcome is BOOM: |
| 1393 | if not quiet: |
| 1394 | self.report_unexpected_exception(out, test, example, |
| 1395 | exc_info) |
| 1396 | failures += 1 |
| 1397 | else: |
| 1398 | assert False, ("unknown outcome", outcome) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1399 | |
| 1400 | # Restore the option flags (in case they were modified) |
| 1401 | self.optionflags = original_optionflags |
| 1402 | |
| 1403 | # Record and return the number of failures and tries. |
| 1404 | self.__record_outcome(test, failures, tries) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1405 | return failures, tries |
| 1406 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1407 | def __record_outcome(self, test, f, t): |
| 1408 | """ |
| 1409 | Record the fact that the given DocTest (`test`) generated `f` |
| 1410 | failures out of `t` tried examples. |
| 1411 | """ |
| 1412 | f2, t2 = self._name2ft.get(test.name, (0,0)) |
| 1413 | self._name2ft[test.name] = (f+f2, t+t2) |
| 1414 | self.failures += f |
| 1415 | self.tries += t |
| 1416 | |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1417 | __LINECACHE_FILENAME_RE = re.compile(r'<doctest ' |
| 1418 | r'(?P<name>[\w\.]+)' |
| 1419 | r'\[(?P<examplenum>\d+)\]>$') |
| 1420 | def __patched_linecache_getlines(self, filename): |
| 1421 | m = self.__LINECACHE_FILENAME_RE.match(filename) |
| 1422 | if m and m.group('name') == self.test.name: |
| 1423 | example = self.test.examples[int(m.group('examplenum'))] |
| 1424 | return example.source.splitlines(True) |
| 1425 | else: |
| 1426 | return self.save_linecache_getlines(filename) |
| 1427 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1428 | def run(self, test, compileflags=None, out=None, clear_globs=True): |
| 1429 | """ |
| 1430 | Run the examples in `test`, and display the results using the |
| 1431 | writer function `out`. |
| 1432 | |
| 1433 | The examples are run in the namespace `test.globs`. If |
| 1434 | `clear_globs` is true (the default), then this namespace will |
| 1435 | be cleared after the test runs, to help with garbage |
| 1436 | collection. If you would like to examine the namespace after |
| 1437 | the test completes, then use `clear_globs=False`. |
| 1438 | |
| 1439 | `compileflags` gives the set of flags that should be used by |
| 1440 | the Python compiler when running the examples. If not |
| 1441 | specified, then it will default to the set of future-import |
| 1442 | flags that apply to `globs`. |
| 1443 | |
| 1444 | The output of each example is checked using |
| 1445 | `DocTestRunner.check_output`, and the results are formatted by |
| 1446 | the `DocTestRunner.report_*` methods. |
| 1447 | """ |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1448 | self.test = test |
| 1449 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1450 | if compileflags is None: |
| 1451 | compileflags = _extract_future_flags(test.globs) |
Jim Fulton | 356fd19 | 2004-08-09 11:34:47 +0000 | [diff] [blame] | 1452 | |
Tim Peters | 6c542b7 | 2004-08-09 16:43:36 +0000 | [diff] [blame] | 1453 | save_stdout = sys.stdout |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1454 | if out is None: |
Tim Peters | 6c542b7 | 2004-08-09 16:43:36 +0000 | [diff] [blame] | 1455 | out = save_stdout.write |
| 1456 | sys.stdout = self._fakeout |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1457 | |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1458 | # Patch pdb.set_trace to restore sys.stdout during interactive |
| 1459 | # debugging (so it's not still redirected to self._fakeout). |
| 1460 | # Note that the interactive output will go to *our* |
| 1461 | # save_stdout, even if that's not the real sys.stdout; this |
| 1462 | # allows us to write test cases for the set_trace behavior. |
Tim Peters | 6c542b7 | 2004-08-09 16:43:36 +0000 | [diff] [blame] | 1463 | save_set_trace = pdb.set_trace |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1464 | self.debugger = _OutputRedirectingPdb(save_stdout) |
| 1465 | self.debugger.reset() |
| 1466 | pdb.set_trace = self.debugger.set_trace |
| 1467 | |
| 1468 | # Patch linecache.getlines, so we can see the example's source |
| 1469 | # when we're inside the debugger. |
| 1470 | self.save_linecache_getlines = linecache.getlines |
| 1471 | linecache.getlines = self.__patched_linecache_getlines |
| 1472 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1473 | try: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1474 | return self.__run(test, compileflags, out) |
| 1475 | finally: |
Tim Peters | 6c542b7 | 2004-08-09 16:43:36 +0000 | [diff] [blame] | 1476 | sys.stdout = save_stdout |
| 1477 | pdb.set_trace = save_set_trace |
Edward Loper | 2de91ba | 2004-08-27 02:07:46 +0000 | [diff] [blame] | 1478 | linecache.getlines = self.save_linecache_getlines |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1479 | if clear_globs: |
| 1480 | test.globs.clear() |
| 1481 | |
| 1482 | #///////////////////////////////////////////////////////////////// |
| 1483 | # Summarization |
| 1484 | #///////////////////////////////////////////////////////////////// |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1485 | def summarize(self, verbose=None): |
| 1486 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1487 | Print a summary of all the test cases that have been run by |
| 1488 | this DocTestRunner, and return a tuple `(f, t)`, where `f` is |
| 1489 | the total number of failed examples, and `t` is the total |
| 1490 | number of tried examples. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1491 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1492 | The optional `verbose` argument controls how detailed the |
| 1493 | summary is. If the verbosity is not specified, then the |
| 1494 | DocTestRunner's verbosity is used. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1495 | """ |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1496 | if verbose is None: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1497 | verbose = self._verbose |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1498 | notests = [] |
| 1499 | passed = [] |
| 1500 | failed = [] |
| 1501 | totalt = totalf = 0 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1502 | for x in self._name2ft.items(): |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1503 | name, (f, t) = x |
| 1504 | assert f <= t |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1505 | totalt += t |
| 1506 | totalf += f |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1507 | if t == 0: |
| 1508 | notests.append(name) |
| 1509 | elif f == 0: |
| 1510 | passed.append( (name, t) ) |
| 1511 | else: |
| 1512 | failed.append(x) |
| 1513 | if verbose: |
| 1514 | if notests: |
| 1515 | print len(notests), "items had no tests:" |
| 1516 | notests.sort() |
| 1517 | for thing in notests: |
| 1518 | print " ", thing |
| 1519 | if passed: |
| 1520 | print len(passed), "items passed all tests:" |
| 1521 | passed.sort() |
| 1522 | for thing, count in passed: |
| 1523 | print " %3d tests in %s" % (count, thing) |
| 1524 | if failed: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1525 | print self.DIVIDER |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1526 | print len(failed), "items had failures:" |
| 1527 | failed.sort() |
| 1528 | for thing, (f, t) in failed: |
| 1529 | print " %3d of %3d in %s" % (f, t, thing) |
| 1530 | if verbose: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1531 | print totalt, "tests in", len(self._name2ft), "items." |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1532 | print totalt - totalf, "passed and", totalf, "failed." |
| 1533 | if totalf: |
| 1534 | print "***Test Failed***", totalf, "failures." |
| 1535 | elif verbose: |
| 1536 | print "Test passed." |
| 1537 | return totalf, totalt |
| 1538 | |
Tim Peters | 82076ef | 2004-09-13 00:52:51 +0000 | [diff] [blame] | 1539 | #///////////////////////////////////////////////////////////////// |
| 1540 | # Backward compatibility cruft to maintain doctest.master. |
| 1541 | #///////////////////////////////////////////////////////////////// |
| 1542 | def merge(self, other): |
| 1543 | d = self._name2ft |
| 1544 | for name, (f, t) in other._name2ft.items(): |
| 1545 | if name in d: |
| 1546 | print "*** DocTestRunner.merge: '" + name + "' in both" \ |
| 1547 | " testers; summing outcomes." |
| 1548 | f2, t2 = d[name] |
| 1549 | f = f + f2 |
| 1550 | t = t + t2 |
| 1551 | d[name] = f, t |
| 1552 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1553 | class OutputChecker: |
| 1554 | """ |
| 1555 | A class used to check the whether the actual output from a doctest |
| 1556 | example matches the expected output. `OutputChecker` defines two |
| 1557 | methods: `check_output`, which compares a given pair of outputs, |
| 1558 | and returns true if they match; and `output_difference`, which |
| 1559 | returns a string describing the differences between two outputs. |
| 1560 | """ |
| 1561 | def check_output(self, want, got, optionflags): |
| 1562 | """ |
Edward Loper | 74bca7a | 2004-08-12 02:27:44 +0000 | [diff] [blame] | 1563 | Return True iff the actual output from an example (`got`) |
| 1564 | matches the expected output (`want`). These strings are |
| 1565 | always considered to match if they are identical; but |
| 1566 | depending on what option flags the test runner is using, |
| 1567 | several non-exact match types are also possible. See the |
| 1568 | documentation for `TestRunner` for more information about |
| 1569 | option flags. |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1570 | """ |
| 1571 | # Handle the common case first, for efficiency: |
| 1572 | # if they're string-identical, always return true. |
| 1573 | if got == want: |
| 1574 | return True |
| 1575 | |
| 1576 | # The values True and False replaced 1 and 0 as the return |
| 1577 | # value for boolean comparisons in Python 2.3. |
| 1578 | if not (optionflags & DONT_ACCEPT_TRUE_FOR_1): |
| 1579 | if (got,want) == ("True\n", "1\n"): |
| 1580 | return True |
| 1581 | if (got,want) == ("False\n", "0\n"): |
| 1582 | return True |
| 1583 | |
| 1584 | # <BLANKLINE> can be used as a special sequence to signify a |
| 1585 | # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. |
| 1586 | if not (optionflags & DONT_ACCEPT_BLANKLINE): |
| 1587 | # Replace <BLANKLINE> in want with a blank line. |
| 1588 | want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER), |
| 1589 | '', want) |
| 1590 | # If a line in got contains only spaces, then remove the |
| 1591 | # spaces. |
| 1592 | got = re.sub('(?m)^\s*?$', '', got) |
| 1593 | if got == want: |
| 1594 | return True |
| 1595 | |
| 1596 | # This flag causes doctest to ignore any differences in the |
| 1597 | # contents of whitespace strings. Note that this can be used |
Tim Peters | 3fa8c20 | 2004-08-23 21:43:39 +0000 | [diff] [blame] | 1598 | # in conjunction with the ELLIPSIS flag. |
Tim Peters | 1cf3aa6 | 2004-08-19 06:49:33 +0000 | [diff] [blame] | 1599 | if optionflags & NORMALIZE_WHITESPACE: |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1600 | got = ' '.join(got.split()) |
| 1601 | want = ' '.join(want.split()) |
| 1602 | if got == want: |
| 1603 | return True |
| 1604 | |
| 1605 | # The ELLIPSIS flag says to let the sequence "..." in `want` |
Tim Peters | 26b3ebb | 2004-08-19 08:10:08 +0000 | [diff] [blame] | 1606 | # match any substring in `got`. |
Tim Peters | 1cf3aa6 | 2004-08-19 06:49:33 +0000 | [diff] [blame] | 1607 | if optionflags & ELLIPSIS: |
Tim Peters | b0a04e1 | 2004-08-20 02:08:04 +0000 | [diff] [blame] | 1608 | if _ellipsis_match(want, got): |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1609 | return True |
| 1610 | |
| 1611 | # We didn't find any match; return false. |
| 1612 | return False |
| 1613 | |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1614 | # Should we do a fancy diff? |
| 1615 | def _do_a_fancy_diff(self, want, got, optionflags): |
| 1616 | # Not unless they asked for a fancy diff. |
Edward Loper | 71f55af | 2004-08-26 01:41:51 +0000 | [diff] [blame] | 1617 | if not optionflags & (REPORT_UDIFF | |
| 1618 | REPORT_CDIFF | |
| 1619 | REPORT_NDIFF): |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1620 | return False |
Tim Peters | 5b799c1 | 2004-08-26 05:21:59 +0000 | [diff] [blame] | 1621 | |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1622 | # If expected output uses ellipsis, a meaningful fancy diff is |
Tim Peters | 5b799c1 | 2004-08-26 05:21:59 +0000 | [diff] [blame] | 1623 | # too hard ... or maybe not. In two real-life failures Tim saw, |
| 1624 | # a diff was a major help anyway, so this is commented out. |
| 1625 | # [todo] _ellipsis_match() knows which pieces do and don't match, |
| 1626 | # and could be the basis for a kick-ass diff in this case. |
| 1627 | ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want: |
| 1628 | ## return False |
| 1629 | |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1630 | # ndiff does intraline difference marking, so can be useful even |
Tim Peters | 5b799c1 | 2004-08-26 05:21:59 +0000 | [diff] [blame] | 1631 | # for 1-line differences. |
Edward Loper | 71f55af | 2004-08-26 01:41:51 +0000 | [diff] [blame] | 1632 | if optionflags & REPORT_NDIFF: |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1633 | return True |
Tim Peters | 5b799c1 | 2004-08-26 05:21:59 +0000 | [diff] [blame] | 1634 | |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1635 | # The other diff types need at least a few lines to be helpful. |
| 1636 | return want.count('\n') > 2 and got.count('\n') > 2 |
| 1637 | |
Edward Loper | ca9111e | 2004-08-26 03:00:24 +0000 | [diff] [blame] | 1638 | def output_difference(self, example, got, optionflags): |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1639 | """ |
| 1640 | Return a string describing the differences between the |
Edward Loper | ca9111e | 2004-08-26 03:00:24 +0000 | [diff] [blame] | 1641 | expected output for a given example (`example`) and the actual |
| 1642 | output (`got`). `optionflags` is the set of option flags used |
| 1643 | to compare `want` and `got`. |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1644 | """ |
Edward Loper | ca9111e | 2004-08-26 03:00:24 +0000 | [diff] [blame] | 1645 | want = example.want |
Edward Loper | 68ba9a6 | 2004-08-12 02:43:49 +0000 | [diff] [blame] | 1646 | # If <BLANKLINE>s are being used, then replace blank lines |
| 1647 | # with <BLANKLINE> in the actual output string. |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1648 | if not (optionflags & DONT_ACCEPT_BLANKLINE): |
Edward Loper | 68ba9a6 | 2004-08-12 02:43:49 +0000 | [diff] [blame] | 1649 | got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1650 | |
Tim Peters | 5b799c1 | 2004-08-26 05:21:59 +0000 | [diff] [blame] | 1651 | # Check if we should use diff. |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1652 | if self._do_a_fancy_diff(want, got, optionflags): |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1653 | # Split want & got into lines. |
Tim Peters | e7edcb8 | 2004-08-26 05:44:27 +0000 | [diff] [blame] | 1654 | want_lines = want.splitlines(True) # True == keep line ends |
| 1655 | got_lines = got.splitlines(True) |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1656 | # Use difflib to find their differences. |
Edward Loper | 71f55af | 2004-08-26 01:41:51 +0000 | [diff] [blame] | 1657 | if optionflags & REPORT_UDIFF: |
Edward Loper | 5662929 | 2004-08-26 01:31:56 +0000 | [diff] [blame] | 1658 | diff = difflib.unified_diff(want_lines, got_lines, n=2) |
| 1659 | diff = list(diff)[2:] # strip the diff header |
| 1660 | kind = 'unified diff with -expected +actual' |
Edward Loper | 71f55af | 2004-08-26 01:41:51 +0000 | [diff] [blame] | 1661 | elif optionflags & REPORT_CDIFF: |
Edward Loper | 5662929 | 2004-08-26 01:31:56 +0000 | [diff] [blame] | 1662 | diff = difflib.context_diff(want_lines, got_lines, n=2) |
| 1663 | diff = list(diff)[2:] # strip the diff header |
| 1664 | kind = 'context diff with expected followed by actual' |
Edward Loper | 71f55af | 2004-08-26 01:41:51 +0000 | [diff] [blame] | 1665 | elif optionflags & REPORT_NDIFF: |
Tim Peters | c6cbab0 | 2004-08-22 19:43:28 +0000 | [diff] [blame] | 1666 | engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) |
| 1667 | diff = list(engine.compare(want_lines, got_lines)) |
| 1668 | kind = 'ndiff with -expected +actual' |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1669 | else: |
| 1670 | assert 0, 'Bad diff option' |
| 1671 | # Remove trailing whitespace on diff output. |
| 1672 | diff = [line.rstrip() + '\n' for line in diff] |
Edward Loper | aacf083 | 2004-08-26 01:19:50 +0000 | [diff] [blame] | 1673 | return 'Differences (%s):\n' % kind + _indent(''.join(diff)) |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1674 | |
| 1675 | # If we're not using diff, then simply list the expected |
| 1676 | # output followed by the actual output. |
Edward Loper | aacf083 | 2004-08-26 01:19:50 +0000 | [diff] [blame] | 1677 | if want and got: |
| 1678 | return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)) |
| 1679 | elif want: |
| 1680 | return 'Expected:\n%sGot nothing\n' % _indent(want) |
| 1681 | elif got: |
| 1682 | return 'Expected nothing\nGot:\n%s' % _indent(got) |
| 1683 | else: |
| 1684 | return 'Expected nothing\nGot nothing\n' |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 1685 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1686 | class DocTestFailure(Exception): |
| 1687 | """A DocTest example has failed in debugging mode. |
| 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 | - got: the actual output |
| 1696 | """ |
| 1697 | def __init__(self, test, example, got): |
| 1698 | self.test = test |
| 1699 | self.example = example |
| 1700 | self.got = got |
| 1701 | |
| 1702 | def __str__(self): |
| 1703 | return str(self.test) |
| 1704 | |
| 1705 | class UnexpectedException(Exception): |
| 1706 | """A DocTest example has encountered an unexpected exception |
| 1707 | |
| 1708 | The exception instance has variables: |
| 1709 | |
| 1710 | - test: the DocTest object being run |
| 1711 | |
| 1712 | - excample: the Example object that failed |
| 1713 | |
| 1714 | - exc_info: the exception info |
| 1715 | """ |
| 1716 | def __init__(self, test, example, exc_info): |
| 1717 | self.test = test |
| 1718 | self.example = example |
| 1719 | self.exc_info = exc_info |
| 1720 | |
| 1721 | def __str__(self): |
| 1722 | return str(self.test) |
Tim Peters | d1b7827 | 2004-08-07 06:03:09 +0000 | [diff] [blame] | 1723 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1724 | class DebugRunner(DocTestRunner): |
| 1725 | r"""Run doc tests but raise an exception as soon as there is a failure. |
| 1726 | |
| 1727 | If an unexpected exception occurs, an UnexpectedException is raised. |
| 1728 | It contains the test, the example, and the original exception: |
| 1729 | |
| 1730 | >>> runner = DebugRunner(verbose=False) |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 1731 | >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', |
| 1732 | ... {}, 'foo', 'foo.py', 0) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1733 | >>> try: |
| 1734 | ... runner.run(test) |
| 1735 | ... except UnexpectedException, failure: |
| 1736 | ... pass |
| 1737 | |
| 1738 | >>> failure.test is test |
| 1739 | True |
| 1740 | |
| 1741 | >>> failure.example.want |
| 1742 | '42\n' |
| 1743 | |
| 1744 | >>> exc_info = failure.exc_info |
| 1745 | >>> raise exc_info[0], exc_info[1], exc_info[2] |
| 1746 | Traceback (most recent call last): |
| 1747 | ... |
| 1748 | KeyError |
| 1749 | |
| 1750 | We wrap the original exception to give the calling application |
| 1751 | access to the test and example information. |
| 1752 | |
| 1753 | If the output doesn't match, then a DocTestFailure is raised: |
| 1754 | |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 1755 | >>> test = DocTestParser().get_doctest(''' |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1756 | ... >>> x = 1 |
| 1757 | ... >>> x |
| 1758 | ... 2 |
| 1759 | ... ''', {}, 'foo', 'foo.py', 0) |
| 1760 | |
| 1761 | >>> try: |
| 1762 | ... runner.run(test) |
| 1763 | ... except DocTestFailure, failure: |
| 1764 | ... pass |
| 1765 | |
| 1766 | DocTestFailure objects provide access to the test: |
| 1767 | |
| 1768 | >>> failure.test is test |
| 1769 | True |
| 1770 | |
| 1771 | As well as to the example: |
| 1772 | |
| 1773 | >>> failure.example.want |
| 1774 | '2\n' |
| 1775 | |
| 1776 | and the actual output: |
| 1777 | |
| 1778 | >>> failure.got |
| 1779 | '1\n' |
| 1780 | |
| 1781 | If a failure or error occurs, the globals are left intact: |
| 1782 | |
| 1783 | >>> del test.globs['__builtins__'] |
| 1784 | >>> test.globs |
| 1785 | {'x': 1} |
| 1786 | |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 1787 | >>> test = DocTestParser().get_doctest(''' |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1788 | ... >>> x = 2 |
| 1789 | ... >>> raise KeyError |
| 1790 | ... ''', {}, 'foo', 'foo.py', 0) |
| 1791 | |
| 1792 | >>> runner.run(test) |
| 1793 | Traceback (most recent call last): |
| 1794 | ... |
| 1795 | UnexpectedException: <DocTest foo from foo.py:0 (2 examples)> |
Tim Peters | d1b7827 | 2004-08-07 06:03:09 +0000 | [diff] [blame] | 1796 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1797 | >>> del test.globs['__builtins__'] |
| 1798 | >>> test.globs |
| 1799 | {'x': 2} |
| 1800 | |
| 1801 | But the globals are cleared if there is no error: |
| 1802 | |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 1803 | >>> test = DocTestParser().get_doctest(''' |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1804 | ... >>> x = 2 |
| 1805 | ... ''', {}, 'foo', 'foo.py', 0) |
| 1806 | |
| 1807 | >>> runner.run(test) |
| 1808 | (0, 1) |
| 1809 | |
| 1810 | >>> test.globs |
| 1811 | {} |
| 1812 | |
| 1813 | """ |
| 1814 | |
| 1815 | def run(self, test, compileflags=None, out=None, clear_globs=True): |
| 1816 | r = DocTestRunner.run(self, test, compileflags, out, False) |
| 1817 | if clear_globs: |
| 1818 | test.globs.clear() |
| 1819 | return r |
| 1820 | |
| 1821 | def report_unexpected_exception(self, out, test, example, exc_info): |
| 1822 | raise UnexpectedException(test, example, exc_info) |
| 1823 | |
| 1824 | def report_failure(self, out, test, example, got): |
| 1825 | raise DocTestFailure(test, example, got) |
| 1826 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1827 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 1828 | ## 6. Test Functions |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1829 | ###################################################################### |
| 1830 | # These should be backwards compatible. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1831 | |
Tim Peters | 82076ef | 2004-09-13 00:52:51 +0000 | [diff] [blame] | 1832 | # For backward compatibility, a global instance of a DocTestRunner |
| 1833 | # class, updated by testmod. |
| 1834 | master = None |
| 1835 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1836 | def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1837 | report=True, optionflags=0, extraglobs=None, |
Tim Peters | 958cc89 | 2004-09-13 14:53:28 +0000 | [diff] [blame] | 1838 | raise_on_error=False, exclude_empty=False): |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1839 | """m=None, name=None, globs=None, verbose=None, isprivate=None, |
Tim Peters | 958cc89 | 2004-09-13 14:53:28 +0000 | [diff] [blame] | 1840 | report=True, optionflags=0, extraglobs=None, raise_on_error=False, |
| 1841 | exclude_empty=False |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1842 | |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1843 | Test examples in docstrings in functions and classes reachable |
| 1844 | 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] | 1845 | with m.__doc__. Unless isprivate is specified, private names |
| 1846 | are not skipped. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1847 | |
| 1848 | 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] | 1849 | not None. m.__test__ maps names to functions, classes and strings; |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1850 | function and class docstrings are tested even if the name is private; |
| 1851 | strings are tested directly, as if they were docstrings. |
| 1852 | |
| 1853 | Return (#failures, #tests). |
| 1854 | |
| 1855 | See doctest.__doc__ for an overview. |
| 1856 | |
| 1857 | Optional keyword arg "name" gives the name of the module; by default |
| 1858 | use m.__name__. |
| 1859 | |
| 1860 | Optional keyword arg "globs" gives a dict to be used as the globals |
| 1861 | when executing examples; by default, use m.__dict__. A copy of this |
| 1862 | dict is actually used for each docstring, so that each docstring's |
| 1863 | examples start with a clean slate. |
| 1864 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1865 | Optional keyword arg "extraglobs" gives a dictionary that should be |
| 1866 | merged into the globals that are used to execute examples. By |
| 1867 | default, no extra globals are used. This is new in 2.4. |
| 1868 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1869 | Optional keyword arg "verbose" prints lots of stuff if true, prints |
| 1870 | only failures if false; by default, it's true iff "-v" is in sys.argv. |
| 1871 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1872 | Optional keyword arg "report" prints a summary at the end when true, |
| 1873 | else prints nothing at the end. In verbose mode, the summary is |
| 1874 | detailed, else very brief (in fact, empty if all tests passed). |
| 1875 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1876 | Optional keyword arg "optionflags" or's together module constants, |
Tim Peters | f82a9de | 2004-08-22 20:51:53 +0000 | [diff] [blame] | 1877 | and defaults to 0. This is new in 2.3. Possible values (see the |
| 1878 | docs for details): |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 1879 | |
| 1880 | DONT_ACCEPT_TRUE_FOR_1 |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1881 | DONT_ACCEPT_BLANKLINE |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1882 | NORMALIZE_WHITESPACE |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1883 | ELLIPSIS |
Edward Loper | 71f55af | 2004-08-26 01:41:51 +0000 | [diff] [blame] | 1884 | REPORT_UDIFF |
| 1885 | REPORT_CDIFF |
| 1886 | REPORT_NDIFF |
Edward Loper | a89f88d | 2004-08-26 02:45:51 +0000 | [diff] [blame] | 1887 | REPORT_ONLY_FIRST_FAILURE |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1888 | |
| 1889 | Optional keyword arg "raise_on_error" raises an exception on the |
| 1890 | first unexpected exception or failure. This allows failures to be |
| 1891 | post-mortem debugged. |
| 1892 | |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 1893 | Deprecated in Python 2.4: |
| 1894 | Optional keyword arg "isprivate" specifies a function used to |
| 1895 | determine whether a name is private. The default function is |
| 1896 | treat all functions as public. Optionally, "isprivate" can be |
| 1897 | set to doctest.is_private to skip over functions marked as private |
| 1898 | using the underscore naming convention; see its docs for details. |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1899 | """ |
| 1900 | |
| 1901 | """ [XX] This is no longer true: |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1902 | Advanced tomfoolery: testmod runs methods of a local instance of |
| 1903 | class doctest.Tester, then merges the results into (or creates) |
| 1904 | global Tester instance doctest.master. Methods of doctest.master |
| 1905 | can be called directly too, if you want to do something unusual. |
| 1906 | Passing report=0 to testmod is especially useful then, to delay |
| 1907 | displaying a summary. Invoke doctest.master.summarize(verbose) |
| 1908 | when you're done fiddling. |
| 1909 | """ |
Tim Peters | 82076ef | 2004-09-13 00:52:51 +0000 | [diff] [blame] | 1910 | global master |
| 1911 | |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 1912 | if isprivate is not None: |
| 1913 | warnings.warn("the isprivate argument is deprecated; " |
| 1914 | "examine DocTestFinder.find() lists instead", |
| 1915 | DeprecationWarning) |
| 1916 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1917 | # If no module was given, then use __main__. |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1918 | if m is None: |
Martin v. Löwis | 4581cfa | 2002-11-22 08:23:09 +0000 | [diff] [blame] | 1919 | # DWA - m will still be None if this wasn't invoked from the command |
| 1920 | # line, in which case the following TypeError is about as good an error |
| 1921 | # as we should expect |
| 1922 | m = sys.modules.get('__main__') |
| 1923 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1924 | # Check that we were actually given a module. |
| 1925 | if not inspect.ismodule(m): |
Walter Dörwald | 70a6b49 | 2004-02-12 17:35:32 +0000 | [diff] [blame] | 1926 | raise TypeError("testmod: module required; %r" % (m,)) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1927 | |
| 1928 | # If no name was given, then use the module's name. |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1929 | if name is None: |
| 1930 | name = m.__name__ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1931 | |
| 1932 | # Find, parse, and run all tests in the given module. |
Tim Peters | 958cc89 | 2004-09-13 14:53:28 +0000 | [diff] [blame] | 1933 | finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 1934 | |
| 1935 | if raise_on_error: |
| 1936 | runner = DebugRunner(verbose=verbose, optionflags=optionflags) |
| 1937 | else: |
| 1938 | runner = DocTestRunner(verbose=verbose, optionflags=optionflags) |
| 1939 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1940 | for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): |
| 1941 | runner.run(test) |
| 1942 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1943 | if report: |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1944 | runner.summarize() |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 1945 | |
Tim Peters | 82076ef | 2004-09-13 00:52:51 +0000 | [diff] [blame] | 1946 | if master is None: |
| 1947 | master = runner |
| 1948 | else: |
| 1949 | master.merge(runner) |
| 1950 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1951 | return runner.failures, runner.tries |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1952 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1953 | def run_docstring_examples(f, globs, verbose=False, name="NoName", |
| 1954 | compileflags=None, optionflags=0): |
| 1955 | """ |
| 1956 | Test examples in the given object's docstring (`f`), using `globs` |
| 1957 | as globals. Optional argument `name` is used in failure messages. |
| 1958 | If the optional argument `verbose` is true, then generate output |
| 1959 | even if there are no failures. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1960 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1961 | `compileflags` gives the set of flags that should be used by the |
| 1962 | Python compiler when running the examples. If not specified, then |
| 1963 | it will default to the set of future-import flags that apply to |
| 1964 | `globs`. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1965 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1966 | Optional keyword arg `optionflags` specifies options for the |
| 1967 | testing and output. See the documentation for `testmod` for more |
| 1968 | information. |
| 1969 | """ |
| 1970 | # Find, parse, and run all tests in the given module. |
| 1971 | finder = DocTestFinder(verbose=verbose, recurse=False) |
| 1972 | runner = DocTestRunner(verbose=verbose, optionflags=optionflags) |
| 1973 | for test in finder.find(f, name, globs=globs): |
| 1974 | runner.run(test, compileflags=compileflags) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1975 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1976 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 1977 | ## 7. Tester |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1978 | ###################################################################### |
| 1979 | # This is provided only for backwards compatibility. It's not |
| 1980 | # actually used in any way. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1981 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1982 | class Tester: |
| 1983 | def __init__(self, mod=None, globs=None, verbose=None, |
| 1984 | isprivate=None, optionflags=0): |
Tim Peters | 3ddd60a | 2004-08-08 02:43:33 +0000 | [diff] [blame] | 1985 | |
| 1986 | warnings.warn("class Tester is deprecated; " |
| 1987 | "use class doctest.DocTestRunner instead", |
| 1988 | DeprecationWarning, stacklevel=2) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1989 | if mod is None and globs is None: |
| 1990 | raise TypeError("Tester.__init__: must specify mod or globs") |
Tim Peters | 4be7a92 | 2004-09-12 22:39:46 +0000 | [diff] [blame] | 1991 | if mod is not None and not inspect.ismodule(mod): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1992 | raise TypeError("Tester.__init__: mod must be a module; %r" % |
| 1993 | (mod,)) |
| 1994 | if globs is None: |
| 1995 | globs = mod.__dict__ |
| 1996 | self.globs = globs |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 1997 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 1998 | self.verbose = verbose |
| 1999 | self.isprivate = isprivate |
| 2000 | self.optionflags = optionflags |
Tim Peters | f727c6c | 2004-08-08 01:48:59 +0000 | [diff] [blame] | 2001 | self.testfinder = DocTestFinder(_namefilter=isprivate) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2002 | self.testrunner = DocTestRunner(verbose=verbose, |
| 2003 | optionflags=optionflags) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2004 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2005 | def runstring(self, s, name): |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 2006 | test = DocTestParser().get_doctest(s, self.globs, name, None, None) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2007 | if self.verbose: |
| 2008 | print "Running string", name |
| 2009 | (f,t) = self.testrunner.run(test) |
| 2010 | if self.verbose: |
| 2011 | print f, "of", t, "examples failed in string", name |
| 2012 | return (f,t) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2013 | |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 2014 | def rundoc(self, object, name=None, module=None): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2015 | f = t = 0 |
| 2016 | tests = self.testfinder.find(object, name, module=module, |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 2017 | globs=self.globs) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2018 | for test in tests: |
| 2019 | (f2, t2) = self.testrunner.run(test) |
| 2020 | (f,t) = (f+f2, t+t2) |
| 2021 | return (f,t) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2022 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2023 | def rundict(self, d, name, module=None): |
| 2024 | import new |
| 2025 | m = new.module(name) |
| 2026 | m.__dict__.update(d) |
Tim Peters | f3f5747 | 2004-08-08 06:11:48 +0000 | [diff] [blame] | 2027 | if module is None: |
| 2028 | module = False |
| 2029 | return self.rundoc(m, name, module) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2030 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2031 | def run__test__(self, d, name): |
| 2032 | import new |
| 2033 | m = new.module(name) |
| 2034 | m.__test__ = d |
Tim Peters | 9661f9a | 2004-09-12 22:45:17 +0000 | [diff] [blame] | 2035 | return self.rundoc(m, name) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2036 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2037 | def summarize(self, verbose=None): |
| 2038 | return self.testrunner.summarize(verbose) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2039 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2040 | def merge(self, other): |
Tim Peters | 82076ef | 2004-09-13 00:52:51 +0000 | [diff] [blame] | 2041 | self.testrunner.merge(other.testrunner) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2042 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2043 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 2044 | ## 8. Unittest Support |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2045 | ###################################################################### |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2046 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2047 | _unittest_reportflags = 0 |
Tim Peters | 38330fe | 2004-08-30 16:19:24 +0000 | [diff] [blame] | 2048 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2049 | def set_unittest_reportflags(flags): |
Tim Peters | 38330fe | 2004-08-30 16:19:24 +0000 | [diff] [blame] | 2050 | """Sets the unittest option flags. |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2051 | |
| 2052 | The old flag is returned so that a runner could restore the old |
| 2053 | value if it wished to: |
| 2054 | |
| 2055 | >>> old = _unittest_reportflags |
| 2056 | >>> set_unittest_reportflags(REPORT_NDIFF | |
| 2057 | ... REPORT_ONLY_FIRST_FAILURE) == old |
| 2058 | True |
| 2059 | |
| 2060 | >>> import doctest |
| 2061 | >>> doctest._unittest_reportflags == (REPORT_NDIFF | |
| 2062 | ... REPORT_ONLY_FIRST_FAILURE) |
| 2063 | True |
Tim Peters | df7a208 | 2004-08-29 00:38:17 +0000 | [diff] [blame] | 2064 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2065 | Only reporting flags can be set: |
| 2066 | |
| 2067 | >>> set_unittest_reportflags(ELLIPSIS) |
| 2068 | Traceback (most recent call last): |
| 2069 | ... |
Tim Peters | 38330fe | 2004-08-30 16:19:24 +0000 | [diff] [blame] | 2070 | ValueError: ('Only reporting flags allowed', 8) |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2071 | |
| 2072 | >>> set_unittest_reportflags(old) == (REPORT_NDIFF | |
| 2073 | ... REPORT_ONLY_FIRST_FAILURE) |
| 2074 | True |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2075 | """ |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2076 | global _unittest_reportflags |
Tim Peters | 38330fe | 2004-08-30 16:19:24 +0000 | [diff] [blame] | 2077 | |
| 2078 | if (flags & REPORTING_FLAGS) != flags: |
| 2079 | raise ValueError("Only reporting flags allowed", flags) |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2080 | old = _unittest_reportflags |
| 2081 | _unittest_reportflags = flags |
| 2082 | return old |
Tim Peters | df7a208 | 2004-08-29 00:38:17 +0000 | [diff] [blame] | 2083 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2084 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2085 | class DocTestCase(unittest.TestCase): |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2086 | |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 2087 | def __init__(self, test, optionflags=0, setUp=None, tearDown=None, |
| 2088 | checker=None): |
Jim Fulton | 07a349c | 2004-08-22 14:10:00 +0000 | [diff] [blame] | 2089 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2090 | unittest.TestCase.__init__(self) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2091 | self._dt_optionflags = optionflags |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 2092 | self._dt_checker = checker |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2093 | self._dt_test = test |
| 2094 | self._dt_setUp = setUp |
| 2095 | self._dt_tearDown = tearDown |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2096 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2097 | def setUp(self): |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2098 | test = self._dt_test |
Tim Peters | df7a208 | 2004-08-29 00:38:17 +0000 | [diff] [blame] | 2099 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2100 | if self._dt_setUp is not None: |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2101 | self._dt_setUp(test) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2102 | |
| 2103 | def tearDown(self): |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2104 | test = self._dt_test |
| 2105 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2106 | if self._dt_tearDown is not None: |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2107 | self._dt_tearDown(test) |
| 2108 | |
| 2109 | test.globs.clear() |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2110 | |
| 2111 | def runTest(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2112 | test = self._dt_test |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2113 | old = sys.stdout |
| 2114 | new = StringIO() |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2115 | optionflags = self._dt_optionflags |
Tim Peters | df7a208 | 2004-08-29 00:38:17 +0000 | [diff] [blame] | 2116 | |
Tim Peters | 38330fe | 2004-08-30 16:19:24 +0000 | [diff] [blame] | 2117 | if not (optionflags & REPORTING_FLAGS): |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2118 | # The option flags don't include any reporting flags, |
| 2119 | # so add the default reporting flags |
| 2120 | optionflags |= _unittest_reportflags |
Tim Peters | df7a208 | 2004-08-29 00:38:17 +0000 | [diff] [blame] | 2121 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2122 | runner = DocTestRunner(optionflags=optionflags, |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 2123 | checker=self._dt_checker, verbose=False) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2124 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2125 | try: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2126 | runner.DIVIDER = "-"*70 |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2127 | failures, tries = runner.run( |
| 2128 | test, out=new.write, clear_globs=False) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2129 | finally: |
| 2130 | sys.stdout = old |
| 2131 | |
| 2132 | if failures: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2133 | raise self.failureException(self.format_failure(new.getvalue())) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2134 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2135 | def format_failure(self, err): |
| 2136 | test = self._dt_test |
| 2137 | if test.lineno is None: |
| 2138 | lineno = 'unknown line number' |
| 2139 | else: |
Jim Fulton | 07a349c | 2004-08-22 14:10:00 +0000 | [diff] [blame] | 2140 | lineno = '%s' % test.lineno |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2141 | lname = '.'.join(test.name.split('.')[-1:]) |
| 2142 | return ('Failed doctest test for %s\n' |
| 2143 | ' File "%s", line %s, in %s\n\n%s' |
| 2144 | % (test.name, test.filename, lineno, lname, err) |
| 2145 | ) |
| 2146 | |
| 2147 | def debug(self): |
| 2148 | r"""Run the test case without results and without catching exceptions |
| 2149 | |
| 2150 | The unit test framework includes a debug method on test cases |
| 2151 | and test suites to support post-mortem debugging. The test code |
| 2152 | is run in such a way that errors are not caught. This way a |
| 2153 | caller can catch the errors and initiate post-mortem debugging. |
| 2154 | |
| 2155 | The DocTestCase provides a debug method that raises |
| 2156 | UnexpectedException errors if there is an unexepcted |
| 2157 | exception: |
| 2158 | |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 2159 | >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2160 | ... {}, 'foo', 'foo.py', 0) |
| 2161 | >>> case = DocTestCase(test) |
| 2162 | >>> try: |
| 2163 | ... case.debug() |
| 2164 | ... except UnexpectedException, failure: |
| 2165 | ... pass |
| 2166 | |
| 2167 | The UnexpectedException contains the test, the example, and |
| 2168 | the original exception: |
| 2169 | |
| 2170 | >>> failure.test is test |
| 2171 | True |
| 2172 | |
| 2173 | >>> failure.example.want |
| 2174 | '42\n' |
| 2175 | |
| 2176 | >>> exc_info = failure.exc_info |
| 2177 | >>> raise exc_info[0], exc_info[1], exc_info[2] |
| 2178 | Traceback (most recent call last): |
| 2179 | ... |
| 2180 | KeyError |
| 2181 | |
| 2182 | If the output doesn't match, then a DocTestFailure is raised: |
| 2183 | |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 2184 | >>> test = DocTestParser().get_doctest(''' |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2185 | ... >>> x = 1 |
| 2186 | ... >>> x |
| 2187 | ... 2 |
| 2188 | ... ''', {}, 'foo', 'foo.py', 0) |
| 2189 | >>> case = DocTestCase(test) |
| 2190 | |
| 2191 | >>> try: |
| 2192 | ... case.debug() |
| 2193 | ... except DocTestFailure, failure: |
| 2194 | ... pass |
| 2195 | |
| 2196 | DocTestFailure objects provide access to the test: |
| 2197 | |
| 2198 | >>> failure.test is test |
| 2199 | True |
| 2200 | |
| 2201 | As well as to the example: |
| 2202 | |
| 2203 | >>> failure.example.want |
| 2204 | '2\n' |
| 2205 | |
| 2206 | and the actual output: |
| 2207 | |
| 2208 | >>> failure.got |
| 2209 | '1\n' |
| 2210 | |
| 2211 | """ |
| 2212 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2213 | self.setUp() |
Edward Loper | 34fcb14 | 2004-08-09 02:45:41 +0000 | [diff] [blame] | 2214 | runner = DebugRunner(optionflags=self._dt_optionflags, |
| 2215 | checker=self._dt_checker, verbose=False) |
Edward Loper | 3a3817f | 2004-08-19 19:26:06 +0000 | [diff] [blame] | 2216 | runner.run(self._dt_test) |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2217 | self.tearDown() |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2218 | |
| 2219 | def id(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2220 | return self._dt_test.name |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2221 | |
| 2222 | def __repr__(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2223 | name = self._dt_test.name.split('.') |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2224 | return "%s (%s)" % (name[-1], '.'.join(name[:-1])) |
| 2225 | |
| 2226 | __str__ = __repr__ |
| 2227 | |
| 2228 | def shortDescription(self): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2229 | return "Doctest: " + self._dt_test.name |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2230 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2231 | def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, |
| 2232 | **options): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2233 | """ |
Tim Peters | 75dc5e1 | 2004-08-22 17:50:45 +0000 | [diff] [blame] | 2234 | Convert doctest tests for a module to a unittest test suite. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2235 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2236 | This converts each documentation string in a module that |
| 2237 | contains doctest tests to a unittest test case. If any of the |
| 2238 | tests in a doc string fail, then the test case fails. An exception |
| 2239 | 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] | 2240 | (sometimes approximate) line number. |
| 2241 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2242 | The `module` argument provides the module to be tested. The argument |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2243 | can be either a module or a module name. |
| 2244 | |
| 2245 | If no argument is given, the calling module is used. |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2246 | |
| 2247 | A number of options may be provided as keyword arguments: |
| 2248 | |
| 2249 | package |
| 2250 | The name of a Python package. Text-file paths will be |
| 2251 | interpreted relative to the directory containing this package. |
| 2252 | The package may be supplied as a package object or as a dotted |
| 2253 | package name. |
| 2254 | |
| 2255 | setUp |
| 2256 | The name of a set-up function. This is called before running the |
| 2257 | tests in each file. The setUp function will be passed a DocTest |
| 2258 | object. The setUp function can access the test globals as the |
| 2259 | globs attribute of the test passed. |
| 2260 | |
| 2261 | tearDown |
| 2262 | The name of a tear-down function. This is called after running the |
| 2263 | tests in each file. The tearDown function will be passed a DocTest |
| 2264 | object. The tearDown function can access the test globals as the |
| 2265 | globs attribute of the test passed. |
| 2266 | |
| 2267 | globs |
| 2268 | A dictionary containing initial global variables for the tests. |
| 2269 | |
| 2270 | optionflags |
| 2271 | A set of doctest option flags expressed as an integer. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2272 | """ |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2273 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2274 | if test_finder is None: |
| 2275 | test_finder = DocTestFinder() |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2276 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2277 | module = _normalize_module(module) |
| 2278 | tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) |
| 2279 | if globs is None: |
| 2280 | globs = module.__dict__ |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2281 | if not tests: |
| 2282 | # Why do we want to do this? Because it reveals a bug that might |
| 2283 | # otherwise be hidden. |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2284 | raise ValueError(module, "has no tests") |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2285 | |
| 2286 | tests.sort() |
| 2287 | suite = unittest.TestSuite() |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2288 | for test in tests: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2289 | if len(test.examples) == 0: |
| 2290 | continue |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2291 | if not test.filename: |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2292 | filename = module.__file__ |
Jim Fulton | 07a349c | 2004-08-22 14:10:00 +0000 | [diff] [blame] | 2293 | if filename[-4:] in (".pyc", ".pyo"): |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2294 | filename = filename[:-1] |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2295 | test.filename = filename |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2296 | suite.addTest(DocTestCase(test, **options)) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2297 | |
| 2298 | return suite |
| 2299 | |
| 2300 | class DocFileCase(DocTestCase): |
| 2301 | |
| 2302 | def id(self): |
| 2303 | return '_'.join(self._dt_test.name.split('.')) |
| 2304 | |
| 2305 | def __repr__(self): |
| 2306 | return self._dt_test.filename |
| 2307 | __str__ = __repr__ |
| 2308 | |
| 2309 | def format_failure(self, err): |
| 2310 | return ('Failed doctest test for %s\n File "%s", line 0\n\n%s' |
| 2311 | % (self._dt_test.name, self._dt_test.filename, err) |
| 2312 | ) |
| 2313 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2314 | def DocFileTest(path, package=None, globs=None, **options): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2315 | package = _normalize_module(package) |
| 2316 | name = path.split('/')[-1] |
| 2317 | dir = os.path.split(package.__file__)[0] |
| 2318 | path = os.path.join(dir, *(path.split('/'))) |
| 2319 | doc = open(path).read() |
| 2320 | |
| 2321 | if globs is None: |
| 2322 | globs = {} |
| 2323 | |
Edward Loper | a1ef611 | 2004-08-09 16:14:41 +0000 | [diff] [blame] | 2324 | test = DocTestParser().get_doctest(doc, globs, name, path, 0) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2325 | |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2326 | return DocFileCase(test, **options) |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2327 | |
| 2328 | def DocFileSuite(*paths, **kw): |
| 2329 | """Creates a suite of doctest files. |
| 2330 | |
| 2331 | One or more text file paths are given as strings. These should |
| 2332 | use "/" characters to separate path segments. Paths are relative |
| 2333 | to the directory of the calling module, or relative to the package |
| 2334 | passed as a keyword argument. |
| 2335 | |
| 2336 | A number of options may be provided as keyword arguments: |
| 2337 | |
| 2338 | package |
| 2339 | The name of a Python package. Text-file paths will be |
| 2340 | interpreted relative to the directory containing this package. |
| 2341 | The package may be supplied as a package object or as a dotted |
| 2342 | package name. |
| 2343 | |
| 2344 | setUp |
| 2345 | 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] | 2346 | tests in each file. The setUp function will be passed a DocTest |
| 2347 | object. The setUp function can access the test globals as the |
| 2348 | globs attribute of the test passed. |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2349 | |
| 2350 | tearDown |
| 2351 | 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] | 2352 | tests in each file. The tearDown function will be passed a DocTest |
| 2353 | object. The tearDown function can access the test globals as the |
| 2354 | globs attribute of the test passed. |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2355 | |
| 2356 | globs |
| 2357 | A dictionary containing initial global variables for the tests. |
Jim Fulton | f54bad4 | 2004-08-28 14:57:56 +0000 | [diff] [blame] | 2358 | |
| 2359 | optionflags |
| 2360 | A set of doctest option flags expressed as an integer. |
Tim Peters | df7a208 | 2004-08-29 00:38:17 +0000 | [diff] [blame] | 2361 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2362 | """ |
| 2363 | suite = unittest.TestSuite() |
| 2364 | |
| 2365 | # We do this here so that _normalize_module is called at the right |
| 2366 | # level. If it were called in DocFileTest, then this function |
| 2367 | # would be the caller and we might guess the package incorrectly. |
| 2368 | kw['package'] = _normalize_module(kw.get('package')) |
| 2369 | |
| 2370 | for path in paths: |
| 2371 | suite.addTest(DocFileTest(path, **kw)) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2372 | |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2373 | return suite |
| 2374 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2375 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 2376 | ## 9. Debugging Support |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2377 | ###################################################################### |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2378 | |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2379 | def script_from_examples(s): |
| 2380 | r"""Extract script from text with examples. |
| 2381 | |
| 2382 | Converts text with examples to a Python script. Example input is |
| 2383 | converted to regular code. Example output and all other words |
| 2384 | are converted to comments: |
| 2385 | |
| 2386 | >>> text = ''' |
| 2387 | ... Here are examples of simple math. |
| 2388 | ... |
| 2389 | ... Python has super accurate integer addition |
| 2390 | ... |
| 2391 | ... >>> 2 + 2 |
| 2392 | ... 5 |
| 2393 | ... |
| 2394 | ... And very friendly error messages: |
| 2395 | ... |
| 2396 | ... >>> 1/0 |
| 2397 | ... To Infinity |
| 2398 | ... And |
| 2399 | ... Beyond |
| 2400 | ... |
| 2401 | ... You can use logic if you want: |
| 2402 | ... |
| 2403 | ... >>> if 0: |
| 2404 | ... ... blah |
| 2405 | ... ... blah |
| 2406 | ... ... |
| 2407 | ... |
| 2408 | ... Ho hum |
| 2409 | ... ''' |
| 2410 | |
| 2411 | >>> print script_from_examples(text) |
Edward Loper | a5db600 | 2004-08-12 02:41:30 +0000 | [diff] [blame] | 2412 | # Here are examples of simple math. |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2413 | # |
Edward Loper | a5db600 | 2004-08-12 02:41:30 +0000 | [diff] [blame] | 2414 | # Python has super accurate integer addition |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2415 | # |
| 2416 | 2 + 2 |
| 2417 | # Expected: |
Edward Loper | a5db600 | 2004-08-12 02:41:30 +0000 | [diff] [blame] | 2418 | ## 5 |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2419 | # |
Edward Loper | a5db600 | 2004-08-12 02:41:30 +0000 | [diff] [blame] | 2420 | # And very friendly error messages: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2421 | # |
| 2422 | 1/0 |
| 2423 | # Expected: |
Edward Loper | a5db600 | 2004-08-12 02:41:30 +0000 | [diff] [blame] | 2424 | ## To Infinity |
| 2425 | ## And |
| 2426 | ## Beyond |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2427 | # |
Edward Loper | a5db600 | 2004-08-12 02:41:30 +0000 | [diff] [blame] | 2428 | # You can use logic if you want: |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2429 | # |
| 2430 | if 0: |
| 2431 | blah |
| 2432 | blah |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2433 | # |
Edward Loper | a5db600 | 2004-08-12 02:41:30 +0000 | [diff] [blame] | 2434 | # Ho hum |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2435 | """ |
Edward Loper | 00f8da7 | 2004-08-26 18:05:07 +0000 | [diff] [blame] | 2436 | output = [] |
| 2437 | for piece in DocTestParser().parse(s): |
| 2438 | if isinstance(piece, Example): |
| 2439 | # Add the example's source code (strip trailing NL) |
| 2440 | output.append(piece.source[:-1]) |
| 2441 | # Add the expected output: |
| 2442 | want = piece.want |
| 2443 | if want: |
| 2444 | output.append('# Expected:') |
| 2445 | output += ['## '+l for l in want.split('\n')[:-1]] |
| 2446 | else: |
| 2447 | # Add non-example text. |
| 2448 | output += [_comment_line(l) |
| 2449 | for l in piece.split('\n')[:-1]] |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2450 | |
Edward Loper | 00f8da7 | 2004-08-26 18:05:07 +0000 | [diff] [blame] | 2451 | # Trim junk on both ends. |
| 2452 | while output and output[-1] == '#': |
| 2453 | output.pop() |
| 2454 | while output and output[0] == '#': |
| 2455 | output.pop(0) |
| 2456 | # Combine the output, and return it. |
| 2457 | return '\n'.join(output) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2458 | |
| 2459 | def testsource(module, name): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2460 | """Extract the test sources from a doctest docstring as a script. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2461 | |
| 2462 | Provide the module (or dotted name of the module) containing the |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2463 | test to be debugged and the name (within the module) of the object |
| 2464 | with the doc string with tests to be debugged. |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2465 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2466 | module = _normalize_module(module) |
| 2467 | tests = DocTestFinder().find(module) |
| 2468 | test = [t for t in tests if t.name == name] |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2469 | if not test: |
| 2470 | raise ValueError(name, "not found in tests") |
| 2471 | test = test[0] |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2472 | testsrc = script_from_examples(test.docstring) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2473 | return testsrc |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2474 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2475 | def debug_src(src, pm=False, globs=None): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2476 | """Debug a single doctest docstring, in argument `src`'""" |
| 2477 | testsrc = script_from_examples(src) |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2478 | debug_script(testsrc, pm, globs) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2479 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2480 | def debug_script(src, pm=False, globs=None): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2481 | "Debug a test script. `src` is the script, as a string." |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2482 | import pdb |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2483 | |
Tim Peters | b6a04d6 | 2004-08-23 21:37:56 +0000 | [diff] [blame] | 2484 | # Note that tempfile.NameTemporaryFile() cannot be used. As the |
| 2485 | # docs say, a file so created cannot be opened by name a second time |
| 2486 | # on modern Windows boxes, and execfile() needs to open it. |
| 2487 | srcfilename = tempfile.mktemp(".py", "doctestdebug") |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2488 | f = open(srcfilename, 'w') |
| 2489 | f.write(src) |
| 2490 | f.close() |
| 2491 | |
Tim Peters | b6a04d6 | 2004-08-23 21:37:56 +0000 | [diff] [blame] | 2492 | try: |
| 2493 | if globs: |
| 2494 | globs = globs.copy() |
| 2495 | else: |
| 2496 | globs = {} |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2497 | |
Tim Peters | b6a04d6 | 2004-08-23 21:37:56 +0000 | [diff] [blame] | 2498 | if pm: |
| 2499 | try: |
| 2500 | execfile(srcfilename, globs, globs) |
| 2501 | except: |
| 2502 | print sys.exc_info()[1] |
| 2503 | pdb.post_mortem(sys.exc_info()[2]) |
| 2504 | else: |
| 2505 | # Note that %r is vital here. '%s' instead can, e.g., cause |
| 2506 | # backslashes to get treated as metacharacters on Windows. |
| 2507 | pdb.run("execfile(%r)" % srcfilename, globs, globs) |
| 2508 | |
| 2509 | finally: |
| 2510 | os.remove(srcfilename) |
Tim Peters | db3756d | 2003-06-29 05:30:48 +0000 | [diff] [blame] | 2511 | |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2512 | def debug(module, name, pm=False): |
Tim Peters | 19397e5 | 2004-08-06 22:02:59 +0000 | [diff] [blame] | 2513 | """Debug a single doctest docstring. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2514 | |
| 2515 | Provide the module (or dotted name of the module) containing the |
| 2516 | 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] | 2517 | with the docstring with tests to be debugged. |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2518 | """ |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2519 | module = _normalize_module(module) |
Jim Fulton | a643b65 | 2004-07-14 19:06:50 +0000 | [diff] [blame] | 2520 | testsrc = testsource(module, name) |
| 2521 | debug_script(testsrc, pm, module.__dict__) |
| 2522 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2523 | ###################################################################### |
Edward Loper | 7c74846 | 2004-08-09 02:06:06 +0000 | [diff] [blame] | 2524 | ## 10. Example Usage |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2525 | ###################################################################### |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2526 | class _TestClass: |
| 2527 | """ |
| 2528 | A pointless class, for sanity-checking of docstring testing. |
| 2529 | |
| 2530 | Methods: |
| 2531 | square() |
| 2532 | get() |
| 2533 | |
| 2534 | >>> _TestClass(13).get() + _TestClass(-12).get() |
| 2535 | 1 |
| 2536 | >>> hex(_TestClass(13).square().get()) |
| 2537 | '0xa9' |
| 2538 | """ |
| 2539 | |
| 2540 | def __init__(self, val): |
| 2541 | """val -> _TestClass object with associated value val. |
| 2542 | |
| 2543 | >>> t = _TestClass(123) |
| 2544 | >>> print t.get() |
| 2545 | 123 |
| 2546 | """ |
| 2547 | |
| 2548 | self.val = val |
| 2549 | |
| 2550 | def square(self): |
| 2551 | """square() -> square TestClass's associated value |
| 2552 | |
| 2553 | >>> _TestClass(13).square().get() |
| 2554 | 169 |
| 2555 | """ |
| 2556 | |
| 2557 | self.val = self.val ** 2 |
| 2558 | return self |
| 2559 | |
| 2560 | def get(self): |
| 2561 | """get() -> return TestClass's associated value. |
| 2562 | |
| 2563 | >>> x = _TestClass(-42) |
| 2564 | >>> print x.get() |
| 2565 | -42 |
| 2566 | """ |
| 2567 | |
| 2568 | return self.val |
| 2569 | |
| 2570 | __test__ = {"_TestClass": _TestClass, |
| 2571 | "string": r""" |
| 2572 | Example of a string object, searched as-is. |
| 2573 | >>> x = 1; y = 2 |
| 2574 | >>> x + y, x * y |
| 2575 | (3, 2) |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 2576 | """, |
Tim Peters | 3fa8c20 | 2004-08-23 21:43:39 +0000 | [diff] [blame] | 2577 | |
Tim Peters | 6ebe61f | 2003-06-27 20:48:05 +0000 | [diff] [blame] | 2578 | "bool-int equivalence": r""" |
| 2579 | In 2.2, boolean expressions displayed |
| 2580 | 0 or 1. By default, we still accept |
| 2581 | them. This can be disabled by passing |
| 2582 | DONT_ACCEPT_TRUE_FOR_1 to the new |
| 2583 | optionflags argument. |
| 2584 | >>> 4 == 4 |
| 2585 | 1 |
| 2586 | >>> 4 == 4 |
| 2587 | True |
| 2588 | >>> 4 > 4 |
| 2589 | 0 |
| 2590 | >>> 4 > 4 |
| 2591 | False |
| 2592 | """, |
Tim Peters | 3fa8c20 | 2004-08-23 21:43:39 +0000 | [diff] [blame] | 2593 | |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2594 | "blank lines": r""" |
Tim Peters | 3fa8c20 | 2004-08-23 21:43:39 +0000 | [diff] [blame] | 2595 | Blank lines can be marked with <BLANKLINE>: |
| 2596 | >>> print 'foo\n\nbar\n' |
| 2597 | foo |
| 2598 | <BLANKLINE> |
| 2599 | bar |
| 2600 | <BLANKLINE> |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2601 | """, |
Tim Peters | 3fa8c20 | 2004-08-23 21:43:39 +0000 | [diff] [blame] | 2602 | |
| 2603 | "ellipsis": r""" |
| 2604 | If the ellipsis flag is used, then '...' can be used to |
| 2605 | elide substrings in the desired output: |
| 2606 | >>> print range(1000) #doctest: +ELLIPSIS |
| 2607 | [0, 1, 2, ..., 999] |
| 2608 | """, |
| 2609 | |
| 2610 | "whitespace normalization": r""" |
| 2611 | If the whitespace normalization flag is used, then |
| 2612 | differences in whitespace are ignored. |
| 2613 | >>> print range(30) #doctest: +NORMALIZE_WHITESPACE |
| 2614 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, |
| 2615 | 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, |
| 2616 | 27, 28, 29] |
| 2617 | """, |
| 2618 | } |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2619 | |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2620 | def _test(): |
Tim Peters | 8485b56 | 2004-08-04 18:46:34 +0000 | [diff] [blame] | 2621 | r = unittest.TextTestRunner() |
| 2622 | r.run(DocTestSuite()) |
Tim Peters | 8a7d2d5 | 2001-01-16 07:10:57 +0000 | [diff] [blame] | 2623 | |
| 2624 | if __name__ == "__main__": |
| 2625 | _test() |