使用requests_mock断言HTTP请求的主体

问题描述 投票:1回答:1

我正在使用requests-mock和pytest来促进我的库的单元测试,它使用requests进行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回调来验证请求格式感觉有点好笑,因为它确实是为了确定是否应该嘲笑这个特定的请求调用。如果我没有使用请求 - 模拟,似乎我会做更像的事情:

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

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

python unit-testing python-requests pytest
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.