【发布时间】: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