You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 16:10:29