def test_base64_encoding(): resp = Response( status_code=200, headers={}, body={"message": "received GET"}, base64_encode=True, ) resp = resp.to_json() assert resp["body"] == b"eyJtZXNzYWdlIjogInJlY2VpdmVkIEdFVCJ9"
def post(self, foo_id): resp = Response( status_code=201, headers={}, body={ "message": "received the following data %s" % router.current_request.body }, ) return resp.to_json()
def dispatch(self, request: Request): """Handles dispatching all requests made.""" self.current_request = request resource = self.routes.get(request.resource, None) # Account for the possibility of a resource not being registered if resource is None: return Response(status_code=404, headers={}, body={ "message": "Endpoint not found" }).to_json() # Create an empty dict for kwargs # TO DO: Test the speed of this, it might be slow kwargs = {} # Dont iterate if there are no path parameters if resource.path_params: for item in resource.path_params: kwargs[item] = request.path_parameters[item] # type: ignore # Instantiate the view class # This is done here to ensure each request has it's own instance view = resource.view_cls() # Call the dispatch method of the view class # This method is defined in view.py return view.dispatch(http_method=request.http_method, **kwargs)
def test_response_obj(): resp = Response(status_code=200, headers={}, body={"message": "received GET"}) j = resp.to_json() assert resp.statusCode == 200 assert type(resp.statusCode) == int assert resp.headers == {} assert type(resp.headers) == dict assert resp.isBase64Encoded == False assert type(resp.isBase64Encoded) == bool assert resp.body["message"] == "received GET" assert type(resp.body) == dict # Test output of to_json() assert type(j["body"]) == str
def dispatch(self, http_method: str, **kwargs): # Lower the http_method because it is all caps from API Gateway event http_method = http_method.lower() func = getattr(self, http_method, None) # If a method is not implemented, return 405 if func is None: return Response(status_code=405, headers={}, body={ "message": "Method not implemented" }).to_json() return func(**kwargs)
def put(self, foo_id): resp = Response(status_code=200, headers={}, body={"message": "received PUT"}) return resp.to_json()
def get(self): resp = Response(status_code=200, headers={}, body={"message": "received GET"}) return resp.to_json()
def test_status_code_type(): """Tests that response object balks on improper type for status_code.""" with pytest.raises(TypeError): resp = Response(status_code="foo", headers={}, body={"message": "received GET"})
def test_body_type(): """Tests that response object balks on improper type for body.""" with pytest.raises(TypeError): resp = Response(status_code=200, headers={}, body="hello world")
def delete(self, **kwargs) -> dict: resp = Response(status_code=405, headers={}, body={"message": "Method not implemented"}) return resp.to_json()