-6ren">
gpt4 book ai didi

python - 如何在 Starlette/FastAPI 中修改 Request 对象的范围字段以进行单元测试

转载 作者:行者123 更新时间:2023-12-05 08:03:29 29 4
gpt4 key购买 nike

假设我有一个带有基本获取请求的 FastAPI 路由,如下所示:

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

我想用它来测试:

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

现在,如果您检查路由中的 request 变量,您将看到一个 starlette.requests.request 对象。这个对象有一个字典字段,request.scope

我们使用 Mangum 将应用程序作为 AWS 上的 Lambda 提供服务,并且我们的实际应用程序能够将名为 aws.event 的字段接收到该对象 (docs) 中。我正在尝试弄清楚如何为端点编写测试。

我想我想做的是以某种方式修改传入的 request.scope 字典,以使用 TestClient 包含此自定义 aws.event 字段。

有没有办法将某些东西传递到测试配置中,从而将自定义字段传播到 Request 对象中?

最佳答案

首先,为了确保我们不会覆盖当前范围:

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

然后,创建一个模拟 Starlette 请求的方法,添加您想要的范围:

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

然后修补starlette.routing.Request:


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

瞧。

关于python - 如何在 Starlette/FastAPI 中修改 Request 对象的范围字段以进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72607204/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com