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()
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, [])
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
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()
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)
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
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))
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)
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
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))
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
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, [])
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)
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)
def __init__(self, avatar): Componentized.__init__(self) self.avatar = avatar self.uid = 12345
def __init__(self, session): Componentized.__init__(self) self.session = session self.flashed_messages = [] self.back = None
def __init__(self, name): Componentized.__init__(self) NamedObject.__init__(self, name)