Пример #1
0
    def __init__(
        self,
        headers=None,
        args=None,
        avatar=None,
        uri="/",
        currentSegments=None,
        cookies=None,
        user="",
        password="",
        isSecure=False,
    ):
        """
        Create a FakeRequest instance.

        @param headers: dict of request headers
        @param args: dict of args
        @param avatar: avatar to pass to the FakeSession instance
        @param uri: request URI
        @param currentSegments: list of segments that have "already been located"
        @param cookies: dict of cookies
        @param user: username (like in http auth)
        @param password: password (like in http auth)
        @param isSecure: whether this request represents an HTTPS url
        """
        Componentized.__init__(self)
        self.uri = uri
        if not uri.startswith("/"):
            raise ValueError("uri must be relative with absolute path")
        self.path = uri
        self.prepath = []
        postpath = uri.split("?")[0]
        assert postpath.startswith("/")
        self.postpath = postpath[1:].split("/")
        if currentSegments is not None:
            for seg in currentSegments:
                assert seg == self.postpath[0]
                self.prepath.append(self.postpath.pop(0))
        else:
            self.prepath.append("")
        self.responseHeaders = Headers()
        self.args = args or {}
        self.sess = FakeSession(avatar)
        self.site = FakeSite()
        self.requestHeaders = Headers()
        if headers:
            for k, v in headers.iteritems():
                self.requestHeaders.setRawHeaders(k, [v])
        if cookies is not None:
            self.cookies = cookies
        else:
            self.cookies = {}
        self.user = user
        self.password = password
        self.secure = isSecure
        self.deferred = defer.Deferred()
Пример #2
0
 def test_configuredLogObserverBeatsComponent(self):
     """
     C{--logger} takes precedence over a ILogObserver component set on
     Application.
     """
     nonlogs = []
     application = Componentized()
     application.setComponent(ILogObserver, nonlogs.append)
     self._checkObserver(self._setupConfiguredLogger(application))
     self.assertEqual(nonlogs, [])
Пример #3
0
    def __init__(self,
                 headers=None,
                 args=None,
                 avatar=None,
                 uri='/',
                 currentSegments=None,
                 cookies=None,
                 user="",
                 password="",
                 isSecure=False):
        """Create a FakeRequest instance.

        headers:
            dict of headers
        args:
            dict of args
        avatar:
            avatar to pass to the FakeSession instance
        uri:
            request URI
        currentSegments:
            list of segments that have "already been located"
        cookies:
            dict of cookies
        user:
            username (like in http auth)
        password:
            password (like in http auth)
        isSecure:
            whether this request represents an HTTPS url
        """
        Componentized.__init__(self)
        self.uri = uri
        self.prepath = []
        postpath = uri.split('?')[0]
        assert postpath.startswith('/')
        self.postpath = postpath[1:].split('/')
        if currentSegments is not None:
            for seg in currentSegments:
                assert seg == self.postpath[0]
                self.prepath.append(self.postpath.pop(0))
        else:
            self.prepath.append('')
        self.headers = headers or {}
        self.args = args or {}
        self.sess = FakeSession(avatar)
        self.site = FakeSite()
        self.received_headers = {}
        if cookies is not None:
            self.cookies = cookies
        else:
            self.cookies = {}
        self.user = user
        self.password = password
        self.secure = isSecure
Пример #4
0
    def __init__(self,
                 headers=None,
                 args=None,
                 avatar=None,
                 uri='/',
                 currentSegments=None,
                 cookies=None,
                 user="",
                 password="",
                 isSecure=False):
        """
        Create a FakeRequest instance.

        @param headers: dict of request headers
        @param args: dict of args
        @param avatar: avatar to pass to the FakeSession instance
        @param uri: request URI
        @param currentSegments: list of segments that have "already been located"
        @param cookies: dict of cookies
        @param user: username (like in http auth)
        @param password: password (like in http auth)
        @param isSecure: whether this request represents an HTTPS url
        """
        Componentized.__init__(self)
        self.uri = uri
        if not uri.startswith('/'):
            raise ValueError('uri must be relative with absolute path')
        self.path = uri
        self.prepath = []
        postpath = uri.split('?')[0]
        assert postpath.startswith('/')
        self.postpath = postpath[1:].split('/')
        if currentSegments is not None:
            for seg in currentSegments:
                assert seg == self.postpath[0]
                self.prepath.append(self.postpath.pop(0))
        else:
            self.prepath.append('')
        self.headers = {}
        self.args = args or {}
        self.sess = FakeSession(avatar)
        self.site = FakeSite()
        self.received_headers = {}
        if headers:
            for k, v in headers.items():
                self.received_headers[k.lower()] = v
        if cookies is not None:
            self.cookies = cookies
        else:
            self.cookies = {}
        self.user = user
        self.password = password
        self.secure = isSecure
        self.deferred = defer.Deferred()
Пример #5
0
 def test_startUsesApplicationLogObserver(self):
     """
     When the L{ILogObserver} component is available on the application,
     that object will be used as the log observer instead of constructing a
     new one.
     """
     application = Componentized()
     logs = []
     application.setComponent(ILogObserver, logs.append)
     logger = app.AppLogger({})
     logger.start(application)
     self._checkObserver(logs)
Пример #6
0
 def test_startUsesApplicationLogObserver(self):
     """
     When the L{ILogObserver} component is available on the application,
     that object will be used as the log observer instead of constructing a
     new one.
     """
     application = Componentized()
     logs = []
     application.setComponent(ILogObserver, logs.append)
     logger = app.AppLogger({})
     logger.start(application)
     self._checkObserver(logs)
Пример #7
0
 def _getAvatar(self, avatarId):
     comp = Componentized()
     user = UrwidUser(comp, avatarId)
     comp.setComponent(IConchUser, user)
     sess = UrwidTerminalSession(comp)
     comp.setComponent(ISession, sess)
     mind = self.mind_factory(comp)
     comp.setComponent(IUrwidMind, mind)
     return user
Пример #8
0
 def test_startUsesConfiguredLogObserver(self):
     """
     When the C{logger} key is specified in the configuration dictionary
     (i.e., when C{--logger} is passed to twistd), the initial log observer
     will be the log observer returned from the callable which the value
     refers to in FQPN form.
     """
     application = Componentized()
     self._checkObserver(self._setupConfiguredLogger(application))
Пример #9
0
 def test_start(self):
     """
     L{app.AppLogger.start} calls L{log.addObserver}, and then writes some
     messages about twistd and the reactor.
     """
     logger = app.AppLogger({})
     observer = []
     logger._getLogObserver = lambda: observer.append
     logger.start(Componentized())
     self._checkObserver(observer)
Пример #10
0
 def _getAvatar(self, avatarId):
     comp = Componentized()
     user = UrwidUser(comp, avatarId)
     comp.setComponent(IConchUser, user)
     sess = UrwidTerminalSession(comp)
     comp.setComponent(ISession, sess)
     self.mind = self.mind_factories[avatarId](comp)
     #instead get correct mind from dictionary using mind = self.mind_factories[avatarId](comp)
     ##add user to mind connections
     self.mind.connections[user.uuid] = {"user": user, "log": []}
     comp.setComponent(IUrwidMind, self.mind)
     return user
Пример #11
0
 def test_configuredLogObserverBeatsLogfile(self):
     """
     C{--logger} takes precedence over a C{--logfile} command line
     argument.
     """
     application = Componentized()
     path = self.mktemp()
     self._checkObserver(self._setupConfiguredLogger(application,
                                                     {"logfile": "path"}))
     self.assertFalse(os.path.exists(path))
Пример #12
0
        def decorator(functionWithRequirements):
            # type: (Any) -> Callable
            injectionComponents = Componentized()
            lifecycle = RequestLifecycle()
            injectionComponents.setComponent(IRequestLifecycle, lifecycle)

            injectors = {}      # type: Dict[str, IDependencyInjector]

            for parameterName, required in requiredParameters.items():
                injectors[parameterName] = required.registerInjector(
                    injectionComponents, parameterName, lifecycle
                )

            for prereq in self._prerequisites:
                prereq(lifecycle)

            for v in injectors.values():
                v.finalize()

            @modified("dependency-injecting route", functionWithRequirements)
            @bindable
            @inlineCallbacks
            def router(instance, request, *args, **routeParams):
                # type: (Any, IRequest, *Any, **Any) -> Any
                injected = routeParams.copy()
                try:
                    yield lifecycle.runPrepareHooks(instance, request)
                    for (k, injector) in injectors.items():
                        injected[k] = yield injector.injectValue(
                            instance, request, routeParams
                        )
                except EarlyExit as ee:
                    result = ee.alternateReturnValue
                else:
                    result = yield _call(
                        instance, functionWithRequirements, *args,
                        **injected
                    )
                returnValue(result)

            functionWithRequirements.injectionComponents = injectionComponents
            routeDecorator(router)
            return functionWithRequirements
Пример #13
0
 def _getAvatar(self, avatarId):
     comp = Componentized()
     user = UrwidUser(comp, avatarId)
     comp.setComponent(IConchUser, user)
     sess = UrwidTerminalSession(comp)
     comp.setComponent(ISession, sess)
     mind = self.mind_factory(comp)
     comp.setComponent(IUrwidMind, mind)
     return user
Пример #14
0
 def test_configuredLogObserverBeatsSyslog(self):
     """
     C{--logger} takes precedence over a C{--syslog} command line
     argument.
     """
     logs = _setupSyslog(self)
     application = Componentized()
     self._checkObserver(self._setupConfiguredLogger(application,
                                                     {"syslog": True},
                                                     UnixAppLogger))
     self.assertEqual(logs, [])
Пример #15
0
    def __init__(self, setup):
        Componentized.__init__(self)
        self.config = setup.asDict()

        # anyone adapting an IGameServer from a str/int/None will get me
        registerGlobal(self, IGameServer)

        self.rooms = WeakValueDictionary()
        self.players = WeakValueDictionary()

        registerIDs(GameRoom, self.rooms, IGameRoom)
        registerIDs(lambda: explode(), self.players, IPlayer)

        # init required components
        IServerService(self)
        IServerSite(self)

        if not self.config['quiet']:
            from ServeLib.Interfaces import IStatsProcessor
            import ServeLib.Statistics
            IStatsProcessor(self)
Пример #16
0
    def __init__(self, setup):
        Componentized.__init__(self)
        self.config = setup.asDict()

        # anyone adapting an IGameServer from a str/int/None will get me
        registerGlobal(self, IGameServer)

        self.rooms = WeakValueDictionary()
        self.players = WeakValueDictionary()

        registerIDs(GameRoom, self.rooms, IGameRoom)
        registerIDs(lambda: explode(), self.players, IPlayer)

        # init required components
        IServerService(self)
        IServerSite(self)

        if not self.config['quiet']:
            from ServeLib.Interfaces import IStatsProcessor
            import ServeLib.Statistics
            IStatsProcessor(self)
Пример #17
0
    def indirect(self, interface):
        """
        Create an L{IConchUser} avatar which will use L{ShellServer} to
        interact with the connection.
        """
        if interface is IConchUser:
            componentized = Componentized()

            user = _BetterTerminalUser(componentized, None)
            session = _BetterTerminalSession(componentized)
            session.transportFactory = TerminalSessionTransport
            session.chainedProtocolFactory = lambda: ServerProtocol(ShellServer, self.store)

            componentized.setComponent(IConchUser, user)
            componentized.setComponent(ISession, session)

            return user

        raise NotImplementedError(interface)
Пример #18
0
 def __init__(self, avatar):
     Componentized.__init__(self)
     self.avatar = avatar
     self.uid = 12345
Пример #19
0
 def __init__(self, session):
     Componentized.__init__(self)
     self.session = session
     self.flashed_messages = []
     self.back = None
Пример #20
0
 def __init__(self, session):
     Componentized.__init__(self)
     self.session = session
     self.flashed_messages = []
     self.back = None
Пример #21
0
 def __init__(self, name):
     Componentized.__init__(self)
     NamedObject.__init__(self, name)
Пример #22
0
 def __init__(self, avatar):
     Componentized.__init__(self)
     self.avatar = avatar
     self.uid = 12345