Ejemplo n.º 1
0
    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)])
Ejemplo n.º 2
0
    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))])
Ejemplo n.º 3
0
    def test_require_login(self):
        self.runtime_environment.configure()
        self.create_pb_server(checker=dict(
            name = 'twisted.cred.checkers.InMemoryUsernamePasswordDatabaseDontUse',
            arguments = dict(test_username='******')
        ))

        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)
Ejemplo n.º 4
0
 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))
Ejemplo n.º 5
0
 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))
Ejemplo n.º 6
0
    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)
Ejemplo n.º 7
0
 def check(value):
     return (
         isinstance(value, cls),
         u"{value!r} is instance of {actual!s}, required {required!s}".
         format(
             value=value,
             actual=fullyQualifiedName(type(value)),
             required=fullyQualifiedName(cls),
         ),
     )
Ejemplo n.º 8
0
    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")
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
Archivo: app.py Proyecto: WnP/klein
        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
Ejemplo n.º 12
0
def generatePage(cgiPage):
    """
    Takes an instance of CGIPage and generates a page from it,
    sending the proper headers and all that
    """
    cgitb.enable()

    ##
    # A bit evil, I know, but we want all output to go to a logging file
    fout = open('/tmp/webservices.log', 'a')
    logging.OUTSTREAM = fout
    logging.ERRSTREAM = fout
    
    try:
        ##
        # Execute the body first, it may want to add to headers or modify them in soem way as
        # well as contentType
        body = cgiPage.body()
        print cgiPage.contentType
        if cgiPage.headers:
            print '\n'.join([h + ': ' + v for h, v in cgiPage.headers.iteritems()])
        print
        print json.dumps(dict(success=True, data=body))
    except Exception, err:
        print cgiPage.contentType
        print
        stream = StringIO()
        traceback.print_exc(file=stream)
        print json.dumps(dict(success=False, data=dict(stacktrace=stream.getvalue(),
                                                       name=reflect.fullyQualifiedName(reflect.getClass(err)),
                                                       msg=str(err))))
Ejemplo n.º 13
0
 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__),))
Ejemplo n.º 14
0
    def _format_exception(self, exctype, message, target_obj, found_names, obj, func):
        formatted = traceback.format_exc()
        argformat = (
            "\nCALL ARGS: lazy_call%s\n"
            "args: %s\n"
            "keywords: %s\n\n") % (format_args(self.args, self.keywords), pprint.pformat(self.args), pprint.pformat(self.keywords))

        if self.is_decorator:
            if self.simple_decorator:
                argformat = ""
            else:
                argformat += "\n"

            try:
                fqname = fullyQualifiedName(func)
            except AttributeError:
                fqname = None

            argformat += "decorated func: %s: %r" % (fqname, func)

        return exctype(("Original exception: \n%s"
            "%s\n\n"
            "%r is %r.%s\n"
            "is_decorator: %r\n"
            "%s") % (formatted, message, obj, target_obj, '.'.join(found_names), self.is_decorator, argformat))
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
    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
Ejemplo n.º 17
0
 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)
Ejemplo n.º 18
0
def generatePage(cgiPage):
    """
    Takes an instance of CGIPage and generates a page from it,
    sending the proper headers and all that
    """
    cgitb.enable()

    ##
    # A bit evil, I know, but we want all output to go to a logging file
    fout = open('/tmp/webservices.log', 'a')
    logging.OUTSTREAM = fout
    logging.ERRSTREAM = fout

    try:
        ##
        # Execute the body first, it may want to add to headers or modify them in soem way as
        # well as contentType
        body = cgiPage.body()
        print cgiPage.contentType
        if cgiPage.headers:
            print '\n'.join(
                [h + ': ' + v for h, v in cgiPage.headers.iteritems()])
        print
        print json.dumps(dict(success=True, data=body))
    except Exception, err:
        print cgiPage.contentType
        print
        stream = StringIO()
        traceback.print_exc(file=stream)
        print json.dumps(
            dict(success=False,
                 data=dict(stacktrace=stream.getvalue(),
                           name=reflect.fullyQualifiedName(
                               reflect.getClass(err)),
                           msg=str(err))))
Ejemplo n.º 19
0
    def _format_exception(self, exctype, message, target_obj, found_names, obj,
                          func):
        formatted = traceback.format_exc()
        argformat = ("\nCALL ARGS: lazy_call%s\n"
                     "args: %s\n"
                     "keywords: %s\n\n") % (format_args(
                         self.args, self.keywords), pprint.pformat(
                             self.args), pprint.pformat(self.keywords))

        if self.is_decorator:
            if self.simple_decorator:
                argformat = ""
            else:
                argformat += "\n"

            try:
                fqname = fullyQualifiedName(func)
            except AttributeError:
                fqname = None

            argformat += "decorated func: %s: %r" % (fqname, func)

        return exctype(
            ("Original exception: \n%s"
             "%s\n\n"
             "%r is %r.%s\n"
             "is_decorator: %r\n"
             "%s") % (formatted, message, obj, target_obj,
                      '.'.join(found_names), self.is_decorator, argformat))
Ejemplo n.º 20
0
    def g(self, request):
        # Bind the method to the instance so it has a better
        # fullyQualifiedName later on.  This is not necessary on Python 3.
        bound_render = render.__get__(self, type(self))

        action = start_action(
            action_type=u"allmydata:web:common-render",
            uri=request.uri,
            method=request.method,
            handler=fullyQualifiedName(bound_render),
        )
        if getattr(request, "dont_apply_extra_processing", False):
            with action:
                return bound_render(request)

        with action.context():
            result = DeferredContext(maybeDeferred(bound_render, request))
            # Apply `_finish` all of our result handling logic to whatever it
            # returned.
            result.addBoth(_finish, bound_render, request)
            d = result.addActionFinish()

        # If the connection is lost then there's no point running our _finish
        # logic because it has nowhere to send anything.  There may also be no
        # point in finishing whatever operation was being performed because
        # the client cannot be informed of its result.  Also, Twisted Web
        # raises exceptions from some Request methods if they're used after
        # the connection is lost.
        request.notifyFinish().addErrback(lambda ignored: d.cancel(), )
        return NOT_DONE_YET
Ejemplo n.º 21
0
    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)))
Ejemplo n.º 22
0
 def _checkFullyQualifiedName(self, obj, expected):
     """
     Helper to check that fully qualified name of C{obj} results to
     C{expected}.
     """
     self.assertEqual(
         reflect.fullyQualifiedName(obj), expected)
Ejemplo n.º 23
0
    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),
            )),
        )
Ejemplo n.º 24
0
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
Ejemplo n.º 25
0
    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
Ejemplo n.º 26
0
 def check(cls, instance):
     for baseClass in inspect.getmro(instance.__class__):
         fqn = reflect.fullyQualifiedName(baseClass)
         if fqn == DEFAULT_WWU_FQN:
             return True
     raise TypeError(
         "You must provide a WireWorkerUniverse subclass instance")
Ejemplo n.º 27
0
    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)))
Ejemplo n.º 28
0
    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),
                )),
        )
Ejemplo n.º 29
0
    def test_simple_trapping(self):
        processor = self._create_processor(error_types=reflect.fullyQualifiedName(FakeError), output_path='trapped')

        try:
            raise FakeError('test')
        except FakeError as fe:
            baton = processor.process(dict())
            self.assertEquals(baton['trapped'], FakeError)
Ejemplo n.º 30
0
 def __repr__(self):
     args = (fullyQualifiedName(self.protocol.__class__),)
     if self.connected:
         args = args + ("",)
     else:
         args = args + ("not ",)
     args = args + (self._mode.name, self.interface)
     return "<%s %slistening on %s/%s>" % args
Ejemplo n.º 31
0
    def test_redirecting_stderr_to_stdout(self):
        test_protocol_name = reflect.fullyQualifiedName(process_provider.RedirectToStdout)
        protocol = self._make_protocol(stderr=dict(protocol=test_protocol_name))
        stdout = self._make_baton_collector(protocol.stdout_protocol)

        protocol.errReceived('some text\n')
        baton = yield stdout.get()
        self.assertEquals(baton, dict(line='some text'))
Ejemplo n.º 32
0
    def _register_plugin(self, plugin):
        name = getattr(plugin, 'name', None) or reflect.fullyQualifiedName(plugin)
        self._fail_if_plugin_name_is_already_registered(plugin, name)

        self._plugin_factory_by_name[name] = plugin
        provided_keywords = getattr(plugin, 'provides', [])
        for keyword in provided_keywords:
            self._providers_by_keyword.setdefault(keyword, []).append(name)
Ejemplo n.º 33
0
def _getChild_done(child, parent):
    Message.log(
        message_type=u"allmydata:web:common-getChild:result",
        result=fullyQualifiedName(type(child)),
    )
    if child is None:
        return resource.NoResource()
    return child
Ejemplo n.º 34
0
 def check(value):
     return (
         iface.providedBy(value),
         u"{value!r} does not provide {interface!s}".format(
             value=value,
             interface=fullyQualifiedName(iface),
         ),
     )
Ejemplo n.º 35
0
 def addException(self, msg, exc, stacktrace):
     t = time.time()
     return self.update(timestamp=t,
                        messages=self.messages + [dict(mtype=MSG_ERROR,
                                                       text=msg,
                                                       name=reflect.fullyQualifiedName(reflect.getClass(exc)),
                                                       stacktrace=stacktrace,
                                                       timestamp=t)])
Ejemplo n.º 36
0
 def __repr__(self):
     args = (fullyQualifiedName(self.protocol.__class__), )
     if self.connected:
         args = args + ("", )
     else:
         args = args + ("not ", )
     args = args + (self._mode.name, self.interface)
     return "<%s %slistening on %s/%s>" % args
Ejemplo n.º 37
0
    def test_unlisteningString(self):
        """
        The string representation of a L{TuntapPort} instance includes the
        tunnel type and interface and the protocol associated with the port.
        """
        if _PY3:
            self.assertRegex(str(self.port),
                             fullyQualifiedName(self.protocol.__class__))

            expected = " not listening on %s/%s>" % (self._tunnelTypeOnly(
                self.helper.TUNNEL_TYPE).name, self.name)
            self.assertTrue(str(self.port).find(expected) != -1)
        else:
            expected = "<%s not listening on %s/%s>" % (
                fullyQualifiedName(self.protocol.__class__),
                self._tunnelTypeOnly(self.helper.TUNNEL_TYPE).name, self.name)
            self.assertEqual(expected, str(self.port))
Ejemplo n.º 38
0
    def test_named_any_simple(self):
        """ Test that the processor can successfully instantiate an instance of its own class. """
        processor_name = reflect.fullyQualifiedName(util_processors.CallNamedAny)
        processor = util_processors.CallNamedAny(name=processor_name, kwargs=dict(name='test_name'))

        result = processor.process(dict())

        self.assertIsInstance(result['result'], util_processors.CallNamedAny)
        self.assertEquals(result['result'].name, 'test_name')
Ejemplo n.º 39
0
    def test_unlisteningString(self):
        """
        The string representation of a L{TuntapPort} instance includes the
        tunnel type and interface and the protocol associated with the port.
        """
        if _PY3:
            self.assertRegex(str(self.port),
                             fullyQualifiedName(self.protocol.__class__))

            expected = " not listening on %s/%s>" % (
                self._tunnelTypeOnly(self.helper.TUNNEL_TYPE).name,
                self.name)
            self.assertTrue(str(self.port).find(expected) != -1)
        else:
            expected = "<%s not listening on %s/%s>" % (
                fullyQualifiedName(self.protocol.__class__),
                self._tunnelTypeOnly(self.helper.TUNNEL_TYPE).name, self.name)
            self.assertEqual(expected, str(self.port))
Ejemplo n.º 40
0
    def test_named_any_replacing_baton(self):
        """ Test that the processor can replace the baton. """
        processor_name = reflect.fullyQualifiedName(util_processors.CallNamedAny)
        processor = util_processors.CallNamedAny(name=processor_name, kwargs=dict(name='test_name'), output_path='')

        result = processor.process(dict())

        self.assertIsInstance(result, util_processors.CallNamedAny)
        self.assertEquals(result.name, 'test_name')
 def test_processor_invokes_the_schema(self):
     schema = reflect.fullyQualifiedName(FakeSchema)
     # We just check if the schema is invoked, we don't really care
     # about the validation here, since we're not unittesting
     # FormEncode.
     processor = processors.FormEncodeValidator(schema, 'input', 'output')
     baton = dict(input='disregarded')
     processor.process(baton)
     self.assertEquals(baton, dict(input='disregarded', output=dict(faked='schema')))
Ejemplo n.º 42
0
    def test_named_any_with_custom_output_path(self):
        """ Test that the processor sets the expected key in the baton. """
        processor_name = reflect.fullyQualifiedName(util_processors.CallNamedAny)
        processor = util_processors.CallNamedAny(name=processor_name, kwargs=dict(name='test_name'), output_path='custom')

        result = processor.process(dict())

        self.assertIsInstance(result['custom'], util_processors.CallNamedAny)
        self.assertEquals(result['custom'].name, 'test_name')
Ejemplo n.º 43
0
 def test_repr(self):
     """
     The C{repr} of a L{failure.Failure} shows the type and string
     representation of the underlying exception.
     """
     f = getDivisionFailure()
     typeName = reflect.fullyQualifiedName(ZeroDivisionError)
     self.assertEqual(
         repr(f), '<twisted.python.failure.Failure '
         '%s: division by zero>' % (typeName, ))
Ejemplo n.º 44
0
 def test_it_can_locate_methods_directly_by_name(self):
     locator = locators.ObjectLocator()
     this_name = "test_it_can_locate_methods_directly_by_name"
     this_fully_qualified_name = ".".join(
         [fullyQualifiedName(self.__class__), this_name],
     )
     self.assertEqual(
         list(locator.locate_by_name(this_fully_qualified_name)),
         [AttributeLoader(cls=self.__class__, attr=this_name)],
     )
Ejemplo n.º 45
0
 def test_repr(self):
     """
     The C{repr} of a L{failure.Failure} shows the type and string
     representation of the underlying exception.
     """
     f = getDivisionFailure()
     typeName = reflect.fullyQualifiedName(ZeroDivisionError)
     self.assertEqual(
         repr(f),
         '<twisted.python.failure.Failure '
         '%s: division by zero>' % (typeName,))
Ejemplo n.º 46
0
def provider_invariant(interface):
    """
    :param zope.interface.Interface interface: An interface to require.

    :return: A pyrsistent invariant which requires that values provide the
        given interface.
    """
    return lambda o: (
        interface.providedBy(o),
        "does not provide {}".format(fullyQualifiedName(interface)),
    )
Ejemplo n.º 47
0
def _getDeprecationSuppression(f):
    """
    Returns a tuple of arguments needed to suppress deprecation warnings from
    a specified function.

    @param f: function to suppress dperecation warnings for
    @type f: L{callable}

    @return: tuple to add to C{suppress} attribute
    """
    return SUPPRESS(category=DeprecationWarning, message="%s was deprecated" % (fullyQualifiedName(f),))
Ejemplo n.º 48
0
 def buildReactor(self):
     """
     Create and return a reactor using C{self.reactorFactory}.
     """
     try:
         from twisted.internet.cfreactor import CFReactor
         from twisted.internet import reactor as globalReactor
     except ImportError:
         pass
     else:
         if (isinstance(globalReactor, CFReactor)
                 and self.reactorFactory is CFReactor):
             raise SkipTest(
                 "CFReactor uses APIs which manipulate global state, "
                 "so it's not safe to run its own reactor-builder tests "
                 "under itself")
     try:
         reactor = self.reactorFactory()
     except:
         # Unfortunately, not all errors which result in a reactor
         # being unusable are detectable without actually
         # instantiating the reactor.  So we catch some more here
         # and skip the test if necessary.  We also log it to aid
         # with debugging, but flush the logged error so the test
         # doesn't fail.
         log.err(None, "Failed to install reactor")
         self.flushLoggedErrors()
         raise SkipTest(Failure().getErrorMessage())
     else:
         if self.requiredInterfaces is not None:
             missing = filter(
                 lambda required: not required.providedBy(reactor),
                 self.requiredInterfaces)
             if missing:
                 self.unbuildReactor(reactor)
                 raise SkipTest(
                     "%s does not provide %s" %
                     (fullyQualifiedName(reactor.__class__), ",".join(
                         [fullyQualifiedName(x) for x in missing])))
     self.addCleanup(self.unbuildReactor, reactor)
     return reactor
Ejemplo n.º 49
0
 def _(request, *args, **kwargs):
     transaction_id = generate_transaction_id()
     request.setHeader('X-Response-Id', transaction_id)
     bound_log = log.bind(system=reflect.fullyQualifiedName(f),
                          transaction_id=transaction_id)
     bound_log.bind(method=request.method,
                    uri=request.uri,
                    clientproto=request.clientproto,
                    referer=request.getHeader("referer"),
                    useragent=request.getHeader("user-agent")).msg(
                        "Received request")
     return bind_log(f)(request, bound_log, *args, **kwargs)
Ejemplo n.º 50
0
 def _(self, request, *args, **kwargs):
     transaction_id = generate_transaction_id()
     request.setHeader('X-Response_Id', transaction_id)
     bound_log = log.bind(system=reflect.fullyQualifiedName(f),
                          transaction_id=transaction_id)
     bound_log.bind(method=request.method,
                    uri=request.uri,
                    clientproto=request.clientproto,
                    referer=request.getHeader('referer'),
                    useragent=request.getHeader('user-agent')).msg(
                        'Recieved request')
     return f(self, request, bound_log, *args, **kwargs)
Ejemplo n.º 51
0
def _getDeprecationSuppression(f):
    """
    Returns a tuple of arguments needed to suppress deprecation warnings from
    a specified function.

    @param f: function to suppress dperecation warnings for
    @type f: L{callable}

    @return: tuple to add to C{suppress} attribute
    """
    return SUPPRESS(category=DeprecationWarning,
                    message='%s was deprecated' % (fullyQualifiedName(f), ))
Ejemplo n.º 52
0
def getDeprecationWarningString(callableThing, version):
    """
    Return a string indicating that the callable was deprecated in the given
    version.

    @param callableThing: A callable to be deprecated.
    @param version: The L{twisted.python.versions.Version} that the callable
        was deprecated in.
    @return: A string describing the deprecation.
    """
    return "%s was deprecated in %s" % (fullyQualifiedName(callableThing),
                                        getVersionString(version))
Ejemplo n.º 53
0
def credentialToDict(cred):
    """
    The main difference here is the ctype is turned into a string representation
    of the class/module name
    """
    return dict(name=cred.name,
                desc=cred.desc,
                ctype=reflect.fullyQualifiedName(cred.ctype),
                cert=cred.cert,
                pkey=cred.pkey,
                active=cred.active,
                metadata=cred.metadata)
Ejemplo n.º 54
0
 def strToFQN(self, x):
     """
     Returns the fully qualified name of the supplied string if it can
     be imported and then reflected back into the FQN, or
     C{None} if not.
     """
     try:
         obj = reflect.namedObject(x)
         fqn = reflect.fullyQualifiedName(obj)
     except:
         return
     return fqn
Ejemplo n.º 55
0
 def objToFQN(self, x):
     """
     Returns the fully qualified name of the supplied object if it can
     be reflected into an FQN and back again, or C{None} if
     not.
     """
     try:
         fqn = reflect.fullyQualifiedName(x)
         reflect.namedObject(fqn)
     except:
         return
     return fqn
Ejemplo n.º 56
0
    def test_listeningString(self):
        """
        The string representation of a L{TuntapPort} instance includes the
        tunnel type and interface and the protocol associated with the port.
        """
        self.port.startListening()
        expected = "<%s listening on %s/%s>" % (
            fullyQualifiedName(self.protocol.__class__),
            self._tunnelTypeOnly(self.helper.TUNNEL_TYPE).name,
            self.system.getTunnel(self.port).name)

        self.assertEqual(expected, str(self.port))
Ejemplo n.º 57
0
 def __init__(self, backend, partition=''):
     """
     @param backend instance providing ion.data.store.IStore interface.
     @param partition Logical name spacing in an otherwise flat
     key/value space.
     @note Design decision on qualifying/naming a store name space (like
     a git repository tree)
     """
     cas.CAStore.__init__(self, backend, partition)
     self.partition = partition
     self.storemeta = cas.StoreContextWrapper(backend, partition + '.meta.')
     self.refs = cas.StoreContextWrapper(backend, partition + '.refs:')
     self.type = reflect.fullyQualifiedName(self.__class__)
Ejemplo n.º 58
0
def DEBUG_calling_name(): #pragma: no cover
    if not DEBUG:
        # TODO: print warning if this code is run
        return "<**CROW2_DEBUG not in environment**>"

    stackframe = inspect.stack()[2] # 0 = us, 1 = who called us, 2 = who called them
    frame = stackframe[0]
    code_name = frame.f_code.co_name

    module = inspect.getmodule(frame)
    modulename = fullyQualifiedName(module)

    return modulename + '.' + code_name
Ejemplo n.º 59
0
 def _(self, request, *args, **kwargs):
     transaction_id = generate_transaction_id()
     request.setHeader('X-Response-Id', transaction_id)
     self.log = self.log.bind(system=reflect.fullyQualifiedName(f),
                              transaction_id=transaction_id)
     self.log.msg("Received request",
                  method=request.method,
                  uri=request.uri,
                  clientproto=request.clientproto,
                  referer=request.getHeader("referer"),
                  useragent=request.getHeader("user-agent"),
                  request_status="received")
     return f(self, request, *args, **kwargs)