HTTPException 的 Pytest 断言问题:500

问题描述 投票:0回答:1

我在测试一个非常简单的 FastAPI 端点时遇到问题,并且无法断言 HTTPException: 500。

这是我的端点从客户端获取 AuthenticationRequest 以从外部系统获取令牌。 AuthenticationRequest 只是用户名和密码的组合。

@authentication_router.post("/authenticate", tags=["Authentication"])
async def authenticate(
    authentication_request: AuthenticationRequest,
    authentication_service: AuthenticationService = Depends()
):
    """
    Authenticate user and retrieve access token.

    Args:v
        authentication_request (AuthenticationRequest): User authentication request.

    Returns:
        dict: Access token if authentication is successful.
    """
    try:
        access_token = authentication_service.authenticate(authentication_request)
        if access_token is None:
            raise HTTPException(status_code=401, detail="Invalid credentials")
        logger.info(f"Authentication is successful for user: {authentication_request.username}")
        return {"access_token": access_token}
    except Exception as e:
        logger.exception("An error occurred during authentication")
        raise HTTPException(status_code=500, detail=str(e))

我可以使用有效的凭据成功测试此端点(test_valid_authentication() 有效)。但是,invalid_credentials 情况对我不起作用,因为 Pytest 没有断言 status_code=500。

这是我的单元测试:

test_data = ApplicationConfiguration()


@pytest.fixture
def client():
    return TestClient(authentication_router)


def test_valid_authentication(client):
    authentication_data = {"username": test_data.TEST_USER, "password": test_data.TEST_PASSWORD}
    response = client.post("/authenticate", json=authentication_data)
    assert response.status_code == 200
    assert "access_token" in response.json()


def test_invalid_authentication(client):
    authentication_data = {"username": "invalid_user", "password": "invalid_password"}
    response = client.post("/authenticate", json=authentication_data)
    assert response.status_code == 500

由于我在端点上使用另一个客户端,因此我用另一个异常状态代码 500 包装原始 401 错误。 我预计这个测试也会成功,因为我在测试中断言 response.status_code == 500。

我想根据响应状态代码 = 500 通过我的 test_invalid_authentication()。 您能帮忙解决这里缺少的一点吗?

Pytest 结果:

    @authentication_router.post("/authenticate", tags=["Authentication"])
    async def authenticate(
        authentication_request: AuthenticationRequest,
        authentication_service: AuthenticationService = Depends()
    ):
        """
        Authenticate user and retrieve access token.

        Args:v
            authentication_request (AuthenticationRequest): User authentication request.

        Returns:
            dict: Access token if authentication is successful.
        """
        try:
            access_token = authentication_service.authenticate(authentication_request)
            if access_token is None:
>               raise HTTPException(status_code=401, detail="Invalid credentials")
E               fastapi.exceptions.HTTPException: 401: Invalid credentials

routers\authentication.py:28: HTTPException

During handling of the above exception, another exception occurred:

   @authentication_router.post("/authenticate", tags=["Authentication"])
    async def authenticate(
        authentication_request: AuthenticationRequest,
        authentication_service: AuthenticationService = Depends()
    ):
        """
        Authenticate user and retrieve access token.

        Args:v
            authentication_request (AuthenticationRequest): User authentication request.

        Returns:
            dict: Access token if authentication is successful.
        """
        try:
            access_token = authentication_service.authenticate(authentication_request)
            if access_token is None:
                raise HTTPException(status_code=401, detail="Invalid credentials")
            logger.info(f"Authentication is successful for user: {authentication_request.username}")
            return {"access_token": access_token}
        except Exception as e:
            logger.exception("An error occurred during authentication")
>           raise HTTPException(status_code=500, detail=str(e))
E           fastapi.exceptions.HTTPException: 500: 401: Invalid credentials


====================================================================== short test summary info ======================================================================= 
FAILED tests\test_authentication.py::test_invalid_authentication - fastapi.exceptions.HTTPException: 500: 401: Invalid credentials
============================================================== 1 failed, 1 passed, 4 warnings in 1.46s =============================================================== 
pytest fastapi
1个回答
0
投票

这个简化的代码示例对我来说效果很好。

from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient

app = FastAPI()


@app.post("/authenticate")
def authenticate():
    try:
        access_token = None
        if access_token is None:
            raise HTTPException(status_code=401, detail="Invalid credentials")
        return {"access_token": access_token}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))



client = TestClient(app)

def test_invalid_authentication():
    authentication_data = {"username": "invalid_user", "password": "invalid_password"}
    response = client.post("/authenticate", json=authentication_data)
    assert response.status_code == 500

我认为你的代码也应该有效。 如果没有,请尝试创建重现问题的最小代码示例。这样我们就可以复制并运行它。

© www.soinside.com 2019 - 2024. All rights reserved.