【问题标题】:Python test - AttributeError: 'NoneType' object has no attribute 'status_code'Python 测试 - AttributeError:“NoneType”对象没有属性“status_code”
【发布时间】:2021-06-02 12:52:14
【问题描述】:

在 python 中编写了一些单元测试,已将其简化为一些函数以专注于该问题

所以2个函数是这个

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'

【问题讨论】:

    标签: python unit-testing error-handling mocking pytest


    【解决方案1】:
    #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
    

    【讨论】:

    • 抱歉没有真正关注,我从请求导入 HTTPError 导入
    • 另外我在代码中发现了错误,所以我无法以这种方式进行测试?
    • 在这种情况下,您的错误可能在这里发生,因为 HTTPError 没有响应属性。打印(HTTPError.response.status_code)回溯(最近一次调用)文件“”,第 1 行,在 属性错误:类型对象 'HTTPError' 没有属性 'response'
    • 您可以尝试在 except 块内打印异常( print(exception))。httperror 也没有响应,并且您打了一个小错字,“status_code”中的代码带有's' 它是 status_codes .. httperror 也没有 status_codes 。您可以通过请求模块调用它来使用状态代码.. requests.status_codes..
    • 在这种情况下,您将不得不参考其他地方。如果我知道“外部服务”,这对我来说很容易。不管怎样,感谢你们互动得这么好。这是我在stackoverflow上的第一个答案。如果你支持它会很好(新手的期望..:))..
    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2017-10-05
    • 2018-03-17
    • 2019-01-10
    相关资源
    最近更新 更多