【问题标题】:Fastapi Testclient not able to send POST request using form-dataFastapi Testclient 无法使用表单数据发送 POST 请求
【发布时间】:2023-01-08 02:06:53
【问题描述】:

目前我正在使用 from fastapi.testclient import TestClient 在 Fastapi 中进行单元测试

def test_login_api_returns_token(session,client):
    form_data = {
        "username": "mike@gmail.com",
        "password": "mike"
    }
    response = client.post(  
        "/api/login", 
        data=form_data
    )
    result = response.json()
    assert response.status_code == 200

当我运行 fastapi 应用程序但无法继续进行单元测试时,我应该得到令牌作为响应。

邮递员请求相同的示例

如何确保表单数据是从 TestClient 发送的?

【问题讨论】:

    标签: unit-testing http-post fastapi starlette httpx


    【解决方案1】:

    尝试将标头设置为 Content-Type 表单数据,例如

    def test_login_api_returns_token(session,client):
        form_data = {
            "username": "mike@gmail.com",
            "password": "mike"
        }
        response = client.post(  
            "/api/login", 
            data=form_data,
            headers={ 'Content-Type': 'multipart/form-data' }
        )
        result = response.json()
        assert response.status_code == 200
    

    【讨论】:

    • 从结果中获取 {'detail': 'Not Found'}。
    • 您可以添加端点代码吗?
    猜你喜欢
    • 2020-06-05
    • 2011-10-03
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 2020-12-29
    相关资源
    最近更新 更多