当前位置: 首页>>代码示例>>Python>>正文


Python reflect.fullyQualifiedName函数代码示例

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


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

示例1: test_classicalRouteWithBranch

    def test_classicalRouteWithBranch(self):
        """
        Multiple instances of a class with a L{Klein} attribute and
        L{Klein.route}'d methods can be created and their L{Klein}s used
        independently.
        """
        class Foo(object):
            app = Klein()

            def __init__(self):
                self.bar_calls = []

            @app.route("/bar/", branch=True)
            def bar(self, request):
                self.bar_calls.append((self, request))
                return "bar"

        foo_1 = Foo()
        foo_1_app = foo_1.app
        foo_2 = Foo()
        foo_2_app = foo_2.app

        dr1 = DummyRequest(1)
        dr2 = DummyRequest(2)

        foo_1_app.execute_endpoint(
            fullyQualifiedName(Foo.bar).replace("Foo.", ""), dr1)
        foo_2_app.execute_endpoint(
            fullyQualifiedName(Foo.bar).replace("Foo.", ""), dr2)
        self.assertEqual(foo_1.bar_calls, [(foo_1, dr1)])
        self.assertEqual(foo_2.bar_calls, [(foo_2, dr2)])
开发者ID:WnP,项目名称:klein,代码行数:31,代码来源:test_app.py

示例2: test_classicalRoute

    def test_classicalRoute(self):
        """
        L{Klein.route} may be used a method decorator when a L{Klein} instance
        is defined as a class variable.
        """
        bar_calls = []
        class Foo(object):
            app = Klein()

            @app.route("/bar")
            def bar(self, request):
                bar_calls.append((self, request))
                return "bar"

        foo = Foo()
        c = foo.app.url_map.bind("bar")
        self.assertEqual(
            c.match("/bar"),
            (fullyQualifiedName(Foo.bar).replace("Foo.", ""), {}))
        self.assertEquals(
            foo.app.execute_endpoint(
                fullyQualifiedName(Foo.bar).replace("Foo.", ""),
                DummyRequest(1)),
            "bar")

        self.assertEqual(bar_calls, [(foo, DummyRequest(1))])
开发者ID:WnP,项目名称:klein,代码行数:26,代码来源:test_app.py

示例3: test_require_login

    def test_require_login(self):
        self.runtime_environment.configure()
        self.create_pb_server(checker=dict(
            name = 'twisted.cred.checkers.InMemoryUsernamePasswordDatabaseDontUse',
            arguments = dict(test_username='test_password')
        ))

        self.application.startService()
        self.addCleanup(self.application.stopService)

        self.server.pipeline_dependency = self.pipeline_dependency

        # connect to the server
        client = pb.PBClientFactory()
        reactor.connectTCP('localhost', self.port, client)

        root = yield client.getRootObject()
        self.addCleanup(root.broker.transport.loseConnection)

        # calling a remote function should result in no such method being found:
        try:
            yield root.callRemote('add', 42, b=93)
        except spread_provider.RemoteError as e:
            self.assertEquals(e.remoteType, reflect.fullyQualifiedName(flavors.NoSuchMethod))
        else:
            self.fail('NoSuchMethod not raised.')

        # attempt to login with different bad credentials
        bad_credentials = list()
        bad_credentials.append(credentials.UsernamePassword('wrong', 'wrong'))
        bad_credentials.append(credentials.UsernamePassword('test_username', 'wrong'))
        bad_credentials.append(credentials.UsernamePassword('wrong', 'test_password'))

        for bad_credential in bad_credentials:
            try:
                yield client.login(bad_credential)
            except spread_provider.RemoteError as e:
                self.assertEquals(e.remoteType, reflect.fullyQualifiedName(error.UnauthorizedLogin))
            else:
                self.fail('NoSuchMethod not raised.')

        perspective = yield client.login(credentials.UsernamePassword('test_username', 'test_password'))

        adding = perspective.callRemote('add', 42, b=93)

        # assert that the baton is on the expected form
        baton = yield self.pipeline.batons.get()
        self.assertEquals(baton['message'], 'add')
        self.assertEquals(baton['args'], (42,))
        self.assertEquals(baton['kwargs'], dict(b=93))

        # callback the deferred in the baton
        baton['deferred'].callback(42+93)

        # the above callbacking should result in the client getting its response
        result = yield adding
        self.assertEquals(result, 42+93)
开发者ID:alexbrasetvik,项目名称:Piped,代码行数:57,代码来源:test_spread_provider.py

示例4: test_deprecatedPreservesName

 def test_deprecatedPreservesName(self):
     """
     The decorated function has the same name as the original.
     """
     version = Version('Twisted', 8, 0, 0)
     dummy = deprecated(version)(dummyCallable)
     self.assertEqual(dummyCallable.__name__, dummy.__name__)
     self.assertEqual(fullyQualifiedName(dummyCallable),
                      fullyQualifiedName(dummy))
开发者ID:Almad,项目名称:twisted,代码行数:9,代码来源:test_deprecate.py

示例5: test_trapping_multiple_types

    def test_trapping_multiple_types(self):
        error_types = [reflect.fullyQualifiedName(FakeError), reflect.fullyQualifiedName(exceptions.ConfigurationError)]
        processor = self._create_processor(error_types=error_types, output_path='trapped')

        for error_type in (FakeError, exceptions.ConfigurationError):
            try:
                raise error_type('test')
            except error_type as fe:
                baton = processor.process(dict())
                self.assertEquals(baton['trapped'], error_type)
开发者ID:alexbrasetvik,项目名称:Piped,代码行数:10,代码来源:test_util_processors.py

示例6: test_route

    def test_route(self):
        """
        L{Klein.route} adds functions as routable endpoints.
        """
        app = Klein()

        @app.route("/foo")
        def foo(request):
            return "foo"

        c = app.url_map.bind("foo")
        self.assertEqual(c.match("/foo"), (fullyQualifiedName(foo), {}))
        self.assertEqual(len(app.endpoints), 1)

        self.assertEqual(app.execute_endpoint(fullyQualifiedName(foo), DummyRequest(1)), "foo")
开发者ID:WnP,项目名称:klein,代码行数:15,代码来源:test_app.py

示例7: test_newStyleClassesOnly

    def test_newStyleClassesOnly(self):
        """
        Test that C{self.module} has no old-style classes in it.
        """
        try:
            module = namedAny(self.module)
        except ImportError as e:
            raise unittest.SkipTest("Not importable: {}".format(e))

        oldStyleClasses = []

        for name, val in inspect.getmembers(module):
            if hasattr(val, "__module__") \
               and val.__module__ == self.module:
                if isinstance(val, types.ClassType):
                    oldStyleClasses.append(fullyQualifiedName(val))

        if oldStyleClasses:

            self.todo = "Not all classes are made new-style yet. See #8243."

            for x in forbiddenModules:
                if self.module.startswith(x):
                    delattr(self, "todo")

            raise unittest.FailTest(
                "Old-style classes in {module}: {val}".format(
                    module=self.module,
                    val=", ".join(oldStyleClasses)))
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:29,代码来源:test_nooldstyle.py

示例8: _relaying_test

    def _relaying_test(self, eliot_logger_publish, eliot_logger_consume):
        """
        Publish an event using ``logger.Logger` with an Eliot relay handler hooked
        up to the root logger and assert that the event ends up b eing seen by
        ``eliot_logger_consumer`.
        """
        cleanup = stdlib_logging_to_eliot_configuration(
            logging.getLogger(),
            eliot_logger_publish,
        )
        self.addCleanup(cleanup)

        logger = logging.getLogger(fullyQualifiedName(self.__class__))
        logger.setLevel(logging.INFO)
        logger.info("Hello, world.")

        [event] = eliot_logger_consume.messages
        self.assertThat(
            event,
            ContainsDict(dict(
                # A couple things from the stdlib side of the fence.
                module=Equals(__name__.split(".")[-1]),
                levelno=Equals(logging.INFO),
                # Also some Eliot stuff.
                task_uuid=IsInstance(unicode),
                task_level=IsInstance(list),
            )),
        )
开发者ID:LeastAuthority,项目名称:leastauthority.com,代码行数:28,代码来源:test_eliot.py

示例9: _determine_calling_module

    def _determine_calling_module(self, by_module):
        if not by_module:
            # if the caller did not specify a module that made the logging call, attempt to find
            # the module by inspecting the stack: record 0 is this, 1 is _should_log, 2 is the
            # logging function, and 3 will be the caller.
            record = inspect.stack()[3]
            # the first element of the record is the frame, which contains the locals and globals
            frame = record[0]
            f_globals = frame.f_globals

            # check the stack frame's globals for the __name__ attribute, which is the module name
            if '__name__' in f_globals:
                by_module = f_globals['__name__']
            else:
                # but it might not be a regular python module (such as a service.tac),
                # in which case we have to fall back to using the __file__ attribute.
                by_module = reflect.filenameToModuleName(f_globals['__file__'])

        elif not isinstance(by_module, basestring):
            # if the caller gave us an actual module, and not just its name, determine its
            # name and use it.
            by_module = reflect.fullyQualifiedName(by_module)
        
        modules = by_module.split('.')
        return modules
开发者ID:alexbrasetvik,项目名称:Piped,代码行数:25,代码来源:log.py

示例10: _checkFullyQualifiedName

 def _checkFullyQualifiedName(self, obj, expected):
     """
     Helper to check that fully qualified name of C{obj} results to
     C{expected}.
     """
     self.assertEquals(
         reflect.fullyQualifiedName(obj), expected)
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:7,代码来源:test_reflect.py

示例11: __exit__

    def __exit__(self, exceptionType, exceptionValue, traceback):
        """
        Check exit exception against expected exception.
        """
        # No exception raised.
        if exceptionType is None:
            self._testCase.fail(
                "{0} not raised ({1} returned)".format(
                    self._expectedName, self._returnValue)
                )

        if not isinstance(exceptionValue, exceptionType):
            # Support some Python 2.6 ridiculousness.  Exceptions raised using
            # the C API appear here as the arguments you might pass to the
            # exception class to create an exception instance.  So... do that
            # to turn them into the instances.
            if isinstance(exceptionValue, tuple):
                exceptionValue = exceptionType(*exceptionValue)
            else:
                exceptionValue = exceptionType(exceptionValue)

        # Store exception so that it can be access from context.
        self.exception = exceptionValue

        # Wrong exception raised.
        if not issubclass(exceptionType, self._expected):
            reason = failure.Failure(exceptionValue, exceptionType, traceback)
            self._testCase.fail(
                "{0} raised instead of {1}:\n {2}".format(
                    fullyQualifiedName(exceptionType),
                    self._expectedName, reason.getTraceback()),
                )

        # All good.
        return True
开发者ID:Architektor,项目名称:PySnip,代码行数:35,代码来源:_synctest.py

示例12: returnQueueException

def returnQueueException(mq, queue):
    excType, excValue, _traceback = sys.exc_info()
    mq.send(queue, json.dumps({'success': False,
                               'data': {'stacktrace': errors.getStacktrace(),
                                        'name': reflect.fullyQualifiedName(excType),
                                        'msg': str(excValue)}}))
    return None
开发者ID:carze,项目名称:vappio,代码行数:7,代码来源:queue.py

示例13: _retry_exception

def _retry_exception(f, steps=(0.1,) * 10, sleep=sleep):
    """
    Retry a function if it raises an exception.

    :return: Whatever the function returns.
    """
    steps = iter(steps)

    while True:
        try:
            Message.new(
                message_type=(
                    u"flocker:provision:libcloud:retry_exception:trying"
                ),
                function=fullyQualifiedName(f),
            ).write()
            return f()
        except:
            # Try to get the next sleep time from the steps iterator.  Do it
            # without raising an exception (StopIteration) to preserve the
            # current exception context.
            for step in steps:
                write_traceback()
                sleep(step)
                break
            else:
                # Didn't hit the break, so didn't iterate at all, so we're out
                # of retry steps.  Fail now.
                raise
开发者ID:ClusterHQ,项目名称:flocker,代码行数:29,代码来源:_libcloud.py

示例14: clientEndpoint

 def clientEndpoint(self, reactor, serverAddress):
     """
     Return an object providing L{IStreamClientEndpoint} for use in creating
     a client to use to establish the connection type to be tested.
     """
     raise NotImplementedError("%s.clientEndpoint() not implemented" % (
             fullyQualifiedName(self.__class__),))
开发者ID:svpcom,项目名称:twisted-cdeferred,代码行数:7,代码来源:connectionmixins.py

示例15: deco

        def deco(f):
            kwargs.setdefault('endpoint', fullyQualifiedName(f))
            if kwargs.pop('branch', False):
                branchKwargs = kwargs.copy()
                branchKwargs['endpoint'] = branchKwargs['endpoint'] + '_branch'

                @wraps(f)
                def branch_f(instance, request, *a, **kw):
                    IKleinRequest(request).branch_segments = kw.pop('__rest__', '').split('/')
                    return _call(instance, f, request, *a, **kw)

                branch_f.segment_count = segment_count

                self._endpoints[branchKwargs['endpoint']] = branch_f
                self._url_map.add(Rule(url.rstrip('/') + '/' + '<path:__rest__>', *args, **branchKwargs))

            @wraps(f)
            def _f(instance, request, *a, **kw):
                return _call(instance, f, request, *a, **kw)

            _f.segment_count = segment_count

            self._endpoints[kwargs['endpoint']] = _f
            self._url_map.add(Rule(url, *args, **kwargs))
            return f
开发者ID:WnP,项目名称:klein,代码行数:25,代码来源:app.py


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