如何使用requests-mock测试多个json响应



我正在使用pytest模块创建一些单元测试,并请求mock来模拟请求的Response对象。我有以下pytest夹具

@pytest.fixture(scope="function")
def mock_response(requests_mock):
test_url = "https://dummy/"
test_json = [{"Name": "TheName"}, {"Name": "TheOtherName"}]
requests_mock.get(test_url, json=test_json, status_code=200)
resp = requests.get(test_url)
return resp

以及以下单元测试

def test_get_product_list(mocker, mock_response):
with requests_mock.Mocker() as m:
ret_val = mock_response
mocker.patch("path_to_function.function_with_request",
return_value=ret_val)
val = function_with_request(123)
assert val == ["TheName", "TheOtherName"]

function_with_request进行API调用,然后解析Response以生成具有Name密钥的值列表

我想用test_json的几个不同值来运行这个测试。我研究了参数化的固定装置,但我看到的例子似乎都不符合我想要的。

这个问题有点老,但我遇到这个问题是因为我完全误读了请求mock文档。(facepalm(虽然最初的Q可能与fixture有关,正如一位评论人士所指出的,可以通过参数化来解决,但我的答案是关于mock和JSON的请求。

根据请求模拟文档,它说:

通过在列表中指定关键字参数,可以提供多个响应以按顺序返回。如果列表已用完,则将继续返回最后一个响应。

示例使用适配器样式:

adapter.register_uri('GET', 'mock://test.com/4', [{'text': 'resp1', 'status_code': 300},
{'text': 'resp2', 'status_code': 200}])

让我感到困惑的是,在字典响应列表中,您必须调用'json'作为关键字。

在JSON的情况下,您将对代码执行以下操作:

@pytest.fixture(scope="function")
def mock_response(requests_mock):
test_url = "https://dummy/"
# assuming you want the first time to return 'TheName' 
# and the 2nd time to return 'TheOtherName'
requests_mock.get(
test_url, 
[
{'json': {"Name": "TheName"}, 'status_code': 200},
{'json': {"Name": "TheOtherName"}, 'status_code': 200}
]
)
resp = requests.get(test_url)
return resp

最新更新