Myk*_*lis 3 python unit-testing pytest python-requests
我在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'
Run Code Online (Sandbox Code Playgroud)
但是使用additional_matcher回调来验证请求格式有点可笑,因为它实际上是用来确定是否应完全嘲笑该特定请求调用。如果我没有使用requests-mock,似乎我会做更多的事情:
def test_foo():
# setup api_mock here...
mylibrary_foo()
api_mock.assert_called_with(data='hello')
Run Code Online (Sandbox Code Playgroud)
是否有通常用于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'}
Run Code Online (Sandbox Code Playgroud)