首页 > 解决方案 > Pytest 引发不适用于自定义异常

问题描述

我在 exceptions.py 文件中定义了以下内容:

class Error(Exception):
    """Base exception raised by api wrapper"""

    def __init__(self, message: str):
        self.message = message
        super().__init__(self.message)


# HTTP response exceptions
class ApiBadRequestError(Error):
    """Bad Request –- Incorrect parameters."""

    def __init__(self, message: str):
        self.message = message
        super().__init__(self.message)

然后我有一个正确引发ApiBadRequestError异常的函数。

在 pytest 中,我正在执行以下操作:

 def test_handle_request_response_raises_correct_exception_for_response_code(
        self, status_code, exception_type, client, create_response
    ):
        response = create_response(status_code=status_code)

        with pytest.raises(ApiBadRequestError) as e:
            a = client._check_response_codes(response)

测试失败是因为pytest.raises它内部isintance(e, ApiBadRequestError)正在返回 False。但是,如果我将测试更改为以下内容:

 def test_handle_request_response_raises_correct_exception_for_response_code(
        self, status_code, exception_type, client, create_response
    ):
        response = create_response(status_code=status_code)

        with pytest.raises(Exception) as e:
            a = client._check_response_codes(response)

它通过了,因为引发的异常被视为一个实例,Exception即使它是ApiBadRequestError

任何帮助将不胜感激,因为我在这里完全被难住了。

标签: pythonexceptionpytestisinstance

解决方案


推荐阅读