Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../usr/lib64/python3....
File: doctest.py
namespace. Each `DocTest` defines the following attributes:
[500] Fix | Delete
[501] Fix | Delete
- examples: the list of examples.
[502] Fix | Delete
[503] Fix | Delete
- globs: The namespace (aka globals) that the examples should
[504] Fix | Delete
be run in.
[505] Fix | Delete
[506] Fix | Delete
- name: A name identifying the DocTest (typically, the name of
[507] Fix | Delete
the object whose docstring this DocTest was extracted from).
[508] Fix | Delete
[509] Fix | Delete
- filename: The name of the file that this DocTest was extracted
[510] Fix | Delete
from, or `None` if the filename is unknown.
[511] Fix | Delete
[512] Fix | Delete
- lineno: The line number within filename where this DocTest
[513] Fix | Delete
begins, or `None` if the line number is unavailable. This
[514] Fix | Delete
line number is zero-based, with respect to the beginning of
[515] Fix | Delete
the file.
[516] Fix | Delete
[517] Fix | Delete
- docstring: The string that the examples were extracted from,
[518] Fix | Delete
or `None` if the string is unavailable.
[519] Fix | Delete
"""
[520] Fix | Delete
def __init__(self, examples, globs, name, filename, lineno, docstring):
[521] Fix | Delete
"""
[522] Fix | Delete
Create a new DocTest containing the given examples. The
[523] Fix | Delete
DocTest's globals are initialized with a copy of `globs`.
[524] Fix | Delete
"""
[525] Fix | Delete
assert not isinstance(examples, str), \
[526] Fix | Delete
"DocTest no longer accepts str; use DocTestParser instead"
[527] Fix | Delete
self.examples = examples
[528] Fix | Delete
self.docstring = docstring
[529] Fix | Delete
self.globs = globs.copy()
[530] Fix | Delete
self.name = name
[531] Fix | Delete
self.filename = filename
[532] Fix | Delete
self.lineno = lineno
[533] Fix | Delete
[534] Fix | Delete
def __repr__(self):
[535] Fix | Delete
if len(self.examples) == 0:
[536] Fix | Delete
examples = 'no examples'
[537] Fix | Delete
elif len(self.examples) == 1:
[538] Fix | Delete
examples = '1 example'
[539] Fix | Delete
else:
[540] Fix | Delete
examples = '%d examples' % len(self.examples)
[541] Fix | Delete
return ('<%s %s from %s:%s (%s)>' %
[542] Fix | Delete
(self.__class__.__name__,
[543] Fix | Delete
self.name, self.filename, self.lineno, examples))
[544] Fix | Delete
[545] Fix | Delete
def __eq__(self, other):
[546] Fix | Delete
if type(self) is not type(other):
[547] Fix | Delete
return NotImplemented
[548] Fix | Delete
[549] Fix | Delete
return self.examples == other.examples and \
[550] Fix | Delete
self.docstring == other.docstring and \
[551] Fix | Delete
self.globs == other.globs and \
[552] Fix | Delete
self.name == other.name and \
[553] Fix | Delete
self.filename == other.filename and \
[554] Fix | Delete
self.lineno == other.lineno
[555] Fix | Delete
[556] Fix | Delete
def __hash__(self):
[557] Fix | Delete
return hash((self.docstring, self.name, self.filename, self.lineno))
[558] Fix | Delete
[559] Fix | Delete
# This lets us sort tests by name:
[560] Fix | Delete
def __lt__(self, other):
[561] Fix | Delete
if not isinstance(other, DocTest):
[562] Fix | Delete
return NotImplemented
[563] Fix | Delete
return ((self.name, self.filename, self.lineno, id(self))
[564] Fix | Delete
<
[565] Fix | Delete
(other.name, other.filename, other.lineno, id(other)))
[566] Fix | Delete
[567] Fix | Delete
######################################################################
[568] Fix | Delete
## 3. DocTestParser
[569] Fix | Delete
######################################################################
[570] Fix | Delete
[571] Fix | Delete
class DocTestParser:
[572] Fix | Delete
"""
[573] Fix | Delete
A class used to parse strings containing doctest examples.
[574] Fix | Delete
"""
[575] Fix | Delete
# This regular expression is used to find doctest examples in a
[576] Fix | Delete
# string. It defines three groups: `source` is the source code
[577] Fix | Delete
# (including leading indentation and prompts); `indent` is the
[578] Fix | Delete
# indentation of the first (PS1) line of the source code; and
[579] Fix | Delete
# `want` is the expected output (including leading indentation).
[580] Fix | Delete
_EXAMPLE_RE = re.compile(r'''
[581] Fix | Delete
# Source consists of a PS1 line followed by zero or more PS2 lines.
[582] Fix | Delete
(?P<source>
[583] Fix | Delete
(?:^(?P<indent> [ ]*) >>> .*) # PS1 line
[584] Fix | Delete
(?:\n [ ]* \.\.\. .*)*) # PS2 lines
[585] Fix | Delete
\n?
[586] Fix | Delete
# Want consists of any non-blank lines that do not start with PS1.
[587] Fix | Delete
(?P<want> (?:(?![ ]*$) # Not a blank line
[588] Fix | Delete
(?![ ]*>>>) # Not a line starting with PS1
[589] Fix | Delete
.+$\n? # But any other line
[590] Fix | Delete
)*)
[591] Fix | Delete
''', re.MULTILINE | re.VERBOSE)
[592] Fix | Delete
[593] Fix | Delete
# A regular expression for handling `want` strings that contain
[594] Fix | Delete
# expected exceptions. It divides `want` into three pieces:
[595] Fix | Delete
# - the traceback header line (`hdr`)
[596] Fix | Delete
# - the traceback stack (`stack`)
[597] Fix | Delete
# - the exception message (`msg`), as generated by
[598] Fix | Delete
# traceback.format_exception_only()
[599] Fix | Delete
# `msg` may have multiple lines. We assume/require that the
[600] Fix | Delete
# exception message is the first non-indented line starting with a word
[601] Fix | Delete
# character following the traceback header line.
[602] Fix | Delete
_EXCEPTION_RE = re.compile(r"""
[603] Fix | Delete
# Grab the traceback header. Different versions of Python have
[604] Fix | Delete
# said different things on the first traceback line.
[605] Fix | Delete
^(?P<hdr> Traceback\ \(
[606] Fix | Delete
(?: most\ recent\ call\ last
[607] Fix | Delete
| innermost\ last
[608] Fix | Delete
) \) :
[609] Fix | Delete
)
[610] Fix | Delete
\s* $ # toss trailing whitespace on the header.
[611] Fix | Delete
(?P<stack> .*?) # don't blink: absorb stuff until...
[612] Fix | Delete
^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
[613] Fix | Delete
""", re.VERBOSE | re.MULTILINE | re.DOTALL)
[614] Fix | Delete
[615] Fix | Delete
# A callable returning a true value iff its argument is a blank line
[616] Fix | Delete
# or contains a single comment.
[617] Fix | Delete
_IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
[618] Fix | Delete
[619] Fix | Delete
def parse(self, string, name='<string>'):
[620] Fix | Delete
"""
[621] Fix | Delete
Divide the given string into examples and intervening text,
[622] Fix | Delete
and return them as a list of alternating Examples and strings.
[623] Fix | Delete
Line numbers for the Examples are 0-based. The optional
[624] Fix | Delete
argument `name` is a name identifying this string, and is only
[625] Fix | Delete
used for error messages.
[626] Fix | Delete
"""
[627] Fix | Delete
string = string.expandtabs()
[628] Fix | Delete
# If all lines begin with the same indentation, then strip it.
[629] Fix | Delete
min_indent = self._min_indent(string)
[630] Fix | Delete
if min_indent > 0:
[631] Fix | Delete
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
[632] Fix | Delete
[633] Fix | Delete
output = []
[634] Fix | Delete
charno, lineno = 0, 0
[635] Fix | Delete
# Find all doctest examples in the string:
[636] Fix | Delete
for m in self._EXAMPLE_RE.finditer(string):
[637] Fix | Delete
# Add the pre-example text to `output`.
[638] Fix | Delete
output.append(string[charno:m.start()])
[639] Fix | Delete
# Update lineno (lines before this example)
[640] Fix | Delete
lineno += string.count('\n', charno, m.start())
[641] Fix | Delete
# Extract info from the regexp match.
[642] Fix | Delete
(source, options, want, exc_msg) = \
[643] Fix | Delete
self._parse_example(m, name, lineno)
[644] Fix | Delete
# Create an Example, and add it to the list.
[645] Fix | Delete
if not self._IS_BLANK_OR_COMMENT(source):
[646] Fix | Delete
output.append( Example(source, want, exc_msg,
[647] Fix | Delete
lineno=lineno,
[648] Fix | Delete
indent=min_indent+len(m.group('indent')),
[649] Fix | Delete
options=options) )
[650] Fix | Delete
# Update lineno (lines inside this example)
[651] Fix | Delete
lineno += string.count('\n', m.start(), m.end())
[652] Fix | Delete
# Update charno.
[653] Fix | Delete
charno = m.end()
[654] Fix | Delete
# Add any remaining post-example text to `output`.
[655] Fix | Delete
output.append(string[charno:])
[656] Fix | Delete
return output
[657] Fix | Delete
[658] Fix | Delete
def get_doctest(self, string, globs, name, filename, lineno):
[659] Fix | Delete
"""
[660] Fix | Delete
Extract all doctest examples from the given string, and
[661] Fix | Delete
collect them into a `DocTest` object.
[662] Fix | Delete
[663] Fix | Delete
`globs`, `name`, `filename`, and `lineno` are attributes for
[664] Fix | Delete
the new `DocTest` object. See the documentation for `DocTest`
[665] Fix | Delete
for more information.
[666] Fix | Delete
"""
[667] Fix | Delete
return DocTest(self.get_examples(string, name), globs,
[668] Fix | Delete
name, filename, lineno, string)
[669] Fix | Delete
[670] Fix | Delete
def get_examples(self, string, name='<string>'):
[671] Fix | Delete
"""
[672] Fix | Delete
Extract all doctest examples from the given string, and return
[673] Fix | Delete
them as a list of `Example` objects. Line numbers are
[674] Fix | Delete
0-based, because it's most common in doctests that nothing
[675] Fix | Delete
interesting appears on the same line as opening triple-quote,
[676] Fix | Delete
and so the first interesting line is called \"line 1\" then.
[677] Fix | Delete
[678] Fix | Delete
The optional argument `name` is a name identifying this
[679] Fix | Delete
string, and is only used for error messages.
[680] Fix | Delete
"""
[681] Fix | Delete
return [x for x in self.parse(string, name)
[682] Fix | Delete
if isinstance(x, Example)]
[683] Fix | Delete
[684] Fix | Delete
def _parse_example(self, m, name, lineno):
[685] Fix | Delete
"""
[686] Fix | Delete
Given a regular expression match from `_EXAMPLE_RE` (`m`),
[687] Fix | Delete
return a pair `(source, want)`, where `source` is the matched
[688] Fix | Delete
example's source code (with prompts and indentation stripped);
[689] Fix | Delete
and `want` is the example's expected output (with indentation
[690] Fix | Delete
stripped).
[691] Fix | Delete
[692] Fix | Delete
`name` is the string's name, and `lineno` is the line number
[693] Fix | Delete
where the example starts; both are used for error messages.
[694] Fix | Delete
"""
[695] Fix | Delete
# Get the example's indentation level.
[696] Fix | Delete
indent = len(m.group('indent'))
[697] Fix | Delete
[698] Fix | Delete
# Divide source into lines; check that they're properly
[699] Fix | Delete
# indented; and then strip their indentation & prompts.
[700] Fix | Delete
source_lines = m.group('source').split('\n')
[701] Fix | Delete
self._check_prompt_blank(source_lines, indent, name, lineno)
[702] Fix | Delete
self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
[703] Fix | Delete
source = '\n'.join([sl[indent+4:] for sl in source_lines])
[704] Fix | Delete
[705] Fix | Delete
# Divide want into lines; check that it's properly indented; and
[706] Fix | Delete
# then strip the indentation. Spaces before the last newline should
[707] Fix | Delete
# be preserved, so plain rstrip() isn't good enough.
[708] Fix | Delete
want = m.group('want')
[709] Fix | Delete
want_lines = want.split('\n')
[710] Fix | Delete
if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
[711] Fix | Delete
del want_lines[-1] # forget final newline & spaces after it
[712] Fix | Delete
self._check_prefix(want_lines, ' '*indent, name,
[713] Fix | Delete
lineno + len(source_lines))
[714] Fix | Delete
want = '\n'.join([wl[indent:] for wl in want_lines])
[715] Fix | Delete
[716] Fix | Delete
# If `want` contains a traceback message, then extract it.
[717] Fix | Delete
m = self._EXCEPTION_RE.match(want)
[718] Fix | Delete
if m:
[719] Fix | Delete
exc_msg = m.group('msg')
[720] Fix | Delete
else:
[721] Fix | Delete
exc_msg = None
[722] Fix | Delete
[723] Fix | Delete
# Extract options from the source.
[724] Fix | Delete
options = self._find_options(source, name, lineno)
[725] Fix | Delete
[726] Fix | Delete
return source, options, want, exc_msg
[727] Fix | Delete
[728] Fix | Delete
# This regular expression looks for option directives in the
[729] Fix | Delete
# source code of an example. Option directives are comments
[730] Fix | Delete
# starting with "doctest:". Warning: this may give false
[731] Fix | Delete
# positives for string-literals that contain the string
[732] Fix | Delete
# "#doctest:". Eliminating these false positives would require
[733] Fix | Delete
# actually parsing the string; but we limit them by ignoring any
[734] Fix | Delete
# line containing "#doctest:" that is *followed* by a quote mark.
[735] Fix | Delete
_OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
[736] Fix | Delete
re.MULTILINE)
[737] Fix | Delete
[738] Fix | Delete
def _find_options(self, source, name, lineno):
[739] Fix | Delete
"""
[740] Fix | Delete
Return a dictionary containing option overrides extracted from
[741] Fix | Delete
option directives in the given source string.
[742] Fix | Delete
[743] Fix | Delete
`name` is the string's name, and `lineno` is the line number
[744] Fix | Delete
where the example starts; both are used for error messages.
[745] Fix | Delete
"""
[746] Fix | Delete
options = {}
[747] Fix | Delete
# (note: with the current regexp, this will match at most once:)
[748] Fix | Delete
for m in self._OPTION_DIRECTIVE_RE.finditer(source):
[749] Fix | Delete
option_strings = m.group(1).replace(',', ' ').split()
[750] Fix | Delete
for option in option_strings:
[751] Fix | Delete
if (option[0] not in '+-' or
[752] Fix | Delete
option[1:] not in OPTIONFLAGS_BY_NAME):
[753] Fix | Delete
raise ValueError('line %r of the doctest for %s '
[754] Fix | Delete
'has an invalid option: %r' %
[755] Fix | Delete
(lineno+1, name, option))
[756] Fix | Delete
flag = OPTIONFLAGS_BY_NAME[option[1:]]
[757] Fix | Delete
options[flag] = (option[0] == '+')
[758] Fix | Delete
if options and self._IS_BLANK_OR_COMMENT(source):
[759] Fix | Delete
raise ValueError('line %r of the doctest for %s has an option '
[760] Fix | Delete
'directive on a line with no example: %r' %
[761] Fix | Delete
(lineno, name, source))
[762] Fix | Delete
return options
[763] Fix | Delete
[764] Fix | Delete
# This regular expression finds the indentation of every non-blank
[765] Fix | Delete
# line in a string.
[766] Fix | Delete
_INDENT_RE = re.compile(r'^([ ]*)(?=\S)', re.MULTILINE)
[767] Fix | Delete
[768] Fix | Delete
def _min_indent(self, s):
[769] Fix | Delete
"Return the minimum indentation of any non-blank line in `s`"
[770] Fix | Delete
indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
[771] Fix | Delete
if len(indents) > 0:
[772] Fix | Delete
return min(indents)
[773] Fix | Delete
else:
[774] Fix | Delete
return 0
[775] Fix | Delete
[776] Fix | Delete
def _check_prompt_blank(self, lines, indent, name, lineno):
[777] Fix | Delete
"""
[778] Fix | Delete
Given the lines of a source string (including prompts and
[779] Fix | Delete
leading indentation), check to make sure that every prompt is
[780] Fix | Delete
followed by a space character. If any line is not followed by
[781] Fix | Delete
a space character, then raise ValueError.
[782] Fix | Delete
"""
[783] Fix | Delete
for i, line in enumerate(lines):
[784] Fix | Delete
if len(line) >= indent+4 and line[indent+3] != ' ':
[785] Fix | Delete
raise ValueError('line %r of the docstring for %s '
[786] Fix | Delete
'lacks blank after %s: %r' %
[787] Fix | Delete
(lineno+i+1, name,
[788] Fix | Delete
line[indent:indent+3], line))
[789] Fix | Delete
[790] Fix | Delete
def _check_prefix(self, lines, prefix, name, lineno):
[791] Fix | Delete
"""
[792] Fix | Delete
Check that every line in the given list starts with the given
[793] Fix | Delete
prefix; if any line does not, then raise a ValueError.
[794] Fix | Delete
"""
[795] Fix | Delete
for i, line in enumerate(lines):
[796] Fix | Delete
if line and not line.startswith(prefix):
[797] Fix | Delete
raise ValueError('line %r of the docstring for %s has '
[798] Fix | Delete
'inconsistent leading whitespace: %r' %
[799] Fix | Delete
(lineno+i+1, name, line))
[800] Fix | Delete
[801] Fix | Delete
[802] Fix | Delete
######################################################################
[803] Fix | Delete
## 4. DocTest Finder
[804] Fix | Delete
######################################################################
[805] Fix | Delete
[806] Fix | Delete
class DocTestFinder:
[807] Fix | Delete
"""
[808] Fix | Delete
A class used to extract the DocTests that are relevant to a given
[809] Fix | Delete
object, from its docstring and the docstrings of its contained
[810] Fix | Delete
objects. Doctests can currently be extracted from the following
[811] Fix | Delete
object types: modules, functions, classes, methods, staticmethods,
[812] Fix | Delete
classmethods, and properties.
[813] Fix | Delete
"""
[814] Fix | Delete
[815] Fix | Delete
def __init__(self, verbose=False, parser=DocTestParser(),
[816] Fix | Delete
recurse=True, exclude_empty=True):
[817] Fix | Delete
"""
[818] Fix | Delete
Create a new doctest finder.
[819] Fix | Delete
[820] Fix | Delete
The optional argument `parser` specifies a class or
[821] Fix | Delete
function that should be used to create new DocTest objects (or
[822] Fix | Delete
objects that implement the same interface as DocTest). The
[823] Fix | Delete
signature for this factory function should match the signature
[824] Fix | Delete
of the DocTest constructor.
[825] Fix | Delete
[826] Fix | Delete
If the optional argument `recurse` is false, then `find` will
[827] Fix | Delete
only examine the given object, and not any contained objects.
[828] Fix | Delete
[829] Fix | Delete
If the optional argument `exclude_empty` is false, then `find`
[830] Fix | Delete
will include tests for objects with empty docstrings.
[831] Fix | Delete
"""
[832] Fix | Delete
self._parser = parser
[833] Fix | Delete
self._verbose = verbose
[834] Fix | Delete
self._recurse = recurse
[835] Fix | Delete
self._exclude_empty = exclude_empty
[836] Fix | Delete
[837] Fix | Delete
def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
[838] Fix | Delete
"""
[839] Fix | Delete
Return a list of the DocTests that are defined by the given
[840] Fix | Delete
object's docstring, or by any of its contained objects'
[841] Fix | Delete
docstrings.
[842] Fix | Delete
[843] Fix | Delete
The optional parameter `module` is the module that contains
[844] Fix | Delete
the given object. If the module is not specified or is None, then
[845] Fix | Delete
the test finder will attempt to automatically determine the
[846] Fix | Delete
correct module. The object's module is used:
[847] Fix | Delete
[848] Fix | Delete
- As a default namespace, if `globs` is not specified.
[849] Fix | Delete
- To prevent the DocTestFinder from extracting DocTests
[850] Fix | Delete
from objects that are imported from other modules.
[851] Fix | Delete
- To find the name of the file containing the object.
[852] Fix | Delete
- To help find the line number of the object within its
[853] Fix | Delete
file.
[854] Fix | Delete
[855] Fix | Delete
Contained objects whose module does not match `module` are ignored.
[856] Fix | Delete
[857] Fix | Delete
If `module` is False, no attempt to find the module will be made.
[858] Fix | Delete
This is obscure, of use mostly in tests: if `module` is False, or
[859] Fix | Delete
is None but cannot be found automatically, then all objects are
[860] Fix | Delete
considered to belong to the (non-existent) module, so all contained
[861] Fix | Delete
objects will (recursively) be searched for doctests.
[862] Fix | Delete
[863] Fix | Delete
The globals for each DocTest is formed by combining `globs`
[864] Fix | Delete
and `extraglobs` (bindings in `extraglobs` override bindings
[865] Fix | Delete
in `globs`). A new copy of the globals dictionary is created
[866] Fix | Delete
for each DocTest. If `globs` is not specified, then it
[867] Fix | Delete
defaults to the module's `__dict__`, if specified, or {}
[868] Fix | Delete
otherwise. If `extraglobs` is not specified, then it defaults
[869] Fix | Delete
to {}.
[870] Fix | Delete
[871] Fix | Delete
"""
[872] Fix | Delete
# If name was not specified, then extract it from the object.
[873] Fix | Delete
if name is None:
[874] Fix | Delete
name = getattr(obj, '__name__', None)
[875] Fix | Delete
if name is None:
[876] Fix | Delete
raise ValueError("DocTestFinder.find: name must be given "
[877] Fix | Delete
"when obj.__name__ doesn't exist: %r" %
[878] Fix | Delete
(type(obj),))
[879] Fix | Delete
[880] Fix | Delete
# Find the module that contains the given object (if obj is
[881] Fix | Delete
# a module, then module=obj.). Note: this may fail, in which
[882] Fix | Delete
# case module will be None.
[883] Fix | Delete
if module is False:
[884] Fix | Delete
module = None
[885] Fix | Delete
elif module is None:
[886] Fix | Delete
module = inspect.getmodule(obj)
[887] Fix | Delete
[888] Fix | Delete
# Read the module's source code. This is used by
[889] Fix | Delete
# DocTestFinder._find_lineno to find the line number for a
[890] Fix | Delete
# given object's docstring.
[891] Fix | Delete
try:
[892] Fix | Delete
file = inspect.getsourcefile(obj)
[893] Fix | Delete
except TypeError:
[894] Fix | Delete
source_lines = None
[895] Fix | Delete
else:
[896] Fix | Delete
if not file:
[897] Fix | Delete
# Check to see if it's one of our special internal "files"
[898] Fix | Delete
# (see __patched_linecache_getlines).
[899] Fix | Delete
file = inspect.getfile(obj)
[900] Fix | Delete
if not file[0]+file[-2:] == '<]>': file = None
[901] Fix | Delete
if file is None:
[902] Fix | Delete
source_lines = None
[903] Fix | Delete
else:
[904] Fix | Delete
if module is not None:
[905] Fix | Delete
# Supply the module globals in case the module was
[906] Fix | Delete
# originally loaded via a PEP 302 loader and
[907] Fix | Delete
# file is not a valid filesystem path
[908] Fix | Delete
source_lines = linecache.getlines(file, module.__dict__)
[909] Fix | Delete
else:
[910] Fix | Delete
# No access to a loader, so assume it's a normal
[911] Fix | Delete
# filesystem path
[912] Fix | Delete
source_lines = linecache.getlines(file)
[913] Fix | Delete
if not source_lines:
[914] Fix | Delete
source_lines = None
[915] Fix | Delete
[916] Fix | Delete
# Initialize globals, and merge in extraglobs.
[917] Fix | Delete
if globs is None:
[918] Fix | Delete
if module is None:
[919] Fix | Delete
globs = {}
[920] Fix | Delete
else:
[921] Fix | Delete
globs = module.__dict__.copy()
[922] Fix | Delete
else:
[923] Fix | Delete
globs = globs.copy()
[924] Fix | Delete
if extraglobs is not None:
[925] Fix | Delete
globs.update(extraglobs)
[926] Fix | Delete
if '__name__' not in globs:
[927] Fix | Delete
globs['__name__'] = '__main__' # provide a default module name
[928] Fix | Delete
[929] Fix | Delete
# Recursively explore `obj`, extracting DocTests.
[930] Fix | Delete
tests = []
[931] Fix | Delete
self._find(tests, obj, name, module, source_lines, globs, {})
[932] Fix | Delete
# Sort the tests by alpha order of names, for consistency in
[933] Fix | Delete
# verbose-mode output. This was a feature of doctest in Pythons
[934] Fix | Delete
# <= 2.3 that got lost by accident in 2.4. It was repaired in
[935] Fix | Delete
# 2.4.4 and 2.5.
[936] Fix | Delete
tests.sort()
[937] Fix | Delete
return tests
[938] Fix | Delete
[939] Fix | Delete
def _from_module(self, module, object):
[940] Fix | Delete
"""
[941] Fix | Delete
Return true if the given object is defined in the given
[942] Fix | Delete
module.
[943] Fix | Delete
"""
[944] Fix | Delete
if module is None:
[945] Fix | Delete
return True
[946] Fix | Delete
elif inspect.getmodule(object) is not None:
[947] Fix | Delete
return module is inspect.getmodule(object)
[948] Fix | Delete
elif inspect.isfunction(object):
[949] Fix | Delete
return module.__dict__ is object.__globals__
[950] Fix | Delete
elif inspect.ismethoddescriptor(object):
[951] Fix | Delete
if hasattr(object, '__objclass__'):
[952] Fix | Delete
obj_mod = object.__objclass__.__module__
[953] Fix | Delete
elif hasattr(object, '__module__'):
[954] Fix | Delete
obj_mod = object.__module__
[955] Fix | Delete
else:
[956] Fix | Delete
return True # [XX] no easy way to tell otherwise
[957] Fix | Delete
return module.__name__ == obj_mod
[958] Fix | Delete
elif inspect.isclass(object):
[959] Fix | Delete
return module.__name__ == object.__module__
[960] Fix | Delete
elif hasattr(object, '__module__'):
[961] Fix | Delete
return module.__name__ == object.__module__
[962] Fix | Delete
elif isinstance(object, property):
[963] Fix | Delete
return True # [XX] no way not be sure.
[964] Fix | Delete
else:
[965] Fix | Delete
raise ValueError("object must be a class or function")
[966] Fix | Delete
[967] Fix | Delete
def _find(self, tests, obj, name, module, source_lines, globs, seen):
[968] Fix | Delete
"""
[969] Fix | Delete
Find tests for the given object and any contained objects, and
[970] Fix | Delete
add them to `tests`.
[971] Fix | Delete
"""
[972] Fix | Delete
if self._verbose:
[973] Fix | Delete
print('Finding tests in %s' % name)
[974] Fix | Delete
[975] Fix | Delete
# If we've already processed this object, then ignore it.
[976] Fix | Delete
if id(obj) in seen:
[977] Fix | Delete
return
[978] Fix | Delete
seen[id(obj)] = 1
[979] Fix | Delete
[980] Fix | Delete
# Find a test for this object, and add it to the list of tests.
[981] Fix | Delete
test = self._get_test(obj, name, module, globs, source_lines)
[982] Fix | Delete
if test is not None:
[983] Fix | Delete
tests.append(test)
[984] Fix | Delete
[985] Fix | Delete
# Look for tests in a module's contained objects.
[986] Fix | Delete
if inspect.ismodule(obj) and self._recurse:
[987] Fix | Delete
for valname, val in obj.__dict__.items():
[988] Fix | Delete
valname = '%s.%s' % (name, valname)
[989] Fix | Delete
# Recurse to functions & classes.
[990] Fix | Delete
if ((inspect.isroutine(inspect.unwrap(val))
[991] Fix | Delete
or inspect.isclass(val)) and
[992] Fix | Delete
self._from_module(module, val)):
[993] Fix | Delete
self._find(tests, val, valname, module, source_lines,
[994] Fix | Delete
globs, seen)
[995] Fix | Delete
[996] Fix | Delete
# Look for tests in a module's __test__ dictionary.
[997] Fix | Delete
if inspect.ismodule(obj) and self._recurse:
[998] Fix | Delete
for valname, val in getattr(obj, '__test__', {}).items():
[999] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function