我正在尝试测试用Fastapi编写的api。我的路由器中有以下方法:
@app.get('/webrecord/check_if_object_exist')
async def check_if_object_exist(payload: WebRecord) -> bool:
key = get_key_of_obj(payload.data) if payload.key is None else payload.key
return await check_if_key_exist(key)
以及我的测试文件中的以下测试:
client = TestClient(app)
class ServiceTest(unittest.TestCase):
.....
def test_check_if_object_is_exist(self):
webrecord_json = {'a':1}
response = client.get("/webrecord/check_if_object_exist", json=webrecord_json)
assert response.status_code == 200
assert response.json(), "webrecord should already be in db, expected : True, got : {}".format(response.json())
当我在调试中运行代码时,我意识到没有达到get方法内的断点。当我更改发布所有内容的请求的类型时,一切正常。
我在做什么错了?
答案 0 :(得分:1)
为了通过GET请求将数据发送到服务器,您必须在url中对其进行编码,因为GET没有任何正文。如果您需要特定的格式(例如JSON),则不建议这样做,因为您必须解析网址,解码参数并将其转换为JSON。
或者,您可以将搜索请求发布到服务器。 POST请求允许的正文可能具有不同的格式(包括JSON)。
@app.get('/webrecord/check_if_object_exist/{key}')
async def check_if_object_exist(key: str, data: str) -> bool:
key = get_key_of_obj(payload.data) if payload.key is None else payload.key
return await check_if_key_exist(key)
client = TestClient(app)
class ServiceTest(unittest.TestCase):
.....
def test_check_if_object_is_exist(self):
response = client.get("/webrecord/check_if_object_exist/key", params={"data": "my_data")
assert response.status_code == 200
assert response.json(), "webrecord should already be in db, expected : True, got : {}".format(response.json())
这将允许从url mydomain.com/webrecord/check_if_object_exist/ {对象的键}中获取请求。
最后一点:我将所有参数都设为必需。您可以通过声明默认为None
来更改它们。参见fastapi Docs