Python 测试 - 属性错误:'NoneType'对象没有属性'status_code'



在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'
#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

最新更新