Python 2.7:使用模拟库的单元测试异常出错
我正在为Python 2.7:使用模拟库的单元测试异常出错,python,unit-testing,exception,mocking,Python,Unit Testing,Exception,Mocking,我正在为APIClient类的以下方法编写单元测试\u make\u post\u request。但我在为这种特殊方法编写单元测试时遇到了问题。此方法调用另外两个方法,其中一个方法引发异常。我试图mock这两个方法,并断言异常正在引发 我无法理解如何以正确的顺序模拟这两种方法,即请求。同时发布和引发异常。另外,我如何验证测试中是否确实引发了异常 我正在测试的情况是,当响应状态\u code不是200时,通过\u raise\u exception方法引发apirestError异常 impor
APIClient
类的以下方法编写单元测试\u make\u post\u request
。但我在为这种特殊方法编写单元测试时遇到了问题。此方法调用另外两个方法,其中一个方法引发异常。我试图mock
这两个方法,并断言异常正在引发
我无法理解如何以正确的顺序模拟这两种方法,即请求。同时发布和引发异常。另外,我如何验证测试中是否确实引发了异常
我正在测试的情况是,当响应状态\u code
不是200
时,通过\u raise\u exception
方法引发apirestError
异常
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
有人能解释一下这个错误的可能原因吗?哪个方法调用可能出错 你是想把状态代码模拟成500,并且不希望出现异常吗?@IndraUprade不,我是在模拟状态代码500。将提出一个例外,这就是我所期望的。但是我如何为整个序列编写测试,即请求返回500=>\u raise\u exception
调用=>APIRequestError
exception-raised。尝试将测试用例放在try-catch块下,捕获异常并断言it@IndraUprade对不起,我听不懂。你是说如果resp.status\u code==200,我应该替换:返回resp else:
用try-catch阻塞,还是我应该在测试中引入try-catch(这不是一个好主意)?你能通过回答给出一个例子吗?不,你的测试课