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