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