Pytest引发不适用于自定义异常

2024-10-01 07:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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的实例,它也会传递

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


Tags: selfclientmessageinitpytestresponsedefstatus