5

Let's say I have a FastAPI route with a basic get request that looks something like:

@router.get("/reports")
async def get_reports(request: Request) -> Dict:
    return 

and I want to test it using:

def test_method_can_access_request_fields():
    client = TestClient()
    response = client.get("/")

Now, if you examine the request variable in the route, you'll see a starlette.requests.request object. This object has a Dict field, request.scope.

We're using Mangum to serve the app as a Lambda on AWS, and our real application is able to receive a field called aws.event into this object (docs). I'm trying to figure out how to write a test for the endpoint.

What I think I want to do is to somehow modify the incoming request.scope Dictionary to include this custom aws.event field using the TestClient.

Is there a way to pass something into the test configuration that will propagate a custom field into the Request object?

John Kealy
  • 1,503
  • 1
  • 13
  • 32

1 Answers1

-1

First, in order to make sure we do not override current scope:

def _update_scope(self, scope1, scope2):
    scope1.update(scope2)
    return scope1

Then, create a method that would mock Starlette's request, adding your desired scope:

def mock_request(self, new_scope):
    return lambda scope, send, receive: Request(self._update_scope(scope, new_scope), send, receive)

then patch starlette.routing.Request:


mock.patch("starlette.routing.Request", mock_request())

voila.

ishefi
  • 480
  • 4
  • 12