【问题标题】:Mock requests exception not being thrown by side_effect模拟请求异常没有被 side_effect 抛出
【发布时间】:2016-09-15 17:46:20
【问题描述】:

所以我正在尝试测试异常处理代码,但 side_effect 无法正常工作。打印的输出显示它正在调用,但 raise_for_status 没有正确地在 side_effect 中抛出异常。为什么没有抛出异常?

更新:好的,不知道为什么会这样,但至少它确实使它落到了右边,除了。我将其更改为使用 patch.object 并为 side_effect 提供了模拟 raise_for_status 和模拟获取对象 HTTPError()。这让它下降到正确的 except 块中,但根据单元测试它仍然没有抛出异常。

这是位于 test_package 中的代码 test_src.py:

import requests
import sys
import traceback

def test_requests_function():
 try:
   response = requests.get('https://google.com/api/test', verify=False)
   response.raise_for_status()
   return response.json()
 except requests.exceptions.RequestException as error:
   return_message = "Exception: {0}".format(str(error))
   return {'return_code' : 500, 'message' : return_message, 'traceback' : traceback.format_exc()}
 except:
   return_message = "Unknown Exception: {0}".format(str(sys.exc_info()[0]))
   return {'return_code' : 500, 'message' : return_message, 'traceback' : traceback.format_exc()}

这是测试代码:

import unittest
from pprint import pprint
import mock
import requests

from test_package import test_src

class TestRequestTestCase(unittest.TestCase):
  @mock.patch.object(requests, 'get')
  def test_request_exception(self, mock_get):
    http_error = requests.exceptions.HTTPError('Unable to connect')
    mock_raise_for_status = mock.Mock(side_effect=http_error)
    mock_get.raise_for_status = mock_raise_for_status
    mock_get.side_effect = http_error

    return_json = test_src.test_requests_function()
    print "\nMock_Get:"
    print id(mock_get)
    pprint(mock_get.__dict__)
    print "\nMock_Raise_For_Status:"
    print id(mock_raise_for_status)
    pprint(mock_raise_for_status.__dict__)
    print "\n"
    pprint(return_json)

所以输出是:

{'message': 'Exception: Unable to connect',
 'return_code': 500,
 'traceback': 'Traceback (most recent call last):\n  File "/Users/yshaban/test/test_package/test_src.py", line 8, in test_requests_function\n    response = requests.get(\'https://google.com/api/test\', verify=False)\n  File "/Users/yshaban/test/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__\n    return _mock_self._mock_call(*args, **kwargs)\n  File "/Users/yshaban/test/lib/python2.7/site-packages/mock/mock.py", line 1118, in _mock_call\n    raise effect\nHTTPError: Unable to connect\n'
}

======================================================================

FAIL: test_request_exception (__main__.TestRequestTestCase)

----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/yshaban/test/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "unit_tests.py", line 36, in test_request_exception
    pprint(return_json)
AssertionError: RequestException not raised

----------------------------------------------------------------------

【问题讨论】:

  • 我不知道测试框架是如何工作的,response 是模拟测试对象吗?如果是,您确定 IT 不处理异常吗?我在第三个输出部分注意到_mock_side_effect 是HTTPError()。
  • 我注意到的另一件事...输出显示 requests.exceptions.HTTPError 是一个未知异常,所以可能与它有关?

标签: python exception testing mocking python-requests


【解决方案1】:

您似乎在修补错误的对象。您应该修补test_src.requests 中的get 函数。将装饰器更改(不要移动)为:

@mock.patch.object(test_src.requests, 'get')

【讨论】:

    猜你喜欢
    • 2019-08-30
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多