Python 2.7:使用模拟库进行单元测试异常时出错

时间:2016-07-31 01:08:40

标签: python unit-testing exception mocking

我正在为_make_post_request类的以下方法APIClient编写单元测试。但是我在为这种特殊方法编写单元测试时遇到了问题。此方法调用另外两个方法,其中一个方法引发异常。我正在尝试mock两个方法并断言异常正在被提出。

我无法理解如何以正确的顺序模拟两个方法,即同时requests.post_raise_exception。另外,我如何验证确实在测试中引发了异常。

我正在测试的情况是,当回复status_code不是200时,APIRequestError方法会引发_raise_exception异常。

import requests

class APIClient:

    def _make_post_request(self, url, data=None, headers=None):
        try:
            resp = requests.post(url, data=data, headers=headers)
            if resp.status_code == 200:
                return resp
            else:
                self._raise_exception(resp)
        except requests.exceptions.ConnectionError:
            print("Connection Error")
        except requests.exceptions.Timeout:
            ......

    @staticmethod
    def _raise_exception(resp):
        status_code = resp.status_code
        error_code = resp.headers['Error-Code']
        error_msg = resp.headers['Error']
        raise APIRequestError(status_code, error_code, error_msg)

这是我到目前为止所尝试的内容。但是这个测试失败了。

import unittest
import mock

class APITest(unittest.TestCase):

    def setUp(self):
        api = APIClient()

    @mock.patch.object(APIClient, '_raise_exception')
    @mock.patch('APIClient.api.requests.post')
    def test_make_post_request_raise_exception(self, resp, exception):

        resp.return_value = mock.Mock(status_code=500, headers={
                                 'Error-Code': 128, 'Error':'Error'})

        e = APIRequestError(500, 128, 'Error')
        exception.side_effect = e

        req_respone = self.api._make_post_request(url='http://exmaple.com')


        exception_response = self.api._raise_exception(req_response)

        # NOW WHAT TO DO HERE?
        # self.assertRaises(??, ??)
        self.assertRaises(e, exception) # this results in error
        self.assertEqual('', exception_response) # this also results in error

这是追溯:

Traceback (most recent call last):
File ".../venv/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File ".../api/tests/test_api.py", line 82, in test_make_post_request_raise_exception
req_respone = self.api._make_post_request(url='http://example.com')
File "api/apiclient/api.py", line 52, in _make_post_request
self._raise_exception(resp)
File ".../venv/local/lib/python2.7/site-packages/mock/mock.py", line 1062, in __call__
return _mock_self._mock_call(*args, **kwargs)
File ".../venv/local/lib/python2.7/site-packages/mock/mock.py", line 1118, in _mock_call
raise effect
APIRequestError

任何人都可以解释一下这个错误的可能原因是什么?哪种方法调用可能出错?

0 个答案:

没有答案