python 无法使用FastAPI和Pytest测试Post请求

nxagd54h  于 2023-03-11  发布在  Python
关注(0)|答案(1)|浏览(221)

我正在尝试使用FastAPI的Testclient测试我的/login API。
但是当我将数据传递给post API时,显示422 error和内容username以及password字段是必需的。

API:

@router.post('/token', response_model=schemas.Token)
async def login(user_credentials: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """
    Login to the system with (Email | Username | Contact)
    """

    user = db.query(models.User).filter(
        (models.User.email == user_credentials.username) |
        (models.User.username == user_credentials.username) |
        (models.User.contact == user_credentials.username)
    ).first()

    if not user:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Invalid Credentials"
        )

    if not utils.verify_pwd(user_credentials.password, user.password):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Invalid Credentials"
        )

    access_token = oauth2.create_access_token(data={'user_id': user.id})

    return {"access_token": access_token, "token_type": "bearer"}

测试代码:

from fastapi.testclient import TestClient

from ..main import app

client = TestClient(app)

def test_auth_token(get_client: TestClient):
    client = get_client.post('/token', json={"username": "admin", "password": "1234567890"})
    assert client.status_code == 200

错误

(venv)  ✘ genex@Genexs-MacBook-Pro: pytest -s
================================================================================== test session starts ===================================================================================
platform darwin -- Python 3.10.8, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/genex/Desktop/basha-bari
plugins: asyncio-0.20.3, anyio-3.6.2
asyncio: mode=strict
collected 1 item                                                                                                                                                                         

apps/utility/test_utility_routers.py {'detail': [{'loc': ['body', 'username'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'password'], 'msg': 'field required', 'type': 'value_error.missing'}]}
F

======================================================================================== FAILURES ========================================================================================
____________________________________________________________________________________ test_auth_token _____________________________________________________________________________________

    def test_auth_token():
        result = client.post('/token', json={"username": "admin", "password": "1234567890"})
        print(result.json())
>       assert result.status_code == 200
E       assert 422 == 200
E        +  where 422 = <Response [422 Unprocessable Entity]>.status_code

apps/utility/test_utility_routers.py:12: AssertionError
================================================================================ short test summary info =================================================================================
FAILED apps/utility/test_utility_routers.py::test_auth_token - assert 422 == 200
=================================================================================== 1 failed in 1.06s ====================================================================================

我使用的是httpxpytest
我应该如何传递有效负载,以便API接收它。

iibxawm4

iibxawm41#

您正在发送带有“content-type”的JSON:“application/x-www-form-urlencoded”这就是问题所在,您应该将请求作为表单数据发送。尝试更改:

response = client.post("/token", data={"username": "admin", "password": "1234567890", "grant_type": "password"},
                           headers={"content-type": "application/x-www-form-urlencoded"})

相关问题