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