How to use to_invocation_context method in localstack

Best Python code snippet using localstack_python

router_asf.py

Source: router_asf.py Github

copy

Full Screen

...11from localstack.services.apigateway.helpers import get_api_region12from localstack.services.apigateway.invocations import invoke_rest_api_from_request13from localstack.utils.aws.aws_responses import LambdaResponse14LOG = logging.getLogger(__name__)15def to_invocation_context(16 request: Request, url_params: Dict[str, Any] = None17) -> ApiInvocationContext:18 """19 Converts an HTTP Request object into an ApiInvocationContext.20 :param request: the original request21 :param url_params: the parameters extracted from the URL matching rules22 :return: the ApiInvocationContext23 """24 if url_params is None:25 url_params = {}26 method = request.method27 path = request.full_path if request.query_string else request.path28 data = restore_payload(request)29 headers = Headers(request.headers)30 # adjust the X-Forwarded-For header31 x_forwarded_for = headers.getlist("X-Forwarded-For")32 x_forwarded_for.append(request.remote_addr)33 x_forwarded_for.append(request.host)34 headers["X-Forwarded-For"] = ", ".join(x_forwarded_for)35 # set the x-localstack-edge header, it is used to parse the domain36 headers[HEADER_LOCALSTACK_EDGE_URL] = request.host_url.strip("/​")37 # FIXME: Use the already parsed url params instead of parsing them into the ApiInvocationContext part-by-part.38 # We already would have all params at hand to avoid _all_ the parsing, but the parsing39 # has side-effects (f.e. setting the region in a thread local)!40 # It would be best to use a small (immutable) context for the already parsed params and the Request object41 # and use it everywhere.42 return ApiInvocationContext(method, path, data, headers, stage=url_params.get("stage"))43def convert_response(result: RequestsResponse) -> Response:44 """45 Utility function to convert a response for the requests library to our internal (Werkzeug based) Response object.46 """47 if result is None:48 return Response()49 if isinstance(result, LambdaResponse):50 headers = Headers(dict(result.headers))51 for k, values in result.multi_value_headers.items():52 for value in values:53 headers.add(k, value)54 else:55 headers = dict(result.headers)56 response = Response(status=result.status_code, headers=headers)57 if isinstance(result.content, dict):58 response.set_json(result.content)59 elif isinstance(result.content, (str, bytes)):60 response.data = result.content61 else:62 raise ValueError(f"Unhandled content type {type(result.content)}")63 return response64class ApigatewayRouter:65 """66 Simple implementation around a Router to manage dynamic restapi routes (routes added by a user through the67 apigateway API).68 """69 router: Router[Handler]70 def __init__(self, router: Router[Handler]):71 self.router = router72 self.registered = False73 def register_routes(self) -> None:74 """Registers parameterized routes for API Gateway user invocations."""75 if self.registered:76 LOG.debug("Skipped API gateway route registration (routes already registered).")77 return78 self.registered = True79 LOG.debug("Registering parameterized API gateway routes.")80 self.router.add(81 "/​",82 host="<api_id>.execute-api.<regex('.*'):server>",83 endpoint=self.invoke_rest_api,84 defaults={"path": "", "stage": None},85 )86 self.router.add(87 "/​<stage>/​",88 host="<api_id>.execute-api.<regex('.*'):server>",89 endpoint=self.invoke_rest_api,90 defaults={"path": ""},91 )92 self.router.add(93 "/​<stage>/​<path:path>",94 host="<api_id>.execute-api.<regex('.*'):server>",95 endpoint=self.invoke_rest_api,96 )97 # add the localstack-specific _user_request_ routes98 self.router.add(99 "/​restapis/​<api_id>/​<stage>/​_user_request_",100 endpoint=self.invoke_rest_api,101 defaults={"path": ""},102 )103 self.router.add(104 "/​restapis/​<api_id>/​<stage>/​_user_request_/​<path:path>",105 endpoint=self.invoke_rest_api,106 )107 def invoke_rest_api(self, request: Request, **url_params: Dict[str, Any]) -> Response:108 if not get_api_region(url_params["api_id"]):109 return Response(status=404)110 invocation_context = to_invocation_context(request, url_params)111 result = invoke_rest_api_from_request(invocation_context)112 if result is not None:113 return convert_response(result)...

Full Screen

Full Screen

provider_asf.py

Source: provider_asf.py Github

copy

Full Screen

...23 @handler("TestInvokeMethod", expand=False)24 def test_invoke_method(25 self, context: RequestContext, request: TestInvokeMethodRequest26 ) -> TestInvokeMethodResponse:27 invocation_context = to_invocation_context(context.request)28 invocation_context.method = request["httpMethod"]29 if data := parse_json_or_yaml(to_str(invocation_context.data or b"")):30 orig_data = data31 if path_with_query_string := orig_data.get("pathWithQueryString"):32 invocation_context.path_with_query_string = path_with_query_string33 invocation_context.data = data.get("body")34 invocation_context.headers = orig_data.get("headers", {})35 result = invoke_rest_api_from_request(invocation_context)36 # TODO: implement the other TestInvokeMethodResponse parameters37 # * multiValueHeaders: Optional[MapOfStringToList]38 # * log: Optional[String]39 # * latency: Optional[Long]40 return TestInvokeMethodResponse(41 status=result.status_code,...

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

13 Best Java Testing Frameworks For 2023

The fact is not alien to us anymore that cross browser testing is imperative to enhance your application’s user experience. Enhanced knowledge of popular and highly acclaimed testing frameworks goes a long way in developing a new app. It holds more significance if you are a full-stack developer or expert programmer.

QA Innovation &#8211; Using the senseshaping concept to discover customer needs

QA Innovation - Using the senseshaping concept to discover customer needsQA testers have a unique role and responsibility to serve the customer. Serving the customer in software testing means protecting customers from application defects, failures, and perceived failures from missing or misunderstood requirements. Testing for known requirements based on documentation or discussion is the core of the testing profession. One unique way QA testers can both differentiate themselves and be innovative occurs when senseshaping is used to improve the application user experience.

Best 23 Web Design Trends To Follow In 2023

Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.

Acquiring Employee Support for Change Management Implementation

Enterprise resource planning (ERP) is a form of business process management software—typically a suite of integrated applications—that assists a company in managing its operations, interpreting data, and automating various back-office processes. The introduction of a new ERP system is analogous to the introduction of a new product into the market. If the product is not handled appropriately, it will fail, resulting in significant losses for the business. Most significantly, the employees’ time, effort, and morale would suffer as a result of the procedure.

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful