使用request_mock声明HTTP请求的主体

软威利斯

我在pytest中使用requests-mock来方便对我的库进行单元测试,该库使用对API调用的请求

除了模拟服务器响应之外,我经常需要验证我的库是否在HTTP正文中发送了预期的有效负载。

我已经能够做到这一点,尽管是间接的,使用additional_matcher在我的测试中的回调:

def mylibrary_foo():
    """Library method that is under test."""
    r = requests.post('http://example.com/foo', data='hellxo')
    return r.text

@requests_mock.Mocker()
def test_foo(m):
    def matcher(request):
        assert request.body == 'hello'
        return True

    m.post('http://example.com/foo', text='bar', additional_matcher=matcher)

    result = mylibrary_foo()
    assert result == 'bar'

但是,使用additional_matcher回调来验证请求格式确实有点可笑,因为它实际上是用来确定是否应完全嘲笑此特定请求调用。如果我没有使用requests-mock,似乎我会做更多的事情:

def test_foo():
   # setup api_mock here...
   mylibrary_foo()
   api_mock.assert_called_with(data='hello')

是否有通常用于request-mock的模式来支持HTTP请求验证?

艾森耶

在验证请求是否被调用以及参数是什么的过程中,我也没有找到任何模式,但是我做的对您来说可能更可接受

def test_foo(m):
    ...
    adapter = m.post('http://example.com/foo', text='bar')
    result = mylibrary_foo()

    # for `called` or `call_count`
    assert adapter.call_count == 1
    assert adapter.called

    # for more in-depth checking of params/body, you can access `.last_request` and `.request_history` of `adapter`
    assert adapter.last_request.json() == {'foo': 'bar'}
    assert adapter.request_history[-1].json() == {'foo': 'bar'}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章