我想用Pytest测试异常。我发送一个HTTP请求并得到一个响应。我希望响应被破坏,因此response.json()将转到the块。下面是例子。
发送请求,收到回复:
def send_message_json():
# ...
try:
response = cls.send_message(method, url, **kwargs)
if response:
return response.json() # this is what should fail
except simplejson.errors.JSONDecodeError as err:
raise err # this is to be achieved
单元测试应该断言应该引发simplejson.errors.JSONDecodeError。
@mock.patch.object(Service, 'send_message_json')
def test_send_message_json_exception(mock_send):
svc = Service()
with pytest.raises(simplejson.errors.JSONDecodeError): # this should assert the exceptions was raised
svc.send_message_json("GET", 'http://my.url/')
我无法激活pytest.mock.object引发的异常。是什么使.json()在模拟中失败?
发布于 2020-10-23 12:00:02
我是通过嘲笑实际请求的反应才弄明白的。
@mock.patch.object(Service, 'send_message') # mock send_message instead
def test_send_message_json_exception(mock_send):
svc = Service()
mocked_response = Response()
mocked_response.status_code = 200
mocked_response.data = '<!doctype html>' # so this is obviously not a JSON
mock_send.return_value = mocked_response # apply the mocked response here
with pytest.raises(simplejson.errors.JSONDecodeError):
svc.send_message_json("GET", 'http://my.url/') # this calls send_message() and returns a bad mocked requests.Response
坏的模拟simplejson.errors.JSONDecodeError在send_message_json()中的mocked_response.json()处失败,并引发mocked_response.json
https://stackoverflow.com/questions/64498985
复制相似问题