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