簡體   English   中英

如何測試 Fastapi 異常處理程序

[英]How to test Fastapi Exception Handler

我創建了一個自定義異常處理程序並想為它編寫測試用例。

這是我的測試用例:

def test_is_exception_raised(app_client):
    exception = CustomException(InvalidSQLStatement())
    with pytest.raises(exception):
        raise exception

    try:
        raise exception
    except Exception as e:
        assert e.message
        assert e.status_code

這是我得到的錯誤:

錯誤信息

我的代碼如下所示: main.py

@app.exception_handler(CustomException)
async def custom_exception_handler(request: Request, exc: CustomException):
    log.error(f"{exc}")
    return JSONResponse(
        status_code=exc.status_code_number,
        content=jsonable_encoder({exc.status_code_number: exc.message}),
    )

exceptions.py

class CustomException(Exception):
    """
    All Custom Exceptions are defined in xyz\exceptions.py
    """

    def __init__(self, exception):
        if not check_if_exception_exists(exception):
            raise KeyError(f"Custom Exception: {exception.__class__.__name__} does not exist.")
        self.message = exception.message
        self.status_code_number = exception.status_code_number

您需要在 class 中使用raises ,如下所示:

with pytest.raises(CustomException):

此外,您聲明status_code_number (在 exceptions.py 中),但在測試用例中使用status_code

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM