简体   繁体   English

如何测试 Fastapi 异常处理程序

[英]How to test Fastapi Exception Handler

I created a custom exception handler and wanted to write test cases for it.我创建了一个自定义异常处理程序并想为它编写测试用例。

This is my Testcase:这是我的测试用例:

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

This is the error I get:这是我得到的错误:

错误信息

My Code looks like this: main.py我的代码如下所示: 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

You need to use raises in the class, like this:您需要在 class 中使用raises ,如下所示:

with pytest.raises(CustomException):

Also, you declare status_code_number (in exceptions.py), but use status_code in test case.此外,您声明status_code_number (在 exceptions.py 中),但在测试用例中使用status_code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM