测试FastAPI路由时遇TypeError:post()仅接受2个位置参数却传入3个
解决FastAPI测试中
TypeError: post() takes 2 positional arguments but 3 were given错误 问题出在client.post的参数传递方式上:
- 你当前代码里
client.post("/users/",json.dumps(data))把序列化后的JSON字符串作为第二个位置参数传入,但TestClient的post方法仅接受1个位置参数(请求路径),额外参数必须通过关键字参数传递。
修正方案:
直接使用json关键字参数传入字典,TestClient会自动帮你完成JSON序列化并设置正确的请求头,代码修改如下:
def test_create_user(client): data = {"username":"testuser","email":"testuser@nofoobar.com","password":"testing"} response = client.post("/users/", json=data) assert response.status_code == 200 assert response.json()["email"] == "testuser@nofoobar.com" assert response.json()["is_active"] == True
如果确实需要手动处理JSON序列化(一般没必要),可以用content关键字参数配合请求头:
import json def test_create_user(client): data = {"username":"testuser","email":"testuser@nofoobar.com","password":"testing"} response = client.post( "/users/", content=json.dumps(data), headers={"Content-Type": "application/json"} ) assert response.status_code == 200 assert response.json()["email"] == "testuser@nofoobar.com" assert response.json()["is_active"] == True
内容的提问来源于stack exchange,提问作者Nidal H
相关产品推荐
相关产品推荐

