模拟请求side_effect不抛出异常

时间:2016-05-19 02:53:34

标签: python exception testing mocking python-requests

所以我试图测试异常处理代码并且side_effect无法正常工作。打印输出显示正在进行调用,但raise_for_status未正确地在side_effect中抛出异常。为什么不抛出异常?

更新:好的,不知道为什么会这样,但它至少会让它落到右边,除了。我将其更改为使用patch.object,并为side_effect提供了模拟raise_for_status和mock get对象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)

所以ouptut是:

{'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

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

1 个答案:

答案 0 :(得分:0)

好像你正在修补错误的对象。您应修补get中的test_src.requests功能。将装饰器更改(不要移动)到:

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