2
# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
3
# Major enhancements and refactoring by:
7
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
9
r"""Module doctest -- a framework for running examples in docstrings.
11
In simplest use, end each module M to be tested with:
17
if __name__ == "__main__":
20
Then running the module as a script will cause the examples in the
21
docstrings to get executed and verified:
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.".
30
Run it with the -v switch instead:
34
and a detailed report of all examples tried is printed to stdout, along
35
with assorted summaries at the end.
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
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
48
__docformat__ = 'reStructuredText en'
52
'register_optionflag',
53
'DONT_ACCEPT_TRUE_FOR_1',
54
'DONT_ACCEPT_BLANKLINE',
55
'NORMALIZE_WHITESPACE',
57
'IGNORE_EXCEPTION_DETAIL',
62
'REPORT_ONLY_FIRST_FAILURE',
64
# 1. Utility Functions
66
# 2. Example & DocTest
77
'UnexpectedException',
82
'run_docstring_examples',
88
'set_unittest_reportflags',
89
# 9. Debugging Support
90
'script_from_examples',
99
import sys, traceback, inspect, linecache, os, re
100
import unittest, difflib, pdb, tempfile
102
from doctest import DocTestFailure, UnexpectedException
103
from StringIO import StringIO
104
from zope.testing.exceptions import DocTestFailureException
106
# Don't whine about the deprecated is_private function in this
108
warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
111
# Tell people to use the builtin module instead.
112
warnings.warn('zope.testing.doctest is deprecated in favour of '
113
'the Python standard library doctest module', DeprecationWarning,
116
class UnusedFootnoteWarning(Warning):
117
"""Warn about a footnote that is defined, but never referenced."""
119
real_pdb_set_trace = pdb.set_trace
121
# There are 4 basic classes:
122
# - Example: a <source, want> pair, plus an intra-docstring line number.
123
# - DocTest: a collection of examples, parsed from a docstring, plus
124
# info about where the docstring came from (name, filename, lineno).
125
# - DocTestFinder: extracts DocTests from a given object's docstring and
126
# its contained objects' docstrings.
127
# - DocTestRunner: runs DocTest cases, and accumulates statistics.
129
# So the basic picture is:
132
# +------+ +---------+ +-------+
133
# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
134
# +------+ +---------+ +-------+
142
from doctest import register_optionflag, \
143
OPTIONFLAGS_BY_NAME, \
144
DONT_ACCEPT_TRUE_FOR_1, \
145
DONT_ACCEPT_BLANKLINE, \
146
NORMALIZE_WHITESPACE, \
148
IGNORE_EXCEPTION_DETAIL, \
153
REPORT_ONLY_FIRST_FAILURE, \
156
INTERPRET_FOOTNOTES = register_optionflag('INTERPRET_FOOTNOTES')
158
# Special string markers for use in `want` strings:
159
BLANKLINE_MARKER = '<BLANKLINE>'
160
ELLIPSIS_MARKER = '...'
162
######################################################################
164
######################################################################
165
# 1. Utility Functions
166
# 2. Example & DocTest -- store test cases
167
# 3. DocTest Parser -- extracts examples from strings
168
# 4. DocTest Finder -- extracts test cases from objects
169
# 5. DocTest Runner -- runs test cases
170
# 6. Test Functions -- convenient wrappers for testing
171
# 7. Tester Class -- for backwards compatibility
172
# 8. Unittest Support
173
# 9. Debugging Support
176
######################################################################
177
## 1. Utility Functions
178
######################################################################
180
def is_private(prefix, base):
181
"""prefix, base -> true iff name prefix + "." + base is "private".
183
Prefix may be an empty string, and base does not contain a period.
184
Prefix is ignored (although functions you write conforming to this
185
protocol may make use of it).
186
Return true iff base begins with an (at least one) underscore, but
187
does not both begin and end with (at least) two underscores.
189
>>> is_private("a.b", "my_func")
191
>>> is_private("____", "_my_func")
193
>>> is_private("someclass", "__init__")
195
>>> is_private("sometypo", "__init_")
197
>>> is_private("x.y.z", "_")
199
>>> is_private("_x.y.z", "__")
201
>>> is_private("", "") # senseless but consistent
204
warnings.warn("is_private is deprecated; it wasn't useful; "
205
"examine DocTestFinder.find() lists instead",
206
DeprecationWarning, stacklevel=2)
207
return base[:1] == "_" and not base[:2] == "__" == base[-2:]
209
def _extract_future_flags(globs):
211
Return the compiler-flags associated with the future features that
212
have been imported into the given namespace (globs).
215
for fname in __future__.all_feature_names:
216
feature = globs.get(fname, None)
217
if feature is getattr(__future__, fname):
218
flags |= feature.compiler_flag
221
def _normalize_module(module, depth=2):
223
Return the module specified by `module`. In particular:
224
- If `module` is a module, then return module.
225
- If `module` is a string, then import and return the
226
module with that name.
227
- If `module` is None, then return the calling module.
228
The calling module is assumed to be the module of
229
the stack frame at the given depth in the call stack.
231
if inspect.ismodule(module):
233
elif isinstance(module, (str, unicode)):
234
return __import__(module, globals(), locals(), ["*"])
236
return sys.modules[sys._getframe(depth).f_globals['__name__']]
238
raise TypeError("Expected a module, string, or None")
240
def _indent(s, indent=4):
242
Add the given number of space characters to the beginning every
243
non-blank line in `s`, and return the result.
245
# This regexp matches the start of non-blank lines:
246
return re.sub('(?m)^(?!$)', indent*' ', s)
248
def _exception_traceback(exc_info):
250
Return a string containing a traceback message for the given
251
exc_info tuple (as returned by sys.exc_info()).
253
# Get a traceback message.
255
exc_type, exc_val, exc_tb = exc_info
256
traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
257
return excout.getvalue()
259
# Override some StringIO methods.
260
class _SpoofOut(StringIO):
262
result = StringIO.getvalue(self)
263
# If anything at all was written, make sure there's a trailing
264
# newline. There's no way for the expected output to indicate
265
# that a trailing newline is missing.
266
if result and not result.endswith("\n"):
268
# Prevent softspace from screwing up the next test case, in
269
# case they used print with a trailing comma in an example.
270
if hasattr(self, "softspace"):
274
def truncate(self, size=None):
275
StringIO.truncate(self, size)
276
if hasattr(self, "softspace"):
279
def write(self, value):
280
if isinstance(value, unicode):
281
value = value.encode('utf8')
282
StringIO.write(self, value)
284
# Worst-case linear-time ellipsis matching.
285
def _ellipsis_match(want, got):
287
Essentially the only subtle case:
288
>>> _ellipsis_match('aa...aa', 'aaa')
291
if ELLIPSIS_MARKER not in want:
294
# Find "the real" strings.
295
ws = want.split(ELLIPSIS_MARKER)
298
# Deal with exact matches possibly needed at one or both ends.
299
startpos, endpos = 0, len(got)
301
if w: # starts with exact match
302
if got.startswith(w):
308
if w: # ends with exact match
315
if startpos > endpos:
316
# Exact end matches required more characters than we have, as in
317
# _ellipsis_match('aa...aa', 'aaa')
320
# For the rest, we only need to find the leftmost non-overlapping
321
# match for each piece. If there's no overall match that way alone,
322
# there's no overall match period.
324
# w may be '' at times, if there are consecutive ellipses, or
325
# due to an ellipsis at the start or end of `want`. That's OK.
326
# Search for an empty string succeeds, and doesn't change startpos.
327
startpos = got.find(w, startpos, endpos)
334
def _comment_line(line):
335
"Return a commented form of the given line"
342
class _OutputRedirectingPdb(pdb.Pdb):
344
A specialized version of the python debugger that redirects stdout
345
to a given stream when interacting with the user. Stdout is *not*
346
redirected when traced code is executed.
348
def __init__(self, out):
350
self.__debugger_used = False
352
pdb.Pdb.__init__(self, stdin=sys.stdin, stdout=out)
354
pdb.Pdb.__init__(self)
356
self.use_rawinput = 1
359
self.__debugger_used = True
360
pdb.Pdb.set_trace(self)
362
def set_continue(self):
363
# Calling set_continue unconditionally would break unit test coverage
364
# reporting, as Bdb.set_continue calls sys.settrace(None).
365
if self.__debugger_used:
366
pdb.Pdb.set_continue(self)
368
def trace_dispatch(self, *args):
369
# Redirect stdout to the given stream.
370
save_stdout = sys.stdout
371
sys.stdout = self.__out
372
# Call Pdb's trace dispatch method.
373
result = pdb.Pdb.trace_dispatch(self, *args)
375
sys.stdout = save_stdout
378
# [XX] Normalize with respect to os.path.pardir?
379
def _module_relative_path(module, path):
380
if not inspect.ismodule(module):
381
raise TypeError('Expected a module: %r' % module)
382
if path.startswith('/'):
383
raise ValueError('Module-relative files may not have absolute paths')
385
# Find the base directory for the path.
386
if hasattr(module, '__file__'):
387
# A normal module/package
388
basedir = os.path.split(module.__file__)[0]
389
elif module.__name__ == '__main__':
390
# An interactive session.
391
if len(sys.argv)>0 and sys.argv[0] != '':
392
basedir = os.path.split(sys.argv[0])[0]
396
# A module w/o __file__ (this includes builtins)
397
raise ValueError("Can't resolve paths relative to the module " +
398
module + " (it has no __file__)")
400
# Combine the base directory and the path.
401
return os.path.join(basedir, *(path.split('/')))
403
######################################################################
404
## 2. Example & DocTest
405
######################################################################
406
## - An "example" is a <source, want> pair, where "source" is a
407
## fragment of source code, and "want" is the expected output for
408
## "source." The Example class also includes information about
409
## where the example was extracted from.
411
## - A "doctest" is a collection of examples, typically extracted from
412
## a string (such as an object's docstring). The DocTest class also
413
## includes information about where the string was extracted from.
417
A single doctest example, consisting of source code and expected
418
output. `Example` defines the following attributes:
420
- source: A single Python statement, always ending with a newline.
421
The constructor adds a newline if needed.
423
- want: The expected output from running the source code (either
424
from stdout, or a traceback in case of exception). `want` ends
425
with a newline unless it's empty, in which case it's an empty
426
string. The constructor adds a newline if needed.
428
- exc_msg: The exception message generated by the example, if
429
the example is expected to generate an exception; or `None` if
430
it is not expected to generate an exception. This exception
431
message is compared against the return value of
432
`traceback.format_exception_only()`. `exc_msg` ends with a
433
newline unless it's `None`. The constructor adds a newline
436
- lineno: The line number within the DocTest string containing
437
this Example where the Example begins. This line number is
438
zero-based, with respect to the beginning of the DocTest.
440
- indent: The example's indentation in the DocTest string.
441
I.e., the number of space characters that preceed the
442
example's first prompt.
444
- options: A dictionary mapping from option flags to True or
445
False, which is used to override default options for this
446
example. Any option flags not contained in this dictionary
447
are left at their default value (as specified by the
448
DocTestRunner's optionflags). By default, no options are set.
450
def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
453
if not source.endswith('\n'):
455
if want and not want.endswith('\n'):
457
if exc_msg is not None and not exc_msg.endswith('\n'):
464
if options is None: options = {}
465
self.options = options
466
self.exc_msg = exc_msg
470
A collection of doctest examples that should be run in a single
471
namespace. Each `DocTest` defines the following attributes:
473
- examples: the list of examples.
475
- globs: The namespace (aka globals) that the examples should
478
- name: A name identifying the DocTest (typically, the name of
479
the object whose docstring this DocTest was extracted from).
481
- filename: The name of the file that this DocTest was extracted
482
from, or `None` if the filename is unknown.
484
- lineno: The line number within filename where this DocTest
485
begins, or `None` if the line number is unavailable. This
486
line number is zero-based, with respect to the beginning of
489
- docstring: The string that the examples were extracted from,
490
or `None` if the string is unavailable.
492
def __init__(self, examples, globs, name, filename, lineno, docstring):
494
Create a new DocTest containing the given examples. The
495
DocTest's globals are initialized with a copy of `globs`.
497
assert not isinstance(examples, basestring), \
498
"DocTest no longer accepts str; use DocTestParser instead"
499
self.examples = examples
500
self.docstring = docstring
501
self.globs = globs.copy()
503
self.filename = filename
507
if len(self.examples) == 0:
508
examples = 'no examples'
509
elif len(self.examples) == 1:
510
examples = '1 example'
512
examples = '%d examples' % len(self.examples)
513
return ('<DocTest %s from %s:%s (%s)>' %
514
(self.name, self.filename, self.lineno, examples))
517
# This lets us sort tests by name:
518
def __cmp__(self, other):
519
if not isinstance(other, DocTest):
521
return cmp((self.name, self.filename, self.lineno, id(self)),
522
(other.name, other.filename, other.lineno, id(other)))
524
######################################################################
526
######################################################################
530
A class used to parse strings containing doctest examples.
532
# This regular expression is used to find doctest examples in a
533
# string. It defines three groups: `source` is the source code
534
# (including leading indentation and prompts); `indent` is the
535
# indentation of the first (PS1) line of the source code; and
536
# `want` is the expected output (including leading indentation).
537
_EXAMPLE_RE = re.compile(r'''
538
# Source consists of a PS1 line followed by zero or more PS2 lines.
540
(?:^(?P<indent> [ ]*) >>> .*) # PS1 line
541
(?:\n [ ]* \.\.\. .*)*) # PS2 lines
543
# Want consists of any non-blank lines that do not start with PS1.
544
(?P<want> (?:(?![ ]*$) # Not a blank line
545
(?![ ]*>>>) # Not a line starting with PS1
546
.*$\n? # But any other line
548
''', re.MULTILINE | re.VERBOSE)
550
# A regular expression for handling `want` strings that contain
551
# expected exceptions. It divides `want` into three pieces:
552
# - the traceback header line (`hdr`)
553
# - the traceback stack (`stack`)
554
# - the exception message (`msg`), as generated by
555
# traceback.format_exception_only()
556
# `msg` may have multiple lines. We assume/require that the
557
# exception message is the first non-indented line starting with a word
558
# character following the traceback header line.
559
_EXCEPTION_RE = re.compile(r"""
560
# Grab the traceback header. Different versions of Python have
561
# said different things on the first traceback line.
562
^(?P<hdr> Traceback\ \(
563
(?: most\ recent\ call\ last
567
\s* $ # toss trailing whitespace on the header.
568
(?P<stack> .*?) # don't blink: absorb stuff until...
569
^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
570
""", re.VERBOSE | re.MULTILINE | re.DOTALL)
572
# A callable returning a true value iff its argument is a blank line
573
# or contains a single comment.
574
_IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
576
# Find footnote references.
577
_FOOTNOTE_REFERENCE_RE = re.compile(r'\[([^\]]+)]_')
579
# Find footnote definitions.
580
_FOOTNOTE_DEFINITION_RE = re.compile(
581
r'^\.\.\s*\[\s*([^\]]+)\s*\].*$', re.MULTILINE)
583
# End of footnote regex. Just looks for any unindented line.
584
_FOOTNOTE_END_RE = re.compile(r'^\S+', re.MULTILINE)
586
def parse(self, string, name='<string>', optionflags=0):
588
Divide the given string into examples and intervening text,
589
and return them as a list of alternating Examples and strings.
590
Line numbers for the Examples are 0-based. The optional
591
argument `name` is a name identifying this string, and is only
592
used for error messages.
594
string = string.expandtabs()
595
# If all lines begin with the same indentation, then strip it.
596
min_indent = self._min_indent(string)
598
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
601
charno, lineno = 0, 0
602
# Find all doctest examples in the string:
603
for m in self._EXAMPLE_RE.finditer(string):
604
# Add the pre-example text to `output`.
605
output.append(string[charno:m.start()])
606
# Update lineno (lines before this example)
607
lineno += string.count('\n', charno, m.start())
608
# Extract info from the regexp match.
609
(source, options, want, exc_msg) = \
610
self._parse_example(m, name, lineno)
611
# Create an Example, and add it to the list.
612
if not self._IS_BLANK_OR_COMMENT(source):
613
output.append( Example(source, want, exc_msg,
615
indent=min_indent+len(m.group('indent')),
617
# Update lineno (lines inside this example)
618
lineno += string.count('\n', m.start(), m.end())
621
# Add any remaining post-example text to `output`.
622
output.append(string[charno:])
624
if optionflags & INTERPRET_FOOTNOTES:
627
# collect all the footnotes
631
# we're collecting prose and examples for a footnote
632
if isinstance(x, Example):
633
x._footnote_name = name
634
elif self._FOOTNOTE_END_RE.search(x):
635
# this looks like prose that ends a footnote
637
footnotes[name] = footnote
642
if not isinstance(x, Example):
644
self._FOOTNOTE_DEFINITION_RE.finditer(x))
647
# all but the last one don't have any code
648
# note: we intentionally reuse the "leaked" value
650
for match in matches:
651
footnotes[match.group(1)] = []
654
name = match.group(1)
657
# if we were still collecting a footnote when the loop ended,
658
# stash it away so it's not lost
660
footnotes[name] = footnote
662
# inject each footnote into the point(s) at which it is referenced
664
defined_footnotes = []
667
if isinstance(x, Example):
668
# we don't want to execute footnotes where they're defined
669
if hasattr(x, '_footnote_name'):
670
defined_footnotes.append(x._footnote_name)
674
for m in self._FOOTNOTE_REFERENCE_RE.finditer(x):
676
if name not in footnotes:
678
'A footnote was referred to, but never'
679
' defined: %r' % name)
682
new_output.extend(footnotes[name])
683
used_footnotes.append(name)
690
# make sure that all of the footnotes found were actually used
691
unused_footnotes = set(defined_footnotes) - set(used_footnotes)
692
for x in unused_footnotes:
693
warnings.warn('a footnote was defined, but never used: %r' % x,
694
UnusedFootnoteWarning)
698
def get_doctest(self, string, globs, name, filename, lineno,
701
Extract all doctest examples from the given string, and
702
collect them into a `DocTest` object.
704
`globs`, `name`, `filename`, and `lineno` are attributes for
705
the new `DocTest` object. See the documentation for `DocTest`
706
for more information.
708
return DocTest(self.get_examples(string, name, optionflags), globs,
709
name, filename, lineno, string)
711
def get_examples(self, string, name='<string>', optionflags=0):
713
Extract all doctest examples from the given string, and return
714
them as a list of `Example` objects. Line numbers are
715
0-based, because it's most common in doctests that nothing
716
interesting appears on the same line as opening triple-quote,
717
and so the first interesting line is called \"line 1\" then.
719
The optional argument `name` is a name identifying this
720
string, and is only used for error messages.
722
return [x for x in self.parse(string, name, optionflags)
723
if isinstance(x, Example)]
725
def _parse_example(self, m, name, lineno):
727
Given a regular expression match from `_EXAMPLE_RE` (`m`),
728
return a pair `(source, want)`, where `source` is the matched
729
example's source code (with prompts and indentation stripped);
730
and `want` is the example's expected output (with indentation
733
`name` is the string's name, and `lineno` is the line number
734
where the example starts; both are used for error messages.
736
# Get the example's indentation level.
737
indent = len(m.group('indent'))
739
# Divide source into lines; check that they're properly
740
# indented; and then strip their indentation & prompts.
741
source_lines = m.group('source').split('\n')
742
self._check_prompt_blank(source_lines, indent, name, lineno)
743
self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
744
source = '\n'.join([sl[indent+4:] for sl in source_lines])
746
# Divide want into lines; check that it's properly indented; and
747
# then strip the indentation. Spaces before the last newline should
748
# be preserved, so plain rstrip() isn't good enough.
749
want = m.group('want')
750
want_lines = want.split('\n')
751
if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
752
del want_lines[-1] # forget final newline & spaces after it
753
self._check_prefix(want_lines, ' '*indent, name,
754
lineno + len(source_lines))
755
want = '\n'.join([wl[indent:] for wl in want_lines])
757
# If `want` contains a traceback message, then extract it.
758
m = self._EXCEPTION_RE.match(want)
760
exc_msg = m.group('msg')
764
# Extract options from the source.
765
options = self._find_options(source, name, lineno)
767
return source, options, want, exc_msg
769
# This regular expression looks for option directives in the
770
# source code of an example. Option directives are comments
771
# starting with "doctest:". Warning: this may give false
772
# positives for string-literals that contain the string
773
# "#doctest:". Eliminating these false positives would require
774
# actually parsing the string; but we limit them by ignoring any
775
# line containing "#doctest:" that is *followed* by a quote mark.
776
_OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
779
def _find_options(self, source, name, lineno):
781
Return a dictionary containing option overrides extracted from
782
option directives in the given source string.
784
`name` is the string's name, and `lineno` is the line number
785
where the example starts; both are used for error messages.
788
# (note: with the current regexp, this will match at most once:)
789
for m in self._OPTION_DIRECTIVE_RE.finditer(source):
790
option_strings = m.group(1).replace(',', ' ').split()
791
for option in option_strings:
792
if (option[0] not in '+-' or
793
option[1:] not in OPTIONFLAGS_BY_NAME):
794
raise ValueError('line %r of the doctest for %s '
795
'has an invalid option: %r' %
796
(lineno+1, name, option))
797
flag = OPTIONFLAGS_BY_NAME[option[1:]]
798
options[flag] = (option[0] == '+')
799
if options and self._IS_BLANK_OR_COMMENT(source):
800
raise ValueError('line %r of the doctest for %s has an option '
801
'directive on a line with no example: %r' %
802
(lineno, name, source))
805
# This regular expression finds the indentation of every non-blank
807
_INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
809
def _min_indent(self, s):
810
"Return the minimum indentation of any non-blank line in `s`"
811
indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
817
def _check_prompt_blank(self, lines, indent, name, lineno):
819
Given the lines of a source string (including prompts and
820
leading indentation), check to make sure that every prompt is
821
followed by a space character. If any line is not followed by
822
a space character, then raise ValueError.
824
for i, line in enumerate(lines):
825
if len(line) >= indent+4 and line[indent+3] != ' ':
826
raise ValueError('line %r of the docstring for %s '
827
'lacks blank after %s: %r' %
829
line[indent:indent+3], line))
831
def _check_prefix(self, lines, prefix, name, lineno):
833
Check that every line in the given list starts with the given
834
prefix; if any line does not, then raise a ValueError.
836
for i, line in enumerate(lines):
837
if line and not line.startswith(prefix):
838
raise ValueError('line %r of the docstring for %s has '
839
'inconsistent leading whitespace: %r' %
840
(lineno+i+1, name, line))
843
######################################################################
845
######################################################################
849
A class used to extract the DocTests that are relevant to a given
850
object, from its docstring and the docstrings of its contained
851
objects. Doctests can currently be extracted from the following
852
object types: modules, functions, classes, methods, staticmethods,
853
classmethods, and properties.
856
def __init__(self, verbose=False, parser=DocTestParser(),
857
recurse=True, _namefilter=None, exclude_empty=True):
859
Create a new doctest finder.
861
The optional argument `parser` specifies a class or
862
function that should be used to create new DocTest objects (or
863
objects that implement the same interface as DocTest). The
864
signature for this factory function should match the signature
865
of the DocTest constructor.
867
If the optional argument `recurse` is false, then `find` will
868
only examine the given object, and not any contained objects.
870
If the optional argument `exclude_empty` is false, then `find`
871
will include tests for objects with empty docstrings.
873
self._parser = parser
874
self._verbose = verbose
875
self._recurse = recurse
876
self._exclude_empty = exclude_empty
877
# _namefilter is undocumented, and exists only for temporary backward-
878
# compatibility support of testmod's deprecated isprivate mess.
879
self._namefilter = _namefilter
881
def find(self, obj, name=None, module=None, globs=None,
882
extraglobs=None, optionflags=0):
884
Return a list of the DocTests that are defined by the given
885
object's docstring, or by any of its contained objects'
888
The optional parameter `module` is the module that contains
889
the given object. If the module is not specified or is None, then
890
the test finder will attempt to automatically determine the
891
correct module. The object's module is used:
893
- As a default namespace, if `globs` is not specified.
894
- To prevent the DocTestFinder from extracting DocTests
895
from objects that are imported from other modules.
896
- To find the name of the file containing the object.
897
- To help find the line number of the object within its
900
Contained objects whose module does not match `module` are ignored.
902
If `module` is False, no attempt to find the module will be made.
903
This is obscure, of use mostly in tests: if `module` is False, or
904
is None but cannot be found automatically, then all objects are
905
considered to belong to the (non-existent) module, so all contained
906
objects will (recursively) be searched for doctests.
908
The globals for each DocTest is formed by combining `globs`
909
and `extraglobs` (bindings in `extraglobs` override bindings
910
in `globs`). A new copy of the globals dictionary is created
911
for each DocTest. If `globs` is not specified, then it
912
defaults to the module's `__dict__`, if specified, or {}
913
otherwise. If `extraglobs` is not specified, then it defaults
917
# If name was not specified, then extract it from the object.
919
name = getattr(obj, '__name__', None)
921
raise ValueError("DocTestFinder.find: name must be given "
922
"when obj.__name__ doesn't exist: %r" %
925
# Find the module that contains the given object (if obj is
926
# a module, then module=obj.). Note: this may fail, in which
927
# case module will be None.
931
module = inspect.getmodule(obj)
933
# Read the module's source code. This is used by
934
# DocTestFinder._find_lineno to find the line number for a
935
# given object's docstring.
937
file = inspect.getsourcefile(obj) or inspect.getfile(obj)
938
source_lines = linecache.getlines(file)
944
# Initialize globals, and merge in extraglobs.
949
globs = module.__dict__.copy()
952
if extraglobs is not None:
953
globs.update(extraglobs)
955
# Recursively expore `obj`, extracting DocTests.
957
self._find(tests, obj, name, module, source_lines, globs, {},
958
optionflags=optionflags)
961
def _filter(self, obj, prefix, base):
963
Return true if the given object should not be examined.
965
return (self._namefilter is not None and
966
self._namefilter(prefix, base))
968
def _from_module(self, module, object):
970
Return true if the given object is defined in the given
975
elif inspect.isfunction(object):
976
return module.__dict__ is object.func_globals
977
elif inspect.isclass(object):
978
return module.__name__ == object.__module__
979
elif inspect.getmodule(object) is not None:
980
return module is inspect.getmodule(object)
981
elif hasattr(object, '__module__'):
982
return module.__name__ == object.__module__
983
elif isinstance(object, property):
984
return True # [XX] no way not be sure.
986
raise ValueError("object must be a class or function")
988
def _find(self, tests, obj, name, module, source_lines, globs, seen,
991
Find tests for the given object and any contained objects, and
995
print 'Finding tests in %s' % name
997
# If we've already processed this object, then ignore it.
1002
# Find a test for this object, and add it to the list of tests.
1003
test = self._get_test(obj, name, module, globs, source_lines,
1005
if test is not None:
1008
# Look for tests in a module's contained objects.
1009
if inspect.ismodule(obj) and self._recurse:
1010
for valname, val in obj.__dict__.items():
1011
# Check if this contained object should be ignored.
1012
if self._filter(val, name, valname):
1014
valname = '%s.%s' % (name, valname)
1015
# Recurse to functions & classes.
1016
if ((inspect.isfunction(val) or inspect.isclass(val)) and
1017
self._from_module(module, val)):
1018
self._find(tests, val, valname, module, source_lines,
1019
globs, seen, optionflags)
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, basestring):
1025
raise ValueError("DocTestFinder.find: __test__ keys "
1026
"must be strings: %r" %
1028
if not (inspect.isfunction(val) or inspect.isclass(val) or
1029
inspect.ismethod(val) or inspect.ismodule(val) or
1030
isinstance(val, basestring)):
1031
raise ValueError("DocTestFinder.find: __test__ values "
1032
"must be strings, functions, methods, "
1033
"classes, or modules: %r" %
1035
valname = '%s.__test__.%s' % (name, valname)
1036
self._find(tests, val, valname, module, source_lines,
1037
globs, seen, optionflags)
1039
# Look for tests in a class's contained objects.
1040
if inspect.isclass(obj) and self._recurse:
1041
for valname, val in obj.__dict__.items():
1042
# Check if this contained object should be ignored.
1043
if self._filter(val, name, valname):
1045
# Special handling for staticmethod/classmethod.
1046
if isinstance(val, staticmethod):
1047
val = getattr(obj, valname)
1048
if isinstance(val, classmethod):
1049
val = getattr(obj, valname).im_func
1051
# Recurse to methods, properties, and nested classes.
1052
if ((inspect.isfunction(val) or inspect.isclass(val) or
1053
isinstance(val, property)) and
1054
self._from_module(module, val)):
1055
valname = '%s.%s' % (name, valname)
1056
self._find(tests, val, valname, module, source_lines,
1057
globs, seen, optionflags)
1059
def _get_test(self, obj, name, module, globs, source_lines, optionflags):
1061
Return a DocTest for the given object, if it defines a docstring;
1062
otherwise, return None.
1064
# Extract the object's docstring. If it doesn't have one,
1065
# then return None (no test for this object).
1066
if isinstance(obj, basestring):
1070
if obj.__doc__ is None:
1073
docstring = obj.__doc__
1074
if not isinstance(docstring, basestring):
1075
docstring = str(docstring)
1076
except (TypeError, AttributeError):
1079
# Find the docstring's location in the file.
1080
lineno = self._find_lineno(obj, source_lines)
1082
# Don't bother if the docstring is empty.
1083
if self._exclude_empty and not docstring:
1086
# Return a DocTest for this object.
1090
filename = getattr(module, '__file__', module.__name__)
1091
if filename[-4:] in (".pyc", ".pyo"):
1092
filename = filename[:-1]
1093
return self._parser.get_doctest(docstring, globs, name,
1094
filename, lineno, optionflags)
1096
def _find_lineno(self, obj, source_lines):
1098
Return a line number of the given object's docstring. Note:
1099
this method assumes that the object has a docstring.
1103
# Find the line number for modules.
1104
if inspect.ismodule(obj):
1107
# Find the line number for classes.
1108
# Note: this could be fooled if a class is defined multiple
1109
# times in a single file.
1110
if inspect.isclass(obj):
1111
if source_lines is None:
1113
pat = re.compile(r'^\s*class\s*%s\b' %
1114
getattr(obj, '__name__', '-'))
1115
for i, line in enumerate(source_lines):
1120
# Find the line number for functions & methods.
1121
if inspect.ismethod(obj): obj = obj.im_func
1122
if inspect.isfunction(obj): obj = obj.func_code
1123
if inspect.istraceback(obj): obj = obj.tb_frame
1124
if inspect.isframe(obj): obj = obj.f_code
1125
if inspect.iscode(obj):
1126
lineno = getattr(obj, 'co_firstlineno', None)-1
1128
# Find the line number where the docstring starts. Assume
1129
# that it's the first line that begins with a quote mark.
1130
# Note: this could be fooled by a multiline function
1131
# signature, where a continuation line begins with a quote
1133
if lineno is not None:
1134
if source_lines is None:
1136
pat = re.compile('(^|.*:)\s*\w*("|\')')
1137
for lineno in range(lineno, len(source_lines)):
1138
if pat.match(source_lines[lineno]):
1141
# We couldn't find the line number.
1144
######################################################################
1145
## 5. DocTest Runner
1146
######################################################################
1148
class DocTestRunner:
1150
A class used to run DocTest test cases, and accumulate statistics.
1151
The `run` method is used to process a single DocTest case. It
1152
returns a tuple `(f, t)`, where `t` is the number of test cases
1153
tried, and `f` is the number of test cases that failed.
1155
>>> tests = DocTestFinder().find(_TestClass)
1156
>>> runner = DocTestRunner(verbose=False)
1157
>>> for test in tests:
1158
... print runner.run(test)
1164
The `summarize` method prints a summary of all the test cases that
1165
have been run by the runner, and returns an aggregated `(f, t)`
1168
>>> runner.summarize(verbose=1)
1169
4 items passed all tests:
1170
2 tests in _TestClass
1171
2 tests in _TestClass.__init__
1172
2 tests in _TestClass.get
1173
1 tests in _TestClass.square
1175
7 passed and 0 failed.
1179
The aggregated number of tried examples and failed examples is
1180
also available via the `tries` and `failures` attributes:
1187
The comparison between expected outputs and actual outputs is done
1188
by an `OutputChecker`. This comparison may be customized with a
1189
number of option flags; see the documentation for `testmod` for
1190
more information. If the option flags are insufficient, then the
1191
comparison may also be customized by passing a subclass of
1192
`OutputChecker` to the constructor.
1194
The test runner's display output can be controlled in two ways.
1195
First, an output function (`out) can be passed to
1196
`TestRunner.run`; this function will be called with strings that
1197
should be displayed. It defaults to `sys.stdout.write`. If
1198
capturing the output is not sufficient, then the display output
1199
can be also customized by subclassing DocTestRunner, and
1200
overriding the methods `report_start`, `report_success`,
1201
`report_unexpected_exception`, and `report_failure`.
1203
# This divider string is used to separate failure messages, and to
1204
# separate sections of the summary.
1207
def __init__(self, checker=None, verbose=None, optionflags=0):
1209
Create a new test runner.
1211
Optional keyword arg `checker` is the `OutputChecker` that
1212
should be used to compare the expected outputs and actual
1213
outputs of doctest examples.
1215
Optional keyword arg 'verbose' prints lots of stuff if true,
1216
only failures if false; by default, it's true iff '-v' is in
1219
Optional argument `optionflags` can be used to control how the
1220
test runner compares expected output to actual output, and how
1221
it displays failures. See the documentation for `testmod` for
1224
self._checker = checker or OutputChecker()
1226
verbose = '-v' in sys.argv
1227
self._verbose = verbose
1228
self.optionflags = optionflags
1229
self.original_optionflags = optionflags
1231
# Keep track of the examples we've run.
1236
# Create a fake output target for capturing doctest output.
1237
self._fakeout = _SpoofOut()
1239
#/////////////////////////////////////////////////////////////////
1241
#/////////////////////////////////////////////////////////////////
1243
def report_start(self, out, test, example):
1245
Report that the test runner is about to process the given
1246
example. (Only displays a message if verbose=True)
1250
out('Trying:\n' + _indent(example.source) +
1251
'Expecting:\n' + _indent(example.want))
1253
out('Trying:\n' + _indent(example.source) +
1254
'Expecting nothing\n')
1256
def report_success(self, out, test, example, got):
1258
Report that the given example ran successfully. (Only
1259
displays a message if verbose=True)
1264
def report_failure(self, out, test, example, got):
1266
Report that the given example failed.
1268
out(self._failure_header(test, example) +
1269
self._checker.output_difference(example, got, self.optionflags))
1271
def report_unexpected_exception(self, out, test, example, exc_info):
1273
Report that the given example raised an unexpected exception.
1275
out(self._failure_header(test, example) +
1276
'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
1278
def _failure_header(self, test, example):
1279
out = [self.DIVIDER]
1281
if test.lineno is not None and example.lineno is not None:
1282
lineno = test.lineno + example.lineno + 1
1285
out.append('File "%s", line %s, in %s' %
1286
(test.filename, lineno, test.name))
1288
out.append('Line %s, in %s' % (example.lineno+1, test.name))
1289
out.append('Failed example:')
1290
source = example.source
1291
out.append(_indent(source))
1292
return '\n'.join(out)
1294
#/////////////////////////////////////////////////////////////////
1296
#/////////////////////////////////////////////////////////////////
1298
def __run(self, test, compileflags, out):
1300
Run the examples in `test`. Write the outcome of each example
1301
with one of the `DocTestRunner.report_*` methods, using the
1302
writer function `out`. `compileflags` is the set of compiler
1303
flags that should be used to execute examples. Return a tuple
1304
`(f, t)`, where `t` is the number of examples tried, and `f`
1305
is the number of examples that failed. The examples are run
1306
in the namespace `test.globs`.
1308
# Keep track of the number of failures and tries.
1309
failures = tries = 0
1311
# Save the option flags (since option directives can be used
1313
original_optionflags = self.optionflags
1315
SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
1317
check = self._checker.check_output
1319
# Process each example.
1320
for examplenum, example in enumerate(test.examples):
1322
# If REPORT_ONLY_FIRST_FAILURE is set, then supress
1323
# reporting after the first failure.
1324
quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1327
# Merge in the example's options.
1328
self.optionflags = original_optionflags
1330
for (optionflag, val) in example.options.items():
1332
self.optionflags |= optionflag
1334
self.optionflags &= ~optionflag
1336
# Record that we started this example.
1339
self.report_start(out, test, example)
1341
# Use a special filename for compile(), so we can retrieve
1342
# the source code during interactive debugging (see
1343
# __patched_linecache_getlines).
1344
# Line number counting starts with 0 so we add one to get
1345
# the real line number.
1346
filename = '<doctest %s[line %d, example %d]>' % (
1347
test.name, example.lineno+1, examplenum)
1349
# Run the example in the given context (globs), and record
1350
# any exception that gets raised. (But don't intercept
1351
# keyboard interrupts.)
1353
# Don't blink! This is where the user's code gets run.
1354
exec compile(example.source, filename, "single",
1355
compileflags, 1) in test.globs
1356
self.debugger.set_continue() # ==== Example Finished ====
1358
except KeyboardInterrupt:
1361
exception = sys.exc_info()
1362
self.debugger.set_continue() # ==== Example Finished ====
1363
got = self._fakeout.getvalue() # the actual output
1364
self._fakeout.truncate(0)
1365
outcome = FAILURE # guilty until proved innocent or insane
1367
# If the example executed without raising any exceptions,
1368
# verify its output.
1369
if exception is None:
1370
if check(example.want, got, self.optionflags):
1373
# The example raised an exception: check if it was expected.
1375
exc_info = sys.exc_info()
1376
exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1378
got += _exception_traceback(exc_info)
1380
# If `example.exc_msg` is None, then we weren't expecting
1382
if example.exc_msg is None:
1385
# We expected an exception: see whether it matches.
1386
elif check(example.exc_msg, exc_msg, self.optionflags):
1389
# Another chance if they didn't care about the detail.
1390
elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
1391
m1 = re.match(r'[^:]*:', example.exc_msg)
1392
m2 = re.match(r'[^:]*:', exc_msg)
1393
if m1 and m2 and check(m1.group(0), m2.group(0),
1397
# Report the outcome.
1398
if outcome is SUCCESS:
1400
self.report_success(out, test, example, got)
1401
elif outcome is FAILURE:
1403
self.report_failure(out, test, example, got)
1405
elif outcome is BOOM:
1407
self.report_unexpected_exception(out, test, example,
1411
assert False, ("unknown outcome", outcome)
1413
# Restore the option flags (in case they were modified)
1414
self.optionflags = original_optionflags
1416
# Record and return the number of failures and tries.
1417
self.__record_outcome(test, failures, tries)
1418
return failures, tries
1420
def __record_outcome(self, test, f, t):
1422
Record the fact that the given DocTest (`test`) generated `f`
1423
failures out of `t` tried examples.
1425
f2, t2 = self._name2ft.get(test.name, (0,0))
1426
self._name2ft[test.name] = (f+f2, t+t2)
1430
__LINECACHE_FILENAME_RE = re.compile(
1431
r'<doctest (?P<name>[\w\.]+)\[line \d+, example (?P<examplenum>\d+)\]>$'
1434
def __patched_linecache_getlines(self, filename, module_globals=None):
1435
m = self.__LINECACHE_FILENAME_RE.match(filename)
1436
if m and m.group('name') == self.test.name:
1437
example = self.test.examples[int(m.group('examplenum'))]
1438
return example.source.splitlines(True)
1440
if module_globals is None:
1441
return self.save_linecache_getlines(filename)
1443
return self.save_linecache_getlines(filename, module_globals)
1445
def run(self, test, compileflags=None, out=None, clear_globs=True):
1447
Run the examples in `test`, and display the results using the
1448
writer function `out`.
1450
The examples are run in the namespace `test.globs`. If
1451
`clear_globs` is true (the default), then this namespace will
1452
be cleared after the test runs, to help with garbage
1453
collection. If you would like to examine the namespace after
1454
the test completes, then use `clear_globs=False`.
1456
`compileflags` gives the set of flags that should be used by
1457
the Python compiler when running the examples. If not
1458
specified, then it will default to the set of future-import
1459
flags that apply to `globs`.
1461
The output of each example is checked using
1462
`DocTestRunner.check_output`, and the results are formatted by
1463
the `DocTestRunner.report_*` methods.
1467
if compileflags is None:
1468
compileflags = _extract_future_flags(test.globs)
1470
save_stdout = sys.stdout
1472
out = save_stdout.write
1473
sys.stdout = self._fakeout
1475
# Patch pdb.set_trace to restore sys.stdout during interactive
1476
# debugging (so it's not still redirected to self._fakeout).
1477
# Note that the interactive output will go to *our*
1478
# save_stdout, even if that's not the real sys.stdout; this
1479
# allows us to write test cases for the set_trace behavior.
1480
save_set_trace = pdb.set_trace
1481
self.debugger = _OutputRedirectingPdb(save_stdout)
1482
self.debugger.reset()
1483
pdb.set_trace = self.debugger.set_trace
1485
# Patch linecache.getlines, so we can see the example's source
1486
# when we're inside the debugger.
1487
self.save_linecache_getlines = linecache.getlines
1488
linecache.getlines = self.__patched_linecache_getlines
1491
return self.__run(test, compileflags, out)
1493
sys.stdout = save_stdout
1494
pdb.set_trace = save_set_trace
1495
linecache.getlines = self.save_linecache_getlines
1499
#/////////////////////////////////////////////////////////////////
1501
#/////////////////////////////////////////////////////////////////
1502
def summarize(self, verbose=None):
1504
Print a summary of all the test cases that have been run by
1505
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1506
the total number of failed examples, and `t` is the total
1507
number of tried examples.
1509
The optional `verbose` argument controls how detailed the
1510
summary is. If the verbosity is not specified, then the
1511
DocTestRunner's verbosity is used.
1514
verbose = self._verbose
1519
for x in self._name2ft.items():
1525
notests.append(name)
1527
passed.append( (name, t) )
1532
print len(notests), "items had no tests:"
1534
for thing in notests:
1537
print len(passed), "items passed all tests:"
1539
for thing, count in passed:
1540
print " %3d tests in %s" % (count, thing)
1543
print len(failed), "items had failures:"
1545
for thing, (f, t) in failed:
1546
print " %3d of %3d in %s" % (f, t, thing)
1548
print totalt, "tests in", len(self._name2ft), "items."
1549
print totalt - totalf, "passed and", totalf, "failed."
1551
print "***Test Failed***", totalf, "failures."
1553
print "Test passed."
1554
return totalf, totalt
1556
#/////////////////////////////////////////////////////////////////
1557
# Backward compatibility cruft to maintain doctest.master.
1558
#/////////////////////////////////////////////////////////////////
1559
def merge(self, other):
1561
for name, (f, t) in other._name2ft.items():
1563
print "*** DocTestRunner.merge: '" + name + "' in both" \
1564
" testers; summing outcomes."
1570
class OutputChecker:
1572
A class used to check the whether the actual output from a doctest
1573
example matches the expected output. `OutputChecker` defines two
1574
methods: `check_output`, which compares a given pair of outputs,
1575
and returns true if they match; and `output_difference`, which
1576
returns a string describing the differences between two outputs.
1578
def check_output(self, want, got, optionflags):
1580
Return True iff the actual output from an example (`got`)
1581
matches the expected output (`want`). These strings are
1582
always considered to match if they are identical; but
1583
depending on what option flags the test runner is using,
1584
several non-exact match types are also possible. See the
1585
documentation for `TestRunner` for more information about
1588
# Handle the common case first, for efficiency:
1589
# if they're string-identical, always return true.
1593
# The values True and False replaced 1 and 0 as the return
1594
# value for boolean comparisons in Python 2.3.
1595
if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1596
if (got,want) == ("True\n", "1\n"):
1598
if (got,want) == ("False\n", "0\n"):
1601
# <BLANKLINE> can be used as a special sequence to signify a
1602
# blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1603
if not (optionflags & DONT_ACCEPT_BLANKLINE):
1604
# Replace <BLANKLINE> in want with a blank line.
1605
want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1607
# If a line in got contains only spaces, then remove the
1609
got = re.sub('(?m)^\s*?$', '', got)
1613
# This flag causes doctest to ignore any differences in the
1614
# contents of whitespace strings. Note that this can be used
1615
# in conjunction with the ELLIPSIS flag.
1616
if optionflags & NORMALIZE_WHITESPACE:
1617
got = ' '.join(got.split())
1618
want = ' '.join(want.split())
1622
# The ELLIPSIS flag says to let the sequence "..." in `want`
1623
# match any substring in `got`.
1624
if optionflags & ELLIPSIS:
1625
if _ellipsis_match(want, got):
1628
# We didn't find any match; return false.
1631
# Should we do a fancy diff?
1632
def _do_a_fancy_diff(self, want, got, optionflags):
1633
# Not unless they asked for a fancy diff.
1634
if not optionflags & (REPORT_UDIFF |
1639
# If expected output uses ellipsis, a meaningful fancy diff is
1640
# too hard ... or maybe not. In two real-life failures Tim saw,
1641
# a diff was a major help anyway, so this is commented out.
1642
# [todo] _ellipsis_match() knows which pieces do and don't match,
1643
# and could be the basis for a kick-ass diff in this case.
1644
##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1647
# ndiff does intraline difference marking, so can be useful even
1648
# for 1-line differences.
1649
if optionflags & REPORT_NDIFF:
1652
# The other diff types need at least a few lines to be helpful.
1653
return want.count('\n') > 2 and got.count('\n') > 2
1655
def output_difference(self, example, got, optionflags):
1657
Return a string describing the differences between the
1658
expected output for a given example (`example`) and the actual
1659
output (`got`). `optionflags` is the set of option flags used
1660
to compare `want` and `got`.
1663
# If <BLANKLINE>s are being used, then replace blank lines
1664
# with <BLANKLINE> in the actual output string.
1665
if not (optionflags & DONT_ACCEPT_BLANKLINE):
1666
got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
1668
# Check if we should use diff.
1669
if self._do_a_fancy_diff(want, got, optionflags):
1670
# Split want & got into lines.
1671
want_lines = want.splitlines(True) # True == keep line ends
1672
got_lines = got.splitlines(True)
1673
# Use difflib to find their differences.
1674
if optionflags & REPORT_UDIFF:
1675
diff = difflib.unified_diff(want_lines, got_lines, n=2)
1676
diff = list(diff)[2:] # strip the diff header
1677
kind = 'unified diff with -expected +actual'
1678
elif optionflags & REPORT_CDIFF:
1679
diff = difflib.context_diff(want_lines, got_lines, n=2)
1680
diff = list(diff)[2:] # strip the diff header
1681
kind = 'context diff with expected followed by actual'
1682
elif optionflags & REPORT_NDIFF:
1683
engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1684
diff = list(engine.compare(want_lines, got_lines))
1685
kind = 'ndiff with -expected +actual'
1687
assert 0, 'Bad diff option'
1688
# Remove trailing whitespace on diff output.
1689
diff = [line.rstrip() + '\n' for line in diff]
1690
return 'Differences (%s):\n' % kind + _indent(''.join(diff))
1692
# If we're not using diff, then simply list the expected
1693
# output followed by the actual output.
1695
return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1697
return 'Expected:\n%sGot nothing\n' % _indent(want)
1699
return 'Expected nothing\nGot:\n%s' % _indent(got)
1701
return 'Expected nothing\nGot nothing\n'
1704
class DebugRunner(DocTestRunner):
1705
r"""Run doc tests but raise an exception as soon as there is a failure.
1707
If an unexpected exception occurs, an UnexpectedException is raised.
1708
It contains the test, the example, and the original exception:
1710
>>> runner = DebugRunner(verbose=False)
1711
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1712
... {}, 'foo', 'foo.py', 0)
1714
... runner.run(test)
1715
... except UnexpectedException, failure:
1718
>>> failure.test is test
1721
>>> failure.example.want
1724
>>> exc_info = failure.exc_info
1725
>>> raise exc_info[0], exc_info[1], exc_info[2]
1726
Traceback (most recent call last):
1730
We wrap the original exception to give the calling application
1731
access to the test and example information.
1733
If the output doesn't match, then a DocTestFailure is raised:
1735
>>> test = DocTestParser().get_doctest('''
1739
... ''', {}, 'foo', 'foo.py', 0)
1742
... runner.run(test)
1743
... except DocTestFailure, failure:
1746
DocTestFailure objects provide access to the test:
1748
>>> failure.test is test
1751
As well as to the example:
1753
>>> failure.example.want
1756
and the actual output:
1761
If a failure or error occurs, the globals are left intact:
1763
>>> del test.globs['__builtins__']
1767
>>> test = DocTestParser().get_doctest('''
1769
... >>> raise KeyError
1770
... ''', {}, 'foo', 'foo.py', 0)
1772
>>> runner.run(test)
1773
Traceback (most recent call last):
1775
UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
1777
>>> del test.globs['__builtins__']
1781
But the globals are cleared if there is no error:
1783
>>> test = DocTestParser().get_doctest('''
1785
... ''', {}, 'foo', 'foo.py', 0)
1787
>>> runner.run(test)
1795
def run(self, test, compileflags=None, out=None, clear_globs=True):
1796
r = DocTestRunner.run(self, test, compileflags, out, False)
1801
def report_unexpected_exception(self, out, test, example, exc_info):
1802
raise UnexpectedException(test, example, exc_info)
1804
def report_failure(self, out, test, example, got):
1805
raise DocTestFailure(test, example, got)
1807
######################################################################
1808
## 6. Test Functions
1809
######################################################################
1810
# These should be backwards compatible.
1812
# For backward compatibility, a global instance of a DocTestRunner
1813
# class, updated by testmod.
1816
def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
1817
report=True, optionflags=0, extraglobs=None,
1818
raise_on_error=False, exclude_empty=False):
1819
"""m=None, name=None, globs=None, verbose=None, isprivate=None,
1820
report=True, optionflags=0, extraglobs=None, raise_on_error=False,
1823
Test examples in docstrings in functions and classes reachable
1824
from module m (or the current module if m is not supplied), starting
1825
with m.__doc__. Unless isprivate is specified, private names
1828
Also test examples reachable from dict m.__test__ if it exists and is
1829
not None. m.__test__ maps names to functions, classes and strings;
1830
function and class docstrings are tested even if the name is private;
1831
strings are tested directly, as if they were docstrings.
1833
Return (#failures, #tests).
1835
See doctest.__doc__ for an overview.
1837
Optional keyword arg "name" gives the name of the module; by default
1840
Optional keyword arg "globs" gives a dict to be used as the globals
1841
when executing examples; by default, use m.__dict__. A copy of this
1842
dict is actually used for each docstring, so that each docstring's
1843
examples start with a clean slate.
1845
Optional keyword arg "extraglobs" gives a dictionary that should be
1846
merged into the globals that are used to execute examples. By
1847
default, no extra globals are used. This is new in 2.4.
1849
Optional keyword arg "verbose" prints lots of stuff if true, prints
1850
only failures if false; by default, it's true iff "-v" is in sys.argv.
1852
Optional keyword arg "report" prints a summary at the end when true,
1853
else prints nothing at the end. In verbose mode, the summary is
1854
detailed, else very brief (in fact, empty if all tests passed).
1856
Optional keyword arg "optionflags" or's together module constants,
1857
and defaults to 0. This is new in 2.3. Possible values (see the
1860
DONT_ACCEPT_TRUE_FOR_1
1861
DONT_ACCEPT_BLANKLINE
1862
NORMALIZE_WHITESPACE
1864
IGNORE_EXCEPTION_DETAIL
1868
REPORT_ONLY_FIRST_FAILURE
1870
Optional keyword arg "raise_on_error" raises an exception on the
1871
first unexpected exception or failure. This allows failures to be
1872
post-mortem debugged.
1874
Deprecated in Python 2.4:
1875
Optional keyword arg "isprivate" specifies a function used to
1876
determine whether a name is private. The default function is
1877
treat all functions as public. Optionally, "isprivate" can be
1878
set to doctest.is_private to skip over functions marked as private
1879
using the underscore naming convention; see its docs for details.
1881
Advanced tomfoolery: testmod runs methods of a local instance of
1882
class doctest.Tester, then merges the results into (or creates)
1883
global Tester instance doctest.master. Methods of doctest.master
1884
can be called directly too, if you want to do something unusual.
1885
Passing report=0 to testmod is especially useful then, to delay
1886
displaying a summary. Invoke doctest.master.summarize(verbose)
1887
when you're done fiddling.
1891
if isprivate is not None:
1892
warnings.warn("the isprivate argument is deprecated; "
1893
"examine DocTestFinder.find() lists instead",
1896
# If no module was given, then use __main__.
1898
# DWA - m will still be None if this wasn't invoked from the command
1899
# line, in which case the following TypeError is about as good an error
1900
# as we should expect
1901
m = sys.modules.get('__main__')
1903
# Check that we were actually given a module.
1904
if not inspect.ismodule(m):
1905
raise TypeError("testmod: module required; %r" % (m,))
1907
# If no name was given, then use the module's name.
1911
# Find, parse, and run all tests in the given module.
1912
finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty)
1915
runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1917
runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1919
for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1928
master.merge(runner)
1930
return runner.failures, runner.tries
1932
def testfile(filename, module_relative=True, name=None, package=None,
1933
globs=None, verbose=None, report=True, optionflags=0,
1934
extraglobs=None, raise_on_error=False, parser=DocTestParser(),
1937
Test examples in the given file. Return (#failures, #tests).
1939
Optional keyword arg "module_relative" specifies how filenames
1940
should be interpreted:
1942
- If "module_relative" is True (the default), then "filename"
1943
specifies a module-relative path. By default, this path is
1944
relative to the calling module's directory; but if the
1945
"package" argument is specified, then it is relative to that
1946
package. To ensure os-independence, "filename" should use
1947
"/" characters to separate path segments, and should not
1948
be an absolute path (i.e., it may not begin with "/").
1950
- If "module_relative" is False, then "filename" specifies an
1951
os-specific path. The path may be absolute or relative (to
1952
the current working directory).
1954
Optional keyword arg "name" gives the name of the test; by default
1955
use the file's basename.
1957
Optional keyword argument "package" is a Python package or the
1958
name of a Python package whose directory should be used as the
1959
base directory for a module relative filename. If no package is
1960
specified, then the calling module's directory is used as the base
1961
directory for module relative filenames. It is an error to
1962
specify "package" if "module_relative" is False.
1964
Optional keyword arg "globs" gives a dict to be used as the globals
1965
when executing examples; by default, use {}. A copy of this dict
1966
is actually used for each docstring, so that each docstring's
1967
examples start with a clean slate.
1969
Optional keyword arg "extraglobs" gives a dictionary that should be
1970
merged into the globals that are used to execute examples. By
1971
default, no extra globals are used.
1973
Optional keyword arg "verbose" prints lots of stuff if true, prints
1974
only failures if false; by default, it's true iff "-v" is in sys.argv.
1976
Optional keyword arg "report" prints a summary at the end when true,
1977
else prints nothing at the end. In verbose mode, the summary is
1978
detailed, else very brief (in fact, empty if all tests passed).
1980
Optional keyword arg "optionflags" or's together module constants,
1981
and defaults to 0. Possible values (see the docs for details):
1983
DONT_ACCEPT_TRUE_FOR_1
1984
DONT_ACCEPT_BLANKLINE
1985
NORMALIZE_WHITESPACE
1987
IGNORE_EXCEPTION_DETAIL
1991
REPORT_ONLY_FIRST_FAILURE
1993
Optional keyword arg "raise_on_error" raises an exception on the
1994
first unexpected exception or failure. This allows failures to be
1995
post-mortem debugged.
1997
Optional keyword arg "parser" specifies a DocTestParser (or
1998
subclass) that should be used to extract tests from the files.
2000
Optional keyword arg "encoding" specifies an encoding that should
2001
be used to convert the file to unicode.
2003
Advanced tomfoolery: testmod runs methods of a local instance of
2004
class doctest.Tester, then merges the results into (or creates)
2005
global Tester instance doctest.master. Methods of doctest.master
2006
can be called directly too, if you want to do something unusual.
2007
Passing report=0 to testmod is especially useful then, to delay
2008
displaying a summary. Invoke doctest.master.summarize(verbose)
2009
when you're done fiddling.
2013
if package and not module_relative:
2014
raise ValueError("Package may only be specified for module-"
2017
# Relativize the path
2019
package = _normalize_module(package)
2020
filename = _module_relative_path(package, filename)
2022
# If no name was given, then use the file's name.
2024
name = os.path.basename(filename)
2026
# Assemble the globals.
2030
globs = globs.copy()
2031
if extraglobs is not None:
2032
globs.update(extraglobs)
2035
runner = DebugRunner(verbose=verbose, optionflags=optionflags)
2037
runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
2039
# Read the file, convert it to a test, and run it.
2040
s = open(filename, 'U').read()
2041
if encoding is None:
2042
encoding = pep263_encoding(s)
2043
if encoding is not None:
2044
s = s.decode(encoding)
2045
test = parser.get_doctest(s, globs, name, filename, 0)
2054
master.merge(runner)
2056
return runner.failures, runner.tries
2058
pep263_re_search = re.compile("coding[:=]\s*([-\w.]+)").search
2059
def pep263_encoding(s):
2060
"""Try to find the encoding of a string by looking for a pep263 coding.
2062
for line in s.split('\n')[:2]:
2063
r = pep263_re_search(line)
2069
def run_docstring_examples(f, globs, verbose=False, name="NoName",
2070
compileflags=None, optionflags=0):
2072
Test examples in the given object's docstring (`f`), using `globs`
2073
as globals. Optional argument `name` is used in failure messages.
2074
If the optional argument `verbose` is true, then generate output
2075
even if there are no failures.
2077
`compileflags` gives the set of flags that should be used by the
2078
Python compiler when running the examples. If not specified, then
2079
it will default to the set of future-import flags that apply to
2082
Optional keyword arg `optionflags` specifies options for the
2083
testing and output. See the documentation for `testmod` for more
2086
# Find, parse, and run all tests in the given module.
2087
finder = DocTestFinder(verbose=verbose, recurse=False)
2088
runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
2089
for test in finder.find(f, name, globs=globs):
2090
runner.run(test, compileflags=compileflags)
2092
######################################################################
2094
######################################################################
2095
# This is provided only for backwards compatibility. It's not
2096
# actually used in any way.
2099
def __init__(self, mod=None, globs=None, verbose=None,
2100
isprivate=None, optionflags=0):
2102
warnings.warn("class Tester is deprecated; "
2103
"use class doctest.DocTestRunner instead",
2104
DeprecationWarning, stacklevel=2)
2105
if mod is None and globs is None:
2106
raise TypeError("Tester.__init__: must specify mod or globs")
2107
if mod is not None and not inspect.ismodule(mod):
2108
raise TypeError("Tester.__init__: mod must be a module; %r" %
2111
globs = mod.__dict__
2114
self.verbose = verbose
2115
self.isprivate = isprivate
2116
self.optionflags = optionflags
2117
self.testfinder = DocTestFinder(_namefilter=isprivate)
2118
self.testrunner = DocTestRunner(verbose=verbose,
2119
optionflags=optionflags)
2121
def runstring(self, s, name):
2122
test = DocTestParser().get_doctest(s, self.globs, name, None, None,
2125
print "Running string", name
2126
(f,t) = self.testrunner.run(test)
2128
print f, "of", t, "examples failed in string", name
2131
def rundoc(self, object, name=None, module=None):
2133
tests = self.testfinder.find(object, name, module=module,
2136
(f2, t2) = self.testrunner.run(test)
2137
(f,t) = (f+f2, t+t2)
2140
def rundict(self, d, name, module=None):
2142
m = new.module(name)
2143
m.__dict__.update(d)
2146
return self.rundoc(m, name, module)
2148
def run__test__(self, d, name):
2150
m = new.module(name)
2152
return self.rundoc(m, name)
2154
def summarize(self, verbose=None):
2155
return self.testrunner.summarize(verbose)
2157
def merge(self, other):
2158
self.testrunner.merge(other.testrunner)
2160
######################################################################
2161
## 8. Unittest Support
2162
######################################################################
2164
from doctest import set_unittest_reportflags
2166
_para_re = re.compile(r'\s*\n\s*\n\s*')
2167
def _unittest_count(docstring):
2170
for p in _para_re.split(docstring):
2174
if p.startswith('>>> '):
2184
class DocTestCase(unittest.TestCase):
2186
def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2189
unittest.TestCase.__init__(self)
2190
self._dt_optionflags = optionflags
2191
self._dt_checker = checker
2192
self._dt_test = test
2193
self._dt_globs = test.globs.copy()
2194
self._dt_setUp = setUp
2195
self._dt_tearDown = tearDown
2197
self._dt_count = _unittest_count(test.docstring)
2199
def countTestCases(self):
2200
return self._dt_count
2203
test = self._dt_test
2205
if self._dt_setUp is not None:
2206
self._dt_setUp(test)
2209
test = self._dt_test
2211
if self._dt_tearDown is not None:
2212
self._dt_tearDown(test)
2214
# restore the original globs
2216
test.globs.update(self._dt_globs)
2218
failureException = DocTestFailureException
2221
test = self._dt_test
2224
optionflags = self._dt_optionflags
2226
if not (optionflags & REPORTING_FLAGS):
2227
# The option flags don't include any reporting flags,
2228
# so add the default reporting flags
2229
optionflags |= doctest._unittest_reportflags
2231
if doctest._unittest_reportflags & REPORT_ONLY_FIRST_FAILURE:
2232
optionflags |= REPORT_ONLY_FIRST_FAILURE
2234
runner = DocTestRunner(optionflags=optionflags,
2235
checker=self._dt_checker, verbose=False)
2237
if isinstance(value, unicode):
2238
value = value.encode('utf8')
2242
runner.DIVIDER = "-"*70
2243
failures, tries = runner.run(
2244
test, out=write, clear_globs=False)
2249
raise self.failureException(self.format_failure(new.getvalue()))
2251
def format_failure(self, err):
2252
test = self._dt_test
2253
if test.lineno is None:
2254
lineno = 'unknown line number'
2256
lineno = '%s' % test.lineno
2257
lname = '.'.join(test.name.split('.')[-1:])
2258
return ('Failed doctest test for %s\n'
2259
' File "%s", line %s, in %s\n\n%s'
2260
% (test.name, test.filename, lineno, lname, err)
2264
r"""Run the test case without results and without catching exceptions
2266
The unit test framework includes a debug method on test cases
2267
and test suites to support post-mortem debugging. The test code
2268
is run in such a way that errors are not caught. This way a
2269
caller can catch the errors and initiate post-mortem debugging.
2271
The DocTestCase provides a debug method that raises
2272
UnexpectedException errors if there is an unexepcted
2275
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
2276
... {}, 'foo', 'foo.py', 0)
2277
>>> case = DocTestCase(test)
2280
... except UnexpectedException, failure:
2283
The UnexpectedException contains the test, the example, and
2284
the original exception:
2286
>>> failure.test is test
2289
>>> failure.example.want
2292
>>> exc_info = failure.exc_info
2293
>>> raise exc_info[0], exc_info[1], exc_info[2]
2294
Traceback (most recent call last):
2298
If the output doesn't match, then a DocTestFailure is raised:
2300
>>> test = DocTestParser().get_doctest('''
2304
... ''', {}, 'foo', 'foo.py', 0)
2305
>>> case = DocTestCase(test)
2309
... except DocTestFailure, failure:
2312
DocTestFailure objects provide access to the test:
2314
>>> failure.test is test
2317
As well as to the example:
2319
>>> failure.example.want
2322
and the actual output:
2330
runner = DebugRunner(optionflags=self._dt_optionflags,
2331
checker=self._dt_checker, verbose=False)
2332
runner.run(self._dt_test, clear_globs=False)
2336
return self._dt_test.name
2339
name = self._dt_test.name.split('.')
2340
return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2344
def shortDescription(self):
2345
return "Doctest: " + self._dt_test.name
2347
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2350
Convert doctest tests for a module to a unittest test suite.
2352
This converts each documentation string in a module that
2353
contains doctest tests to a unittest test case. If any of the
2354
tests in a doc string fail, then the test case fails. An exception
2355
is raised showing the name of the file containing the test and a
2356
(sometimes approximate) line number.
2358
The `module` argument provides the module to be tested. The argument
2359
can be either a module or a module name.
2361
If no argument is given, the calling module is used.
2363
A number of options may be provided as keyword arguments:
2366
A set-up function. This is called before running the
2367
tests in each file. The setUp function will be passed a DocTest
2368
object. The setUp function can access the test globals as the
2369
globs attribute of the test passed.
2372
A tear-down function. This is called after running the
2373
tests in each file. The tearDown function will be passed a DocTest
2374
object. The tearDown function can access the test globals as the
2375
globs attribute of the test passed.
2378
A dictionary containing initial global variables for the tests.
2381
A set of doctest option flags expressed as an integer.
2384
if test_finder is None:
2385
test_finder = DocTestFinder()
2387
module = _normalize_module(module)
2388
tests = test_finder.find(module, globs=globs, extraglobs=extraglobs,
2389
optionflags=options.get('optionflags', 0))
2391
globs = module.__dict__
2393
# Why do we want to do this? Because it reveals a bug that might
2394
# otherwise be hidden.
2395
raise ValueError(module, "has no tests")
2398
suite = unittest.TestSuite()
2400
if len(test.examples) == 0:
2402
if not test.filename:
2403
filename = module.__file__
2404
if filename[-4:] in (".pyc", ".pyo"):
2405
filename = filename[:-1]
2406
test.filename = filename
2407
suite.addTest(DocTestCase(test, **options))
2411
class DocFileCase(DocTestCase):
2414
return '_'.join(self._dt_test.name.split('.'))
2417
return self._dt_test.filename
2420
def format_failure(self, err):
2421
return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2422
% (self._dt_test.name, self._dt_test.filename, err)
2425
def DocFileTest(path, module_relative=True, package=None,
2426
globs=None, parser=DocTestParser(),
2427
encoding=None, **options):
2431
globs = globs.copy()
2433
if package and not module_relative:
2434
raise ValueError("Package may only be specified for module-"
2437
# Relativize the path.
2439
package = _normalize_module(package)
2440
path = _module_relative_path(package, path)
2441
if "__file__" not in globs:
2442
globs["__file__"] = path
2444
# Find the file and read it.
2445
name = os.path.basename(path)
2446
doc = open(path, 'U').read()
2448
# If an encoding is specified, use it to convert the file to unicode
2449
if encoding is None:
2450
encoding = pep263_encoding(doc)
2451
if encoding is not None:
2452
doc = doc.decode(encoding)
2454
optionflags = options.get('optionflags', 0)
2455
# Convert it to a test, and wrap it in a DocFileCase.
2456
test = parser.get_doctest(doc, globs, name, path, 0, optionflags)
2457
return DocFileCase(test, **options)
2459
def DocFileSuite(*paths, **kw):
2460
"""A unittest suite for one or more doctest files.
2462
The path to each doctest file is given as a string; the
2463
interpretation of that string depends on the keyword argument
2466
A number of options may be provided as keyword arguments:
2469
If "module_relative" is True, then the given file paths are
2470
interpreted as os-independent module-relative paths. By
2471
default, these paths are relative to the calling module's
2472
directory; but if the "package" argument is specified, then
2473
they are relative to that package. To ensure os-independence,
2474
"filename" should use "/" characters to separate path
2475
segments, and may not be an absolute path (i.e., it may not
2478
If "module_relative" is False, then the given file paths are
2479
interpreted as os-specific paths. These paths may be absolute
2480
or relative (to the current working directory).
2483
A Python package or the name of a Python package whose directory
2484
should be used as the base directory for module relative paths.
2485
If "package" is not specified, then the calling module's
2486
directory is used as the base directory for module relative
2487
filenames. It is an error to specify "package" if
2488
"module_relative" is False.
2491
A set-up function. This is called before running the
2492
tests in each file. The setUp function will be passed a DocTest
2493
object. The setUp function can access the test globals as the
2494
globs attribute of the test passed.
2497
A tear-down function. This is called after running the
2498
tests in each file. The tearDown function will be passed a DocTest
2499
object. The tearDown function can access the test globals as the
2500
globs attribute of the test passed.
2503
A dictionary containing initial global variables for the tests.
2506
A set of doctest option flags expressed as an integer.
2509
A DocTestParser (or subclass) that should be used to extract
2510
tests from the files.
2513
An encoding that will be used to convert the files to unicode.
2515
suite = unittest.TestSuite()
2517
# We do this here so that _normalize_module is called at the right
2518
# level. If it were called in DocFileTest, then this function
2519
# would be the caller and we might guess the package incorrectly.
2520
if kw.get('module_relative', True):
2521
kw['package'] = _normalize_module(kw.get('package'))
2524
suite.addTest(DocFileTest(path, **kw))
2528
######################################################################
2529
## 9. Debugging Support
2530
######################################################################
2532
def script_from_examples(s):
2533
r"""Extract script from text with examples.
2535
Converts text with examples to a Python script. Example input is
2536
converted to regular code. Example output and all other words
2537
are converted to comments:
2540
... Here are examples of simple math.
2542
... Python has super accurate integer addition
2547
... And very friendly error messages:
2554
... You can use logic if you want:
2564
>>> print script_from_examples(text)
2565
# Here are examples of simple math.
2567
# Python has super accurate integer addition
2573
# And very friendly error messages:
2581
# You can use logic if you want:
2590
for piece in DocTestParser().parse(s):
2591
if isinstance(piece, Example):
2592
# Add the example's source code (strip trailing NL)
2593
output.append(piece.source[:-1])
2594
# Add the expected output:
2597
output.append('# Expected:')
2598
output += ['## '+l for l in want.split('\n')[:-1]]
2600
# Add non-example text.
2601
output += [_comment_line(l)
2602
for l in piece.split('\n')[:-1]]
2604
# Trim junk on both ends.
2605
while output and output[-1] == '#':
2607
while output and output[0] == '#':
2609
# Combine the output, and return it.
2610
return '\n'.join(output)
2612
def testsource(module, name):
2613
"""Extract the test sources from a doctest docstring as a script.
2615
Provide the module (or dotted name of the module) containing the
2616
test to be debugged and the name (within the module) of the object
2617
with the doc string with tests to be debugged.
2619
module = _normalize_module(module)
2620
tests = DocTestFinder().find(module)
2621
test = [t for t in tests if t.name == name]
2623
raise ValueError(name, "not found in tests")
2625
testsrc = script_from_examples(test.docstring)
2628
def debug_src(src, pm=False, globs=None):
2629
"""Debug a single doctest docstring, in argument `src`'"""
2630
testsrc = script_from_examples(src)
2631
debug_script(testsrc, pm, globs)
2633
def debug_script(src, pm=False, globs=None):
2634
"Debug a test script. `src` is the script, as a string."
2637
# Note that tempfile.NameTemporaryFile() cannot be used. As the
2638
# docs say, a file so created cannot be opened by name a second time
2639
# on modern Windows boxes, and execfile() needs to open it.
2640
srcfilename = tempfile.mktemp(".py", "doctestdebug")
2641
f = open(srcfilename, 'w')
2647
globs = globs.copy()
2653
execfile(srcfilename, globs, globs)
2655
print sys.exc_info()[1]
2656
pdb.post_mortem(sys.exc_info()[2])
2658
# Note that %r is vital here. '%s' instead can, e.g., cause
2659
# backslashes to get treated as metacharacters on Windows.
2660
pdb.run("execfile(%r)" % srcfilename, globs, globs)
2663
os.remove(srcfilename)
2665
def debug(module, name, pm=False):
2666
"""Debug a single doctest docstring.
2668
Provide the module (or dotted name of the module) containing the
2669
test to be debugged and the name (within the module) of the object
2670
with the docstring with tests to be debugged.
2672
module = _normalize_module(module)
2673
testsrc = testsource(module, name)
2674
debug_script(testsrc, pm, module.__dict__)
2676
######################################################################
2677
## 10. Example Usage
2678
######################################################################
2681
A pointless class, for sanity-checking of docstring testing.
2687
>>> _TestClass(13).get() + _TestClass(-12).get()
2689
>>> hex(_TestClass(13).square().get())
2693
def __init__(self, val):
2694
"""val -> _TestClass object with associated value val.
2696
>>> t = _TestClass(123)
2704
"""square() -> square TestClass's associated value
2706
>>> _TestClass(13).square().get()
2710
self.val = self.val ** 2
2714
"""get() -> return TestClass's associated value.
2716
>>> x = _TestClass(-42)
2723
__test__ = {"_TestClass": _TestClass,
2725
Example of a string object, searched as-is.
2731
"bool-int equivalence": r"""
2732
In 2.2, boolean expressions displayed
2733
0 or 1. By default, we still accept
2734
them. This can be disabled by passing
2735
DONT_ACCEPT_TRUE_FOR_1 to the new
2736
optionflags argument.
2748
Blank lines can be marked with <BLANKLINE>:
2749
>>> print 'foo\n\nbar\n'
2757
If the ellipsis flag is used, then '...' can be used to
2758
elide substrings in the desired output:
2759
>>> print range(1000) #doctest: +ELLIPSIS
2763
"whitespace normalization": r"""
2764
If the whitespace normalization flag is used, then
2765
differences in whitespace are ignored.
2766
>>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2767
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2768
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2773
def _test_footnotes():
2778
If the INTERPRET_FOOTNOTES flag is passed as part of optionflags, then
2779
footnotes will be looked up and their code injected at each point of
2780
reference. For example:
2784
Here is some text that references a footnote [1]_
2789
.. [1] and here we increment ``counter``
2792
Footnotes can also be referenced after they are defined: [1]_
2797
Footnotes can also be "citations", which just means that the value in
2798
the brackets is alphanumeric: [citation]_
2800
>>> print from_citation
2803
.. [citation] this is a citation.
2804
>>> from_citation = 'hi'
2806
Footnotes can contain more than one example: [multi example]_
2817
.. [multi example] Here's a footnote with multiple examples:
2821
and now another (note indentation to make this part of the footnote):
2830
More than one footnote can be referenced at a time [1]_ [2]_
2835
.. [2] let's multiply ``counter`` by two
2842
If the INTERPRET_FOOTNOTES optionflag isn't set, footnotes are ignored.
2845
... This is a doctest. [#1]_
2849
... .. [#1] a footnote
2850
... Here we set up the variable
2855
>>> print_structure(doctest)
2856
Prose| This is a doctest. [#1]_
2858
Prose| .. [#1] a footnote
2862
If INTERPRET_FOOTNOTES is set, footnotes are also copied to the point at
2863
which they are referenced.
2865
>>> print_structure(doctest, optionflags=INTERPRET_FOOTNOTES)
2866
Prose| This is a doctest. [#1]_
2870
Prose| .. [#1] a footnote
2873
>>> print_structure("""
2874
... Footnotes can have code that starts with no prose. [#quick code]_
2876
... .. [#quick code]
2877
... >>> print 'this is some code'
2878
... this is some code
2879
... """, optionflags=INTERPRET_FOOTNOTES)
2880
Prose| Footnotes can have code that starts with no prose. [#quick code]_
2881
Code | print 'this is some code'
2885
>>> print_structure("""
2886
... Footnotes can be back-to-back [#first]_ [#second]_
2891
... """, optionflags=INTERPRET_FOOTNOTES)
2892
Prose| Footnotes can be back-to-back [#first]_ [#second]_
2893
Prose| Footnotes can be back-to-back [#first]_ [#second]_
2898
>>> print_structure("""
2899
... .. [#no code] Footnotes can also be defined with no code.
2900
... """, optionflags=INTERPRET_FOOTNOTES)
2901
Prose| .. [#no code] Footnotes can also be defined with no code.
2903
If there are multiple footnotes with no code, then one with code, they are
2906
>>> print_structure("""
2907
... I'd like some code to go here [#some code]_
2908
... .. [#no code 1] Footnotes can also be defined with no code.
2909
... .. [#no code 2] Footnotes can also be defined with no code.
2910
... .. [#no code 3] Footnotes can also be defined with no code.
2914
... """, optionflags=INTERPRET_FOOTNOTES)
2915
Prose| I'd like some code to go here [#some code]_
2920
The non-autonumbered flavor of labels works too.
2922
>>> print_structure("""
2923
... Here is some text. [foo]_
2927
... """, optionflags=INTERPRET_FOOTNOTES)
2928
Prose| Here is some text. [foo]_
2935
def print_structure(doctest, optionflags=0):
2937
first_line = s.strip().split('\n')[0]
2939
if len(first_line) <= MAX_LENGTH:
2942
return '%s...' % first_line[:MAX_LENGTH].strip()
2944
parser = DocTestParser()
2945
for x in parser.parse(doctest, optionflags=optionflags):
2946
if isinstance(x, Example):
2947
result = 'Code | ' + preview(x.source)
2949
result = 'Prose| ' + preview(x)
2951
print result.strip()
2955
r = unittest.TextTestRunner()
2956
r.run(DocTestSuite(optionflags=INTERPRET_FOOTNOTES))
2958
if __name__ == "__main__":
2962
# - make tracebacks show where the footnote was referenced
2963
# - teach script_from_examples and testsource about INTERPRET_FOOTNOTES
2964
# - update comments (including docstring for testfile)