Debian Codegraph @

lib-python/3/doctest.py

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