def test_init(): conf = {'MIDDLEWARES': ['tests.issue_0029.test_manager.AddOne']} with patch_conf(conf): m = MiddlewareManager() m.init() assert m.middlewares == [AddOne]
def test_instance(): MiddlewareManager._instance = None i1 = MiddlewareManager.instance() i2 = MiddlewareManager.instance() assert i1 is i2 MiddlewareManager._instance = None
def test_caller_extra(): m = MiddlewareManager() rn = m.get('return_n', return_n) assert run(rn(0)) == 0 with pytest.raises(ValueError): run(rn(0))
def test_build_stack(): m = MiddlewareManager() m.middlewares = [ AddOne, DoNothing, ] rn = m.get('return_n', return_n) # noinspection PyProtectedMember,PyUnresolvedReferences assert len(rn._stack) == 1
def test_caller_stack(): m = MiddlewareManager() m.middlewares = [ AddOne, AddOne, ] rn = m.get('return_n', return_n) assert run(rn(40)) == 42
def test_next_not_called(): m = MiddlewareManager() m.middlewares = [BadPlayer] rn = m.get('return_n', return_n) error_msg = '"BadPlayer.return_n" did not call `self.next()`, or forgot ' \ 'to await it' with pytest.raises(TypeError) as exec_info: run(rn(0)) assert str(exec_info.value) == error_msg
def test_health_check(): with patch_conf({'MIDDLEWARES': None}): assert len(list(MiddlewareManager.health_check())) == 1 with patch_conf({'MIDDLEWARES': ['does.not.Exist']}): assert len(list(MiddlewareManager.health_check())) == 1 conf = {'MIDDLEWARES': ['tests.issue_0029.test_manager.IsNotMiddleware']} with patch_conf(conf): assert len(list(MiddlewareManager.health_check())) == 1 conf = {'MIDDLEWARES': ['tests.issue_0029.test_manager.AddOne']} with patch_conf(conf): assert len(list(MiddlewareManager.health_check())) == 0
async def render_list(self, request=None) -> List[Text]: """ Render the translation as a list if there is multiple strings for this single key. :param request: Bot request. """ from bernard.middleware import MiddlewareManager if request: tz = await request.user.get_timezone() locale = await request.get_locale() flags = await request.get_trans_flags() else: tz = None locale = self.wd.list_locales()[0] flags = {} rp = MiddlewareManager.instance()\ .get('resolve_trans_params', self._resolve_params) resolved_params = await rp(self.params, request) f = I18nFormatter(self.wd.choose_locale(locale), tz) return self.wd.get( self.key, self.count, f, locale, resolved_params, flags, )
def test_flush(): args = [] kwargs = {} async def do_flush(*a, **k): args.extend(a) kwargs.update(k) mm = MiddlewareManager.instance() mm.middlewares = [AutoSleep] flush = mm.get('flush', do_flush) run(flush(None, [lyr.Stack([lyr.Text('hello'), lyr.Text('wassup')])])) assert args == [ None, [ lyr.Stack([ lyr.RawText('hello'), ]), lyr.Stack([ lyr.Sleep(0.7), ]), lyr.Stack([ lyr.RawText('wassup'), ]), ] ] assert kwargs == {}
async def get_trans_flags(self) -> 'Flags': """ Gives a chance to middlewares to make the translation flags """ from bernard.middleware import MiddlewareManager async def make_flags(request: Request) -> 'Flags': return {} mf = MiddlewareManager.instance().get('make_trans_flags', make_flags) return await mf(self)
async def postback_me(msg: BaseMessage, platform: Platform) -> Response: """ Provides the front-end with details about the user. This output can be completed using the `api_postback_me` middleware hook. """ async def get_basic_info(_msg: BaseMessage, _platform: Platform): user = _msg.get_user() return { 'friendly_name': await user.get_friendly_name(), 'locale': await user.get_locale(), 'platform': _platform.NAME, } func = MiddlewareManager.instance().get('api_postback_me', get_basic_info) return json_response(await func(msg, platform))
async def _handle_message(self, message: BaseMessage, responder: Responder) -> Optional[Dict]: """ Handles a message: find a state and run it. :return: The register that was saved """ async def noop(request: Request, responder: Responder): pass mm = MiddlewareManager.instance() reg_manager = self.register\ .work_on_register(message.get_conversation().id) async with reg_manager as reg: request = Request(message, reg) await request.transform() if not request.stack.layers: return logger.debug('Incoming message: %s', request.stack) await mm.get('pre_handle', noop)(request, responder) # noinspection PyBroadException try: state, trigger, dnr = \ await self._build_state(request, message, responder) except Exception: logger.exception('Error while finding a transition from %s', reg.get(Register.STATE)) reporter.report(request, None) return if state is None: logger.debug( 'No next state found but "%s" is not confusing, stopping', request.message, ) return state = await self._run_state(responder, state, trigger, request) # noinspection PyBroadException try: await responder.flush(request) except MissingTranslationError as e: responder.clear() responder.send([RawText(str(e))]) await responder.flush(request) reporter.report(request, state.name()) logger.exception('Missing translation in state %s', state.name()) except Exception: reporter.report(request, state.name()) logger.exception('Could not flush content after %s', state.name()) else: if not dnr: reg.replacement = await self._build_state_register( state, request, responder, ) return reg.replacement