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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import __builtin__
  5. import commands
  6. import doctest
  7. import inspect
  8. import logging
  9. import os
  10. import re
  11. import sys
  12. import traceback
  13. import unittest
  14. from inspect import getmodule
  15. from StringIO import StringIO
  16. from doctest import REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE, _unittest_reportflags, DocTestRunner, _extract_future_flags, pdb, _OutputRedirectingPdb, _exception_traceback, linecache
  17. import nose.core as nose
  18. from nose.plugins import doctests, Plugin
  19. from nose.util import anyp, getpackage, test_address, resolve_name, tolist
  20. log = logging.getLogger(__name__)
  21.  
  22. def default_argv():
  23.     UserConfig = UserConfig
  24.     import IPython
  25.     ipcdir = os.path.dirname(UserConfig.__file__)
  26.     ipconf = os.path.join(ipcdir, 'ipythonrc')
  27.     return [
  28.         '--colors=NoColor',
  29.         '--noterm_title',
  30.         '-rcfile=%s' % ipconf]
  31.  
  32.  
  33. class py_file_finder(object):
  34.     
  35.     def __init__(self, test_filename):
  36.         self.test_filename = test_filename
  37.  
  38.     
  39.     def __call__(self, name):
  40.         get_py_filename = get_py_filename
  41.         import IPython.genutils
  42.         
  43.         try:
  44.             return get_py_filename(name)
  45.         except IOError:
  46.             test_dir = os.path.dirname(self.test_filename)
  47.             new_path = os.path.join(test_dir, name)
  48.             return get_py_filename(new_path)
  49.  
  50.  
  51.  
  52.  
  53. def _run_ns_sync(self, arg_s, runner = None):
  54.     
  55.     try:
  56.         fname = _run_ns_sync.test_filename
  57.     except AttributeError:
  58.         fname = arg_s
  59.  
  60.     finder = py_file_finder(fname)
  61.     out = _ip.IP.magic_run_ori(arg_s, runner, finder)
  62.     if hasattr(_run_ns_sync, 'test_globs'):
  63.         _run_ns_sync.test_globs.update(_ip.user_ns)
  64.     
  65.     return out
  66.  
  67.  
  68. class ipnsdict(dict):
  69.     
  70.     def __init__(self, *a):
  71.         dict.__init__(self, *a)
  72.         self._savedict = { }
  73.  
  74.     
  75.     def clear(self):
  76.         dict.clear(self)
  77.         self.update(self._savedict)
  78.  
  79.     
  80.     def _checkpoint(self):
  81.         self._savedict.clear()
  82.         self._savedict.update(self)
  83.  
  84.     
  85.     def update(self, other):
  86.         self._checkpoint()
  87.         dict.update(self, other)
  88.         self.pop('_', None)
  89.         self['__builtins__'] = __builtin__
  90.  
  91.  
  92.  
  93. def start_ipython():
  94.     if hasattr(start_ipython, 'already_called'):
  95.         return None
  96.     start_ipython.already_called = True
  97.     import new
  98.     import IPython
  99.     
  100.     def xsys(cmd):
  101.         cmd = _ip.IP.var_expand(cmd, depth = 1)
  102.         sys.stdout.write(commands.getoutput(cmd))
  103.         sys.stdout.flush()
  104.  
  105.     _displayhook = sys.displayhook
  106.     _excepthook = sys.excepthook
  107.     _main = sys.modules.get('__main__')
  108.     argv = default_argv()
  109.     (user_ns, global_ns) = IPython.ipapi.make_user_namespaces(ipnsdict(), dict())
  110.     IPython.Shell.IPShell(argv, user_ns, global_ns)
  111.     sys.modules['__main__'] = _main
  112.     sys.displayhook = _displayhook
  113.     sys.excepthook = _excepthook
  114.     _ip = IPython.ipapi.get()
  115.     __builtin__._ip = _ip
  116.     _ip.system = xsys
  117.     im = new.instancemethod(_run_ns_sync, _ip.IP, _ip.IP.__class__)
  118.     _ip.IP.magic_run_ori = _ip.IP.magic_run
  119.     _ip.IP.magic_run = im
  120.     history = history
  121.     import IPython
  122.     history.init_ipython(_ip)
  123.     if not hasattr(_ip.IP, 'magic_history'):
  124.         raise RuntimeError("Can't load magics, aborting")
  125.     hasattr(_ip.IP, 'magic_history')
  126.  
  127. start_ipython()
  128.  
  129. def is_extension_module(filename):
  130.     return os.path.splitext(filename)[1].lower() in ('.so', '.pyd')
  131.  
  132.  
  133. class DocTestSkip(object):
  134.     ds_skip = 'Doctest to skip.\n    >>> 1 #doctest: +SKIP\n    '
  135.     
  136.     def __init__(self, obj):
  137.         self.obj = obj
  138.  
  139.     
  140.     def __getattribute__(self, key):
  141.         if key == '__doc__':
  142.             return DocTestSkip.ds_skip
  143.         return getattr(object.__getattribute__(self, 'obj'), key)
  144.  
  145.  
  146.  
  147. class DocTestFinder(doctest.DocTestFinder):
  148.     
  149.     def _from_module(self, module, object):
  150.         if module is None:
  151.             return True
  152.         if inspect.isfunction(object):
  153.             return module.__dict__ is object.func_globals
  154.         if inspect.isbuiltin(object):
  155.             return module.__name__ == object.__module__
  156.         if inspect.isclass(object):
  157.             return module.__name__ == object.__module__
  158.         if inspect.ismethod(object):
  159.             return module.__name__ == object.im_class.__module__
  160.         if inspect.getmodule(object) is not None:
  161.             return module is inspect.getmodule(object)
  162.         if hasattr(object, '__module__'):
  163.             return module.__name__ == object.__module__
  164.         if isinstance(object, property):
  165.             return True
  166.         raise ValueError('object must be a class or function')
  167.  
  168.     
  169.     def _find(self, tests, obj, name, module, source_lines, globs, seen):
  170.         if hasattr(obj, 'skip_doctest'):
  171.             obj = DocTestSkip(obj)
  172.         
  173.         doctest.DocTestFinder._find(self, tests, obj, name, module, source_lines, globs, seen)
  174.         isroutine = isroutine
  175.         isclass = isclass
  176.         ismodule = ismodule
  177.         import inspect
  178.         if inspect.ismodule(obj) and self._recurse:
  179.             for valname, val in obj.__dict__.items():
  180.                 valname1 = '%s.%s' % (name, valname)
  181.                 if (isroutine(val) or isclass(val)) and self._from_module(module, val):
  182.                     self._find(tests, val, valname1, module, source_lines, globs, seen)
  183.                     continue
  184.             
  185.         
  186.         if inspect.isclass(obj) and self._recurse:
  187.             for valname, val in obj.__dict__.items():
  188.                 if isinstance(val, staticmethod):
  189.                     val = getattr(obj, valname)
  190.                 
  191.                 if isinstance(val, classmethod):
  192.                     val = getattr(obj, valname).im_func
  193.                 
  194.                 if (inspect.isfunction(val) and inspect.isclass(val) and inspect.ismethod(val) or isinstance(val, property)) and self._from_module(module, val):
  195.                     valname = '%s.%s' % (name, valname)
  196.                     self._find(tests, val, valname, module, source_lines, globs, seen)
  197.                     continue
  198.             
  199.         
  200.  
  201.  
  202.  
  203. class IPDoctestOutputChecker(doctest.OutputChecker):
  204.     random_re = re.compile('#\\s*random\\s+')
  205.     
  206.     def check_output(self, want, got, optionflags):
  207.         ret = doctest.OutputChecker.check_output(self, want, got, optionflags)
  208.         if not ret and self.random_re.search(want):
  209.             return True
  210.         return ret
  211.  
  212.  
  213.  
  214. class DocTestCase(doctests.DocTestCase):
  215.     
  216.     def __init__(self, test, optionflags = 0, setUp = None, tearDown = None, checker = None, obj = None, result_var = '_'):
  217.         self._result_var = result_var
  218.         doctests.DocTestCase.__init__(self, test, optionflags = optionflags, setUp = setUp, tearDown = tearDown, checker = checker)
  219.         self._dt_optionflags = optionflags
  220.         self._dt_checker = checker
  221.         self._dt_test = test
  222.         self._dt_setUp = setUp
  223.         self._dt_tearDown = tearDown
  224.         runner = IPDocTestRunner(optionflags = optionflags, checker = checker, verbose = False)
  225.         self._dt_runner = runner
  226.         self._ori_dir = os.getcwd()
  227.  
  228.     
  229.     def runTest(self):
  230.         test = self._dt_test
  231.         runner = self._dt_runner
  232.         old = sys.stdout
  233.         new = StringIO()
  234.         optionflags = self._dt_optionflags
  235.         if not optionflags & REPORTING_FLAGS:
  236.             optionflags |= _unittest_reportflags
  237.         
  238.         
  239.         try:
  240.             curdir = os.getcwd()
  241.             os.chdir(self._ori_dir)
  242.             runner.DIVIDER = '-' * 70
  243.             (failures, tries) = runner.run(test, out = new.write, clear_globs = False)
  244.         finally:
  245.             sys.stdout = old
  246.             os.chdir(curdir)
  247.  
  248.         if failures:
  249.             raise self.failureException(self.format_failure(new.getvalue()))
  250.         failures
  251.  
  252.     
  253.     def setUp(self):
  254.         if isinstance(self._dt_test.examples[0], IPExample):
  255.             _ip.IP.user_ns.update(self._dt_test.globs)
  256.             self._dt_test.globs = _ip.IP.user_ns
  257.         
  258.         super(DocTestCase, self).setUp()
  259.  
  260.     
  261.     def tearDown(self):
  262.         
  263.         try:
  264.             super(DocTestCase, self).tearDown()
  265.         except AttributeError:
  266.             exc = None
  267.             if exc.args[0] != self._result_var:
  268.                 raise 
  269.             exc.args[0] != self._result_var
  270.  
  271.  
  272.  
  273.  
  274. class IPExample(doctest.Example):
  275.     pass
  276.  
  277.  
  278. class IPExternalExample(doctest.Example):
  279.     
  280.     def __init__(self, source, want, exc_msg = None, lineno = 0, indent = 0, options = None):
  281.         doctest.Example.__init__(self, source, want, exc_msg, lineno, indent, options)
  282.         self.source += '\n'
  283.  
  284.  
  285.  
  286. class IPDocTestParser(doctest.DocTestParser):
  287.     _PS1_PY = '>>>'
  288.     _PS2_PY = '\\.\\.\\.'
  289.     _PS1_IP = 'In\\ \\[\\d+\\]:'
  290.     _PS2_IP = '\\ \\ \\ \\.\\.\\.+:'
  291.     _RE_TPL = '\n        # Source consists of a PS1 line followed by zero or more PS2 lines.\n        (?P<source>\n            (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*)    # PS1 line\n            (?:\\n           [ ]*  (?P<ps2> %s) .*)*)  # PS2 lines\n        \\n? # a newline\n        # Want consists of any non-blank lines that do not start with PS1.\n        (?P<want> (?:(?![ ]*$)    # Not a blank line\n                     (?![ ]*%s)   # Not a line starting with PS1\n                     (?![ ]*%s)   # Not a line starting with PS2\n                     .*$\\n?       # But any other line\n                  )*)\n                  '
  292.     _EXAMPLE_RE_PY = re.compile(_RE_TPL % (_PS1_PY, _PS2_PY, _PS1_PY, _PS2_PY), re.MULTILINE | re.VERBOSE)
  293.     _EXAMPLE_RE_IP = re.compile(_RE_TPL % (_PS1_IP, _PS2_IP, _PS1_IP, _PS2_IP), re.MULTILINE | re.VERBOSE)
  294.     _RANDOM_TEST = re.compile('#\\s*all-random\\s+')
  295.     _EXTERNAL_IP = re.compile('#\\s*ipdoctest:\\s*EXTERNAL')
  296.     
  297.     def ip2py(self, source):
  298.         out = []
  299.         newline = out.append
  300.         for lnum, line in enumerate(source.strip().splitlines()):
  301.             newline(_ip.IP.prefilter(line, lnum > 0))
  302.         
  303.         newline('')
  304.         return '\n'.join(out)
  305.  
  306.     
  307.     def parse(self, string, name = '<string>'):
  308.         string = string.expandtabs()
  309.         min_indent = self._min_indent(string)
  310.         output = []
  311.         (charno, lineno) = (0, 0)
  312.         if self._RANDOM_TEST.search(string):
  313.             random_marker = '\n# random'
  314.         else:
  315.             random_marker = ''
  316.         ip2py = False
  317.         terms = list(self._EXAMPLE_RE_PY.finditer(string))
  318.         if terms:
  319.             Example = doctest.Example
  320.         else:
  321.             terms = list(self._EXAMPLE_RE_IP.finditer(string))
  322.             if self._EXTERNAL_IP.search(string):
  323.                 Example = IPExternalExample
  324.             else:
  325.                 Example = IPExample
  326.                 ip2py = True
  327.         for m in terms:
  328.             output.append(string[charno:m.start()])
  329.             lineno += string.count('\n', charno, m.start())
  330.             (source, options, want, exc_msg) = self._parse_example(m, name, lineno, ip2py)
  331.             want += random_marker
  332.             if Example is IPExternalExample:
  333.                 options[doctest.NORMALIZE_WHITESPACE] = True
  334.                 want += '\n'
  335.             
  336.             if not self._IS_BLANK_OR_COMMENT(source):
  337.                 output.append(Example(source, want, exc_msg, lineno = lineno, indent = min_indent + len(m.group('indent')), options = options))
  338.             
  339.             lineno += string.count('\n', m.start(), m.end())
  340.             charno = m.end()
  341.         
  342.         output.append(string[charno:])
  343.         return output
  344.  
  345.     
  346.     def _parse_example(self, m, name, lineno, ip2py = False):
  347.         indent = len(m.group('indent'))
  348.         source_lines = m.group('source').split('\n')
  349.         ps1 = m.group('ps1')
  350.         ps2 = m.group('ps2')
  351.         ps1_len = len(ps1)
  352.         self._check_prompt_blank(source_lines, indent, name, lineno, ps1_len)
  353.         if ps2:
  354.             self._check_prefix(source_lines[1:], ' ' * indent + ps2, name, lineno)
  355.         
  356.         source = []([ sl[indent + ps1_len + 1:] for sl in source_lines ])
  357.         want = m.group('want')
  358.         want_lines = want.split('\n')
  359.         if len(want_lines) > 1 and re.match(' *$', want_lines[-1]):
  360.             del want_lines[-1]
  361.         
  362.         self._check_prefix(want_lines, ' ' * indent, name, lineno + len(source_lines))
  363.         want_lines[0] = re.sub('Out\\[\\d+\\]: \\s*?\\n?', '', want_lines[0])
  364.         want = []([ wl[indent:] for wl in want_lines ])
  365.         m = self._EXCEPTION_RE.match(want)
  366.         options = self._find_options(source, name, lineno)
  367.         return (source, options, want, exc_msg)
  368.  
  369.     
  370.     def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
  371.         space_idx = indent + ps1_len
  372.         min_len = space_idx + 1
  373.         for i, line in enumerate(lines):
  374.             if len(line) >= min_len and line[space_idx] != ' ':
  375.                 raise ValueError('line %r of the docstring for %s lacks blank after %s: %r' % (lineno + i + 1, name, line[indent:space_idx], line))
  376.             line[space_idx] != ' '
  377.         
  378.  
  379.  
  380. SKIP = doctest.register_optionflag('SKIP')
  381.  
  382. class IPDocTestRunner(doctest.DocTestRunner, object):
  383.     
  384.     def run(self, test, compileflags = None, out = None, clear_globs = True):
  385.         _run_ns_sync.test_globs = test.globs
  386.         _run_ns_sync.test_filename = test.filename
  387.         return super(IPDocTestRunner, self).run(test, compileflags, out, clear_globs)
  388.  
  389.  
  390.  
  391. class DocFileCase(doctest.DocFileCase):
  392.     
  393.     def address(self):
  394.         return (self._dt_test.filename, None, None)
  395.  
  396.  
  397.  
  398. class ExtensionDoctest(doctests.Doctest):
  399.     name = 'extdoctest'
  400.     enabled = True
  401.     
  402.     def __init__(self, exclude_patterns = None):
  403.         if exclude_patterns is None:
  404.             exclude_patterns = []
  405.         
  406.         self.exclude_patterns = map(re.compile, exclude_patterns)
  407.         doctests.Doctest.__init__(self)
  408.  
  409.     
  410.     def options(self, parser, env = os.environ):
  411.         Plugin.options(self, parser, env)
  412.         parser.add_option('--doctest-tests', action = 'store_true', dest = 'doctest_tests', default = env.get('NOSE_DOCTEST_TESTS', True), help = 'Also look for doctests in test modules. Note that classes, methods and functions should have either doctests or non-doctest tests, not both. [NOSE_DOCTEST_TESTS]')
  413.         parser.add_option('--doctest-extension', action = 'append', dest = 'doctestExtension', help = 'Also look for doctests in files with this extension [NOSE_DOCTEST_EXTENSION]')
  414.         env_setting = env.get('NOSE_DOCTEST_EXTENSION')
  415.         if env_setting is not None:
  416.             parser.set_defaults(doctestExtension = tolist(env_setting))
  417.         
  418.  
  419.     
  420.     def configure(self, options, config):
  421.         Plugin.configure(self, options, config)
  422.         self.doctest_tests = options.doctest_tests
  423.         self.extension = tolist(options.doctestExtension)
  424.         self.parser = doctest.DocTestParser()
  425.         self.finder = DocTestFinder()
  426.         self.checker = IPDoctestOutputChecker()
  427.         self.globs = None
  428.         self.extraglobs = None
  429.  
  430.     
  431.     def loadTestsFromExtensionModule(self, filename):
  432.         (bpath, mod) = os.path.split(filename)
  433.         modname = os.path.splitext(mod)[0]
  434.         
  435.         try:
  436.             sys.path.append(bpath)
  437.             module = __import__(modname)
  438.             tests = list(self.loadTestsFromModule(module))
  439.         finally:
  440.             sys.path.pop()
  441.  
  442.         return tests
  443.  
  444.     
  445.     def loadTestsFromModule(self, module):
  446.         if not self.matches(module.__name__):
  447.             log.debug("Doctest doesn't want module %s", module)
  448.             return None
  449.         tests = self.finder.find(module, globs = self.globs, extraglobs = self.extraglobs)
  450.         if not tests:
  451.             return None
  452.         optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
  453.         tests.sort()
  454.         module_file = module.__file__
  455.         for test in tests:
  456.             if not test.examples:
  457.                 continue
  458.             
  459.             if not test.filename:
  460.                 test.filename = module_file
  461.             
  462.             yield DocTestCase(test, optionflags = optionflags, checker = self.checker)
  463.         
  464.  
  465.     
  466.     def loadTestsFromFile(self, filename):
  467.         if is_extension_module(filename):
  468.             for t in self.loadTestsFromExtensionModule(filename):
  469.                 yield t
  470.             
  471.         elif self.extension and anyp(filename.endswith, self.extension):
  472.             name = os.path.basename(filename)
  473.             dh = open(filename)
  474.             
  475.             try:
  476.                 doc = dh.read()
  477.             finally:
  478.                 dh.close()
  479.  
  480.             test = self.parser.get_doctest(doc, globs = {
  481.                 '__file__': filename }, name = name, filename = filename, lineno = 0)
  482.             if test.examples:
  483.                 yield DocFileCase(test)
  484.             else:
  485.                 yield False
  486.         
  487.  
  488.     
  489.     def wantFile(self, filename):
  490.         for pat in self.exclude_patterns:
  491.             if pat.search(filename):
  492.                 return False
  493.         
  494.         if is_extension_module(filename):
  495.             return True
  496.         return doctests.Doctest.wantFile(self, filename)
  497.  
  498.  
  499.  
  500. class IPythonDoctest(ExtensionDoctest):
  501.     name = 'ipdoctest'
  502.     enabled = True
  503.     
  504.     def makeTest(self, obj, parent):
  505.         optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
  506.         doctests = self.finder.find(obj, module = getmodule(parent))
  507.         if doctests:
  508.             for test in doctests:
  509.                 if len(test.examples) == 0:
  510.                     continue
  511.                 
  512.                 yield DocTestCase(test, obj = obj, optionflags = optionflags, checker = self.checker)
  513.             
  514.         
  515.  
  516.     
  517.     def options(self, parser, env = os.environ):
  518.         Plugin.options(self, parser, env)
  519.         parser.add_option('--ipdoctest-tests', action = 'store_true', dest = 'ipdoctest_tests', default = env.get('NOSE_IPDOCTEST_TESTS', True), help = 'Also look for doctests in test modules. Note that classes, methods and functions should have either doctests or non-doctest tests, not both. [NOSE_IPDOCTEST_TESTS]')
  520.         parser.add_option('--ipdoctest-extension', action = 'append', dest = 'ipdoctest_extension', help = 'Also look for doctests in files with this extension [NOSE_IPDOCTEST_EXTENSION]')
  521.         env_setting = env.get('NOSE_IPDOCTEST_EXTENSION')
  522.         if env_setting is not None:
  523.             parser.set_defaults(ipdoctest_extension = tolist(env_setting))
  524.         
  525.  
  526.     
  527.     def configure(self, options, config):
  528.         Plugin.configure(self, options, config)
  529.         self.doctest_tests = options.ipdoctest_tests
  530.         self.extension = tolist(options.ipdoctest_extension)
  531.         self.parser = IPDocTestParser()
  532.         self.finder = DocTestFinder(parser = self.parser)
  533.         self.checker = IPDoctestOutputChecker()
  534.         self.globs = None
  535.         self.extraglobs = None
  536.  
  537.  
  538.