【问题标题】:Mock wrong JSON response with Pytest to raise simplejson.errors.JSONDecodeError on purpose使用 Pytest 模拟错误的 JSON 响应以故意引发 simplejson.errors.JSONDecodeError
【发布时间】:2020-10-23 11:18:11
【问题描述】:

我想用 Pytest 测试异常。我发送一个 HTTP 请求并得到响应。我希望响应损坏,因此 response.json() 转到 except 块。以下是示例。

发送请求,接收响应:

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() 在模拟中失败?

【问题讨论】:

  • @mock.patch.object(Service, 'send_message_json', side_effect=JSONDecodeError)
  • @hoefling 使用这种方法我在想,无论我对函数做了什么更改,它都会抛出这个错误。因此,例如,如果我对这个不应该通过的方法 send_message_json() 进行更改,side_effect 是否仍然会抛出一个不会抛出的错误??

标签: python unit-testing exception mocking pytest


【解决方案1】:

我通过模拟实际请求的响应来解决这个问题。

  1. 在原始问题中有 send_message_json() 方法。
  2. 它调用返回 requests.Response 的 send_message() 方法。所以我模拟了 send_message() 的返回值,它也是一个模拟,而不是 send_message_json():
@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
  1. 错误的模拟 requests.Response 在 send_message_json() 中的 mocked_response.json() 处失败并引发 simplejson.errors.JSONDecodeError

【讨论】:

  • 这个 Response() 来自哪个库?
  • @Learner 来自requests
猜你喜欢
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 2014-02-02
  • 1970-01-01
相关资源
最近更新 更多