Python测试属性错误:“非类型”对象没有属性“状态\代码”

2024-04-24 16:02:03 发布

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

用python编写一些单元测试,已经将其简化为一些函数来关注这个问题

这是两个函数

def function_to_throw_http_error():
    logger.info("function_to_throw_http_error")


def function_to_catch_http_error():
    try:
        function_to_throw_http_error()
    except HTTPError as http_err:
        logger.error(f"HTTP error occurred external service: {http_err}")
        return {"statusCode": http_err.response.status_code, "body": http_err.response.reason}

这是什么

    @patch(
        "functions.my_file.function_to_throw_http_error", Mock(side_effect=HTTPError(Mock(status_code=404), 'error')),
    )
    def test_catching_http_error_reposnse(self):
        response = function_to_catch_http_error()
        self.assertTrue('error' in str(response))

但是当我运行测试时,我得到了以下错误

>           return {"statusCode": http_err.response.status_code, "body": http_err.response.reason}
E           AttributeError: 'NoneType' object has no attribute 'status_code'

Tags: to函数httpreturnresponsedefstatuscode
1条回答
网友
1楼 · 发布于 2024-04-24 16:02:03
#the builtins module itself has no HTTPError as default class
import builtins
print(dir(builtins))
#just printing out the exception classes from buitins directory

''''['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError']'''

# so in order to use HTTPError use the requests module

import requests
try:
    #your required code
    pass
except requests.HTTPError as exception:
    #print your exception using print(exception)
    pass

相关问题 更多 >