def test_middleware_for_serverless() -> None: route = Route("/test/{id}") def cors_middleware( request: HttpRequest, next: Callable[[HttpRequest], HttpResponse]) -> HttpResponse: assert hasattr(request, "route") assert request.route is not None assert request.route == route assert request.path_parameters == {"id": "123"} assert request.route.parameters == {"id": "123"} response = next(request) response._headers.set("Access-Control-Allow-Origin", "*") return response def ok_handler(request: HttpRequest) -> HttpResponse: return HttpResponse(status=200) middleware_pipeline = MiddlewarePipeline() middleware_pipeline.append(cors_middleware) serverless_callback = AwsServerlessFunction(ok_handler, route, middleware_pipeline) dir_path = os.path.dirname(os.path.realpath(__file__)) event_json = json.load( open(os.path.join(dir_path, "../fixtures/lambda_http_api_event.json"))) response = serverless_callback(event_json, {}) assert "headers" in response assert "access-control-allow-origin" in response["headers"]
def test_successing_pipeline(): pipeline = MiddlewarePipeline() pipeline.append(ErrorCatchingMiddleware(), ProxingMiddleware(), RespondingMiddleware()) response = pipeline(HttpRequest("get")) response.body.seek(0) assert int(response.status_code) == 201 assert response.body.read() == b"Proxed Response"
def test_erroring_middleware_pipeline(): pipeline = MiddlewarePipeline() pipeline.append(ErrorCatchingMiddleware(), ProxingMiddleware(), ErroringMiddleware()) response = pipeline(HttpRequest("get")) assert 500 == int(response.status_code) assert response.as_str(), "Error"
def test_erroring_middleware_pipeline(): pipeline = MiddlewarePipeline() pipeline.append(ErrorCatchingMiddleware(), ProxingMiddleware(), ErroringMiddleware()) response = pipeline(HttpRequest("get")) assert response.status_code == 500 assert isinstance(response.body, RuntimeError)
def test_empty_pipeline(): pipeline = MiddlewarePipeline() with pytest.raises(RuntimeError): pipeline(HttpRequest("get"))