【问题标题】:Assert body of HTTP requests using requests_mock使用 requests_mock 断言 HTTP 请求的主体
【发布时间】:2017-12-08 23:53:39
【问题描述】:

我正在使用 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 回调来验证请求格式感觉有点好笑,因为它实际上是为了确定这个特定的请求调用是否应该被模拟。如果我不使用 requests-mock,我似乎会做一些类似的事情:

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

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

【问题讨论】:

    标签: python unit-testing python-requests pytest


    【解决方案1】:

    我也没有发现任何模式来验证是否调用了请求或参数是什么,但我所做的可能对你来说更容易接受

    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'}
    

    【讨论】:

    猜你喜欢
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2014-01-25
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多