def test_path_with_removed_args(path, args, expected): request = Request(path.encode("utf8"), {}, "1.1", "GET", None) actual = utils.path_with_removed_args(request, args) assert expected == actual # Run the test again but this time use the path= argument request = Request("/".encode("utf8"), {}, "1.1", "GET", None) actual = utils.path_with_removed_args(request, args, path=path) assert expected == actual
def prepare_slack_request(headers: Dict[Text, Any]) -> Request: request = Request( b"/webhooks/slack/webhook", headers=Header(headers), version="1.1", method="POST", transport=None, app=None, ) request.body = b"""{"foo": "bar"}""" return request
async def user_auth(request: Request): request = await check_request(request, ('login', 'password')) user = await User.find(user_login=request['login']) await check_pass(request['password'], user.hashed_password) if user.totp_active: if '2FA_code' not in request.keys(): raise InvalidUsage('2FA code is required') await user.check_totp(request.get('2FA_code')) token = await Token.add(user.id) token = encode_auth_token(user.id, token.id) response = json({'Authorization': token}) response.cookies['Authorization'] = token return response
def test_request_id_defaults_uuid(): request = Request(b"/", {}, None, "GET", None, Mock()) assert isinstance(request.id, UUID) # Makes sure that it has been cached and not called multiple times assert request.id == request.id == request._id
def test_path_with_added_args(path, added_args, expected): request = Request( path.encode('utf8'), {}, '1.1', 'GET', None ) actual = utils.path_with_added_args(request, added_args) assert expected == actual
async def server_info(request: Request): fetch_keys = [ "json", "token", "form", "args", "raw_args", "cookies", "ip", "port", "remote_addr", "scheme", "host", "content_type", "path", "url", "headers" ] ret = {} for k in fetch_keys: try: ret[k] = getattr(request, "k") except BaseException as e: ret[k] = f'@@ error: {type(e)} {e} @@' return json({ "auth": request.get('auth'), "json": request.json, "token": request.token, "form": request.form, "args": request.args, "raw_args": request.raw_args, "cookies": request.cookies, "ip": request.ip, "port": request.port, "remote_addr": request.remote_addr, "scheme": request.scheme, "host": request.host, "content_type": request.content_type, "path": request.path, "url": request.url, "headers": request.headers, })
def test_parse_unicode(self, app): req = Request.from_values('/bubble?foo=barß') parser = RequestParser() parser.add_argument('foo') args = parser.parse_args(req) assert args['foo'] == 'barß'
def test_path_with_format(path, format, extra_qs, expected): request = Request( path.encode('utf8'), {}, '1.1', 'GET', None ) actual = utils.path_with_format(request, format, extra_qs) assert expected == actual
async def test_resolve_route_with_typed_args(self, sanic_router, route_generator, benchmark): typed_routes = route_generator.add_typed_parameters( route_generator.generate_random_direct_route(max_route_depth=4), max_route_depth=8, ) router, typed_routes = sanic_router(route_details=typed_routes) route_to_call = choice(typed_routes) url = route_generator.generate_url_for_template( template=route_to_call[-1]) print("{} -> {}".format(route_to_call[-1], url)) result = benchmark.pedantic( router.get, (Request( "/{}".format(url).encode(), {"host": "localhost"}, "v1", route_to_call[0], None, None, ), ), iterations=1000, rounds=1000, ) assert await result[0](None) == 1
def _before_request_fn(self, request: Request, attributes: List[AnyStr] = None): operation_name = request.endpoint headers = {} for k, v in request.headers.items(): headers[k.lower()] = v try: span_ctx = self.tracer.extract(opentracing.Format.HTTP_HEADERS, headers) scope = self.tracer.start_active_span(operation_name, child_of=span_ctx) except (opentracing.InvalidCarrierException, opentracing.SpanContextCorruptedException): scope = self.tracer.start_active_span(operation_name) req_scope = tuple(sorted(request.items())) self._current_scopes[req_scope] = scope span = scope.span span.set_tag(tags.COMPONENT, 'Sanic') span.set_tag(tags.HTTP_METHOD, request.method) span.set_tag(tags.HTTP_URL, request.url) span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER) for attr in attributes: if hasattr(request, attr): payload = str(getattr(request, attr)) if payload: span.set_tag(attr, payload) self._call_start_span_cb(span, request)
async def test_endpoint_cached_component(some_app, sanic_request): async def hello(my_var: EndpointCached, another_var: EndpointCached): return my_var, another_var async def world(my_var: EndpointCached): return my_var some_app.add_component(EndpointCachedComponent) kw = await some_app.resolver.resolve(request=sanic_request, func=hello) ret = await hello(**kw) assert type(ret[0]) is str assert type(ret[1]) is str assert len(some_app.cache_engine._endpoints) == 1 assert len(some_app.cache_engine._endpoints[hello].values()) == 2 assert ret[0] in some_app.cache_engine._endpoints[hello].values() assert ret[1] in some_app.cache_engine._endpoints[hello].values() # same endpoint, result should be cached for "my_var" and "another_var" kw2 = await some_app.resolver.resolve(request=sanic_request, func=hello) ret2 = await hello(**kw2) assert len(some_app.cache_engine._endpoints) == 1 assert ret2[0] in some_app.cache_engine._endpoints[hello].values() assert ret2[1] in some_app.cache_engine._endpoints[hello].values() # both my_var and another_var should be equal assert ret == ret2 # creating a new request new_request = Request( url_bytes=b"/foo/baz", headers={}, version=None, method="POST", transport=None, ) kw3 = await some_app.resolver.resolve(request=new_request, func=hello) ret3 = await hello(**kw3) # since the cache is bound to the endpoint, the result should be the same assert type(ret3[0]) is str assert type(ret3[1]) is str assert len(some_app.cache_engine._endpoints) == 1 assert ret3[0] in some_app.cache_engine._endpoints[hello].values() assert ret3[1] in some_app.cache_engine._endpoints[hello].values() assert ret == ret2 assert ret == ret3 # now, with another endpoint kw4 = await some_app.resolver.resolve(request=sanic_request, func=world) ret4 = await world(**kw4) assert type(ret4) is str assert len(some_app.cache_engine._endpoints) == 2 assert ret4 not in some_app.cache_engine._endpoints[hello].values() assert ret4 in some_app.cache_engine._endpoints[world].values() assert ret[0] != ret4 assert ret[1] != ret4
async def check_request(request: Request, data: Union[Iterable, str], need_auth: bool = False): """ Валидатор реквеста Проверка на содержание data в request и валидация на соответствие типу string :param need_auth: если True, то проверяется наличие токена в куках :param request: request пользователя :param data: Данные, которые должны быть в реквесте :return: Exception или Request (+ User) """ for key in data: if key not in request.json.keys(): raise InvalidUsage(f'{key} info is missing') if not isinstance(request.json.get(key), str): try: request.json[key] = str(request.json[key]) except AttributeError: raise InvalidUsage(f'{key} must be string') if need_auth: if request.cookies.get('Authorization') is None: raise Unauthorized('You need to be authorized') user_id, token = decode_auth_token(request.cookies.get('Authorization')) try: user = await User.find(user_id=user_id) except User.DoesNotExist: raise InvalidUsage('This user does not exist') await Token.check_valid(token, user.id) try: return request.json, user except InvalidUsage: return user return request.json
def test_passing_arguments_object(self, app): req = Request.from_values('/bubble?foo=bar') parser = RequestParser() parser.add_argument(Argument('foo')) args = parser.parse_args(req) assert args['foo'] == 'bar'
def test_parse_ignore(self, app): req = Request.from_values('/bubble?foo=bar') parser = RequestParser() parser.add_argument('foo', type=int, ignore=True, store_missing=True), args = parser.parse_args(req) assert args['foo'] is None
def _verify_auth_token(self, request: Request): # Flask normally handles OPTIONS requests on its own, but in the # case it is configured to forward those to the application, we # need to ignore authentication headers and let the request through # to avoid unwanted interactions with CORS. if request.method != 'OPTIONS': # pragma: no cover token = self.get_bearer_token(request) payload = self.user_service.validate_auth_token(token) # print(payload) self.user_service.validate_access_policy(payload['sub'], payload['role_ids'], payload['iat']) request.headers['user'] = payload['user'] request.headers['roles'] = payload['role_ids'] request.headers['permissions'] = payload['permissions'] request.headers['auth_token'] = token return request
async def test_lbheartbeat(app): responses = [] request = Request(b"/__lbheartbeat__", {}, "1.1", "GET", "http", app) await app.handle_request(request, lambda r: responses.append(r), None) assert len(responses) == 1 response = responses.pop() assert response.status == 200 assert response.body == b""
def test_request_id_generates_from_request(monkeypatch): monkeypatch.setattr(Request, "generate_id", Mock()) Request.generate_id.return_value = 1 request = Request(b"/", {}, None, "GET", None, Mock()) for _ in range(10): request.id Request.generate_id.assert_called_once_with(request)
def test_parse_store_missing(self, app): req = Request.from_values('/bubble') parser = RequestParser() parser.add_argument('foo', store_missing=False) args = parser.parse_args(req) assert 'foo' not in args
def test_parse_choices_insensitive(self, app): req = Request.from_values('/bubble?foo=BAT') parser = RequestParser() parser.add_argument('foo', choices=['bat'], case_sensitive=False), args = parser.parse_args(req) assert 'bat' == args.get('foo') # both choices and args are case_insensitive req = Request.from_values('/bubble?foo=bat') parser = RequestParser() parser.add_argument('foo', choices=['BAT'], case_sensitive=False), args = parser.parse_args(req) assert 'bat' == args.get('foo')
def test_parse_choices_sensitive(self, app): req = Request.from_values('/bubble?foo=BAT') parser = RequestParser() parser.add_argument('foo', choices=['bat'], case_sensitive=True), with pytest.raises(BadRequest): parser.parse_args(req)
def test_parse_choices(self, app): req = Request.from_values('/bubble?foo=bar') parser = RequestParser() parser.add_argument('foo', choices=['bat']), with pytest.raises(BadRequest): parser.parse_args(req)
def test_parse_choices_correct(self, app): req = Request.from_values('/bubble?foo=bat') parser = RequestParser() parser.add_argument('foo', choices=['bat']), args = parser.parse_args(req) assert args['foo'] == 'bat'
def test_request_id_defaults_uuid(): request = Request(b"/", {}, None, "GET", None, Mock()) request.app.config.REQUEST_ID_HEADER = "foo" assert isinstance(request.id, UUID) # Makes sure that it has been cached and not called multiple times assert request.id == request.id == request._id
def test_type_callable(self, app): req = Request.from_values('/bubble?foo=1') parser = RequestParser() parser.add_argument('foo', type=lambda x: x, required=False), args = parser.parse_args(req) assert args['foo'] == '1'
def on_headers_complete(self): self.request = Request( url_bytes=self.url, headers=CIDict(self.headers), version=self.parser.get_http_version(), method=self.parser.get_method().decode(), transport=self.transport )
def user_reset_password(request: Request): content: dict = request.json email = content.get('email', '') user_service.request_reset_user_password(email, confirm_url=request.url_for( 'user_confirm_reset_password', token='')) return {'message': f'Confirmation link was sent to the email {email}'}
async def handle_message(sid: Text, data: Dict) -> Any: output_channel = SocketIOVoiceOutput(sio, self.bot_message_evt, self.botium_speech_url, self.botium_speech_apikey, self.botium_speech_language, self.botium_speech_voice) if self.session_persistence: if not data.get("session_id"): rasa.shared.utils.io.raise_warning( "A message without a valid session_id " "was received. This message will be " "ignored. Make sure to set a proper " "session id using the " "`session_request` socketIO event." ) return sender_id = data["session_id"] else: sender_id = sid if data['message'] and data['message'].startswith('data:'): header, encoded = data['message'].split(",", 1) audioData = base64.b64decode(encoded.encode('ascii')) convertEndpoint = f"{self.botium_speech_url}/api/convert/WAVTOMONOWAV" logger.debug(f"handle_message - Calling Convert Endpoint: {convertEndpoint}") res = urlopen(Request(url=convertEndpoint, data=audioData, method='POST', headers= { 'content-type': 'audio/wav' })) audioDataWav = res.read() #with open('decoded_image.wav', 'wb') as file_to_save: # file_to_save.write(audioData) audioEndpoint = f"{self.botium_speech_url}/api/stt/{self.botium_speech_language}" logger.debug(f"handle_message - Calling Speech Endpoint: {audioEndpoint}") res = urlopen(Request(url=audioEndpoint, data=audioDataWav, method='POST', headers= { 'content-type': 'audio/wav' })) resJson = json.loads(res.read().decode('utf-8')) logger.debug(f"handle_message - Calling Speech Endpoint: {audioEndpoint} => {resJson}") message = resJson["text"] await sio.emit(self.user_message_evt, {"text": message}, room=sid) else: message = data['message'] message = UserMessage( message, output_channel, sender_id, input_channel=self.name() ) await on_new_message(message)
def create_req(app): return Request( b"http://127.0.0.1:42101/webhooks/hangouts/webhook", None, None, "POST", None, app=app, )
def test_request_parser_remove_argument(self): req = Request.from_values('/bubble?foo=baz') parser = RequestParser() parser.add_argument('foo', type=int) parser_copy = parser.copy() parser_copy.remove_argument('foo') args = parser_copy.parse_args(req) assert args == {}
async def user_delete_2fa(request: Request): request, user = await check_request(request, ['2FA_code'], True) if user.totp_active: await user.check_totp(request.get('2FA_code')) await user.update(totp_active=False, totp_key=None) return text('Success') else: raise InvalidUsage('Two-factor authentication not activated')
def middleware_with_no_tag(request: Request): if request.headers.get("content-type") == "application/json": request.headers["accepts"] = "plain/text" else: request.headers["accepts"] = "application/json"