• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python util.src函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nose.util.src函数的典型用法代码示例。如果您正苦于以下问题:Python src函数的具体用法?Python src怎么用?Python src使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了src函数的16个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_test_address

    def test_test_address(self):
        # test addresses are specified as
        #     package.module:class.method
        #     /path/to/file.py:class.method
        # converted into 3-tuples (file, module, callable)
        # all terms optional
        test_address = util.test_address
        absfile = util.absfile
        class Foo:
            def bar(self):
                pass
        def baz():
            pass

        f = Foo()

        class FooTC(unittest.TestCase):
            def test_one(self):
                pass
            def test_two(self):
                pass

        class CustomTestType(type):
            pass
        class CustomTC(unittest.TestCase):
            __metaclass__ = CustomTestType
            def test_one(self):
                pass
            def test_two(self):
                pass

        foo_funct = case.FunctionTestCase(baz)
        foo_functu = unittest.FunctionTestCase(baz)

        foo_mtc = case.MethodTestCase(unbound_method(Foo, Foo.bar))

        me = util.src(absfile(__file__))
        self.assertEqual(test_address(baz),
                         (me, __name__, 'baz'))
        assert test_address(Foo) == (me, __name__, 'Foo')
        assert test_address(unbound_method(Foo, Foo.bar)) == (me, __name__,
                                                              'Foo.bar')
        assert test_address(f) == (me, __name__, 'Foo')
        assert test_address(f.bar) == (me, __name__, 'Foo.bar')
        assert test_address(nose) == (
            util.src(absfile(nose.__file__)), 'nose', None)

        # test passing the actual test callable, as the
        # missed test plugin must do
        self.assertEqual(test_address(FooTC('test_one')),
                         (me, __name__, 'FooTC.test_one'))
        self.assertEqual(test_address(CustomTC('test_one')),
                         (me, __name__, 'CustomTC.test_one'))
        self.assertEqual(test_address(foo_funct),
                         (me, __name__, 'baz'))
        self.assertEqual(test_address(foo_functu),
                         (me, __name__, 'baz'))
        self.assertEqual(test_address(foo_mtc),
                         (me, __name__, 'Foo.bar'))
开发者ID:AndryulE,项目名称:kitsune,代码行数:59,代码来源:test_utils.py


示例2: loadTestsFromModule

 def loadTestsFromModule(self, module):
     """Load doctests from the module.
     """
     log.debug("loading from %s", module)
     if not self.matches(module.__name__):
         log.debug("Doctest doesn't want module %s", module)
         return
     try:
         tests = self.finder.find(module)
     except AttributeError:
         log.exception("Attribute error loading from %s", module)
         # nose allows module.__test__ = False; doctest does not and throws
         # AttributeError
         return
     if not tests:
         log.debug("No tests found in %s", module)
         return
     tests.sort()
     module_file = src(module.__file__)
     # FIXME this breaks the id plugin somehow (tests probably don't
     # get wrapped in result proxy or something)
     cases = []
     for test in tests:
         if not test.examples:
             continue
         if not test.filename:
             test.filename = module_file
         cases.append(DocTestCase(test,
                                  optionflags=self.optionflags,
                                  result_var=self.doctest_result_var))
     if cases:
         yield self.suiteClass(cases, context=module, can_split=False)
开发者ID:rupenp,项目名称:python-nlg,代码行数:32,代码来源:doctests.py


示例3: wantModuleCoverage

 def wantModuleCoverage(self, name, module):
     if not hasattr(module, "__file__"):
         log.debug("no coverage of %s: no __file__", name)
         return False
     module_file = src(module.__file__)
     if not module_file or not module_file.endswith(".py"):
         log.debug("no coverage of %s: not a python file", name)
         return False
     if self.coverPackages:
         for package in self.coverPackages:
             if re.findall(r"^%s\b" % re.escape(package), name) and (
                 self.coverTests or not self.conf.testMatch.search(name)
             ):
                 log.debug("coverage for %s", name)
                 return True
     if name in self.skipModules:
         log.debug("no coverage for %s: loaded before coverage start", name)
         return False
     if self.conf.testMatch.search(name) and not self.coverTests:
         log.debug("no coverage for %s: is a test", name)
         return False
     # accept any package that passed the previous tests, unless
     # coverPackages is on -- in that case, if we wanted this
     # module, we would have already returned True
     return not self.coverPackages
开发者ID:yarbelk,项目名称:nose,代码行数:25,代码来源:cover.py


示例4: loadTestsFromModule

 def loadTestsFromModule(self, module):
     if not self.matches(module.__name__):
         npd.log.debug("Doctest doesn't want module %s", module)
         return
     try:
         tests = self.finder.find(module)
     except AttributeError:
         # nose allows module.__test__ = False; doctest does not and
         # throws AttributeError
         return
     if not tests:
         return
     tests.sort()
     module_file = src(module.__file__)
     for test in tests:
         if not test.examples:
             continue
         if not test.filename:
             test.filename = module_file
         # Set test namespace; test altered in place
         self.set_test_context(test)
         yield self.doctest_case_class(test,
                                       optionflags=self.doctest_optflags,
                                       checker=self.out_check_class(),
                                       result_var=self.doctest_result_var)
开发者ID:7924102,项目名称:numpy,代码行数:25,代码来源:noseclasses.py


示例5: makeName

 def makeName(self, addr):
     log.debug("Make name %s", addr)
     filename, module, call = addr
     if filename is not None:
         head = src(filename)
     else:
         head = module
     if call is not None:
         return "%s:%s" % (head, call)
     return head
开发者ID:ethanhelfman,项目名称:InstaGet,代码行数:10,代码来源:testid.py


示例6: test_subcommand_success

def test_subcommand_success():
    """Make sure shiva finds and delegates to a Deployment instance method and
    extracts the result, when all goes well.

    """
    status, output = inner_main([src(__file__),
                                 '--shiva-subcommand',
                                 'get_lock_name'])
    eq_(wake_pickle(output), 'harvey')
    eq_(status, 0)
开发者ID:erikrose,项目名称:shiva,代码行数:10,代码来源:test_commandline.py


示例7: test_subcommand_should_not_deploy

def test_subcommand_should_not_deploy():
    """If a shiva subcommand raises ShouldNotDeploy, it should get pickled and
    printed.

    """
    status, output = inner_main([src(__file__),
                                 '--shiva-subcommand',
                                 'check_out'])
    assert_raises(ShouldNotDeploy, wake_pickle, output)
    eq_(status, 0)
开发者ID:erikrose,项目名称:shiva,代码行数:10,代码来源:test_commandline.py


示例8: _printError

    def _printError(self, kind, err, test, isFailure=True):
        """Output a human-readable error report to the stream.

        kind -- the (string) type of incident the precipitated this call
        err -- exc_info()-style traceback triple
        test -- the test that precipitated this call

        """
        if isFailure or self._showAdvisories:
            # Don't bind third item to a local var; that can create circular
            # refs which are expensive to collect. See the sys.exc_info() docs.
            exception_type, exception_value = err[:2]
            extracted_tb = extract_tb(err[2])
            formatted_traceback = ''.join(format_list(extracted_tb))
            # TODO: Canonicalize the path to remove /kitsune/../kitsune
            # nonsense. Don't relativize, though, as that hurts the ability to
            # paste into running editors.
            writeln = self.stream.writeln
            write = self.stream.write
            with self.bar.dodging():
                writeln('\n' + (self._codes['bold'] if isFailure else '') +
                        '%s: %s' % (kind, nose_selector(test)))

                if isFailure:  # Then show traceback
                    # File name and line num in a format vi can take:
                    try:
                        address = test_address(test)
                    except TypeError:
                        # Explodes if the function passed to @with_setup
                        # applied to a test generator has an error.
                        address = None
                    if address:  # None if no such callable found. No sense
                                 # trying to find the test frame if there's no
                                 # such thing.
                        file, line = frame_of_test(address,
                                                   exception_type,
                                                   exception_value,
                                                   extracted_tb)[:2]
                        writeln(' ' * len(kind) + '  %s +%s %s' %
                                (os.environ.get('EDITOR', 'vi'), line,
                                 human_path(src(file), self._cwd)))

                    write(self._codes['sgr0'])  # end bold

                    # Traceback:
                    # TODO: Think about using self._exc_info_to_string, which
                    # does some pretty whizzy skipping of unittest frames.
                    write(formatted_traceback)

                    # Exception:
                    write(''.join(format_exception_only(exception_type,
                                                        exception_value)))
                else:
                    write(self._codes['sgr0'])  # end bold
开发者ID:disqus,项目名称:nose-progressive,代码行数:54,代码来源:result.py


示例9: test_address

    def test_address(self):
        from nose.util import absfile, src
        class TC(unittest.TestCase):
            def runTest(self):
                raise Exception("error")

        def dummy(i):
            pass

        def test():
            pass

        class Test:
            def test(self):
                pass

            def test_gen(self):
                def tryit(i):
                    pass
                for i in range (0, 2):
                    yield tryit, i

            def try_something(self, a, b):
                pass

        fl = src(absfile(__file__))
        case = nose.case.Test(TC())
        self.assertEqual(case.address(), (fl, __name__, 'TC.runTest'))

        case = nose.case.Test(nose.case.FunctionTestCase(test))
        self.assertEqual(case.address(), (fl, __name__, 'test'))

        case = nose.case.Test(nose.case.FunctionTestCase(
            dummy, arg=(1,), descriptor=test))
        self.assertEqual(case.address(), (fl, __name__, 'test'))

        case = nose.case.Test(nose.case.MethodTestCase(
                                  unbound_method(Test, Test.test)))
        self.assertEqual(case.address(), (fl, __name__, 'Test.test'))

        case = nose.case.Test(
            nose.case.MethodTestCase(unbound_method(Test, Test.try_something),
                                     arg=(1,2,),
                                     descriptor=unbound_method(Test,
                                                               Test.test_gen)))
        self.assertEqual(case.address(),
                         (fl, __name__, 'Test.test_gen'))

        case = nose.case.Test(
            nose.case.MethodTestCase(unbound_method(Test, Test.test_gen),
                                     test=dummy, arg=(1,)))
        self.assertEqual(case.address(),
                         (fl, __name__, 'Test.test_gen'))
开发者ID:adpayne237,项目名称:zambiamobile,代码行数:53,代码来源:test_cases.py


示例10: loadTestsFromModule

    def loadTestsFromModule(self, module):
        if not self.matches(module.__name__):
            npd.log.debug("Doctest doesn't want module %s", module)
            return
        try:
            tests = self.finder.find(module)
        except AttributeError:
            # nose allows module.__test__ = False; doctest does not and
            # throws AttributeError
            return
        if not tests:
            return
        tests.sort()
        module_file = src(module.__file__)
        for test in tests:
            if not test.examples:
                continue
            if not test.filename:
                test.filename = module_file

            pkg_name = get_package_name(os.path.dirname(test.filename))

            # Each doctest should execute in an environment equivalent to
            # starting Python and executing "import numpy as np", and,
            # for SciPy packages, an additional import of the local
            # package (so that scipy.linalg.basic.py's doctests have an
            # implicit "from scipy import linalg" as well.
            #
            # Note: __file__ allows the doctest in NoseTester to run
            # without producing an error
            test.globs = {'__builtins__':__builtins__,
                          '__file__':'__main__',
                          '__name__':'__main__',
                          'np':numpy}

            # add appropriate scipy import for SciPy tests
            if 'scipy' in pkg_name:
                p = pkg_name.split('.')
                p1 = '.'.join(p[:-1])
                p2 = p[-1]
                test.globs[p2] = __import__(pkg_name, test.globs, {}, [p2])

            # always use whitespace and ellipsis options
            optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS

            yield NumpyDocTestCase(test,
                                   optionflags=optionflags,
                                   checker=NumpyOutputChecker())
开发者ID:agramfort,项目名称:nipype,代码行数:48,代码来源:noseclasses.py


示例11: test_index_when_syntax_error_below_test_frame

def test_index_when_syntax_error_below_test_frame():
    """Make sure we manage to find the test frame if there's a SyntaxError below it.

    Here we present to ``index_of_test_frame()`` a traceback that represents
    this test raising a SyntaxError indirectly, in a function called by same
    test.

    """
    extracted_tb = [('/nose/case.py', 183, 'runTest', 'self.test(*self.arg)'),
                    # Legit path so the frame finder can compare to the address of DummyCase:
                    (src(realpath(__file__)), 34, 'test_index_when_syntax_error_below_test_frame', 'deeper()'),
                    ('/noseprogressive/tests/test_utils.py', 33, 'deeper', 'import noseprogressive.tests.syntaxerror')]
    eq_(index_of_test_frame(extracted_tb,
                            SyntaxError,
                            SyntaxError('invalid syntax',
                                        ('/tests/syntaxerror.py', 1, 1, ':bad\n')),
                            dummy_test),
        1)
开发者ID:JingzheTian,项目名称:popcorn_maker,代码行数:18,代码来源:test_utils.py


示例12: loadTestsFromModule

 def loadTestsFromModule(self, module):
     if not self.matches(module.__name__):
         log.debug("Doctest doesn't want module %s", module)
         return
     try:
         tests = self.finder.find(module)
     except AttributeError:
         # nose allows module.__test__ = False; doctest does not and throws
         # AttributeError
         return
     if not tests:
         return
     tests.sort()
     module_file = src(module.__file__)
     for test in tests:
         if not test.examples:
             continue
         if not test.filename:
             test.filename = module_file
         yield DocTestCase(test)
开发者ID:adrianpike,项目名称:wwscc,代码行数:20,代码来源:doctests.py


示例13: __init__

 def __init__(self, name, workingDir=None):
     if workingDir is None:
         workingDir = os.getcwd()
     self.name = name
     self.workingDir = workingDir
     self.filename, self.module, self.call = split_test_name(name)
     log.debug('Test name %s resolved to file %s, module %s, call %s',
               name, self.filename, self.module, self.call)
     if self.filename is None:
         if self.module is not None:
             self.filename = getfilename(self.module, self.workingDir)
     if self.filename:
         self.filename = src(self.filename)
         if not op_isabs(self.filename):
             self.filename = op_abspath(op_join(workingDir,
                                                self.filename))
         if self.module is None:
             self.module = getpackage(self.filename)
     log.debug(
         'Final resolution of test name %s: file %s module %s call %s',
         name, self.filename, self.module, self.call)
开发者ID:ethanhelfman,项目名称:InstaGet,代码行数:21,代码来源:selector.py


示例14: format_traceback

def format_traceback(extracted_tb,
                     exc_type,
                     exc_value,
                     cwd='',
                     term=None,
                     function_color=12,
                     dim_color=8,
                     editor='vi'):
    """Return an iterable of formatted Unicode traceback frames.

    Also include a pseudo-frame at the end representing the exception itself.

    Format things more compactly than the stock formatter, and make every
    frame an editor shortcut.

    """
    def format_shortcut(editor,
                        file,
                        line,
                        function=None):
        """Return a pretty-printed editor shortcut."""
        return template % dict(editor=editor,
                               line=line,
                               file=file,
                               function=(u'  # ' + function) if function else u'',
                               funcemph=term.color(function_color),
                               # Underline is also nice and doesn't make us
                               # worry about appearance on different background
                               # colors.
                               plain=term.normal,
                               fade=term.color(dim_color) + term.bold)

    extracted_tb = _unicode_decode_extracted_tb(extracted_tb)
    if not term:
        term = Terminal()

    if extracted_tb:
        # Shorten file paths:
        for i, (file, line, function, text) in enumerate(extracted_tb):
            extracted_tb[i] = human_path(src(file), cwd), line, function, text

        line_width = len(unicode(max(the_line for _, the_line, _, _ in extracted_tb)))
        template = (u'  %(fade)s%(editor)s +%(line)-' + unicode(line_width) + u's '
                     '%(file)s%(plain)s'
                     '%(funcemph)s%(function)s%(plain)s\n')

        # Stack frames:
        for i, (file, line, function, text) in enumerate(extracted_tb):
            text = (text and text.strip()) or u''

            yield (format_shortcut(editor, file, line, function) +
                   (u'    %s\n' % text))

    # Exception:
    if exc_type is SyntaxError:
        # Format a SyntaxError to look like our other traceback lines.
        # SyntaxErrors have a format different from other errors and include a
        # file path which looks out of place in our newly highlit, editor-
        # shortcutted world.
        exc_lines = [format_shortcut(editor, exc_value.filename, exc_value.lineno)]
        formatted_exception = format_exception_only(SyntaxError, exc_value)[1:]
    else:
        exc_lines = []
        formatted_exception = format_exception_only(exc_type, exc_value)
    exc_lines.extend([_decode(f) for f in formatted_exception])
    yield u''.join(exc_lines)
开发者ID:singingwolfboy,项目名称:nose-progressive,代码行数:66,代码来源:tracebacks.py


示例15: format_traceback

def format_traceback(extracted_tb,
                     exc_type,
                     exc_value,
                     cwd='',
                     term=None,
                     function_color=12,
                     dim_color=8,
                     editor='vi',
                     template=DEFAULT_EDITOR_SHORTCUT_TEMPLATE):
    """Return an iterable of formatted Unicode traceback frames.

    Also include a pseudo-frame at the end representing the exception itself.

    Format things more compactly than the stock formatter, and make every
    frame an editor shortcut.

    """
    def format_shortcut(editor,
                        path,
                        line_number,
                        function=None):
        """Return a pretty-printed editor shortcut."""
        return template.format(editor=editor,
                               line_number=line_number or 0,
                               path=path,
                               function=function or u'',
                               hash_if_function=u'  # ' if function else u'',
                               function_format=term.color(function_color),
                               # Underline is also nice and doesn't make us
                               # worry about appearance on different background
                               # colors.
                               normal=term.normal,
                               dim_format=term.color(dim_color) + term.bold,
                               line_number_max_width=line_number_max_width,
                               term=term)

    template += '\n'  # Newlines are awkward to express on the command line.
    extracted_tb = _unicode_decode_extracted_tb(extracted_tb)
    if not term:
        term = Terminal()

    if extracted_tb:
        # Shorten file paths:
        for i, (file, line_number, function, text) in enumerate(extracted_tb):
            extracted_tb[i] = human_path(src(file), cwd), line_number, function, text

        line_number_max_width = len(unicode(max(the_line for _, the_line, _, _ in extracted_tb)))

        # Stack frames:
        for i, (path, line_number, function, text) in enumerate(extracted_tb):
            text = (text and text.strip()) or u''

            yield (format_shortcut(editor, path, line_number, function) +
                   (u'    %s\n' % text))

    # Exception:
    if exc_type is SyntaxError:
        # Format a SyntaxError to look like our other traceback lines.
        # SyntaxErrors have a format different from other errors and include a
        # file path which looks out of place in our newly highlit, editor-
        # shortcutted world.
        if hasattr(exc_value, 'filename') and hasattr(exc_value, 'lineno'):
            exc_lines = [format_shortcut(editor, exc_value.filename, exc_value.lineno)]
            formatted_exception = format_exception_only(SyntaxError, exc_value)[1:]
        else:
            # The logcapture plugin may format exceptions as strings,
            # stripping them of the full filename and lineno
            exc_lines = []
            formatted_exception = format_exception_only(SyntaxError, exc_value)
            formatted_exception.append(u'(Try --nologcapture for a more detailed traceback)\n')
    else:
        exc_lines = []
        formatted_exception = format_exception_only(exc_type, exc_value)
    exc_lines.extend([_decode(f) for f in formatted_exception])
    yield u''.join(exc_lines)
开发者ID:erikrose,项目名称:nose-progressive,代码行数:75,代码来源:tracebacks.py


示例16: loadTestsFromDir

    def loadTestsFromDir(self, path):
        """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("load from dir %s", path)
        plugins = self.config.plugins
        plugins.beforeDirectory(path)
        if self.config.addPaths:
            paths_added = add_path(path, self.config)

        entries = os.listdir(path)
        sort_list(entries, regex_last_key(self.config.testMatch))
        for entry in entries:
            # this hard-coded initial-dot test will be removed:
            # http://code.google.com/p/python-nose/issues/detail?id=82
            if entry.startswith('.'):
                continue
            if src(entry) == '__init__.py':
                continue
            entry_path = op_abspath(op_join(path, entry))
            is_file = op_isfile(entry_path)
            wanted = False
            if is_file:
                is_dir = False
                wanted = self.selector.wantFile(entry_path)
            else:
                is_dir = op_isdir(entry_path)
                if is_dir:
                    # this hard-coded initial-underscore test will be removed:
                    # http://code.google.com/p/python-nose/issues/detail?id=82
                    if entry.startswith('_'):
                        continue
                    wanted = self.selector.wantDirectory(entry_path)
            is_package = ispackage(entry_path)

            # Python 3.3 now implements PEP 420: Implicit Namespace Packages.
            # As a result, it's now possible that parent paths that have a
            # segment with the same basename as our package ends up
            # in module.__path__.  So we have to keep track of what we've
            # visited, and not-revisit them again.
            if wanted and not self._haveVisited(entry_path):
                self._addVisitedPath(entry_path)
                if is_file:
                    plugins.beforeContext()
                    if entry.endswith('.py'):
                        yield self.loadTestsFromName(
                            entry_path, discovered=True)
                    else:
                        yield self.loadTestsFromFile(entry_path)
                    plugins.afterContext()
                elif is_package:
                    # Load the entry as a package: given the full path,
                    # loadTestsFromName() will figure it out
                    yield self.loadTestsFromName(
                        entry_path, discovered=True)
                else:
                    # Another test dir in this one: recurse lazily
                    yield self.suiteClass(
                        lambda: self.loadTestsFromDir(entry_path))
        tests = []
        for test in plugins.loadTestsFromDir(path):
            tests.append(test)
        # TODO: is this try/except needed?
        try:
            if tests:
                yield self.suiteClass(tests)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            yield self.suiteClass([Failure(*sys.exc_info())])

        # pop paths
        if self.config.addPaths:
            for p in paths_added:
              remove_path(p)
        plugins.afterDirectory(path)
开发者ID:Averroes,项目名称:nose,代码行数:78,代码来源:loader.py



注:本文中的nose.util.src函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.test_address函数代码示例发布时间:2022-05-27
下一篇:
Python util.safe_str函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap