warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning, stacklevel=<NUM_LIT:2>)<EOL>return base[:<NUM_LIT:1>] == "<STR_LIT:_>" and not base[:<NUM_LIT:2>] == "<STR_LIT>" == base[-<NUM_LIT:2>:]<EOL>

prefix, base -> true iff name prefix + "." + base is "private".

    Prefix may be an empty string, and base does not contain a period.
    Prefix is ignored (although functions you write conforming to this
    protocol may make use of it).
    Return true iff base begins with an (at least one) underscore, but
    does not both begin and end with (at least) two underscores.


flags = <NUM_LIT:0><EOL>for fname in __future__.all_feature_names:<EOL><INDENT>feature = globs.get(fname, None)<EOL>if feature is getattr(__future__, fname):<EOL><INDENT>flags |= feature.compiler_flag<EOL><DEDENT><DEDENT>return flags<EOL>

Return the compiler-flags associated with the future features that
have been imported into the given namespace (globs).


if inspect.ismodule(module):<EOL><INDENT>return module<EOL><DEDENT>elif isinstance(module, str):<EOL><INDENT>return __import__(module, globals(), locals(), ["<STR_LIT:*>"])<EOL><DEDENT>elif module is None:<EOL><INDENT>return sys.modules[sys._getframe(depth).f_globals['<STR_LIT>']]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>

Return the module specified by `module`.  In particular:
  - If `module` is a module, then return module.
  - If `module` is a string, then import and return the
    module with that name.
  - If `module` is None, then return the calling module.
    The calling module is assumed to be the module of
    the stack frame at the given depth in the call stack.


<EOL>return re.sub('<STR_LIT>', indent*'<STR_LIT:U+0020>', s)<EOL>

Add the given number of space characters to the beginning every
non-blank line in `s`, and return the result.


<EOL>excout = StringIO()<EOL>exc_type, exc_val, exc_tb = exc_info<EOL>traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)<EOL>return excout.getvalue()<EOL>

Return a string containing a traceback message for the given
exc_info tuple (as returned by sys.exc_info()).


line = line.rstrip()<EOL>if line:<EOL><INDENT>return '<STR_LIT>'+line<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT:#>'<EOL><DEDENT>

Return a commented form of the given line


def run_docstring_examples(f, globs, verbose=False, name="<STR_LIT>",<EOL>compileflags=None, optionflags=<NUM_LIT:0>):

<EOL>finder = DocTestFinder(verbose=verbose, recurse=False)<EOL>runner = DocTestRunner(verbose=verbose, optionflags=optionflags)<EOL>for test in finder.find(f, name, globs=globs):<EOL><INDENT>runner.run(test, compileflags=compileflags)<EOL><DEDENT>

Test examples in the given object's docstring (`f`), using `globs`
as globals.  Optional argument `name` is used in failure messages.
If the optional argument `verbose` is true, then generate output
even if there are no failures.

`compileflags` gives the set of flags that should be used by the
Python compiler when running the examples.  If not specified, then
it will default to the set of future-import flags that apply to
`globs`.

Optional keyword arg `optionflags` specifies options for the
testing and output.  See the documentation for `testmod` for more
information.


suite = unittest.TestSuite()<EOL>if kw.get('<STR_LIT>', True):<EOL><INDENT>kw['<STR_LIT>'] = _normalize_module(kw.get('<STR_LIT>'))<EOL><DEDENT>for path in paths:<EOL><INDENT>suite.addTest(DocFileTest(path, **kw))<EOL><DEDENT>return suite<EOL>

A unittest suite for one or more doctest files.

    The path to each doctest file is given as a string; the
    interpretation of that string depends on the keyword argument
    "module_relative".

    A number of options may be provided as keyword arguments:

    module_relative
      If "module_relative" is True, then the given file paths are
      interpreted as os-independent module-relative paths.  By
      default, these paths are relative to the calling module's
      directory; but if the "package" argument is specified, then
      they are relative to that package.  To ensure os-independence,
      "filename" should use "/" characters to separate path
      segments, and may not be an absolute path (i.e., it may not
      begin with "/").

      If "module_relative" is False, then the given file paths are
      interpreted as os-specific paths.  These paths may be absolute
      or relative (to the current working directory).

    package
      A Python package or the name of a Python package whose directory
      should be used as the base directory for module relative paths.
      If "package" is not specified, then the calling module's
      directory is used as the base directory for module relative
      filenames.  It is an error to specify "package" if
      "module_relative" is False.

    setUp
      A set-up function.  This is called before running the
      tests in each file. The setUp function will be passed a DocTest
      object.  The setUp function can access the test globals as the
      globs attribute of the test passed.

    tearDown
      A tear-down function.  This is called after running the
      tests in each file.  The tearDown function will be passed a DocTest
      object.  The tearDown function can access the test globals as the
      globs attribute of the test passed.

    globs
      A dictionary containing initial global variables for the tests.

    optionflags
      A set of doctest option flags expressed as an integer.

    parser
      A DocTestParser (or subclass) that should be used to extract
      tests from the files.


def debug_src(src, pm=False, globs=None):

testsrc = script_from_examples(src)<EOL>debug_script(testsrc, pm, globs)<EOL>

Debug a single doctest docstring, in argument `src`


def debug_script(src, pm=False, globs=None):

import pdb<EOL>srcfilename = tempfile.mktemp("<STR_LIT>", "<STR_LIT>")<EOL>f = open(srcfilename, '<STR_LIT:w>')<EOL>f.write(src)<EOL>f.close()<EOL>try:<EOL><INDENT>if globs:<EOL><INDENT>globs = globs.copy()<EOL><DEDENT>else:<EOL><INDENT>globs = {}<EOL><DEDENT>if pm:<EOL><INDENT>try:<EOL><INDENT>exec(compile(open(srcfilename, "<STR_LIT:rb>").read(), srcfilename, '<STR_LIT>'), globs, globs)<EOL><DEDENT>except:<EOL><INDENT>print(sys.exc_info()[<NUM_LIT:1>])<EOL>pdb.post_mortem(sys.exc_info()[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>pdb.run("<STR_LIT>" % srcfilename, globs, globs)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>os.remove(srcfilename)<EOL><DEDENT>

Debug a test script.  `src` is the script, as a string.


module = _normalize_module(module)<EOL>testsrc = testsource(module, name)<EOL>debug_script(testsrc, pm, module.__dict__)<EOL>

Debug a single doctest docstring.

    Provide the module (or dotted name of the module) containing the
    test to be debugged and the name (within the module) of the object
    with the docstring with tests to be debugged.


def __init__(self, examples, globs, name, filename, lineno, docstring):

assert not isinstance(examples, str),"<STR_LIT>"<EOL>self.examples = examples<EOL>self.docstring = docstring<EOL>self.globs = globs.copy()<EOL>self.name = name<EOL>self.filename = filename<EOL>self.lineno = lineno<EOL>

Create a new DocTest containing the given examples.  The
DocTest's globals are initialized with a copy of `globs`.


def parse(self, string, name='<STR_LIT>'):

string = string.expandtabs()<EOL>min_indent = self._min_indent(string)<EOL>if min_indent > <NUM_LIT:0>:<EOL><INDENT>string = '<STR_LIT:\n>'.join([l[min_indent:] for l in string.split('<STR_LIT:\n>')])<EOL><DEDENT>output = []<EOL>charno, lineno = <NUM_LIT:0>, <NUM_LIT:0><EOL>for m in self._EXAMPLE_RE.finditer(string):<EOL><INDENT>output.append(string[charno:m.start()])<EOL>lineno += string.count('<STR_LIT:\n>', charno, m.start())<EOL>(source, options, want, exc_msg) =self._parse_example(m, name, lineno)<EOL>if not self._IS_BLANK_OR_COMMENT(source):<EOL><INDENT>output.append( Example(source, want, exc_msg,<EOL>lineno=lineno,<EOL>indent=min_indent+len(m.group('<STR_LIT>')),<EOL>options=options) )<EOL><DEDENT>lineno += string.count('<STR_LIT:\n>', m.start(), m.end())<EOL>charno = m.end()<EOL><DEDENT>output.append(string[charno:])<EOL>return output<EOL>

Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based.  The optional
argument `name` is a name identifying this string, and is only
used for error messages.


def get_examples(self, string, name='<STR_LIT>'):

return [x for x in self.parse(string, name)<EOL>if isinstance(x, Example)]<EOL>

Extract all doctest examples from the given string, and return
them as a list of `Example` objects.  Line numbers are
0-based, because it's most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
and so the first interesting line is called \"line 1\" then.

The optional argument `name` is a name identifying this
string, and is only used for error messages.


def _parse_example(self, m, name, lineno):

<EOL>indent = len(m.group('<STR_LIT>'))<EOL>source_lines = m.group('<STR_LIT:source>').split('<STR_LIT:\n>')<EOL>self._check_prompt_blank(source_lines, indent, name, lineno)<EOL>self._check_prefix(source_lines[<NUM_LIT:1>:], '<STR_LIT:U+0020>'*indent + '<STR_LIT:.>', name, lineno)<EOL>source = '<STR_LIT:\n>'.join([sl[indent+<NUM_LIT:4>:] for sl in source_lines])<EOL>want = m.group('<STR_LIT>')<EOL>want_lines = want.split('<STR_LIT:\n>')<EOL>if len(want_lines) > <NUM_LIT:1> and re.match(r'<STR_LIT>', want_lines[-<NUM_LIT:1>]):<EOL><INDENT>del want_lines[-<NUM_LIT:1>]  <EOL><DEDENT>self._check_prefix(want_lines, '<STR_LIT:U+0020>'*indent, name,<EOL>lineno + len(source_lines))<EOL>want = '<STR_LIT:\n>'.join([wl[indent:] for wl in want_lines])<EOL>m = self._EXCEPTION_RE.match(want)<EOL>if m:<EOL><INDENT>exc_msg = m.group('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>exc_msg = None<EOL><DEDENT>options = self._find_options(source, name, lineno)<EOL>return source, options, want, exc_msg<EOL>

Given a regular expression match from `_EXAMPLE_RE` (`m`),
return a pair `(source, want)`, where `source` is the matched
example's source code (with prompts and indentation stripped);
and `want` is the example's expected output (with indentation
stripped).

`name` is the string's name, and `lineno` is the line number
where the example starts; both are used for error messages.


def _find_options(self, source, name, lineno):

options = {}<EOL>for m in self._OPTION_DIRECTIVE_RE.finditer(source):<EOL><INDENT>option_strings = m.group(<NUM_LIT:1>).replace('<STR_LIT:U+002C>', '<STR_LIT:U+0020>').split()<EOL>for option in option_strings:<EOL><INDENT>if (option[<NUM_LIT:0>] not in '<STR_LIT>' or<EOL>option[<NUM_LIT:1>:] not in OPTIONFLAGS_BY_NAME):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(lineno+<NUM_LIT:1>, name, option))<EOL><DEDENT>flag = OPTIONFLAGS_BY_NAME[option[<NUM_LIT:1>:]]<EOL>options[flag] = (option[<NUM_LIT:0>] == '<STR_LIT:+>')<EOL><DEDENT><DEDENT>if options and self._IS_BLANK_OR_COMMENT(source):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(lineno, name, source))<EOL><DEDENT>return options<EOL>

Return a dictionary containing option overrides extracted from
option directives in the given source string.

`name` is the string's name, and `lineno` is the line number
where the example starts; both are used for error messages.


indents = [len(indent) for indent in self._INDENT_RE.findall(s)]<EOL>if len(indents) > <NUM_LIT:0>:<EOL><INDENT>return min(indents)<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

Return the minimum indentation of any non-blank line in `s`


def _check_prompt_blank(self, lines, indent, name, lineno):

for i, line in enumerate(lines):<EOL><INDENT>if len(line) >= indent+<NUM_LIT:4> and line[indent+<NUM_LIT:3>] != '<STR_LIT:U+0020>':<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(lineno+i+<NUM_LIT:1>, name,<EOL>line[indent:indent+<NUM_LIT:3>], line))<EOL><DEDENT><DEDENT>

Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character.  If any line is not followed by
a space character, then raise ValueError.


def _check_prefix(self, lines, prefix, name, lineno):

for i, line in enumerate(lines):<EOL><INDENT>if line and not line.startswith(prefix):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' %<EOL>(lineno+i+<NUM_LIT:1>, name, line))<EOL><DEDENT><DEDENT>

Check that every line in the given list starts with the given
prefix; if any line does not, then raise a ValueError.


def __init__(self, verbose=False, parser=DocTestParser(),<EOL>recurse=True, _namefilter=None, exclude_empty=True):

self._parser = parser<EOL>self._verbose = verbose<EOL>self._recurse = recurse<EOL>self._exclude_empty = exclude_empty<EOL>self._namefilter = _namefilter<EOL>

Create a new doctest finder.

The optional argument `parser` specifies a class or
function that should be used to create new DocTest objects (or
objects that implement the same interface as DocTest).  The
signature for this factory function should match the signature
of the DocTest constructor.

If the optional argument `recurse` is false, then `find` will
only examine the given object, and not any contained objects.

If the optional argument `exclude_empty` is false, then `find`
will include tests for objects with empty docstrings.


def find(self, obj, name=None, module=None, globs=None,<EOL>extraglobs=None):

<EOL>if name is None:<EOL><INDENT>name = getattr(obj, '<STR_LIT>', None)<EOL>if name is None:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(type(obj),))<EOL><DEDENT><DEDENT>if module is False:<EOL><INDENT>module = None<EOL><DEDENT>elif module is None:<EOL><INDENT>module = inspect.getmodule(obj)<EOL><DEDENT>try:<EOL><INDENT>file = inspect.getsourcefile(obj) or inspect.getfile(obj)<EOL>source_lines = linecache.getlines(file)<EOL>if not source_lines:<EOL><INDENT>source_lines = None<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>source_lines = None<EOL><DEDENT>if globs is None:<EOL><INDENT>if module is None:<EOL><INDENT>globs = {}<EOL><DEDENT>else:<EOL><INDENT>globs = module.__dict__.copy()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>globs = globs.copy()<EOL><DEDENT>if extraglobs is not None:<EOL><INDENT>globs.update(extraglobs)<EOL><DEDENT>tests = []<EOL>self._find(tests, obj, name, module, source_lines, globs, {})<EOL>tests.sort()<EOL>return tests<EOL>

Return a list of the DocTests that are defined by the given
object's docstring, or by any of its contained objects'
docstrings.

The optional parameter `module` is the module that contains
the given object.  If the module is not specified or is None, then
the test finder will attempt to automatically determine the
correct module.  The object's module is used:

    - As a default namespace, if `globs` is not specified.
    - To prevent the DocTestFinder from extracting DocTests
      from objects that are imported from other modules.
    - To find the name of the file containing the object.
    - To help find the line number of the object within its
      file.

Contained objects whose module does not match `module` are ignored.

If `module` is False, no attempt to find the module will be made.
This is obscure, of use mostly in tests:  if `module` is False, or
is None but cannot be found automatically, then all objects are
considered to belong to the (non-existent) module, so all contained
objects will (recursively) be searched for doctests.

The globals for each DocTest is formed by combining `globs`
and `extraglobs` (bindings in `extraglobs` override bindings
in `globs`).  A new copy of the globals dictionary is created
for each DocTest.  If `globs` is not specified, then it
defaults to the module's `__dict__`, if specified, or {}
otherwise.  If `extraglobs` is not specified, then it defaults
to {}.


return (self._namefilter is not None and<EOL>self._namefilter(prefix, base))<EOL>

Return true if the given object should not be examined.


if module is None:<EOL><INDENT>return True<EOL><DEDENT>elif inspect.isfunction(object):<EOL><INDENT>return module.__dict__ is object.__globals__<EOL><DEDENT>elif inspect.isclass(object):<EOL><INDENT>return module.__name__ == getattr(object, '<STR_LIT>', None)<EOL><DEDENT>elif inspect.getmodule(object) is not None:<EOL><INDENT>return module is inspect.getmodule(object)<EOL><DEDENT>elif hasattr(object, '<STR_LIT>'):<EOL><INDENT>return module.__name__ == object.__module__<EOL><DEDENT>elif isinstance(object, property):<EOL><INDENT>return True <EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Return true if the given object is defined in the given
module.


def _find_lineno(self, obj, source_lines):

lineno = None<EOL>if inspect.ismodule(obj):<EOL><INDENT>lineno = <NUM_LIT:0><EOL><DEDENT>if inspect.isclass(obj):<EOL><INDENT>if source_lines is None:<EOL><INDENT>return None<EOL><DEDENT>pat = re.compile(r'<STR_LIT>' %<EOL>getattr(obj, '<STR_LIT>', '<STR_LIT:->'))<EOL>for i, line in enumerate(source_lines):<EOL><INDENT>if pat.match(line):<EOL><INDENT>lineno = i<EOL>break<EOL><DEDENT><DEDENT><DEDENT>if inspect.ismethod(obj): obj = obj.__func__<EOL>if inspect.isfunction(obj): obj = obj.__code__<EOL>if inspect.istraceback(obj): obj = obj.tb_frame<EOL>if inspect.isframe(obj): obj = obj.f_code<EOL>if inspect.iscode(obj):<EOL><INDENT>lineno = getattr(obj, '<STR_LIT>', None)-<NUM_LIT:1><EOL><DEDENT>if lineno is not None:<EOL><INDENT>if source_lines is None:<EOL><INDENT>return lineno+<NUM_LIT:1><EOL><DEDENT>pat = re.compile('<STR_LIT>')<EOL>for lineno in range(lineno, len(source_lines)):<EOL><INDENT>if pat.match(source_lines[lineno]):<EOL><INDENT>return lineno<EOL><DEDENT><DEDENT><DEDENT>return None<EOL>

Return a line number of the given object's docstring.  Note:
this method assumes that the object has a docstring.


def __init__(self, checker=None, verbose=None, optionflags=<NUM_LIT:0>):

self._checker = checker or OutputChecker()<EOL>if verbose is None:<EOL><INDENT>verbose = '<STR_LIT>' in sys.argv<EOL><DEDENT>self._verbose = verbose<EOL>self.optionflags = optionflags<EOL>self.original_optionflags = optionflags<EOL>self.tries = <NUM_LIT:0><EOL>self.failures = <NUM_LIT:0><EOL>self._name2ft = {}<EOL>self._fakeout = _SpoofOut()<EOL>

Create a new test runner.

Optional keyword arg `checker` is the `OutputChecker` that
should be used to compare the expected outputs and actual
outputs of doctest examples.

Optional keyword arg 'verbose' prints lots of stuff if true,
only failures if false; by default, it's true iff '-v' is in
sys.argv.

Optional argument `optionflags` can be used to control how the
test runner compares expected output to actual output, and how
it displays failures.  See the documentation for `testmod` for
more information.


if verbose is None:<EOL><INDENT>verbose = self._verbose<EOL><DEDENT>notests = []<EOL>passed = []<EOL>failed = []<EOL>totalt = totalf = <NUM_LIT:0><EOL>for x in list(self._name2ft.items()):<EOL><INDENT>name, (f, t) = x<EOL>assert f <= t<EOL>totalt += t<EOL>totalf += f<EOL>if t == <NUM_LIT:0>:<EOL><INDENT>notests.append(name)<EOL><DEDENT>elif f == <NUM_LIT:0>:<EOL><INDENT>passed.append( (name, t) )<EOL><DEDENT>else:<EOL><INDENT>failed.append(x)<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>if notests:<EOL><INDENT>print(len(notests), "<STR_LIT>")<EOL>notests.sort()<EOL>for thing in notests:<EOL><INDENT>print("<STR_LIT:U+0020>", thing)<EOL><DEDENT><DEDENT>if passed:<EOL><INDENT>print(len(passed), "<STR_LIT>")<EOL>passed.sort()<EOL>for thing, count in passed:<EOL><INDENT>print("<STR_LIT>" % (count, thing))<EOL><DEDENT><DEDENT><DEDENT>if failed:<EOL><INDENT>print(self.DIVIDER)<EOL>print(len(failed), "<STR_LIT>")<EOL>failed.sort()<EOL>for thing, (f, t) in failed:<EOL><INDENT>print("<STR_LIT>" % (f, t, thing))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print(totalt, "<STR_LIT>", len(self._name2ft), "<STR_LIT>")<EOL>print(totalt - totalf, "<STR_LIT>", totalf, "<STR_LIT>")<EOL><DEDENT>if totalf:<EOL><INDENT>print("<STR_LIT>", totalf, "<STR_LIT>")<EOL><DEDENT>elif verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return totalf, totalt<EOL>

Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.

The optional `verbose` argument controls how detailed the
summary is.  If the verbosity is not specified, then the
DocTestRunner's verbosity is used.


def check_output(self, want, got, optionflags):

<EOL>if got == want:<EOL><INDENT>return True<EOL><DEDENT>if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):<EOL><INDENT>if (got,want) == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return True<EOL><DEDENT>if (got,want) == ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>if not (optionflags & DONT_ACCEPT_BLANKLINE):<EOL><INDENT>want = re.sub('<STR_LIT>' % re.escape(BLANKLINE_MARKER),<EOL>'<STR_LIT>', want)<EOL>got = re.sub('<STR_LIT>', '<STR_LIT>', got)<EOL>if got == want:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>if optionflags & NORMALIZE_WHITESPACE:<EOL><INDENT>got = '<STR_LIT:U+0020>'.join(got.split())<EOL>want = '<STR_LIT:U+0020>'.join(want.split())<EOL>if got == want:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>if optionflags & ELLIPSIS:<EOL><INDENT>if _ellipsis_match(want, got):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Return True iff the actual output from an example (`got`)
matches the expected output (`want`).  These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible.  See the
documentation for `TestRunner` for more information about
option flags.


def output_difference(self, example, got, optionflags):

want = example.want<EOL>if not (optionflags & DONT_ACCEPT_BLANKLINE):<EOL><INDENT>got = re.sub('<STR_LIT>', BLANKLINE_MARKER, got)<EOL><DEDENT>if self._do_a_fancy_diff(want, got, optionflags):<EOL><INDENT>want_lines = want.splitlines(True)  <EOL>got_lines = got.splitlines(True)<EOL>if optionflags & REPORT_UDIFF:<EOL><INDENT>diff = difflib.unified_diff(want_lines, got_lines, n=<NUM_LIT:2>)<EOL>diff = list(diff)[<NUM_LIT:2>:] <EOL>kind = '<STR_LIT>'<EOL><DEDENT>elif optionflags & REPORT_CDIFF:<EOL><INDENT>diff = difflib.context_diff(want_lines, got_lines, n=<NUM_LIT:2>)<EOL>diff = list(diff)[<NUM_LIT:2>:] <EOL>kind = '<STR_LIT>'<EOL><DEDENT>elif optionflags & REPORT_NDIFF:<EOL><INDENT>engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)<EOL>diff = list(engine.compare(want_lines, got_lines))<EOL>kind = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>assert <NUM_LIT:0>, '<STR_LIT>'<EOL><DEDENT>diff = [line.rstrip() + '<STR_LIT:\n>' for line in diff]<EOL>return '<STR_LIT>' % kind + _indent('<STR_LIT>'.join(diff))<EOL><DEDENT>if want and got:<EOL><INDENT>return '<STR_LIT>' % (_indent(want), _indent(got))<EOL><DEDENT>elif want:<EOL><INDENT>return '<STR_LIT>' % _indent(want)<EOL><DEDENT>elif got:<EOL><INDENT>return '<STR_LIT>' % _indent(got)<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>

Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`).  `optionflags` is the set of option flags used
to compare `want` and `got`.


class Key(object):<EOL><INDENT>def __init__(self, obj):<EOL><INDENT>self.obj = obj<EOL><DEDENT>def __lt__(self, other):<EOL><INDENT>return mycmp(self.obj, other.obj) < <NUM_LIT:0><EOL><DEDENT>def __gt__(self, other):<EOL><INDENT>return mycmp(self.obj, other.obj) > <NUM_LIT:0><EOL><DEDENT>def __eq__(self, other):<EOL><INDENT>return mycmp(self.obj, other.obj) == <NUM_LIT:0><EOL><DEDENT><DEDENT>return Key<EOL>

Convert a cmp= function into a key= function


def autohelp_directive(dirname, arguments, options, content, lineno,<EOL>content_offset, block_text, state, state_machine):

config = Config(parserClass=OptBucket,<EOL>plugins=BuiltinPluginManager())<EOL>parser = config.getParser(TestProgram.usage())<EOL>rst = ViewList()<EOL>for line in parser.format_help().split('<STR_LIT:\n>'):<EOL><INDENT>rst.append(line, '<STR_LIT>')<EOL><DEDENT>rst.append('<STR_LIT>', '<STR_LIT>')<EOL>rst.append('<STR_LIT>', '<STR_LIT>')<EOL>rst.append('<STR_LIT>', '<STR_LIT>')<EOL>for opt in parser:<EOL><INDENT>rst.append(opt.options(), '<STR_LIT>')<EOL>rst.append('<STR_LIT>', '<STR_LIT>')<EOL>rst.append('<STR_LIT:U+0020>' + opt.help + '<STR_LIT:\n>', '<STR_LIT>')<EOL>rst.append('<STR_LIT:\n>', '<STR_LIT>')    <EOL><DEDENT>node = nodes.section()<EOL>node.document = state.document<EOL>surrounding_title_styles = state.memo.title_styles<EOL>surrounding_section_level = state.memo.section_level<EOL>state.memo.title_styles = []<EOL>state.memo.section_level = <NUM_LIT:0><EOL>state.nested_parse(rst, <NUM_LIT:0>, node, match_titles=<NUM_LIT:1>)<EOL>state.memo.title_styles = surrounding_title_styles<EOL>state.memo.section_level = surrounding_section_level<EOL>return node.children<EOL>


try:<EOL><INDENT>self.status.pop('<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>if not hasattr(options, '<STR_LIT>'):<EOL><INDENT>self.enabled = False<EOL>return<EOL><DEDENT>if config.worker:<EOL><INDENT>return<EOL><DEDENT>self.config = config<EOL>try:<EOL><INDENT>workers = int(options.multiprocess_workers)<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>workers = <NUM_LIT:0><EOL><DEDENT>if workers:<EOL><INDENT>_import_mp()<EOL>if Process is None:<EOL><INDENT>self.enabled = False<EOL>return<EOL><DEDENT>self.enabled = True<EOL>self.config.multiprocess_workers = workers<EOL>t = float(options.multiprocess_timeout)<EOL>self.config.multiprocess_timeout = t<EOL>r = int(options.multiprocess_restartworker)<EOL>self.config.multiprocess_restartworker = r<EOL>self.status['<STR_LIT>'] = True<EOL><DEDENT>


self.loaderClass = loader.__class__<EOL>

Remember loader class so MultiProcessTestRunner can instantiate
        the right loader.


<EOL>return MultiProcessTestRunner(stream=runner.stream,<EOL>verbosity=self.config.verbosity,<EOL>config=self.config,<EOL>loaderClass=self.loaderClass)<EOL>

Replace test runner with MultiProcessTestRunner.


if not fixt:<EOL><INDENT>return False<EOL><DEDENT>if getattr(context, '<STR_LIT>', False):<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

Callback that we use to check whether the fixtures found in a
context or ancestor are ones we care about.

Contexts can tell us that their fixtures are reentrant by setting
_multiprocess_can_split_. So if we see that, we return False to
disregard those fixtures.


<EOL>log.debug("<STR_LIT>",<EOL>id(self), self, self._tests)<EOL>if self.resultProxy:<EOL><INDENT>result, orig = self.resultProxy(result, self), result<EOL><DEDENT>else:<EOL><INDENT>result, orig = result, result<EOL><DEDENT>try:<EOL><INDENT>self.setUp()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>self.error_context = '<STR_LIT>'<EOL>result.addError(self, self._exc_info())<EOL>return<EOL><DEDENT>try:<EOL><INDENT>for test in self._tests:<EOL><INDENT>if (isinstance(test,nose.case.Test)<EOL>and self.arg is not None):<EOL><INDENT>test.test.arg = self.arg<EOL><DEDENT>else:<EOL><INDENT>test.arg = self.arg<EOL><DEDENT>test.testQueue = self.testQueue<EOL>test.tasks = self.tasks<EOL>if result.shouldStop:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>break<EOL><DEDENT>try:<EOL><INDENT>test(orig)<EOL><DEDENT>except KeyboardInterrupt as e:<EOL><INDENT>timeout = isinstance(e, TimedOutException)<EOL>if timeout:<EOL><INDENT>msg = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>'<EOL><DEDENT>log.debug(msg, test, self)<EOL>err = (TimedOutException,TimedOutException(str(test)),<EOL>sys.exc_info()[<NUM_LIT:2>])<EOL>test.config.plugins.addError(test,err)<EOL>orig.addError(test,err)<EOL>if not timeout:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>self.has_run = True<EOL>try:<EOL><INDENT>self.tearDown()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>self.error_context = '<STR_LIT>'<EOL>result.addError(self, self._exc_info())<EOL><DEDENT><DEDENT>

Run tests in suite inside of suite fixtures.


if not self.available():<EOL><INDENT>return<EOL><DEDENT>self._create_pfile()<EOL>self.prof = hotshot.Profile(self.pfile)<EOL>

Create profile stats file and load profiler.


if not self.available():<EOL><INDENT>self.enabled = False<EOL>return<EOL><DEDENT>Plugin.configure(self, options, conf)<EOL>self.conf = conf<EOL>if options.profile_stats_file:<EOL><INDENT>self.pfile = options.profile_stats_file<EOL>self.clean_stats_file = False<EOL><DEDENT>else:<EOL><INDENT>self.pfile = None<EOL>self.clean_stats_file = True<EOL><DEDENT>self.fileno = None<EOL>self.sort = options.profile_sort<EOL>self.restrict = tolist(options.profile_restrict)<EOL>


log.debug('<STR_LIT>')<EOL>self.prof.close()<EOL>prof_stats = stats.load(self.pfile)<EOL>prof_stats.sort_stats(self.sort)<EOL>compat_25 = hasattr(prof_stats, '<STR_LIT>')<EOL>if compat_25:<EOL><INDENT>tmp = prof_stats.stream<EOL>prof_stats.stream = stream<EOL><DEDENT>else:<EOL><INDENT>tmp = sys.stdout<EOL>sys.stdout = stream<EOL><DEDENT>try:<EOL><INDENT>if self.restrict:<EOL><INDENT>log.debug('<STR_LIT>', self.restrict)<EOL>prof_stats.print_stats(*self.restrict)<EOL><DEDENT>else:<EOL><INDENT>prof_stats.print_stats()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if compat_25:<EOL><INDENT>prof_stats.stream = tmp<EOL><DEDENT>else:<EOL><INDENT>sys.stdout = tmp<EOL><DEDENT><DEDENT>


if not self.available():<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>self.prof.close()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>if self.clean_stats_file:<EOL><INDENT>if self.fileno:<EOL><INDENT>try:<EOL><INDENT>os.close(self.fileno)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>os.unlink(self.pfile)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return None<EOL>

Clean up stats file, if configured to do so.


meth = getattr(plugin, call, None)<EOL>if meth is not None:<EOL><INDENT>if call == '<STR_LIT>' andlen(inspect.getargspec(meth)[<NUM_LIT:0>]) == <NUM_LIT:2>:<EOL><INDENT>orig_meth = meth<EOL>meth = lambda module, path, **kwargs: orig_meth(module)<EOL><DEDENT>self.plugins.append((plugin, meth))<EOL><DEDENT>

Add plugin to my list of plugins to call, if it has the attribute
        I'm bound to.


result = None<EOL>static = [a for (static, a)<EOL>in zip(getattr(self.method, '<STR_LIT>', []), arg)<EOL>if static]<EOL>for p, meth in self.plugins:<EOL><INDENT>result = meth(*arg, **kw)<EOL>arg = static[:]<EOL>arg.append(result)<EOL><DEDENT>return result<EOL>

Call plugins in a chain, where the result of each plugin call is
        sent to the next plugin as input. The final output result is returned.


for p, meth in self.plugins:<EOL><INDENT>result = None<EOL>try:<EOL><INDENT>result = meth(*arg, **kw)<EOL>if result is not None:<EOL><INDENT>for r in result:<EOL><INDENT>yield r<EOL><DEDENT><DEDENT><DEDENT>except (KeyboardInterrupt, SystemExit):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>exc = sys.exc_info()<EOL>yield Failure(*exc)<EOL>continue<EOL><DEDENT><DEDENT>

Call all plugins, yielding each item in each non-None result.


for p, meth in self.plugins:<EOL><INDENT>result = meth(*arg, **kw)<EOL>if result is not None:<EOL><INDENT>return result<EOL><DEDENT><DEDENT>

Call all plugins, returning the first non-None result.


def _loadTestsFromNames(self, names, module=None):

suite = []<EOL>for p, meth in self.plugins:<EOL><INDENT>result = meth(names, module=module)<EOL>if result is not None:<EOL><INDENT>suite_part, names = result<EOL>if suite_part:<EOL><INDENT>suite.extend(suite_part)<EOL><DEDENT><DEDENT><DEDENT>return suite, names<EOL>

Chainable but not quite normal. Plugins return a tuple of
        (tests, names) after processing the names. The tests are added
        to a suite that is accumulated throughout the full call, while
        names are input for the next plugin in the chain.


def addPlugins(self, plugins=(), extraplugins=()):

self._extraplugins = extraplugins<EOL>for plug in iterchain(plugins, extraplugins):<EOL><INDENT>self.addPlugin(plug)<EOL><DEDENT>

extraplugins are maintained in a separate list and
        re-added by loadPlugins() to prevent their being overwritten
        by plugins added by a subclass of PluginManager


log.debug("<STR_LIT>")<EOL>self.config = config<EOL>cfg = PluginProxy('<STR_LIT>', self._plugins)<EOL>cfg(options, config)<EOL>enabled = [plug for plug in self._plugins if plug.enabled]<EOL>self.plugins = enabled<EOL>self.sort()<EOL>log.debug("<STR_LIT>", enabled)<EOL>

Configure the set of plugins with the given options
        and config instance. After configuration, disabled plugins
        are removed from the plugins list.


from pkg_resources import iter_entry_points<EOL>loaded = {}<EOL>for entry_point, adapt in self.entry_points:<EOL><INDENT>for ep in iter_entry_points(entry_point):<EOL><INDENT>if ep.name in loaded:<EOL><INDENT>continue<EOL><DEDENT>loaded[ep.name] = True<EOL>log.debug('<STR_LIT>', self.__class__.__name__, ep)<EOL>try:<EOL><INDENT>plugcls = ep.load()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except Exception as e:<EOL><INDENT>warn("<STR_LIT>" % (ep, e),<EOL>RuntimeWarning)<EOL>continue<EOL><DEDENT>if adapt:<EOL><INDENT>plug = adapt(plugcls())<EOL><DEDENT>else:<EOL><INDENT>plug = plugcls()<EOL><DEDENT>self.addPlugin(plug)<EOL><DEDENT><DEDENT>super(EntryPointPluginManager, self).loadPlugins()<EOL>

Load plugins by iterating the `nose.plugins` entry point.


from nose.plugins import builtin<EOL>for plug in builtin.plugins:<EOL><INDENT>self.addPlugin(plug())<EOL><DEDENT>super(BuiltinPluginManager, self).loadPlugins()<EOL>


Plugin.configure(self, options, conf)<EOL>self._mod_stack = []<EOL>


mods = sys.modules.copy()<EOL>self._mod_stack.append(mods)<EOL>


mods = self._mod_stack.pop()<EOL>to_del = [ m for m in sys.modules.keys() if m not in mods ]<EOL>if to_del:<EOL><INDENT>log.debug('<STR_LIT>', to_del)<EOL>for mod in to_del:<EOL><INDENT>del sys.modules[mod]<EOL><DEDENT><DEDENT>sys.modules.update(mods)<EOL>

Pop my mod stack and restore sys.modules to the state
        it was in when mod stack was pushed.


def loadTestsFromNames(self, names, module=None):

<EOL>if not names or len(names) == <NUM_LIT:1>:<EOL><INDENT>return <EOL><DEDENT>loader = self.loader<EOL>plugins = self.conf.plugins<EOL>def lazy():<EOL><INDENT>for name in names:<EOL><INDENT>plugins.beforeContext()<EOL>yield loader.loadTestsFromName(name, module=module)<EOL>plugins.afterContext()<EOL><DEDENT><DEDENT>return (loader.suiteClass(lazy), [])<EOL>

Create a lazy suite that calls beforeContext and afterContext
        around each name. The side-effect of this is that full context
        fixtures will be set up and torn down around each test named.


self.loader = loader<EOL>

Get handle on test loader so we can use it in loadTestsFromNames.


Plugin.configure(self, options, config)<EOL>self.doctest_result_var = options.doctest_result_var<EOL>self.doctest_tests = options.doctest_tests<EOL>self.extension = tolist(options.doctestExtension)<EOL>self.fixtures = options.doctestFixtures<EOL>self.finder = doctest.DocTestFinder()<EOL>self.optionflags = <NUM_LIT:0><EOL>if options.doctestOptions:<EOL><INDENT>flags = "<STR_LIT:U+002C>".join(options.doctestOptions).split('<STR_LIT:U+002C>')<EOL>for flag in flags:<EOL><INDENT>try:<EOL><INDENT>if flag.startswith('<STR_LIT:+>'):<EOL><INDENT>self.optionflags |= getattr(doctest, flag[<NUM_LIT:1>:])<EOL><DEDENT>elif flag.startswith('<STR_LIT:->'):<EOL><INDENT>self.optionflags &= ~getattr(doctest, flag[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>" % (flag,))<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(flag[<NUM_LIT:1>:],))<EOL><DEDENT><DEDENT><DEDENT>


self.suiteClass = loader.suiteClass<EOL>

Capture loader's suiteClass.

        This is used to create test suites from doctest files.


log.debug("<STR_LIT>", module)<EOL>if not self.matches(module.__name__):<EOL><INDENT>log.debug("<STR_LIT>", module)<EOL>return<EOL><DEDENT>try:<EOL><INDENT>tests = self.finder.find(module)<EOL><DEDENT>except AttributeError:<EOL><INDENT>log.exception("<STR_LIT>", module)<EOL>return<EOL><DEDENT>if not tests:<EOL><INDENT>log.debug("<STR_LIT>", module)<EOL>return<EOL><DEDENT>tests.sort()<EOL>module_file = src(module.__file__)<EOL>cases = []<EOL>for test in tests:<EOL><INDENT>if not test.examples:<EOL><INDENT>continue<EOL><DEDENT>if not test.filename:<EOL><INDENT>test.filename = module_file<EOL><DEDENT>cases.append(DocTestCase(test,<EOL>optionflags=self.optionflags,<EOL>result_var=self.doctest_result_var))<EOL><DEDENT>if cases:<EOL><INDENT>yield self.suiteClass(cases, context=module, can_split=False)<EOL><DEDENT>


if self.extension and anyp(filename.endswith, self.extension):<EOL><INDENT>name = os.path.basename(filename)<EOL>dh = open(filename)<EOL>try:<EOL><INDENT>doc = dh.read()<EOL><DEDENT>finally:<EOL><INDENT>dh.close()<EOL><DEDENT>fixture_context = None<EOL>globs = {'<STR_LIT>': filename}<EOL>if self.fixtures:<EOL><INDENT>base, ext = os.path.splitext(name)<EOL>dirname = os.path.dirname(filename)<EOL>sys.path.append(dirname)<EOL>fixt_mod = base + self.fixtures<EOL>try:<EOL><INDENT>fixture_context = __import__(<EOL>fixt_mod, globals(), locals(), ["<STR_LIT>"])<EOL><DEDENT>except ImportError as e:<EOL><INDENT>log.debug(<EOL>"<STR_LIT>", fixt_mod, e, sys.path)<EOL><DEDENT>log.debug("<STR_LIT>",<EOL>fixt_mod, fixture_context)<EOL>if hasattr(fixture_context, '<STR_LIT>'):<EOL><INDENT>globs = fixture_context.globs(globs)                    <EOL><DEDENT><DEDENT>parser = doctest.DocTestParser()<EOL>test = parser.get_doctest(<EOL>doc, globs=globs, name=name,<EOL>filename=filename, lineno=<NUM_LIT:0>)<EOL>if test.examples:<EOL><INDENT>case = DocFileCase(<EOL>test,<EOL>optionflags=self.optionflags,<EOL>setUp=getattr(fixture_context, '<STR_LIT>', None),<EOL>tearDown=getattr(fixture_context, '<STR_LIT>', None),<EOL>result_var=self.doctest_result_var)<EOL>if fixture_context:<EOL><INDENT>yield ContextList((case,), context=fixture_context)<EOL><DEDENT>else:<EOL><INDENT>yield case<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield False<EOL><DEDENT><DEDENT>

Load doctests from the file.

        Tests are loaded only if filename's extension matches
        configured doctest extension.


name = getattr(obj, '<STR_LIT>', '<STR_LIT>' % type(obj))<EOL>doctests = self.finder.find(obj, module=getmodule(parent), name=name)<EOL>if doctests:<EOL><INDENT>for test in doctests:<EOL><INDENT>if len(test.examples) == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>yield DocTestCase(test, obj=obj, optionflags=self.optionflags,<EOL>result_var=self.doctest_result_var)<EOL><DEDENT><DEDENT>

Look for doctests in the given object, which will be a
        function, method or class.


<EOL>if file.endswith('<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>if (self.extension<EOL>and anyp(file.endswith, self.extension)<EOL>and (not self.conf.exclude<EOL>or not [_f for _f in [exc.search(file)<EOL>for exc in self.conf.exclude] if _f])):<EOL><INDENT>return True<EOL><DEDENT>return None<EOL>

Override to select all modules and any file ending with
        configured doctest extension.


if not self:<EOL><INDENT>return True<EOL><DEDENT>return self._allow(record) and not self._deny(record)<EOL>

returns whether this record should be printed


def record_matches_key(key):<EOL><INDENT>return record == key or record.startswith(key + '<STR_LIT:.>')<EOL><DEDENT>return anyp(bool, map(record_matches_key, matchers))<EOL>

return the bool of whether `record` starts with
        any item in `matchers`


self.conf = conf<EOL>if not options.logcapture or conf.loggingConfig:<EOL><INDENT>self.enabled = False<EOL><DEDENT>self.logformat = options.logcapture_format<EOL>self.logdatefmt = options.logcapture_datefmt<EOL>self.clear = options.logcapture_clear<EOL>self.loglevel = options.logcapture_level<EOL>if options.logcapture_filters:<EOL><INDENT>self.filters = options.logcapture_filters.split('<STR_LIT:U+002C>')<EOL><DEDENT>


self.start()<EOL>

Set up logging handler before test run begins.


def wrap_ob(ob):<EOL><INDENT>for name in args:<EOL><INDENT>setattr(ob, name, True)<EOL><DEDENT>for name, value in kwargs.iteritems():<EOL><INDENT>setattr(ob, name, value)<EOL><DEDENT>return ob<EOL><DEDENT>return wrap_ob<EOL>

Decorator that adds attributes to classes or functions
    for use with the Attribute (-a) plugin.


def get_method_attr(method, cls, attr_name, default = False):

Missing = object()<EOL>value = getattr(method, attr_name, Missing)<EOL>if value is Missing and cls is not None:<EOL><INDENT>value = getattr(cls, attr_name, Missing)<EOL><DEDENT>if value is Missing:<EOL><INDENT>return default<EOL><DEDENT>return value<EOL>

Look up an attribute on a method/ function.
    If the attribute isn't found there, looking it up in the
    method's class, if any.


self.attribs = []<EOL>if compat_24 and options.eval_attr:<EOL><INDENT>eval_attr = tolist(options.eval_attr)<EOL>for attr in eval_attr:<EOL><INDENT>def eval_in_context(expr, obj, cls):<EOL><INDENT>return eval(expr, None, ContextHelper(obj, cls))<EOL><DEDENT>self.attribs.append([(attr, eval_in_context)])<EOL><DEDENT><DEDENT>if options.attr:<EOL><INDENT>std_attr = tolist(options.attr)<EOL>for attr in std_attr:<EOL><INDENT>attr_group = []<EOL>for attrib in attr.strip().split("<STR_LIT:U+002C>"):<EOL><INDENT>if not attrib:<EOL><INDENT>continue<EOL><DEDENT>items = attrib.split("<STR_LIT:=>", <NUM_LIT:1>)<EOL>if len(items) > <NUM_LIT:1>:<EOL><INDENT>key, value = items<EOL><DEDENT>else:<EOL><INDENT>key = items[<NUM_LIT:0>]<EOL>if key[<NUM_LIT:0>] == "<STR_LIT:!>":<EOL><INDENT>key = key[<NUM_LIT:1>:]<EOL>value = False<EOL><DEDENT>else:<EOL><INDENT>value = True<EOL><DEDENT><DEDENT>attr_group.append((key, value))<EOL><DEDENT>self.attribs.append(attr_group)<EOL><DEDENT><DEDENT>if self.attribs:<EOL><INDENT>self.enabled = True<EOL><DEDENT>

Configure the plugin and system, based on selected options.

        attr and eval_attr may each be lists.

        self.attribs will be a list of lists of tuples. In that list, each
        list is a group of attributes, all of which must match for the rule to
        match.


def validateAttrib(self, method, cls = None):

<EOL>any = False<EOL>for group in self.attribs:<EOL><INDENT>match = True<EOL>for key, value in group:<EOL><INDENT>attr = get_method_attr(method, cls, key)<EOL>if callable(value):<EOL><INDENT>if not value(key, method, cls):<EOL><INDENT>match = False<EOL>break<EOL><DEDENT><DEDENT>elif value is True:<EOL><INDENT>if not bool(attr):<EOL><INDENT>match = False<EOL>break<EOL><DEDENT><DEDENT>elif value is False:<EOL><INDENT>if bool(attr):<EOL><INDENT>match = False<EOL>break<EOL><DEDENT><DEDENT>elif type(attr) in (list, tuple):<EOL><INDENT>if not str(value).lower() in [str(x).lower()<EOL>for x in attr]:<EOL><INDENT>match = False<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if (value != attr<EOL>and str(value).lower() != str(attr).lower()):<EOL><INDENT>match = False<EOL>break<EOL><DEDENT><DEDENT><DEDENT>any = any or match<EOL><DEDENT>if any:<EOL><INDENT>return None<EOL><DEDENT>return False<EOL>

Verify whether a method has the required attributes
        The method is considered a match if it matches all attributes
        for any attribute group.
        .


return self.validateAttrib(function)<EOL>

Accept the function if its attributes match.


try:<EOL><INDENT>cls = method.im_class<EOL><DEDENT>except AttributeError:<EOL><INDENT>return False<EOL><DEDENT>return self.validateAttrib(method, cls)<EOL>

Accept the method if its attributes match.


env_opt = '<STR_LIT>'<EOL>parser.add_option('<STR_LIT>', action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>', default=env.get(env_opt, False),<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>


if not self.can_configure:<EOL><INDENT>return<EOL><DEDENT>self.conf = conf<EOL>disable = getattr(options, '<STR_LIT>', False)<EOL>if disable:<EOL><INDENT>self.enabled = False<EOL><DEDENT>

Configure plugin. Skip plugin is enabled by default.


self.add_options(parser, env)<EOL>

Add command-line options for this plugin.

        The base plugin class adds --with-$name by default, used to enable the
        plugin.

        .. warning :: Don't implement addOptions unless you want to override
                      all default option handling behavior, including
                      warnings for conflicting options. Implement
                      :meth:`options
                      <nose.plugins.base.IPluginInterface.options>`
                      instead.


def add_options(self, parser, env=None):

<EOL>if env is None:<EOL><INDENT>env = os.environ<EOL><DEDENT>try:<EOL><INDENT>self.options(parser, env)<EOL>self.can_configure = True<EOL><DEDENT>except OptionConflictError as e:<EOL><INDENT>warn("<STR_LIT>"<EOL>"<STR_LIT>" % (self, e), RuntimeWarning)<EOL>self.enabled = False<EOL>self.can_configure = False<EOL><DEDENT>

Non-camel-case version of func name for backwards compatibility.

        .. warning ::

           DEPRECATED: Do not use this method,
           use :meth:`options <nose.plugins.base.IPluginInterface.options>`
           instead.


env_opt = '<STR_LIT>' % self.name.upper()<EOL>env_opt = env_opt.replace('<STR_LIT:->', '<STR_LIT:_>')<EOL>parser.add_option("<STR_LIT>" % self.name,<EOL>action="<STR_LIT:store_true>",<EOL>dest=self.enableOpt,<EOL>default=env.get(env_opt),<EOL>help="<STR_LIT>" %<EOL>(self.__class__.__name__, self.help(), env_opt))<EOL>

Register commandline options.

        Implement this method for normal options behavior with protection from
        OptionConflictErrors. If you override this method and want the default
        --with-$name option to be registered, be sure to call super().


if not self.can_configure:<EOL><INDENT>return<EOL><DEDENT>self.conf = conf<EOL>if hasattr(options, self.enableOpt):<EOL><INDENT>self.enabled = getattr(options, self.enableOpt)<EOL><DEDENT>

Configure the plugin and system, based on selected options.

        The base plugin class sets the plugin to enabled if the enable option
        for the plugin (self.enableOpt) is true.


if self.__class__.__doc__:<EOL><INDENT>return textwrap.dedent(self.__class__.__doc__)<EOL><DEDENT>return "<STR_LIT>"<EOL>

Return help for this plugin. This will be output as the help
        section of the --with-$name option that enables the plugin.


pass<EOL>

Called to allow plugin to register command-line options with the
        parser. DO NOT return a value from this method unless you want to stop
        all other plugins from setting their options.

        .. warning ::

           DEPRECATED -- implement
           :meth:`options <nose.plugins.base.IPluginInterface.options>` instead.


pass<EOL>

Called after a context (generally a module) has been
        lazy-loaded, imported, setup, had its tests loaded and
        executed, and torn down.


pass<EOL>

Called after all tests have been loaded from directory at path
        and run.

        :param path: the directory that has finished processing
        :type path: string


def afterImport(self, filename, module):

pass<EOL>

Called after module is imported from filename. afterImport
        is called even if the import failed.

        :param filename: The file that was loaded
        :type filename: string
        :param filename: The name of the module
        :type module: string


pass<EOL>

Called before a context (generally a module) is
        examined. Because the context is not yet loaded, plugins don't
        get to know what the context is; so any context operations
        should use a stack that is pushed in `beforeContext` and popped
        in `afterContext` to ensure they operate symmetrically.

        `beforeContext` and `afterContext` are mainly useful for tracking
        and restoring global state around possible changes from within a
        context, whatever the context may be. If you need to operate on
        contexts themselves, see `startContext` and `stopContext`, which
        are passed the context in question, but are called after
        it has been loaded (imported in the module case).


pass<EOL>

Called before tests are loaded from directory at path.

        :param path: the directory that is about to be processed


def beforeImport(self, filename, module):

Called before module is imported from filename.

        :param filename: The file that will be loaded
        :param module: The name of the module found in file
        :type module: string


pass<EOL>

Called before any tests are collected or run. Use this to
        perform any setup needed before testing begins.


pass<EOL>

Called after the command line has been parsed, with the
        parsed options and the config container. Here, implement any
        config storage or changes to state or operation that are set
        by command line options.

        DO NOT return a value from this method unless you want to
        stop all other plugins from being configured.


pass<EOL>

Called after all report output, including output from all
        plugins, has been sent to the stream. Use this to print final
        test results or perform final cleanup. Return None to allow
        other plugins to continue printing, or any other value to stop
        them.

        :param result: test result object

        .. Note:: When tests are run under a test runner other than
           :class:`nose.core.TextTestRunner`, such as
           via ``python setup.py test``, this method may be called
           **before** the default report output is sent.


pass<EOL>

Return iterable of tests from a directory. May be a
        generator.  Each item returned must be a runnable
        unittest.TestCase (or subclass) instance or suite instance.
        Return None if your plugin cannot collect any tests from
        directory.

        :param  path: The path to the directory.


def loadTestsFromModule(self, module, path=None):

pass<EOL>

Return iterable of tests in a module. May be a
        generator. Each item returned must be a runnable
        unittest.TestCase (or subclass) instance.
        Return None if your plugin cannot
        collect any tests from module.

        :param module: The module object
        :type module: python module
        :param path: the path of the module to search, to distinguish from
            namespace package modules

            .. note::

               NEW. The ``path`` parameter will only be passed by nose 0.11
               or above.


def loadTestsFromName(self, name, module=None, importPath=None):

pass<EOL>

Return tests in this file or module. Return None if you are not able
        to load any tests, or an iterable if you are. May be a
        generator.

        :param name: The test name. May be a file or module name plus a test
            callable. Use split_test_name to split into parts. Or it might
            be some crazy name of your own devising, in which case, do
            whatever you want.
        :param module: Module from which the name is to be loaded
        :param importPath: Path from which file (must be a python module) was
            found

            .. warning:: DEPRECATED: this argument will NOT be passed.


pass<EOL>

Return a tuple of (tests loaded, remaining names). Return
        None if you are not able to load any tests. Multiple plugins
        may implement loadTestsFromNames; the remaining name list from
        each will be passed to the next as input.

        :param names: List of test names.
        :type names: iterable
        :param module: Module from which the names are to be loaded


pass<EOL>

Return tests in this file. Return None if you are not
        interested in loading any tests, or an iterable if you are and
        can load some. May be a generator. *If you are interested in
        loading tests from the file and encounter no errors, but find
        no tests, yield False or return [False].*

        .. Note:: This method replaces loadTestsFromPath from the 0.9
                  API.

        :param filename: The full path to the file or directory.


pass<EOL>

.. warning:: DEPRECATED -- use loadTestsFromFile instead


pass<EOL>

Return tests in this test case class. Return None if you are
        not able to load any tests, or an iterable if you are. May be a
        generator.

        :param cls: The test case class. Must be subclass of
           :class:`unittest.TestCase`.


pass<EOL>

Return tests in this test class. Class will *not* be a
        unittest.TestCase subclass. Return None if you are not able to
        load any tests, an iterable if you are. May be a generator.

        :param cls: The test case class. Must be **not** be subclass of
           :class:`unittest.TestCase`.


pass<EOL>

Given an object and its parent, return or yield one or more
        test cases. Each test must be a unittest.TestCase (or subclass)
        instance. This is called before default test loading to allow
        plugins to load an alternate test case or cases for an
        object. May be a generator.

        :param obj: The object to be made into a test
        :param parent: The parent of obj (eg, for a method, the class)


pass<EOL>

Called to allow plugin to register command line
        options with the parser.

        DO NOT return a value from this method unless you want to stop
        all other plugins from setting their options.

        :param parser: options parser instance
        :type parser: :class:`ConfigParser.ConfigParser`
        :param env: environment, default is os.environ


pass<EOL>

Called before tests are loaded. To replace the test loader,
        return a test loader. To allow other plugins to process the
        test loader, return None. Only one plugin may replace the test
        loader. Only valid when using nose.TestProgram.

        :param loader: :class:`nose.loader.TestLoader`
             (or other loader) instance


pass<EOL>

Called before the first test is run. To use a different
        test result handler for all tests than the given result,
        return a test result handler. NOTE however that this handler
        will only be seen by tests, that is, inside of the result
        proxy system. The TestRunner and TestProgram -- whether nose's
        or other -- will continue to see the original result
        handler. For this reason, it is usually better to monkeypatch
        the result (for instance, if you want to handle some
        exceptions in a unique way). Only one plugin may replace the
        result, but many may monkeypatch it. If you want to
        monkeypatch and stop other plugins from doing so, monkeypatch
        and return the patched result.

        :param result: :class:`nose.result.TextTestResult`
             (or other result) instance


pass<EOL>

Called before tests are run. To replace the test runner,
        return a test runner. To allow other plugins to process the
        test runner, return None. Only valid when using nose.TestProgram.

        :param runner: :class:`nose.core.TextTestRunner`
             (or other runner) instance


pass<EOL>

Called after all error output has been printed. Print your
        plugin's report to the provided stream. Return None to allow
        other plugins to print reports, any other value to stop them.

        :param stream: stream object; send your output here
        :type stream: file-like object


Called before test output begins. To direct test output to a
        new stream, return a stream object, which must implement a
        `write(msg)` method. If you only want to note the stream, not
        capture or redirect it, then return None.

        :param stream: stream object; send your output here
        :type stream: file-like object


pass<EOL>

Called before context setup and the running of tests in the
        context. Note that tests have already been *loaded* from the
        context before this call.

        :param context: the context about to be setup. May be a module or
             class, or any other object that contains tests.


pass<EOL>

Called after the tests in a context have run and the
        context has been torn down.

        :param context: the context about to be setup. May be a module or
             class, or any other object that contains tests.


pass<EOL>

Return true if you want the main test selector to collect
        tests from this class, false if you don't, and None if you don't
        care.

        :param cls: The class being examined by the selector


pass<EOL>

Return true if you want test collection to descend into this
        directory, false if you do not, and None if you don't care.

        :param dirname: Full path to directory being examined by the selector


pass<EOL>

Return true if you want to collect tests from this file,
        false if you do not and None if you don't care.

        Change from 0.9: The optional package parameter is no longer passed.

        :param file: Full path to file being examined by the selector


pass<EOL>

Return true to collect this function as a test, false to
        prevent it from being collected, and None if you don't care.

        :param function: The function object being examined by the selector


pass<EOL>

Return true to collect this method as a test, false to
        prevent it from being collected, and None if you don't care.

        :param method: The method object being examined by the selector
        :type method: unbound method


pass<EOL>

Return true if you want to collection to descend into this
        module, false to prevent the collector from descending into the
        module, and None if you don't care.

        :param module: The module object being examined by the selector
        :type module: python module


pass<EOL>

.. warning:: DEPRECATED -- this method will not be called, it has
             been folded into wantModule.


env_opt = '<STR_LIT>'<EOL>parser.add_option('<STR_LIT>',<EOL>action="<STR_LIT:store_true>",<EOL>dest=self.enableOpt,<EOL>default=env.get(env_opt),<EOL>help="<STR_LIT>" %<EOL>(self.__class__.__name__, self.help(), env_opt))<EOL>


<EOL>if file.endswith('<STR_LIT>'):<EOL><INDENT>return True<EOL><DEDENT>

Override to return True for all files ending with .py


return True<EOL>


block = []<EOL>for line in text.splitlines(True):<EOL><INDENT>block.append(line)<EOL>line = line.strip()<EOL>if not line or line.startswith('<STR_LIT>') and not line.strip('<STR_LIT:=>'):<EOL><INDENT>yield "<STR_LIT>".join(block)<EOL>block = []<EOL><DEDENT><DEDENT>if block:<EOL><INDENT>yield "<STR_LIT>".join(block)<EOL><DEDENT>

a bunch of === characters is also considered a blank line


from nose import run<EOL>from nose.config import Config<EOL>from nose.plugins.manager import PluginManager<EOL>buffer = Buffer()<EOL>if '<STR_LIT>' not in kw:<EOL><INDENT>plugins = kw.pop('<STR_LIT>', [])<EOL>if isinstance(plugins, list):<EOL><INDENT>plugins = PluginManager(plugins=plugins)<EOL><DEDENT>env = kw.pop('<STR_LIT>', {})<EOL>kw['<STR_LIT>'] = Config(env=env, plugins=plugins)<EOL><DEDENT>if '<STR_LIT>' not in kw:<EOL><INDENT>kw['<STR_LIT>'] = ['<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>kw['<STR_LIT>'].stream = buffer<EOL>stderr = sys.stderr<EOL>stdout = sys.stdout<EOL>if kw.pop('<STR_LIT>', False):<EOL><INDENT>sys.stdout = sys.stderr = buffer<EOL>restore = True<EOL><DEDENT>else:<EOL><INDENT>restore = False<EOL>warn("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>DeprecationWarning, stacklevel=<NUM_LIT:2>)<EOL><DEDENT>try:<EOL><INDENT>run(*arg, **kw)<EOL><DEDENT>finally:<EOL><INDENT>if restore:<EOL><INDENT>sys.stderr = stderr<EOL>sys.stdout = stdout<EOL><DEDENT><DEDENT>out = buffer.getvalue()<EOL>print(munge_nose_output_for_doctest(out))<EOL>

Specialized version of nose.run for use inside of doctests that
test test runs.

This version of run() prints the result output to stdout.  Before
printing, the output is processed by replacing the timing
information with an ellipsis (...), removing traceback stacks, and
removing trailing whitespace.

Use this version of run wherever you are writing a doctest that
tests nose (or unittest) test result output.

Note: do not use doctest: +ELLIPSIS when testing nose output,
since ellipses ("test_foo ... ok") in your expected test runner
output may match multiple lines of output, causing spurious test
passes!


self.buffer()<EOL>return self.__buffer<EOL>


raise NotImplementedError<EOL>

returns a suite object of tests to run (unittest.TestSuite())

        If self.suitepath is None, this must be implemented. The returned suite
        object will be executed with all plugins activated.  It may return
        None.

        Here is an example of a basic suite object you can return ::

            >>> import unittest
            >>> class SomeTest(unittest.TestCase):
            ...     def runTest(self):
            ...         raise ValueError("Now do something, plugin!")
            ...
            >>> unittest.TestSuite([SomeTest()]) # doctest: +ELLIPSIS
            <unittest...TestSuite tests=[<...SomeTest testMethod=runTest>]>


from nose.config import Config<EOL>from nose.core import TestProgram<EOL>from nose.plugins.manager import PluginManager<EOL>suite = None<EOL>stream = Buffer()<EOL>conf = Config(env=self.env,<EOL>stream=stream,<EOL>plugins=PluginManager(plugins=self.plugins))<EOL>if self.ignoreFiles is not None:<EOL><INDENT>conf.ignoreFiles = self.ignoreFiles<EOL><DEDENT>if not self.suitepath:<EOL><INDENT>suite = self.makeSuite()<EOL><DEDENT>self.nose = TestProgram(argv=self.argv, config=conf, suite=suite,<EOL>exit=False)<EOL>self.output = AccessDecorator(stream)<EOL>

execute the plugin on the internal test suite.


self.argv = ['<STR_LIT>', self.activate]<EOL>if self.args:<EOL><INDENT>self.argv.extend(self.args)<EOL><DEDENT>if self.suitepath:<EOL><INDENT>self.argv.append(self.suitepath)<EOL><DEDENT>self._execPlugin()<EOL>

runs nosetests with the specified test suite, all plugins
        activated.


parser.add_option(<EOL>"<STR_LIT>", "<STR_LIT>", action="<STR_LIT>",<EOL>default=not env.get(self.env_opt), dest="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>


self.conf = conf<EOL>if not options.capture:<EOL><INDENT>self.enabled = False<EOL><DEDENT>

Configure plugin. Plugin is enabled by default.


self.start()<EOL>


while self.stdout:<EOL><INDENT>self.end()<EOL><DEDENT>


try:<EOL><INDENT>self.status.pop('<STR_LIT>')<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>super(Coverage, self).configure(options, conf)<EOL>if conf.worker:<EOL><INDENT>return<EOL><DEDENT>if self.enabled:<EOL><INDENT>try:<EOL><INDENT>import coverage<EOL><DEDENT>except ImportError:<EOL><INDENT>log.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>self.enabled = False<EOL>return<EOL><DEDENT><DEDENT>self.conf = conf<EOL>self.coverErase = options.cover_erase<EOL>self.coverTests = options.cover_tests<EOL>self.coverPackages = []<EOL>if options.cover_packages:<EOL><INDENT>for pkgs in [tolist(x) for x in options.cover_packages]:<EOL><INDENT>self.coverPackages.extend(pkgs)<EOL><DEDENT><DEDENT>self.coverInclusive = options.cover_inclusive<EOL>if self.coverPackages:<EOL><INDENT>log.info("<STR_LIT>",<EOL>self.coverPackages)<EOL><DEDENT>self.coverHtmlDir = None<EOL>if options.cover_html:<EOL><INDENT>self.coverHtmlDir = options.cover_html_dir<EOL>log.debug('<STR_LIT>', self.coverHtmlDir)<EOL><DEDENT>self.coverBranches = options.cover_branches<EOL>self.coverXmlFile = None<EOL>if options.cover_min_percentage:<EOL><INDENT>self.coverMinPercentage = int(options.cover_min_percentage.rstrip('<STR_LIT:%>'))<EOL><DEDENT>if options.cover_xml:<EOL><INDENT>self.coverXmlFile = options.cover_xml_file<EOL>log.debug('<STR_LIT>', self.coverXmlFile)<EOL><DEDENT>if self.enabled:<EOL><INDENT>self.status['<STR_LIT>'] = True<EOL>self.coverInstance = coverage.coverage(auto_data=False,<EOL>branch=self.coverBranches, data_suffix=None)<EOL><DEDENT>


log.debug("<STR_LIT>")<EOL>self.coverInstance.stop()<EOL>self.coverInstance.combine()<EOL>self.coverInstance.save()<EOL>modules = [module<EOL>for name, module in sys.modules.items()<EOL>if self.wantModuleCoverage(name, module)]<EOL>log.debug("<STR_LIT>", modules)<EOL>self.coverInstance.report(modules, file=stream)<EOL>if self.coverHtmlDir:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>self.coverInstance.html_report(modules, self.coverHtmlDir)<EOL><DEDENT>if self.coverXmlFile:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>self.coverInstance.xml_report(modules, self.coverXmlFile)<EOL><DEDENT>if self.coverMinPercentage:<EOL><INDENT>f = StringIO.StringIO()<EOL>self.coverInstance.report(modules, file=f)<EOL>m = re.search(r'<STR_LIT>', f.getvalue())<EOL>if m:<EOL><INDENT>percentage = int(m.groups()[<NUM_LIT:0>])<EOL>if percentage < self.coverMinPercentage:<EOL><INDENT>log.error('<STR_LIT>'<EOL>'<STR_LIT>' % self.coverMinPercentage)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.error("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>


if self.coverInclusive:<EOL><INDENT>if file.endswith("<STR_LIT>"):<EOL><INDENT>if package and self.coverPackages:<EOL><INDENT>for want in self.coverPackages:<EOL><INDENT>if package.startswith(want):<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return None<EOL>

If inclusive coverage enabled, return true for all source files
        in wanted packages.


Plugin.options(self, parser, env)<EOL>parser.add_option('<STR_LIT>', action='<STR_LIT:store>', dest='<STR_LIT>',<EOL>default='<STR_LIT>', metavar="<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_option('<STR_LIT>', action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>', default=False,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>


Plugin.configure(self, options, conf)<EOL>if options.failed:<EOL><INDENT>self.enabled = True<EOL>self.loopOnFailed = True<EOL>log.debug("<STR_LIT>")<EOL><DEDENT>self.idfile = os.path.expanduser(options.testIdFile)<EOL>if not os.path.isabs(self.idfile):<EOL><INDENT>self.idfile = os.path.join(conf.workingDir, self.idfile)<EOL><DEDENT>self.id = <NUM_LIT:1><EOL>self.ids = {}<EOL>self.tests = {}<EOL>self.failed = []<EOL>self.source_names = []<EOL>self._seen = {}<EOL>self._write_hashes = conf.verbosity >= <NUM_LIT:2><EOL>


if result.wasSuccessful():<EOL><INDENT>self.failed = []<EOL><DEDENT>if self.collecting:<EOL><INDENT>ids = dict(list(zip(list(self.tests.values()), list(self.tests.keys()))))<EOL><DEDENT>else:<EOL><INDENT>ids = self.ids<EOL><DEDENT>fh = open(self.idfile, '<STR_LIT:wb>')<EOL>dump({'<STR_LIT>': ids,<EOL>'<STR_LIT>': self.failed,<EOL>'<STR_LIT>': self.source_names}, fh)<EOL>fh.close()<EOL>log.debug('<STR_LIT>',<EOL>ids, self.failed, self.idfile)<EOL>


log.debug('<STR_LIT>', names, module)<EOL>try:<EOL><INDENT>fh = open(self.idfile, '<STR_LIT:rb>')<EOL>data = load(fh)<EOL>if '<STR_LIT>' in data:<EOL><INDENT>self.ids = data['<STR_LIT>']<EOL>self.failed = data['<STR_LIT>']<EOL>self.source_names = data['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>self.ids = data<EOL>self.failed = []<EOL>self.source_names = names<EOL><DEDENT>if self.ids:<EOL><INDENT>self.id = max(self.ids) + <NUM_LIT:1><EOL>self.tests = dict(list(zip(list(self.ids.values()), list(self.ids.keys()))))<EOL><DEDENT>else:<EOL><INDENT>self.id = <NUM_LIT:1><EOL><DEDENT>log.debug(<EOL>'<STR_LIT>',<EOL>self.ids, self.tests, self.failed, self.source_names,<EOL>self.idfile)<EOL>fh.close()<EOL><DEDENT>except IOError:<EOL><INDENT>log.debug('<STR_LIT>', self.idfile)<EOL><DEDENT>if self.loopOnFailed and self.failed:<EOL><INDENT>self.collecting = False<EOL>names = self.failed<EOL>self.failed = []<EOL><DEDENT>translated = []<EOL>new_source = []<EOL>really_new = []<EOL>for name in names:<EOL><INDENT>trans = self.tr(name)<EOL>if trans != name:<EOL><INDENT>translated.append(trans)<EOL><DEDENT>else:<EOL><INDENT>new_source.append(name)<EOL><DEDENT><DEDENT>if new_source:<EOL><INDENT>new_set = set(new_source)<EOL>old_set = set(self.source_names)<EOL>log.debug("<STR_LIT>", old_set, new_set)<EOL>really_new = [s for s in new_source<EOL>if not s in old_set]<EOL>if really_new:<EOL><INDENT>self.source_names.extend(really_new)<EOL><DEDENT>if not translated:<EOL><INDENT>names = new_source<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.collecting = False<EOL><DEDENT>log.debug("<STR_LIT>",<EOL>translated, really_new, names)<EOL>return (None, translated + really_new or names)<EOL>

Translate ids in the list of requested names into their
        test addresses, if they are found in my dict of tests.


self.stream = stream<EOL>

Get handle on output stream so the plugin can print id #s


self.conf = conf<EOL>self.enabled = options.debugErrors or options.debugFailures<EOL>self.enabled_for_errors = options.debugErrors<EOL>self.enabled_for_failures = options.debugFailures<EOL>

Configure which kinds of exceptions trigger plugin.


env_opt = '<STR_LIT>'<EOL>parser.add_option('<STR_LIT>', action='<STR_LIT:store_true>',<EOL>dest='<STR_LIT>', default=env.get(env_opt, False),<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>


if not self.can_configure:<EOL><INDENT>return<EOL><DEDENT>self.conf = conf<EOL>disable = getattr(options, '<STR_LIT>', False)<EOL>if disable:<EOL><INDENT>self.enabled = False<EOL><DEDENT>


return CONTROL_CHARACTERS.sub('<STR_LIT:?>', value)<EOL>

Replaces invalid XML characters with '?'.


return xml_safe(cdata).replace('<STR_LIT>', '<STR_LIT>')<EOL>

Escape a string for an XML CDATA section.


if inspect.isclass(obj):<EOL><INDENT>cls_name = obj.__name__<EOL><DEDENT>else:<EOL><INDENT>cls_name = obj.__class__.__name__<EOL><DEDENT>mod = inspect.getmodule(obj)<EOL>if mod:<EOL><INDENT>name = mod.__name__<EOL>if name.startswith('<STR_LIT>'):<EOL><INDENT>name = name[len('<STR_LIT>'):]<EOL><DEDENT>return "<STR_LIT>" % (name, cls_name)<EOL><DEDENT>else:<EOL><INDENT>return cls_name<EOL><DEDENT>

Returns a nice name for class object or class instance.

        >>> nice_classname(Exception()) # doctest: +ELLIPSIS
        '...Exception'
        >>> nice_classname(Exception) # doctest: +ELLIPSIS
        '...Exception'


exc = exc_info[<NUM_LIT:1>]<EOL>if exc is None:<EOL><INDENT>result = exc_info[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>result = str(exc)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>try:<EOL><INDENT>result = unicode(exc)<EOL><DEDENT>except UnicodeError:<EOL><INDENT>result = exc.args[<NUM_LIT:0>]<EOL><DEDENT><DEDENT><DEDENT>return xml_safe(result)<EOL>


attr = xml_safe(attr)<EOL>if isinstance(attr, unicode) and not UNICODE_STRINGS:<EOL><INDENT>attr = attr.encode(self.encoding)<EOL><DEDENT>return saxutils.quoteattr(attr)<EOL>

Escape an XML attribute. Value can be unicode.


Plugin.options(self, parser, env)<EOL>parser.add_option(<EOL>'<STR_LIT>', action='<STR_LIT:store>',<EOL>dest='<STR_LIT>', metavar="<STR_LIT>",<EOL>default=env.get('<STR_LIT>', '<STR_LIT>'),<EOL>help=("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"))<EOL>


Plugin.configure(self, options, config)<EOL>self.config = config<EOL>if self.enabled:<EOL><INDENT>self.stats = {'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0><EOL>}<EOL>self.errorlist = []<EOL>self.error_report_file = codecs.open(options.xunit_file, '<STR_LIT:w>',<EOL>self.encoding, '<STR_LIT:replace>')<EOL><DEDENT>


self.stats['<STR_LIT>'] = self.encoding<EOL>self.stats['<STR_LIT>'] = (self.stats['<STR_LIT>'] + self.stats['<STR_LIT>']<EOL>+ self.stats['<STR_LIT>'] + self.stats['<STR_LIT>'])<EOL>self.error_report_file.write(<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>'<EOL>u'<STR_LIT>' % self.stats)<EOL>self.error_report_file.write(u'<STR_LIT>'.join([self._forceUnicode(e)<EOL>for e in self.errorlist]))<EOL>self.error_report_file.write(u'<STR_LIT>')<EOL>self.error_report_file.close()<EOL>if self.config.verbosity > <NUM_LIT:1>:<EOL><INDENT>stream.writeln("<STR_LIT:->" * <NUM_LIT>)<EOL>stream.writeln("<STR_LIT>" % self.error_report_file.name)<EOL><DEDENT>

Writes an Xunit-formatted XML file

        The file includes a report of test errors and failures.


if not self.can_configure:<EOL><INDENT>return<EOL><DEDENT>self.enabled = options.detailedErrors<EOL>self.conf = conf<EOL>


parser.add_option('<STR_LIT>',<EOL>action='<STR_LIT:store_true>',<EOL>dest=self.enableOpt,<EOL>default=env.get('<STR_LIT>'),<EOL>help="<STR_LIT>" %<EOL>(self.help()))<EOL>


<EOL>log.debug("<STR_LIT>")<EOL>loader.suiteClass = TestSuiteFactory(self.conf)<EOL>

Install collect-only suite class in TestLoader.


return make_instancemethod(TextTestResult.addError, result)<EOL>

Create a new addError method to patch into a result instance
    that recognizes the errorClasses attribute and deals with
    errorclasses correctly.


return make_instancemethod(TextTestResult.printErrors, result)<EOL>

Create a new printErrors method that prints errorClasses items
    as well.


return make_instancemethod(TextTestResult.printLabel, result)<EOL>

Create a new printLabel method that prints errorClasses items
    as well.


return make_instancemethod(TextTestResult.wasSuccessful, result)<EOL>

Create a new wasSuccessful method that checks errorClasses for
    exceptions that were put into other slots than error or failure
    but that still count as not success.


return make_instancemethod(TextTestResult.addSkip, result)<EOL>

Create a new addSkip method to patch into a result instance
    that delegates to addError.


def __init__(self, config=None, importer=None, workingDir=None,<EOL>selector=None):

if config is None:<EOL><INDENT>config = Config()<EOL><DEDENT>if importer is None:<EOL><INDENT>importer = Importer(config=config)<EOL><DEDENT>if workingDir is None:<EOL><INDENT>workingDir = config.workingDir<EOL><DEDENT>if selector is None:<EOL><INDENT>selector = defaultSelector(config)<EOL><DEDENT>elif isclass(selector):<EOL><INDENT>selector = selector(config)<EOL><DEDENT>self.config = config<EOL>self.importer = importer<EOL>self.workingDir = op_normpath(op_abspath(workingDir))<EOL>self.selector = selector<EOL>if config.addPaths:<EOL><INDENT>add_path(workingDir, config)        <EOL><DEDENT>self.suiteClass = ContextSuiteFactory(config=config)<EOL>unittest.TestLoader.__init__(self)<EOL>

Initialize a test loader.

        Parameters (all optional):

        * config: provide a `nose.config.Config`_ or other config class
          instance; if not provided a `nose.config.Config`_ with
          default values is used.
        * importer: provide an importer instance that implements
          `importFromPath`. If not provided, a
          `nose.importer.Importer`_ is used.
        * workingDir: the directory to which file and module names are
          relative. If not provided, assumed to be the current working
          directory.
        * selector: a selector class or instance. If a class is
          provided, it will be instantiated with one argument, the
          current config. If not provided, a `nose.selector.Selector`_
          is used.


log.debug("<STR_LIT>", path)<EOL>plugins = self.config.plugins<EOL>plugins.beforeDirectory(path)<EOL>if self.config.addPaths:<EOL><INDENT>paths_added = add_path(path, self.config)<EOL><DEDENT>entries = os.listdir(path)<EOL>sort_list(entries, regex_last_key(self.config.testMatch))<EOL>for entry in entries:<EOL><INDENT>if entry.startswith('<STR_LIT:.>'):<EOL><INDENT>continue<EOL><DEDENT>entry_path = op_abspath(op_join(path, entry))<EOL>is_file = op_isfile(entry_path)<EOL>wanted = False<EOL>if is_file:<EOL><INDENT>is_dir = False<EOL>wanted = self.selector.wantFile(entry_path)<EOL><DEDENT>else:<EOL><INDENT>is_dir = op_isdir(entry_path)<EOL>if is_dir:<EOL><INDENT>if entry.startswith('<STR_LIT:_>'):<EOL><INDENT>continue<EOL><DEDENT>wanted = self.selector.wantDirectory(entry_path)<EOL><DEDENT><DEDENT>is_package = ispackage(entry_path)<EOL>if wanted:<EOL><INDENT>if is_file:<EOL><INDENT>plugins.beforeContext()<EOL>if entry.endswith('<STR_LIT>'):<EOL><INDENT>yield self.loadTestsFromName(<EOL>entry_path, discovered=True)<EOL><DEDENT>else:<EOL><INDENT>yield self.loadTestsFromFile(entry_path)<EOL><DEDENT>plugins.afterContext()<EOL><DEDENT>elif is_package:<EOL><INDENT>yield self.loadTestsFromName(<EOL>entry_path, discovered=True)<EOL><DEDENT>else:<EOL><INDENT>yield self.suiteClass(<EOL>lambda: self.loadTestsFromDir(entry_path))<EOL><DEDENT><DEDENT><DEDENT>tests = []<EOL>for test in plugins.loadTestsFromDir(path):<EOL><INDENT>tests.append(test)<EOL><DEDENT>try:<EOL><INDENT>if tests:<EOL><INDENT>yield self.suiteClass(tests)<EOL><DEDENT><DEDENT>except (KeyboardInterrupt, SystemExit):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>yield self.suiteClass([Failure(*sys.exc_info())])<EOL><DEDENT>if self.config.addPaths:<EOL><INDENT>for p in paths_added:<EOL><INDENT>remove_path(p)<EOL><DEDENT><DEDENT>plugins.afterDirectory(path)<EOL>

Load tests from the directory at path. This is a generator
        -- each suite of tests from a module or other file is yielded
        and is expected to be executed before the next file is
        examined.


log.debug("<STR_LIT>", filename)<EOL>try:<EOL><INDENT>tests = [test for test in<EOL>self.config.plugins.loadTestsFromFile(filename)]<EOL>if tests:<EOL><INDENT>tests = filter(None, tests)<EOL>return self.suiteClass(tests)<EOL><DEDENT>else:<EOL><INDENT>open(filename, '<STR_LIT:r>').close() <EOL>raise ValueError("<STR_LIT>"<EOL>% filename)<EOL><DEDENT><DEDENT>except (KeyboardInterrupt, SystemExit):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>exc = sys.exc_info()<EOL>return self.suiteClass(<EOL>[Failure(exc[<NUM_LIT:0>], exc[<NUM_LIT:1>], exc[<NUM_LIT:2>],<EOL>address=(filename, None, None))])<EOL><DEDENT>

Load tests from a non-module file. Default is to raise a
        ValueError; plugins may implement `loadTestsFromFile` to
        provide a list of tests loaded from the file.


def loadTestsFromGenerator(self, generator, module):

def generate(g=generator, m=module):<EOL><INDENT>try:<EOL><INDENT>for test in g():<EOL><INDENT>test_func, arg = self.parseGeneratedTest(test)<EOL>if not callable(test_func):<EOL><INDENT>test_func = getattr(m, test_func)<EOL><DEDENT>yield FunctionTestCase(test_func, arg=arg, descriptor=g)<EOL><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>exc = sys.exc_info()<EOL>yield Failure(exc[<NUM_LIT:0>], exc[<NUM_LIT:1>], exc[<NUM_LIT:2>],<EOL>address=test_address(generator))<EOL><DEDENT><DEDENT>return self.suiteClass(generate, context=generator, can_split=False)<EOL>

Lazy-load tests from a generator function. The generator function
        may yield either:

        * a callable, or
        * a function name resolvable within the same module


def loadTestsFromGeneratorMethod(self, generator, cls):

<EOL>if hasattr(generator, '<STR_LIT>'):<EOL><INDENT>cls = generator.im_class<EOL><DEDENT>inst = cls()<EOL>method = generator.__name__<EOL>generator = getattr(inst, method)<EOL>def generate(g=generator, c=cls):<EOL><INDENT>try:<EOL><INDENT>for test in g():<EOL><INDENT>test_func, arg = self.parseGeneratedTest(test)<EOL>if not callable(test_func):<EOL><INDENT>test_func = unbound_method(c, getattr(c, test_func))<EOL><DEDENT>if ismethod(test_func):<EOL><INDENT>yield MethodTestCase(test_func, arg=arg, descriptor=g)<EOL><DEDENT>elif isfunction(test_func):<EOL><INDENT>yield MethodTestCase(g, test=test_func, arg=arg)<EOL><DEDENT>else:<EOL><INDENT>yield Failure(<EOL>TypeError,<EOL>"<STR_LIT>" % test_func)<EOL><DEDENT><DEDENT><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>exc = sys.exc_info()<EOL>yield Failure(exc[<NUM_LIT:0>], exc[<NUM_LIT:1>], exc[<NUM_LIT:2>],<EOL>address=test_address(generator))<EOL><DEDENT><DEDENT>return self.suiteClass(generate, context=generator, can_split=False)<EOL>

Lazy-load tests from a generator method.

        This is more complicated than loading from a generator function,
        since a generator method may yield:

        * a function
        * a bound or unbound method, or
        * a method name


def loadTestsFromModule(self, module, path=None, discovered=False):

log.debug("<STR_LIT>", module)<EOL>tests = []<EOL>test_classes = []<EOL>test_funcs = []<EOL>if not discovered or self.selector.wantModule(module):<EOL><INDENT>for item in dir(module):<EOL><INDENT>test = getattr(module, item, None)<EOL>if isclass(test):<EOL><INDENT>if self.selector.wantClass(test):<EOL><INDENT>test_classes.append(test)<EOL><DEDENT><DEDENT>elif isfunction(test) and self.selector.wantFunction(test):<EOL><INDENT>test_funcs.append(test)<EOL><DEDENT><DEDENT>sort_list(test_classes, lambda x: x.__name__)<EOL>sort_list(test_funcs, func_lineno)<EOL>tests = map(lambda t: self.makeTest(t, parent=module),<EOL>test_classes + test_funcs)<EOL><DEDENT>module_paths = getattr(module, '<STR_LIT>', [])<EOL>if path:<EOL><INDENT>path = os.path.realpath(path)<EOL><DEDENT>for module_path in module_paths:<EOL><INDENT>log.debug("<STR_LIT>", module_path)<EOL>log.debug("<STR_LIT>",<EOL>path, module_path, os.path.realpath(module_path))<EOL>if (self.config.traverseNamespace or not path) oros.path.realpath(module_path).startswith(path):<EOL><INDENT>tests.extend(self.loadTestsFromDir(module_path))<EOL><DEDENT><DEDENT>for test in self.config.plugins.loadTestsFromModule(module, path):<EOL><INDENT>tests.append(test)<EOL><DEDENT>return self.suiteClass(ContextList(tests, context=module))<EOL>

Load all tests from module and return a suite containing
        them. If the module has been discovered and is not test-like,
        the suite will be empty by default, though plugins may add
        their own tests.


def loadTestsFromName(self, name, module=None, discovered=False):

<EOL>log.debug("<STR_LIT>", name, module)<EOL>suite = self.suiteClass<EOL>plug_tests = self.config.plugins.loadTestsFromName(name, module)<EOL>if plug_tests:<EOL><INDENT>return suite(plug_tests)<EOL><DEDENT>addr = TestAddress(name, workingDir=self.workingDir)<EOL>if module:<EOL><INDENT>if addr.call:<EOL><INDENT>name = addr.call<EOL><DEDENT>parent, obj = self.resolve(name, module)<EOL>if (isclass(parent)<EOL>and getattr(parent, '<STR_LIT>', None) != module.__name__):<EOL><INDENT>parent = transplant_class(parent, module.__name__)<EOL>obj = getattr(parent, obj.__name__)<EOL><DEDENT>log.debug("<STR_LIT>", parent, obj, module)<EOL>if isinstance(obj, Failure):<EOL><INDENT>return suite([obj])<EOL><DEDENT>else:<EOL><INDENT>return suite(ContextList([self.makeTest(obj, parent)],<EOL>context=parent))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if addr.module:<EOL><INDENT>try:<EOL><INDENT>if addr.filename is None:<EOL><INDENT>module = resolve_name(addr.module)<EOL><DEDENT>else:<EOL><INDENT>self.config.plugins.beforeImport(<EOL>addr.filename, addr.module)<EOL>try:<EOL><INDENT>module = self.importer.importFromPath(<EOL>addr.filename, addr.module)<EOL><DEDENT>finally:<EOL><INDENT>self.config.plugins.afterImport(<EOL>addr.filename, addr.module)<EOL><DEDENT><DEDENT><DEDENT>except (KeyboardInterrupt, SystemExit):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>exc = sys.exc_info()<EOL>return suite([Failure(exc[<NUM_LIT:0>], exc[<NUM_LIT:1>], exc[<NUM_LIT:2>],<EOL>address=addr.totuple())])<EOL><DEDENT>if addr.call:<EOL><INDENT>return self.loadTestsFromName(addr.call, module)<EOL><DEDENT>else:<EOL><INDENT>return self.loadTestsFromModule(<EOL>module, addr.filename,<EOL>discovered=discovered)<EOL><DEDENT><DEDENT>elif addr.filename:<EOL><INDENT>path = addr.filename<EOL>if addr.call:<EOL><INDENT>package = getpackage(path)<EOL>if package is None:<EOL><INDENT>return suite([<EOL>Failure(ValueError,<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(addr.call, path),<EOL>address=addr.totuple())])<EOL><DEDENT>return self.loadTestsFromName(addr.call, module=package)<EOL><DEDENT>else:<EOL><INDENT>if op_isdir(path):<EOL><INDENT>return LazySuite(<EOL>lambda: self.loadTestsFromDir(path))<EOL><DEDENT>elif op_isfile(path):<EOL><INDENT>return self.loadTestsFromFile(path)<EOL><DEDENT>else:<EOL><INDENT>return suite([<EOL>Failure(OSError, "<STR_LIT>" % path,<EOL>address=addr.totuple())])<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>return suite([<EOL>Failure(ValueError, "<STR_LIT>" % name,<EOL>address=addr.totuple())])<EOL><DEDENT><DEDENT>

Load tests from the entity with the given name.

        The name may indicate a file, directory, module, or any object
        within a module. See `nose.util.split_test_name` for details on
        test name parsing.


plug_res = self.config.plugins.loadTestsFromNames(names, module)<EOL>if plug_res:<EOL><INDENT>suite, names = plug_res<EOL>if suite:<EOL><INDENT>return self.suiteClass([<EOL>self.suiteClass(suite),<EOL>unittest.TestLoader.loadTestsFromNames(self, names, module)<EOL>])<EOL><DEDENT><DEDENT>return unittest.TestLoader.loadTestsFromNames(self, names, module)<EOL>

Load tests from all names, returning a suite containing all
        tests.


def wanted(attr, cls=cls, sel=self.selector):<EOL><INDENT>item = getattr(cls, attr, None)<EOL>if isfunction(item):<EOL><INDENT>item = unbound_method(cls, item)<EOL><DEDENT>elif not ismethod(item):<EOL><INDENT>return False<EOL><DEDENT>return sel.wantMethod(item)<EOL><DEDENT>cases = [self.makeTest(getattr(cls, case), cls)<EOL>for case in filter(wanted, dir(cls))]<EOL>for test in self.config.plugins.loadTestsFromTestClass(cls):<EOL><INDENT>cases.append(test)<EOL><DEDENT>return self.suiteClass(ContextList(cases, context=cls))<EOL>

Load tests from a test class that is *not* a unittest.TestCase
        subclass.

        In this case, we can't depend on the class's `__init__` taking method
        name arguments, so we have to compose a MethodTestCase for each
        method in the class that looks testlike.


plug_tests = []<EOL>try:<EOL><INDENT>addr = test_address(obj)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>addr = None<EOL><DEDENT>for test in self.config.plugins.makeTest(obj, parent):<EOL><INDENT>plug_tests.append(test)<EOL><DEDENT>try:<EOL><INDENT>if plug_tests:<EOL><INDENT>return self.suiteClass(plug_tests)<EOL><DEDENT><DEDENT>except (KeyboardInterrupt, SystemExit):<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>exc = sys.exc_info()<EOL>return Failure(exc[<NUM_LIT:0>], exc[<NUM_LIT:1>], exc[<NUM_LIT:2>], address=addr)<EOL><DEDENT>if isfunction(obj) and parent and not isinstance(parent, types.ModuleType):<EOL><INDENT>obj = unbound_method(parent, obj)<EOL><DEDENT>if isinstance(obj, unittest.TestCase):<EOL><INDENT>return obj<EOL><DEDENT>elif isclass(obj):<EOL><INDENT>if parent and obj.__module__ != parent.__name__:<EOL><INDENT>obj = transplant_class(obj, parent.__name__)<EOL><DEDENT>if issubclass(obj, unittest.TestCase):<EOL><INDENT>return self.loadTestsFromTestCase(obj)<EOL><DEDENT>else:<EOL><INDENT>return self.loadTestsFromTestClass(obj)<EOL><DEDENT><DEDENT>elif ismethod(obj):<EOL><INDENT>if parent is None:<EOL><INDENT>parent = obj.__class__<EOL><DEDENT>if issubclass(parent, unittest.TestCase):<EOL><INDENT>return parent(obj.__name__)<EOL><DEDENT>else:<EOL><INDENT>if isgenerator(obj):<EOL><INDENT>return self.loadTestsFromGeneratorMethod(obj, parent)<EOL><DEDENT>else:<EOL><INDENT>return MethodTestCase(obj)<EOL><DEDENT><DEDENT><DEDENT>elif isfunction(obj):<EOL><INDENT>if parent and obj.__module__ != parent.__name__:<EOL><INDENT>obj = transplant_func(obj, parent.__name__)<EOL><DEDENT>if isgenerator(obj):<EOL><INDENT>return self.loadTestsFromGenerator(obj, parent)<EOL><DEDENT>else:<EOL><INDENT>return FunctionTestCase(obj)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return Failure(TypeError,<EOL>"<STR_LIT>" % obj,<EOL>address=addr)<EOL><DEDENT>

Given a test object and its parent, return a test case
        or test suite.


obj = module<EOL>parts = name.split('<STR_LIT:.>')<EOL>for part in parts:<EOL><INDENT>parent, obj = obj, getattr(obj, part, None)<EOL><DEDENT>if obj is None:<EOL><INDENT>obj = Failure(ValueError, "<STR_LIT>" % name)<EOL><DEDENT>return parent, obj<EOL>


return sys.exc_info()<EOL>


e = self.exc_info()<EOL>if sys.platform == '<STR_LIT>':<EOL><INDENT>if isinstance(e[<NUM_LIT:0>], StringException):<EOL><INDENT>e = (str(e[<NUM_LIT:0>]), e[<NUM_LIT:1>], e[<NUM_LIT:2>])<EOL><DEDENT><DEDENT>return e<EOL>

Bottleneck to fix up IronPython string exceptions


<EOL>log.debug("<STR_LIT>", id(self), self, self._tests)<EOL>if self.resultProxy:<EOL><INDENT>result, orig = self.resultProxy(result, self), result<EOL><DEDENT>else:<EOL><INDENT>result, orig = result, result<EOL><DEDENT>try:<EOL><INDENT>self.setUp()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>self.error_context = '<STR_LIT>'<EOL>result.addError(self, self._exc_info())<EOL>return<EOL><DEDENT>try:<EOL><INDENT>for test in self._tests:<EOL><INDENT>if result.shouldStop:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>break<EOL><DEDENT>test(orig)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>self.has_run = True<EOL>try:<EOL><INDENT>self.tearDown()<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>raise<EOL><DEDENT>except:<EOL><INDENT>self.error_context = '<STR_LIT>'<EOL>result.addError(self, self._exc_info())<EOL><DEDENT><DEDENT>

Run tests in suite inside of suite fixtures.


log.debug("<STR_LIT>", context)<EOL>if context is None:<EOL><INDENT>return<EOL><DEDENT>if hasattr(context, '<STR_LIT>'):<EOL><INDENT>context = context.im_class<EOL><DEDENT>elif hasattr(context, '<STR_LIT>'):<EOL><INDENT>context = context.__self__.__class__<EOL><DEDENT>if hasattr(context, '<STR_LIT>'):<EOL><INDENT>ancestors = context.__module__.split('<STR_LIT:.>')<EOL><DEDENT>elif hasattr(context, '<STR_LIT>'):<EOL><INDENT>ancestors = context.__name__.split('<STR_LIT:.>')[:-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % context)<EOL><DEDENT>while ancestors:<EOL><INDENT>log.debug("<STR_LIT>", context, ancestors)<EOL>yield resolve_name('<STR_LIT:.>'.join(ancestors))<EOL>ancestors.pop()<EOL><DEDENT>

Return the ancestry of the context (that is, all of the
        packages and modules containing the context), in order of
        descent with the outermost ancestor last.
        This method is a generator.


kw['<STR_LIT>'] = False<EOL>return TestProgram(*arg, **kw).success<EOL>

Collect and run tests, returning success or failure.

    The arguments to `run()` are the same as to `main()`:

    * module: All tests are in this module (default: None)
    * defaultTest: Tests to load (default: '.')
    * argv: Command line arguments (default: None; sys.argv is read)
    * testRunner: Test runner instance (default: None)
    * testLoader: Test loader instance (default: None)
    * env: Environment; ignored if config is provided (default: None;
      os.environ is read)
    * config: :class:`nose.config.Config` instance (default: None)
    * suite: Suite or list of tests to run (default: None). Passing a
      suite or lists of tests will bypass all test discovery and
      loading. *ALSO NOTE* that if you pass a unittest.TestSuite
      instance as the suite, context fixtures at the class, module and
      package level will not be used, and many plugin hooks will not
      be called. If you want normal nose behavior, either pass a list
      of tests, or a fully-configured :class:`nose.suite.ContextSuite`.
    * plugins: List of plugins to use; ignored if config is provided
      (default: load plugins with DefaultPluginManager)
    * addplugins: List of **extra** plugins to use. Pass a list of plugin
      instances in this argument to make custom plugins available while
      still using the DefaultPluginManager.

    With the exception that the ``exit`` argument is always set
    to False.


main(defaultTest=name, **kw)<EOL>

Collect and run tests in a single module only. Defaults to running
    tests in __main__. Additional arguments to TestProgram may be passed
    as keyword arguments.


<EOL>setuptools_incompat = ('<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>')<EOL>plugins = RestrictedPluginManager(exclude=setuptools_incompat)<EOL>conf = Config(files=all_config_files(),<EOL>plugins=plugins)<EOL>conf.configure(argv=['<STR_LIT>'])<EOL>loader = defaultTestLoader(conf)<EOL>if conf.testNames:<EOL><INDENT>suite = loader.loadTestsFromNames(conf.testNames)<EOL><DEDENT>else:<EOL><INDENT>suite = loader.loadTestsFromNames(('<STR_LIT:.>',))<EOL><DEDENT>return FinalizingSuiteWrapper(suite, plugins.finalize)<EOL>

TestSuite replacement entry point. Use anywhere you might use a
    unittest.TestSuite. The collector will, by default, load options from
    all config files and execute loader.loadTestsFromNames() on the
    configured testNames, or '.' if no testNames are configured.


def makeConfig(self, env, plugins=None):

cfg_files = all_config_files()<EOL>if plugins:<EOL><INDENT>manager = PluginManager(plugins=plugins)<EOL><DEDENT>else:<EOL><INDENT>manager = DefaultPluginManager()<EOL><DEDENT>return Config(<EOL>env=env, files=cfg_files, plugins=manager)<EOL>

Load a Config, pre-filled with user config files if any are
        found.


self.config.configure(argv, doc=self.usage())<EOL>log.debug("<STR_LIT>", self.config)<EOL>if self.config.options.version:<EOL><INDENT>from nose import __version__<EOL>sys.stdout = sys.__stdout__<EOL>print("<STR_LIT>" % (os.path.basename(sys.argv[<NUM_LIT:0>]), __version__))<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>if self.config.options.showPlugins:<EOL><INDENT>self.showPlugins()<EOL>sys.exit(<NUM_LIT:0>)<EOL><DEDENT>if self.testLoader is None:<EOL><INDENT>self.testLoader = defaultTestLoader(config=self.config)<EOL><DEDENT>elif isclass(self.testLoader):<EOL><INDENT>self.testLoader = self.testLoader(config=self.config)<EOL><DEDENT>plug_loader = self.config.plugins.prepareTestLoader(self.testLoader)<EOL>if plug_loader is not None:<EOL><INDENT>self.testLoader = plug_loader<EOL><DEDENT>log.debug("<STR_LIT>", self.testLoader)<EOL>if self.config.testNames:<EOL><INDENT>self.testNames = self.config.testNames<EOL><DEDENT>else:<EOL><INDENT>self.testNames = tolist(self.defaultTest)<EOL><DEDENT>log.debug('<STR_LIT>', self.defaultTest)<EOL>log.debug('<STR_LIT>', self.testNames)<EOL>if self.config.workingDir is not None:<EOL><INDENT>os.chdir(self.config.workingDir)<EOL><DEDENT>self.createTests()<EOL>

Parse argv and env and configure running environment.


log.debug("<STR_LIT>", self.suite)<EOL>if self.suite is not None:<EOL><INDENT>self.test = self.testLoader.suiteClass(self.suite)<EOL><DEDENT>else:<EOL><INDENT>self.test = self.testLoader.loadTestsFromNames(self.testNames)<EOL><DEDENT>

Create the tests to run. If a self.suite
        is set, then that suite will be used. Otherwise, tests will be
        loaded from the given test names (self.testNames) using the
        test loader.


log.debug("<STR_LIT>")<EOL>if self.testRunner is None:<EOL><INDENT>self.testRunner = TextTestRunner(stream=self.config.stream,<EOL>verbosity=self.config.verbosity,<EOL>config=self.config)<EOL><DEDENT>plug_runner = self.config.plugins.prepareTestRunner(self.testRunner)<EOL>if plug_runner is not None:<EOL><INDENT>self.testRunner = plug_runner<EOL><DEDENT>result = self.testRunner.run(self.test)<EOL>self.success = result.wasSuccessful()<EOL>if self.exit:<EOL><INDENT>sys.exit(not self.success)<EOL><DEDENT>return self.success<EOL>

Run Tests. Returns true on success, false on failure, and sets
        self.success to the same value.


import textwrap<EOL>class DummyParser:<EOL><INDENT>def __init__(self):<EOL><INDENT>self.options = []<EOL><DEDENT>def add_option(self, *arg, **kw):<EOL><INDENT>self.options.append((arg, kw.pop('<STR_LIT>', '<STR_LIT>')))<EOL><DEDENT><DEDENT>v = self.config.verbosity<EOL>self.config.plugins.sort()<EOL>for p in self.config.plugins:<EOL><INDENT>print("<STR_LIT>" % p.name)<EOL>if v >= <NUM_LIT:2>:<EOL><INDENT>print("<STR_LIT>" % p.score)<EOL>print('<STR_LIT:\n>'.join(textwrap.wrap(p.help().strip(),<EOL>initial_indent='<STR_LIT:U+0020>',<EOL>subsequent_indent='<STR_LIT:U+0020>')))<EOL>if v >= <NUM_LIT:3>:<EOL><INDENT>parser = DummyParser()<EOL>p.addOptions(parser)<EOL>if len(parser.options):<EOL><INDENT>print()<EOL>print("<STR_LIT>")<EOL>for opts, help in parser.options:<EOL><INDENT>print('<STR_LIT>' % ('<STR_LIT:U+002CU+0020>'.join(opts)))<EOL>if help:<EOL><INDENT>print('<STR_LIT:\n>'.join(<EOL>textwrap.wrap(help.strip(),<EOL>initial_indent='<STR_LIT:U+0020>',<EOL>subsequent_indent='<STR_LIT:U+0020>')))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>print()<EOL><DEDENT><DEDENT>


_TextTestResult.printErrors(self)<EOL>for cls in self.errorClasses.keys():<EOL><INDENT>storage, label, isfail = self.errorClasses[cls]<EOL>if isfail:<EOL><INDENT>self.printErrorList(label, storage)<EOL><DEDENT><DEDENT>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.config.plugins.report(self.stream)<EOL><DEDENT>

Overrides to print all errorClasses errors as well.


write = self.stream.write<EOL>writeln = self.stream.writeln<EOL>taken = float(stop - start)<EOL>run = self.testsRun<EOL>plural = run != <NUM_LIT:1> and "<STR_LIT:s>" or "<STR_LIT>"<EOL>writeln(self.separator2)<EOL>writeln("<STR_LIT>" % (run, plural, taken))<EOL>writeln()<EOL>summary = {}<EOL>eckeys = self.errorClasses.keys()<EOL>for cls in eckeys:<EOL><INDENT>storage, label, isfail = self.errorClasses[cls]<EOL>count = len(storage)<EOL>if not count:<EOL><INDENT>continue<EOL><DEDENT>summary[label] = count<EOL><DEDENT>if len(self.failures):<EOL><INDENT>summary['<STR_LIT>'] = len(self.failures)<EOL><DEDENT>if len(self.errors):<EOL><INDENT>summary['<STR_LIT>'] = len(self.errors)<EOL><DEDENT>if not self.wasSuccessful():<EOL><INDENT>write("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>write("<STR_LIT:OK>")<EOL><DEDENT>items = summary.items()<EOL>if items:<EOL><INDENT>items.sort()<EOL>write("<STR_LIT>")<EOL>write("<STR_LIT:U+002CU+0020>".join(["<STR_LIT>" % (label, count) for<EOL>label, count in items]))<EOL>writeln("<STR_LIT:)>")<EOL><DEDENT>else:<EOL><INDENT>writeln()<EOL><DEDENT>

Called by the test runner to print the final summary of test
        run results.


if self.errors or self.failures:<EOL><INDENT>return False<EOL><DEDENT>for cls in self.errorClasses.keys():<EOL><INDENT>storage, label, isfail = self.errorClasses[cls]<EOL>if not isfail:<EOL><INDENT>continue<EOL><DEDENT>if storage:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Overrides to check that there are no errors in errorClasses
        lists that are marked as errors and should cause a run to
        fail.