首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >用Pytest模拟错误的JSON响应以故意提高simplejson.errors.JSONDecodeError

用Pytest模拟错误的JSON响应以故意提高simplejson.errors.JSONDecodeError
EN

Stack Overflow用户
提问于 2020-10-23 11:18:11
回答 1查看 1.3K关注 0票数 0

我想用Pytest测试异常。我发送一个HTTP请求并得到一个响应。我希望响应被破坏,因此response.json()将转到the块。下面是例子。

发送请求,收到回复:

代码语言:javascript
代码运行次数:0
运行
复制
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。

代码语言:javascript
代码运行次数:0
运行
复制
@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()在模拟中失败?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-23 12:00:02

我是通过嘲笑实际请求的反应才弄明白的。

  1. 在最初的问题中有send_message_json()方法,
  2. ,它调用返回requests.Response的send_message()方法。因此,我模拟了send_message()的返回值,它也是一个模拟值,而不是send_message

代码语言:javascript
代码运行次数:0
运行
复制
@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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64498985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档