home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_415 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  41.6 KB  |  1,325 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __docformat__ = 'reStructuredText en'
  5. __all__ = [
  6.     'register_optionflag',
  7.     'DONT_ACCEPT_TRUE_FOR_1',
  8.     'DONT_ACCEPT_BLANKLINE',
  9.     'NORMALIZE_WHITESPACE',
  10.     'ELLIPSIS',
  11.     'SKIP',
  12.     'IGNORE_EXCEPTION_DETAIL',
  13.     'COMPARISON_FLAGS',
  14.     'REPORT_UDIFF',
  15.     'REPORT_CDIFF',
  16.     'REPORT_NDIFF',
  17.     'REPORT_ONLY_FIRST_FAILURE',
  18.     'REPORTING_FLAGS',
  19.     'Example',
  20.     'DocTest',
  21.     'DocTestParser',
  22.     'DocTestFinder',
  23.     'DocTestRunner',
  24.     'OutputChecker',
  25.     'DocTestFailure',
  26.     'UnexpectedException',
  27.     'DebugRunner',
  28.     'testmod',
  29.     'testfile',
  30.     'run_docstring_examples',
  31.     'Tester',
  32.     'DocTestSuite',
  33.     'DocFileSuite',
  34.     'set_unittest_reportflags',
  35.     'script_from_examples',
  36.     'testsource',
  37.     'debug_src',
  38.     'debug']
  39. import __future__
  40. import sys
  41. import traceback
  42. import inspect
  43. import linecache
  44. import os
  45. import re
  46. import unittest
  47. import difflib
  48. import pdb
  49. import tempfile
  50. import warnings
  51. from StringIO import StringIO
  52. from collections import namedtuple
  53. TestResults = namedtuple('TestResults', 'failed attempted')
  54. OPTIONFLAGS_BY_NAME = { }
  55.  
  56. def register_optionflag(name):
  57.     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
  58.  
  59. DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
  60. DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
  61. NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
  62. ELLIPSIS = register_optionflag('ELLIPSIS')
  63. SKIP = register_optionflag('SKIP')
  64. IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
  65. COMPARISON_FLAGS = DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | SKIP | IGNORE_EXCEPTION_DETAIL
  66. REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
  67. REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
  68. REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
  69. REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
  70. REPORTING_FLAGS = REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE
  71. BLANKLINE_MARKER = '<BLANKLINE>'
  72. ELLIPSIS_MARKER = '...'
  73.  
  74. def _extract_future_flags(globs):
  75.     flags = 0
  76.     for fname in __future__.all_feature_names:
  77.         feature = globs.get(fname, None)
  78.         if feature is getattr(__future__, fname):
  79.             flags |= feature.compiler_flag
  80.             continue
  81.     
  82.     return flags
  83.  
  84.  
  85. def _normalize_module(module, depth = 2):
  86.     if inspect.ismodule(module):
  87.         return module
  88.     if isinstance(module, (str, unicode)):
  89.         return __import__(module, globals(), locals(), [
  90.             '*'])
  91.     if module is None:
  92.         return sys.modules[sys._getframe(depth).f_globals['__name__']]
  93.     raise TypeError('Expected a module, string, or None')
  94.  
  95.  
  96. def _load_testfile(filename, package, module_relative):
  97.     if module_relative:
  98.         package = _normalize_module(package, 3)
  99.         filename = _module_relative_path(package, filename)
  100.         if hasattr(package, '__loader__'):
  101.             if hasattr(package.__loader__, 'get_data'):
  102.                 file_contents = package.__loader__.get_data(filename)
  103.                 return (file_contents.replace(os.linesep, '\n'), filename)
  104.         
  105.     
  106.     return (open(filename).read(), filename)
  107.  
  108.  
  109. def _indent(s, indent = 4):
  110.     return re.sub('(?m)^(?!$)', indent * ' ', s)
  111.  
  112.  
  113. def _exception_traceback(exc_info):
  114.     excout = StringIO()
  115.     (exc_type, exc_val, exc_tb) = exc_info
  116.     traceback.print_exception(exc_type, exc_val, exc_tb, file = excout)
  117.     return excout.getvalue()
  118.  
  119.  
  120. class _SpoofOut(StringIO):
  121.     
  122.     def getvalue(self):
  123.         result = StringIO.getvalue(self)
  124.         if result and not result.endswith('\n'):
  125.             result += '\n'
  126.         
  127.         if hasattr(self, 'softspace'):
  128.             del self.softspace
  129.         
  130.         return result
  131.  
  132.     
  133.     def truncate(self, size = None):
  134.         StringIO.truncate(self, size)
  135.         if hasattr(self, 'softspace'):
  136.             del self.softspace
  137.         
  138.  
  139.  
  140.  
  141. def _ellipsis_match(want, got):
  142.     if ELLIPSIS_MARKER not in want:
  143.         return want == got
  144.     ws = want.split(ELLIPSIS_MARKER)
  145.     startpos = 0
  146.     endpos = len(got)
  147.     w = ws[0]
  148.     if w:
  149.         if got.startswith(w):
  150.             startpos = len(w)
  151.             del ws[0]
  152.         else:
  153.             return False
  154.     got.startswith(w)
  155.     w = ws[-1]
  156.     if w:
  157.         if got.endswith(w):
  158.             endpos -= len(w)
  159.             del ws[-1]
  160.         else:
  161.             return False
  162.     got.endswith(w)
  163.     if startpos > endpos:
  164.         return False
  165.     for w in ws:
  166.         startpos = got.find(w, startpos, endpos)
  167.         if startpos < 0:
  168.             return False
  169.         startpos += len(w)
  170.     
  171.     return True
  172.  
  173.  
  174. def _comment_line(line):
  175.     line = line.rstrip()
  176.     if line:
  177.         return '# ' + line
  178.     return '#'
  179.  
  180.  
  181. class _OutputRedirectingPdb(pdb.Pdb):
  182.     
  183.     def __init__(self, out):
  184.         self._OutputRedirectingPdb__out = out
  185.         self._OutputRedirectingPdb__debugger_used = False
  186.         pdb.Pdb.__init__(self, stdout = out)
  187.  
  188.     
  189.     def set_trace(self, frame = None):
  190.         self._OutputRedirectingPdb__debugger_used = True
  191.         if frame is None:
  192.             frame = sys._getframe().f_back
  193.         
  194.         pdb.Pdb.set_trace(self, frame)
  195.  
  196.     
  197.     def set_continue(self):
  198.         if self._OutputRedirectingPdb__debugger_used:
  199.             pdb.Pdb.set_continue(self)
  200.         
  201.  
  202.     
  203.     def trace_dispatch(self, *args):
  204.         save_stdout = sys.stdout
  205.         sys.stdout = self._OutputRedirectingPdb__out
  206.         
  207.         try:
  208.             return pdb.Pdb.trace_dispatch(self, *args)
  209.         finally:
  210.             sys.stdout = save_stdout
  211.  
  212.  
  213.  
  214.  
  215. def _module_relative_path(module, path):
  216.     if not inspect.ismodule(module):
  217.         raise TypeError, 'Expected a module: %r' % module
  218.     inspect.ismodule(module)
  219.     if path.startswith('/'):
  220.         raise ValueError, 'Module-relative files may not have absolute paths'
  221.     path.startswith('/')
  222.     if hasattr(module, '__file__'):
  223.         basedir = os.path.split(module.__file__)[0]
  224.     elif module.__name__ == '__main__':
  225.         if len(sys.argv) > 0 and sys.argv[0] != '':
  226.             basedir = os.path.split(sys.argv[0])[0]
  227.         else:
  228.             basedir = os.curdir
  229.     else:
  230.         raise ValueError("Can't resolve paths relative to the module " + module + ' (it has no __file__)')
  231.     return hasattr(module, '__file__').path.join(basedir, *path.split('/'))
  232.  
  233.  
  234. class Example:
  235.     
  236.     def __init__(self, source, want, exc_msg = None, lineno = 0, indent = 0, options = None):
  237.         if not source.endswith('\n'):
  238.             source += '\n'
  239.         
  240.         if want and not want.endswith('\n'):
  241.             want += '\n'
  242.         
  243.         if exc_msg is not None and not exc_msg.endswith('\n'):
  244.             exc_msg += '\n'
  245.         
  246.         self.source = source
  247.         self.want = want
  248.         self.lineno = lineno
  249.         self.indent = indent
  250.         if options is None:
  251.             options = { }
  252.         
  253.         self.options = options
  254.         self.exc_msg = exc_msg
  255.  
  256.  
  257.  
  258. class DocTest:
  259.     
  260.     def __init__(self, examples, globs, name, filename, lineno, docstring):
  261.         self.examples = examples
  262.         self.docstring = docstring
  263.         self.globs = globs.copy()
  264.         self.name = name
  265.         self.filename = filename
  266.         self.lineno = lineno
  267.  
  268.     
  269.     def __repr__(self):
  270.         if len(self.examples) == 0:
  271.             examples = 'no examples'
  272.         elif len(self.examples) == 1:
  273.             examples = '1 example'
  274.         else:
  275.             examples = '%d examples' % len(self.examples)
  276.         return '<DocTest %s from %s:%s (%s)>' % (self.name, self.filename, self.lineno, examples)
  277.  
  278.     
  279.     def __cmp__(self, other):
  280.         if not isinstance(other, DocTest):
  281.             return -1
  282.         return cmp((self.name, self.filename, self.lineno, id(self)), (other.name, other.filename, other.lineno, id(other)))
  283.  
  284.  
  285.  
  286. class DocTestParser:
  287.     _EXAMPLE_RE = re.compile('\n        # Source consists of a PS1 line followed by zero or more PS2 lines.\n        (?P<source>\n            (?:^(?P<indent> [ ]*) >>>    .*)    # PS1 line\n            (?:\\n           [ ]*  \\.\\.\\. .*)*)  # PS2 lines\n        \\n?\n        # Want consists of any non-blank lines that do not start with PS1.\n        (?P<want> (?:(?![ ]*$)    # Not a blank line\n                     (?![ ]*>>>)  # Not a line starting with PS1\n                     .*$\\n?       # But any other line\n                  )*)\n        ', re.MULTILINE | re.VERBOSE)
  288.     _EXCEPTION_RE = re.compile("\n        # Grab the traceback header.  Different versions of Python have\n        # said different things on the first traceback line.\n        ^(?P<hdr> Traceback\\ \\(\n            (?: most\\ recent\\ call\\ last\n            |   innermost\\ last\n            ) \\) :\n        )\n        \\s* $                # toss trailing whitespace on the header.\n        (?P<stack> .*?)      # don't blink: absorb stuff until...\n        ^ (?P<msg> \\w+ .*)   #     a line *starts* with alphanum.\n        ", re.VERBOSE | re.MULTILINE | re.DOTALL)
  289.     _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$').match
  290.     
  291.     def parse(self, string, name = '<string>'):
  292.         string = string.expandtabs()
  293.         min_indent = self._min_indent(string)
  294.         output = []
  295.         (charno, lineno) = (0, 0)
  296.         for m in self._EXAMPLE_RE.finditer(string):
  297.             output.append(string[charno:m.start()])
  298.             lineno += string.count('\n', charno, m.start())
  299.             (source, options, want, exc_msg) = self._parse_example(m, name, lineno)
  300.             if not self._IS_BLANK_OR_COMMENT(source):
  301.                 output.append(Example(source, want, exc_msg, lineno = lineno, indent = min_indent + len(m.group('indent')), options = options))
  302.             
  303.             lineno += string.count('\n', m.start(), m.end())
  304.             charno = m.end()
  305.         
  306.         output.append(string[charno:])
  307.         return output
  308.  
  309.     
  310.     def get_doctest(self, string, globs, name, filename, lineno):
  311.         return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
  312.  
  313.     
  314.     def get_examples(self, string, name = '<string>'):
  315.         return _[1]
  316.  
  317.     
  318.     def _parse_example(self, m, name, lineno):
  319.         indent = len(m.group('indent'))
  320.         source_lines = m.group('source').split('\n')
  321.         self._check_prompt_blank(source_lines, indent, name, lineno)
  322.         self._check_prefix(source_lines[1:], ' ' * indent + '.', name, lineno)
  323.         source = []([ sl[indent + 4:] for sl in source_lines ])
  324.         want = m.group('want')
  325.         want_lines = want.split('\n')
  326.         self._check_prefix(want_lines, ' ' * indent, name, lineno + len(source_lines))
  327.         want = []([ wl[indent:] for wl in want_lines ])
  328.         m = self._EXCEPTION_RE.match(want)
  329.         options = self._find_options(source, name, lineno)
  330.         return (source, options, want, exc_msg)
  331.  
  332.     _OPTION_DIRECTIVE_RE = re.compile('#\\s*doctest:\\s*([^\\n\\\'"]*)$', re.MULTILINE)
  333.     
  334.     def _find_options(self, source, name, lineno):
  335.         options = { }
  336.         for m in self._OPTION_DIRECTIVE_RE.finditer(source):
  337.             option_strings = m.group(1).replace(',', ' ').split()
  338.             for option in option_strings:
  339.                 if option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME:
  340.                     raise ValueError('line %r of the doctest for %s has an invalid option: %r' % (lineno + 1, name, option))
  341.                 option[1:] not in OPTIONFLAGS_BY_NAME
  342.                 flag = OPTIONFLAGS_BY_NAME[option[1:]]
  343.                 options[flag] = option[0] == '+'
  344.             
  345.         
  346.         if options and self._IS_BLANK_OR_COMMENT(source):
  347.             raise ValueError('line %r of the doctest for %s has an option directive on a line with no example: %r' % (lineno, name, source))
  348.         self._IS_BLANK_OR_COMMENT(source)
  349.         return options
  350.  
  351.     _INDENT_RE = re.compile('^([ ]*)(?=\\S)', re.MULTILINE)
  352.     
  353.     def _min_indent(self, s):
  354.         indents = [ len(indent) for indent in self._INDENT_RE.findall(s) ]
  355.         if len(indents) > 0:
  356.             return min(indents)
  357.         return 0
  358.  
  359.     
  360.     def _check_prompt_blank(self, lines, indent, name, lineno):
  361.         for i, line in enumerate(lines):
  362.             if len(line) >= indent + 4 and line[indent + 3] != ' ':
  363.                 raise ValueError('line %r of the docstring for %s lacks blank after %s: %r' % (lineno + i + 1, name, line[indent:indent + 3], line))
  364.             line[indent + 3] != ' '
  365.         
  366.  
  367.     
  368.     def _check_prefix(self, lines, prefix, name, lineno):
  369.         for i, line in enumerate(lines):
  370.             if line and not line.startswith(prefix):
  371.                 raise ValueError('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (lineno + i + 1, name, line))
  372.             not line.startswith(prefix)
  373.         
  374.  
  375.  
  376.  
  377. class DocTestFinder:
  378.     
  379.     def __init__(self, verbose = False, parser = DocTestParser(), recurse = True, exclude_empty = True):
  380.         self._parser = parser
  381.         self._verbose = verbose
  382.         self._recurse = recurse
  383.         self._exclude_empty = exclude_empty
  384.  
  385.     
  386.     def find(self, obj, name = None, module = None, globs = None, extraglobs = None):
  387.         if name is None:
  388.             name = getattr(obj, '__name__', None)
  389.             if name is None:
  390.                 raise ValueError("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),))
  391.             name is None
  392.         
  393.         if module is False:
  394.             module = None
  395.         elif module is None:
  396.             module = inspect.getmodule(obj)
  397.         
  398.         
  399.         try:
  400.             if not inspect.getsourcefile(obj):
  401.                 pass
  402.             file = inspect.getfile(obj)
  403.             if module is not None:
  404.                 source_lines = linecache.getlines(file, module.__dict__)
  405.             else:
  406.                 source_lines = linecache.getlines(file)
  407.             if not source_lines:
  408.                 source_lines = None
  409.         except TypeError:
  410.             source_lines = None
  411.  
  412.         if globs is None:
  413.             if module is None:
  414.                 globs = { }
  415.             else:
  416.                 globs = module.__dict__.copy()
  417.         else:
  418.             globs = globs.copy()
  419.         if extraglobs is not None:
  420.             globs.update(extraglobs)
  421.         
  422.         if '__name__' not in globs:
  423.             globs['__name__'] = '__main__'
  424.         
  425.         tests = []
  426.         self._find(tests, obj, name, module, source_lines, globs, { })
  427.         tests.sort()
  428.         return tests
  429.  
  430.     
  431.     def _from_module(self, module, object):
  432.         if module is None:
  433.             return True
  434.         if inspect.getmodule(object) is not None:
  435.             return module is inspect.getmodule(object)
  436.         if inspect.isfunction(object):
  437.             return module.__dict__ is object.func_globals
  438.         if inspect.isclass(object):
  439.             return module.__name__ == object.__module__
  440.         if hasattr(object, '__module__'):
  441.             return module.__name__ == object.__module__
  442.         if isinstance(object, property):
  443.             return True
  444.         raise ValueError('object must be a class or function')
  445.  
  446.     
  447.     def _find(self, tests, obj, name, module, source_lines, globs, seen):
  448.         if self._verbose:
  449.             print 'Finding tests in %s' % name
  450.         
  451.         if id(obj) in seen:
  452.             return None
  453.         seen[id(obj)] = 1
  454.         test = self._get_test(obj, name, module, globs, source_lines)
  455.         if test is not None:
  456.             tests.append(test)
  457.         
  458.         if inspect.ismodule(obj) and self._recurse:
  459.             for valname, val in obj.__dict__.items():
  460.                 valname = '%s.%s' % (name, valname)
  461.                 if (inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val):
  462.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  463.                     continue
  464.             
  465.         
  466.         if inspect.ismodule(obj) and self._recurse:
  467.             for valname, val in getattr(obj, '__test__', { }).items():
  468.                 if not isinstance(valname, basestring):
  469.                     raise ValueError('DocTestFinder.find: __test__ keys must be strings: %r' % (type(valname),))
  470.                 isinstance(valname, basestring)
  471.                 if not inspect.isfunction(val) and inspect.isclass(val) and inspect.ismethod(val) and inspect.ismodule(val) or isinstance(val, basestring):
  472.                     raise ValueError('DocTestFinder.find: __test__ values must be strings, functions, methods, classes, or modules: %r' % (type(val),))
  473.                 isinstance(val, basestring)
  474.                 valname = '%s.__test__.%s' % (name, valname)
  475.                 self._find(tests, val, valname, module, source_lines, globs, seen)
  476.             
  477.         
  478.         if inspect.isclass(obj) and self._recurse:
  479.             for valname, val in obj.__dict__.items():
  480.                 if isinstance(val, staticmethod):
  481.                     val = getattr(obj, valname)
  482.                 
  483.                 if isinstance(val, classmethod):
  484.                     val = getattr(obj, valname).im_func
  485.                 
  486.                 if (inspect.isfunction(val) and inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val):
  487.                     valname = '%s.%s' % (name, valname)
  488.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  489.                     continue
  490.             
  491.         
  492.  
  493.     
  494.     def _get_test(self, obj, name, module, globs, source_lines):
  495.         if isinstance(obj, basestring):
  496.             docstring = obj
  497.         else:
  498.             
  499.             try:
  500.                 if obj.__doc__ is None:
  501.                     docstring = ''
  502.                 else:
  503.                     docstring = obj.__doc__
  504.                     if not isinstance(docstring, basestring):
  505.                         docstring = str(docstring)
  506.             except (TypeError, AttributeError):
  507.                 docstring = ''
  508.             
  509.  
  510.         lineno = self._find_lineno(obj, source_lines)
  511.         if self._exclude_empty and not docstring:
  512.             return None
  513.         if module is None:
  514.             filename = None
  515.         else:
  516.             filename = getattr(module, '__file__', module.__name__)
  517.             if filename[-4:] in ('.pyc', '.pyo'):
  518.                 filename = filename[:-1]
  519.             
  520.         return self._parser.get_doctest(docstring, globs, name, filename, lineno)
  521.  
  522.     
  523.     def _find_lineno(self, obj, source_lines):
  524.         lineno = None
  525.         if inspect.ismodule(obj):
  526.             lineno = 0
  527.         
  528.         if inspect.isclass(obj):
  529.             if source_lines is None:
  530.                 return None
  531.             pat = re.compile('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-'))
  532.             for i, line in enumerate(source_lines):
  533.                 if pat.match(line):
  534.                     lineno = i
  535.                     break
  536.                     continue
  537.                 source_lines is None
  538.             
  539.         
  540.         if inspect.ismethod(obj):
  541.             obj = obj.im_func
  542.         
  543.         if inspect.isfunction(obj):
  544.             obj = obj.func_code
  545.         
  546.         if inspect.istraceback(obj):
  547.             obj = obj.tb_frame
  548.         
  549.         if inspect.isframe(obj):
  550.             obj = obj.f_code
  551.         
  552.         if inspect.iscode(obj):
  553.             lineno = getattr(obj, 'co_firstlineno', None) - 1
  554.         
  555.  
  556.  
  557.  
  558. class DocTestRunner:
  559.     DIVIDER = '*' * 70
  560.     
  561.     def __init__(self, checker = None, verbose = None, optionflags = 0):
  562.         if not checker:
  563.             pass
  564.         self._checker = OutputChecker()
  565.         if verbose is None:
  566.             verbose = '-v' in sys.argv
  567.         
  568.         self._verbose = verbose
  569.         self.optionflags = optionflags
  570.         self.original_optionflags = optionflags
  571.         self.tries = 0
  572.         self.failures = 0
  573.         self._name2ft = { }
  574.         self._fakeout = _SpoofOut()
  575.  
  576.     
  577.     def report_start(self, out, test, example):
  578.         if self._verbose:
  579.             if example.want:
  580.                 out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want))
  581.             else:
  582.                 out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n')
  583.         
  584.  
  585.     
  586.     def report_success(self, out, test, example, got):
  587.         if self._verbose:
  588.             out('ok\n')
  589.         
  590.  
  591.     
  592.     def report_failure(self, out, test, example, got):
  593.         out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags))
  594.  
  595.     
  596.     def report_unexpected_exception(self, out, test, example, exc_info):
  597.         out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  598.  
  599.     
  600.     def _failure_header(self, test, example):
  601.         out = [
  602.             self.DIVIDER]
  603.         if test.filename:
  604.             if test.lineno is not None and example.lineno is not None:
  605.                 lineno = test.lineno + example.lineno + 1
  606.             else:
  607.                 lineno = '?'
  608.             out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name))
  609.         else:
  610.             out.append('Line %s, in %s' % (example.lineno + 1, test.name))
  611.         out.append('Failed example:')
  612.         source = example.source
  613.         out.append(_indent(source))
  614.         return '\n'.join(out)
  615.  
  616.     
  617.     def __run(self, test, compileflags, out):
  618.         failures = tries = 0
  619.         original_optionflags = self.optionflags
  620.         (SUCCESS, FAILURE, BOOM) = range(3)
  621.         check = self._checker.check_output
  622.         for examplenum, example in enumerate(test.examples):
  623.             if self.optionflags & REPORT_ONLY_FIRST_FAILURE:
  624.                 pass
  625.             quiet = failures > 0
  626.             self.optionflags = original_optionflags
  627.             if example.options:
  628.                 for optionflag, val in example.options.items():
  629.                     if val:
  630.                         self.optionflags |= optionflag
  631.                         continue
  632.                     self
  633.                     self.optionflags &= ~optionflag
  634.                 
  635.             
  636.             if self.optionflags & SKIP:
  637.                 continue
  638.             
  639.             tries += 1
  640.             if not quiet:
  641.                 self.report_start(out, test, example)
  642.             
  643.             filename = '<doctest %s[%d]>' % (test.name, examplenum)
  644.             
  645.             try:
  646.                 exec compile(example.source, filename, 'single', compileflags, 1) in test.globs
  647.                 self.debugger.set_continue()
  648.                 exception = None
  649.             except KeyboardInterrupt:
  650.                 raise 
  651.             except:
  652.                 exception = sys.exc_info()
  653.                 self.debugger.set_continue()
  654.  
  655.             got = self._fakeout.getvalue()
  656.             self._fakeout.truncate(0)
  657.             outcome = FAILURE
  658.             if exception is None:
  659.                 if check(example.want, got, self.optionflags):
  660.                     outcome = SUCCESS
  661.                 
  662.             else:
  663.                 exc_info = sys.exc_info()
  664.                 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
  665.                 if not quiet:
  666.                     got += _exception_traceback(exc_info)
  667.                 
  668.                 if example.exc_msg is None:
  669.                     outcome = BOOM
  670.                 elif check(example.exc_msg, exc_msg, self.optionflags):
  671.                     outcome = SUCCESS
  672.                 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
  673.                     m1 = re.match('[^:]*:', example.exc_msg)
  674.                     m2 = re.match('[^:]*:', exc_msg)
  675.                     if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags):
  676.                         outcome = SUCCESS
  677.                     
  678.                 
  679.             if outcome is SUCCESS:
  680.                 if not quiet:
  681.                     self.report_success(out, test, example, got)
  682.                 
  683.             quiet
  684.             if outcome is FAILURE:
  685.                 if not quiet:
  686.                     self.report_failure(out, test, example, got)
  687.                 
  688.                 failures += 1
  689.                 continue
  690.             if outcome is BOOM:
  691.                 if not quiet:
  692.                     self.report_unexpected_exception(out, test, example, exc_info)
  693.                 
  694.                 failures += 1
  695.                 continue
  696.         
  697.         self.optionflags = original_optionflags
  698.         self._DocTestRunner__record_outcome(test, failures, tries)
  699.         return TestResults(failures, tries)
  700.  
  701.     
  702.     def __record_outcome(self, test, f, t):
  703.         (f2, t2) = self._name2ft.get(test.name, (0, 0))
  704.         self._name2ft[test.name] = (f + f2, t + t2)
  705.         self.failures += f
  706.         self.tries += t
  707.  
  708.     __LINECACHE_FILENAME_RE = re.compile('<doctest (?P<name>[\\w\\.]+)\\[(?P<examplenum>\\d+)\\]>$')
  709.     
  710.     def __patched_linecache_getlines(self, filename, module_globals = None):
  711.         m = self._DocTestRunner__LINECACHE_FILENAME_RE.match(filename)
  712.         if m and m.group('name') == self.test.name:
  713.             example = self.test.examples[int(m.group('examplenum'))]
  714.             return example.source.splitlines(True)
  715.         return self.save_linecache_getlines(filename, module_globals)
  716.  
  717.     
  718.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  719.         self.test = test
  720.         if compileflags is None:
  721.             compileflags = _extract_future_flags(test.globs)
  722.         
  723.         save_stdout = sys.stdout
  724.         if out is None:
  725.             out = save_stdout.write
  726.         
  727.         sys.stdout = self._fakeout
  728.         save_set_trace = pdb.set_trace
  729.         self.debugger = _OutputRedirectingPdb(save_stdout)
  730.         self.debugger.reset()
  731.         pdb.set_trace = self.debugger.set_trace
  732.         self.save_linecache_getlines = linecache.getlines
  733.         linecache.getlines = self._DocTestRunner__patched_linecache_getlines
  734.         
  735.         try:
  736.             return self._DocTestRunner__run(test, compileflags, out)
  737.         finally:
  738.             sys.stdout = save_stdout
  739.             pdb.set_trace = save_set_trace
  740.             linecache.getlines = self.save_linecache_getlines
  741.             if clear_globs:
  742.                 test.globs.clear()
  743.             
  744.  
  745.  
  746.     
  747.     def summarize(self, verbose = None):
  748.         if verbose is None:
  749.             verbose = self._verbose
  750.         
  751.         notests = []
  752.         passed = []
  753.         failed = []
  754.         totalt = totalf = 0
  755.         for x in self._name2ft.items():
  756.             (f, t) = (name,)
  757.             totalt += t
  758.             totalf += f
  759.             if t == 0:
  760.                 notests.append(name)
  761.                 continue
  762.             x
  763.             if f == 0:
  764.                 passed.append((name, t))
  765.                 continue
  766.             failed.append(x)
  767.         
  768.         if verbose:
  769.             if notests:
  770.                 print len(notests), 'items had no tests:'
  771.                 notests.sort()
  772.                 for thing in notests:
  773.                     print '   ', thing
  774.                 
  775.             
  776.             if passed:
  777.                 print len(passed), 'items passed all tests:'
  778.                 passed.sort()
  779.                 for thing, count in passed:
  780.                     print ' %3d tests in %s' % (count, thing)
  781.                 
  782.             
  783.         
  784.         if failed:
  785.             print self.DIVIDER
  786.             print len(failed), 'items had failures:'
  787.             failed.sort()
  788.             for f, t in failed:
  789.                 print ' %3d of %3d in %s' % (f, t, thing)
  790.             
  791.         
  792.         if verbose:
  793.             print totalt, 'tests in', len(self._name2ft), 'items.'
  794.             print totalt - totalf, 'passed and', totalf, 'failed.'
  795.         
  796.         if totalf:
  797.             print '***Test Failed***', totalf, 'failures.'
  798.         elif verbose:
  799.             print 'Test passed.'
  800.         
  801.         return TestResults(totalf, totalt)
  802.  
  803.     
  804.     def merge(self, other):
  805.         d = self._name2ft
  806.         for f, t in other._name2ft.items():
  807.             if name in d:
  808.                 (f2, t2) = d[name]
  809.                 f = f + f2
  810.                 t = t + t2
  811.             
  812.             d[name] = (f, t)
  813.         
  814.  
  815.  
  816.  
  817. class OutputChecker:
  818.     
  819.     def check_output(self, want, got, optionflags):
  820.         if got == want:
  821.             return True
  822.         return False
  823.  
  824.     
  825.     def _do_a_fancy_diff(self, want, got, optionflags):
  826.         if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF):
  827.             return False
  828.         if optionflags & REPORT_NDIFF:
  829.             return True
  830.         if want.count('\n') > 2:
  831.             pass
  832.         return got.count('\n') > 2
  833.  
  834.     
  835.     def output_difference(self, example, got, optionflags):
  836.         want = example.want
  837.         if not optionflags & DONT_ACCEPT_BLANKLINE:
  838.             got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
  839.         
  840.         if self._do_a_fancy_diff(want, got, optionflags):
  841.             want_lines = want.splitlines(True)
  842.             got_lines = got.splitlines(True)
  843.             if optionflags & REPORT_UDIFF:
  844.                 diff = difflib.unified_diff(want_lines, got_lines, n = 2)
  845.                 diff = list(diff)[2:]
  846.                 kind = 'unified diff with -expected +actual'
  847.             elif optionflags & REPORT_CDIFF:
  848.                 diff = difflib.context_diff(want_lines, got_lines, n = 2)
  849.                 diff = list(diff)[2:]
  850.                 kind = 'context diff with expected followed by actual'
  851.             elif optionflags & REPORT_NDIFF:
  852.                 engine = difflib.Differ(charjunk = difflib.IS_CHARACTER_JUNK)
  853.                 diff = list(engine.compare(want_lines, got_lines))
  854.                 kind = 'ndiff with -expected +actual'
  855.             
  856.             diff = [ line.rstrip() + '\n' for line in diff ]
  857.             return 'Differences (%s):\n' % kind + _indent(''.join(diff))
  858.         if want and got:
  859.             return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
  860.         if want:
  861.             return 'Expected:\n%sGot nothing\n' % _indent(want)
  862.         if got:
  863.             return 'Expected nothing\nGot:\n%s' % _indent(got)
  864.         return 'Expected nothing\nGot nothing\n'
  865.  
  866.  
  867.  
  868. class DocTestFailure(Exception):
  869.     
  870.     def __init__(self, test, example, got):
  871.         self.test = test
  872.         self.example = example
  873.         self.got = got
  874.  
  875.     
  876.     def __str__(self):
  877.         return str(self.test)
  878.  
  879.  
  880.  
  881. class UnexpectedException(Exception):
  882.     
  883.     def __init__(self, test, example, exc_info):
  884.         self.test = test
  885.         self.example = example
  886.         self.exc_info = exc_info
  887.  
  888.     
  889.     def __str__(self):
  890.         return str(self.test)
  891.  
  892.  
  893.  
  894. class DebugRunner(DocTestRunner):
  895.     
  896.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  897.         r = DocTestRunner.run(self, test, compileflags, out, False)
  898.         if clear_globs:
  899.             test.globs.clear()
  900.         
  901.         return r
  902.  
  903.     
  904.     def report_unexpected_exception(self, out, test, example, exc_info):
  905.         raise UnexpectedException(test, example, exc_info)
  906.  
  907.     
  908.     def report_failure(self, out, test, example, got):
  909.         raise DocTestFailure(test, example, got)
  910.  
  911.  
  912. master = None
  913.  
  914. def testmod(m = None, name = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, exclude_empty = False):
  915.     global master
  916.     if m is None:
  917.         m = sys.modules.get('__main__')
  918.     
  919.     if not inspect.ismodule(m):
  920.         raise TypeError('testmod: module required; %r' % (m,))
  921.     inspect.ismodule(m)
  922.     if name is None:
  923.         name = m.__name__
  924.     
  925.     finder = DocTestFinder(exclude_empty = exclude_empty)
  926.     if raise_on_error:
  927.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  928.     else:
  929.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  930.     for test in finder.find(m, name, globs = globs, extraglobs = extraglobs):
  931.         runner.run(test)
  932.     
  933.     if report:
  934.         runner.summarize()
  935.     
  936.     if master is None:
  937.         master = runner
  938.     else:
  939.         master.merge(runner)
  940.     return TestResults(runner.failures, runner.tries)
  941.  
  942.  
  943. def testfile(filename, module_relative = True, name = None, package = None, globs = None, verbose = None, report = True, optionflags = 0, extraglobs = None, raise_on_error = False, parser = DocTestParser(), encoding = None):
  944.     global master
  945.     if package and not module_relative:
  946.         raise ValueError('Package may only be specified for module-relative paths.')
  947.     not module_relative
  948.     (text, filename) = _load_testfile(filename, package, module_relative)
  949.     if name is None:
  950.         name = os.path.basename(filename)
  951.     
  952.     if globs is None:
  953.         globs = { }
  954.     else:
  955.         globs = globs.copy()
  956.     if extraglobs is not None:
  957.         globs.update(extraglobs)
  958.     
  959.     if '__name__' not in globs:
  960.         globs['__name__'] = '__main__'
  961.     
  962.     if raise_on_error:
  963.         runner = DebugRunner(verbose = verbose, optionflags = optionflags)
  964.     else:
  965.         runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  966.     if encoding is not None:
  967.         text = text.decode(encoding)
  968.     
  969.     test = parser.get_doctest(text, globs, name, filename, 0)
  970.     runner.run(test)
  971.     if report:
  972.         runner.summarize()
  973.     
  974.     if master is None:
  975.         master = runner
  976.     else:
  977.         master.merge(runner)
  978.     return TestResults(runner.failures, runner.tries)
  979.  
  980.  
  981. def run_docstring_examples(f, globs, verbose = False, name = 'NoName', compileflags = None, optionflags = 0):
  982.     finder = DocTestFinder(verbose = verbose, recurse = False)
  983.     runner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  984.     for test in finder.find(f, name, globs = globs):
  985.         runner.run(test, compileflags = compileflags)
  986.     
  987.  
  988.  
  989. class Tester:
  990.     
  991.     def __init__(self, mod = None, globs = None, verbose = None, optionflags = 0):
  992.         warnings.warn('class Tester is deprecated; use class doctest.DocTestRunner instead', DeprecationWarning, stacklevel = 2)
  993.         if mod is None and globs is None:
  994.             raise TypeError('Tester.__init__: must specify mod or globs')
  995.         globs is None
  996.         if mod is not None and not inspect.ismodule(mod):
  997.             raise TypeError('Tester.__init__: mod must be a module; %r' % (mod,))
  998.         not inspect.ismodule(mod)
  999.         if globs is None:
  1000.             globs = mod.__dict__
  1001.         
  1002.         self.globs = globs
  1003.         self.verbose = verbose
  1004.         self.optionflags = optionflags
  1005.         self.testfinder = DocTestFinder()
  1006.         self.testrunner = DocTestRunner(verbose = verbose, optionflags = optionflags)
  1007.  
  1008.     
  1009.     def runstring(self, s, name):
  1010.         test = DocTestParser().get_doctest(s, self.globs, name, None, None)
  1011.         if self.verbose:
  1012.             print 'Running string', name
  1013.         
  1014.         (f, t) = self.testrunner.run(test)
  1015.         if self.verbose:
  1016.             print f, 'of', t, 'examples failed in string', name
  1017.         
  1018.         return TestResults(f, t)
  1019.  
  1020.     
  1021.     def rundoc(self, object, name = None, module = None):
  1022.         f = t = 0
  1023.         tests = self.testfinder.find(object, name, module = module, globs = self.globs)
  1024.         for test in tests:
  1025.             (f2, t2) = self.testrunner.run(test)
  1026.             f = f + f2
  1027.             t = t + t2
  1028.         
  1029.         return TestResults(f, t)
  1030.  
  1031.     
  1032.     def rundict(self, d, name, module = None):
  1033.         import types
  1034.         m = types.ModuleType(name)
  1035.         m.__dict__.update(d)
  1036.         if module is None:
  1037.             module = False
  1038.         
  1039.         return self.rundoc(m, name, module)
  1040.  
  1041.     
  1042.     def run__test__(self, d, name):
  1043.         import types
  1044.         m = types.ModuleType(name)
  1045.         m.__test__ = d
  1046.         return self.rundoc(m, name)
  1047.  
  1048.     
  1049.     def summarize(self, verbose = None):
  1050.         return self.testrunner.summarize(verbose)
  1051.  
  1052.     
  1053.     def merge(self, other):
  1054.         self.testrunner.merge(other.testrunner)
  1055.  
  1056.  
  1057. _unittest_reportflags = 0
  1058.  
  1059. def set_unittest_reportflags(flags):
  1060.     global _unittest_reportflags
  1061.     if flags & REPORTING_FLAGS != flags:
  1062.         raise ValueError('Only reporting flags allowed', flags)
  1063.     flags & REPORTING_FLAGS != flags
  1064.     old = _unittest_reportflags
  1065.     _unittest_reportflags = flags
  1066.     return old
  1067.  
  1068.  
  1069. class DocTestCase(unittest.TestCase):
  1070.     
  1071.     def __init__(self, test, optionflags = 0, setUp = None, tearDown = None, checker = None):
  1072.         unittest.TestCase.__init__(self)
  1073.         self._dt_optionflags = optionflags
  1074.         self._dt_checker = checker
  1075.         self._dt_test = test
  1076.         self._dt_setUp = setUp
  1077.         self._dt_tearDown = tearDown
  1078.  
  1079.     
  1080.     def setUp(self):
  1081.         test = self._dt_test
  1082.         if self._dt_setUp is not None:
  1083.             self._dt_setUp(test)
  1084.         
  1085.  
  1086.     
  1087.     def tearDown(self):
  1088.         test = self._dt_test
  1089.         if self._dt_tearDown is not None:
  1090.             self._dt_tearDown(test)
  1091.         
  1092.         test.globs.clear()
  1093.  
  1094.     
  1095.     def runTest(self):
  1096.         test = self._dt_test
  1097.         old = sys.stdout
  1098.         new = StringIO()
  1099.         optionflags = self._dt_optionflags
  1100.         if not optionflags & REPORTING_FLAGS:
  1101.             optionflags |= _unittest_reportflags
  1102.         
  1103.         runner = DocTestRunner(optionflags = optionflags, checker = self._dt_checker, verbose = False)
  1104.         
  1105.         try:
  1106.             runner.DIVIDER = '-' * 70
  1107.             (failures, tries) = runner.run(test, out = new.write, clear_globs = False)
  1108.         finally:
  1109.             sys.stdout = old
  1110.  
  1111.         if failures:
  1112.             raise self.failureException(self.format_failure(new.getvalue()))
  1113.         failures
  1114.  
  1115.     
  1116.     def format_failure(self, err):
  1117.         test = self._dt_test
  1118.         if test.lineno is None:
  1119.             lineno = 'unknown line number'
  1120.         else:
  1121.             lineno = '%s' % test.lineno
  1122.         lname = '.'.join(test.name.split('.')[-1:])
  1123.         return 'Failed doctest test for %s\n  File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err)
  1124.  
  1125.     
  1126.     def debug(self):
  1127.         self.setUp()
  1128.         runner = DebugRunner(optionflags = self._dt_optionflags, checker = self._dt_checker, verbose = False)
  1129.         runner.run(self._dt_test, clear_globs = False)
  1130.         self.tearDown()
  1131.  
  1132.     
  1133.     def id(self):
  1134.         return self._dt_test.name
  1135.  
  1136.     
  1137.     def __repr__(self):
  1138.         name = self._dt_test.name.split('.')
  1139.         return '%s (%s)' % (name[-1], '.'.join(name[:-1]))
  1140.  
  1141.     __str__ = __repr__
  1142.     
  1143.     def shortDescription(self):
  1144.         return 'Doctest: ' + self._dt_test.name
  1145.  
  1146.  
  1147.  
  1148. def DocTestSuite(module = None, globs = None, extraglobs = None, test_finder = None, **options):
  1149.     if test_finder is None:
  1150.         test_finder = DocTestFinder()
  1151.     
  1152.     module = _normalize_module(module)
  1153.     tests = test_finder.find(module, globs = globs, extraglobs = extraglobs)
  1154.     if not tests:
  1155.         raise ValueError(module, 'has no tests')
  1156.     tests
  1157.     tests.sort()
  1158.     suite = unittest.TestSuite()
  1159.     for test in tests:
  1160.         if len(test.examples) == 0:
  1161.             continue
  1162.         
  1163.         if not test.filename:
  1164.             filename = module.__file__
  1165.             if filename[-4:] in ('.pyc', '.pyo'):
  1166.                 filename = filename[:-1]
  1167.             
  1168.             test.filename = filename
  1169.         
  1170.         suite.addTest(DocTestCase(test, **options))
  1171.     
  1172.     return suite
  1173.  
  1174.  
  1175. class DocFileCase(DocTestCase):
  1176.     
  1177.     def id(self):
  1178.         return '_'.join(self._dt_test.name.split('.'))
  1179.  
  1180.     
  1181.     def __repr__(self):
  1182.         return self._dt_test.filename
  1183.  
  1184.     __str__ = __repr__
  1185.     
  1186.     def format_failure(self, err):
  1187.         return 'Failed doctest test for %s\n  File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err)
  1188.  
  1189.  
  1190.  
  1191. def DocFileTest(path, module_relative = True, package = None, globs = None, parser = DocTestParser(), encoding = None, **options):
  1192.     if globs is None:
  1193.         globs = { }
  1194.     else:
  1195.         globs = globs.copy()
  1196.     if package and not module_relative:
  1197.         raise ValueError('Package may only be specified for module-relative paths.')
  1198.     not module_relative
  1199.     (doc, path) = _load_testfile(path, package, module_relative)
  1200.     if '__file__' not in globs:
  1201.         globs['__file__'] = path
  1202.     
  1203.     name = os.path.basename(path)
  1204.     if encoding is not None:
  1205.         doc = doc.decode(encoding)
  1206.     
  1207.     test = parser.get_doctest(doc, globs, name, path, 0)
  1208.     return DocFileCase(test, **options)
  1209.  
  1210.  
  1211. def DocFileSuite(*paths, **kw):
  1212.     suite = unittest.TestSuite()
  1213.     if kw.get('module_relative', True):
  1214.         kw['package'] = _normalize_module(kw.get('package'))
  1215.     
  1216.     for path in paths:
  1217.         suite.addTest(DocFileTest(path, **kw))
  1218.     
  1219.     return suite
  1220.  
  1221.  
  1222. def script_from_examples(s):
  1223.     output = []
  1224.     for piece in DocTestParser().parse(s):
  1225.         if isinstance(piece, Example):
  1226.             output.append(piece.source[:-1])
  1227.             want = piece.want
  1228.             if want:
  1229.                 output.append('# Expected:')
  1230.                 [] += [ '## ' + l for l in want.split('\n')[:-1] ]
  1231.             
  1232.         want
  1233.         [] += [ _comment_line(l) for l in piece.split('\n')[:-1] ]
  1234.     
  1235.     while output and output[-1] == '#':
  1236.         output.pop()
  1237.         continue
  1238.         []
  1239.     while output and output[0] == '#':
  1240.         output.pop(0)
  1241.         continue
  1242.         output
  1243.     return '\n'.join(output) + '\n'
  1244.  
  1245.  
  1246. def testsource(module, name):
  1247.     module = _normalize_module(module)
  1248.     tests = DocTestFinder().find(module)
  1249.     test = _[1]
  1250.     if not test:
  1251.         raise ValueError(name, 'not found in tests')
  1252.     test
  1253.     test = test[0]
  1254.     testsrc = script_from_examples(test.docstring)
  1255.     return testsrc
  1256.  
  1257.  
  1258. def debug_src(src, pm = False, globs = None):
  1259.     testsrc = script_from_examples(src)
  1260.     debug_script(testsrc, pm, globs)
  1261.  
  1262.  
  1263. def debug_script(src, pm = False, globs = None):
  1264.     import pdb
  1265.     srcfilename = tempfile.mktemp('.py', 'doctestdebug')
  1266.     f = open(srcfilename, 'w')
  1267.     f.write(src)
  1268.     f.close()
  1269.     
  1270.     try:
  1271.         if globs:
  1272.             globs = globs.copy()
  1273.         else:
  1274.             globs = { }
  1275.         if pm:
  1276.             
  1277.             try:
  1278.                 execfile(srcfilename, globs, globs)
  1279.             print sys.exc_info()[1]
  1280.             pdb.post_mortem(sys.exc_info()[2])
  1281.  
  1282.         else:
  1283.             pdb.run('execfile(%r)' % srcfilename, globs, globs)
  1284.     finally:
  1285.         os.remove(srcfilename)
  1286.  
  1287.  
  1288.  
  1289. def debug(module, name, pm = False):
  1290.     module = _normalize_module(module)
  1291.     testsrc = testsource(module, name)
  1292.     debug_script(testsrc, pm, module.__dict__)
  1293.  
  1294.  
  1295. class _TestClass:
  1296.     
  1297.     def __init__(self, val):
  1298.         self.val = val
  1299.  
  1300.     
  1301.     def square(self):
  1302.         self.val = self.val ** 2
  1303.         return self
  1304.  
  1305.     
  1306.     def get(self):
  1307.         return self.val
  1308.  
  1309.  
  1310. __test__ = {
  1311.     '_TestClass': _TestClass,
  1312.     'string': '\n                      Example of a string object, searched as-is.\n                      >>> x = 1; y = 2\n                      >>> x + y, x * y\n                      (3, 2)\n                      ',
  1313.     'bool-int equivalence': '\n                                    In 2.2, boolean expressions displayed\n                                    0 or 1.  By default, we still accept\n                                    them.  This can be disabled by passing\n                                    DONT_ACCEPT_TRUE_FOR_1 to the new\n                                    optionflags argument.\n                                    >>> 4 == 4\n                                    1\n                                    >>> 4 == 4\n                                    True\n                                    >>> 4 > 4\n                                    0\n                                    >>> 4 > 4\n                                    False\n                                    ',
  1314.     'blank lines': "\n                Blank lines can be marked with <BLANKLINE>:\n                    >>> print 'foo\\n\\nbar\\n'\n                    foo\n                    <BLANKLINE>\n                    bar\n                    <BLANKLINE>\n            ",
  1315.     'ellipsis': "\n                If the ellipsis flag is used, then '...' can be used to\n                elide substrings in the desired output:\n                    >>> print range(1000) #doctest: +ELLIPSIS\n                    [0, 1, 2, ..., 999]\n            ",
  1316.     'whitespace normalization': '\n                If the whitespace normalization flag is used, then\n                differences in whitespace are ignored.\n                    >>> print range(30) #doctest: +NORMALIZE_WHITESPACE\n                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,\n                     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n                     27, 28, 29]\n            ' }
  1317.  
  1318. def _test():
  1319.     testfiles = _[1]
  1320.     return 0
  1321.  
  1322. if __name__ == '__main__':
  1323.     sys.exit(_test())
  1324.  
  1325.