简体   繁体   English

使用 FastAPI testclient 时如何检查 JSON 响应类型

[英]How to check the JSON response types when using FastAPI testclient

I'm using the FastAPI testclient to test the response of my API routes.我正在使用 FastAPI 测试客户端来测试我的 API 路由的响应。 Now I want to determine the types of the JSON response.现在我想确定 JSON 响应的类型。

For example my response is:例如我的回答是:

{"userID": 50}

I know how to test this hard coded:我知道如何测试这个硬编码:

assert response.json == {'userID': 50}

But my goal is to check only if the response returns the key userID or check the type of the key value.但我的目标是仅检查响应是否返回键userID或检查键值的类型。 For example:例如:

assert response.json == {'userID': int}

Ultimately, I am only looking for a way to check whether the desired key names are present.最终,我只是在寻找一种方法来检查是否存在所需的键名。

You can use any regular Python supported way of checking a type:您可以使用任何常规的 Python 支持的方式来检查类型:

user_response = response.json()
assert type(user_response['userID']) == int

or或者

assert isinstance(user_response['userID'], 3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM