I'm creating some unit tests using the pytest module and requests-mock for mocking the Response object for requests. I have the following pytest fixture
@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
and the following unit test
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"]
The function_with_request
makes an API call and then parses the Response
to make a list of values with the Name
key
I want to run this test with a few different values for test_json
. I looked into parameterized fixtures, but none of the examples I saw seemed to match what I'm looking for.
This question's a bit old but I encountered this issue because I completely misread the requests-mock docs. (facepalm) While the original Q might be related to fixtures, which is solvable with parametrizing it as one commented noted, my answer is about requests-mock and JSON, explicitly.
From the requests-mock docs it says:
Multiple responses can be provided to be returned in order by specifying the keyword parameters in a list. If the list is exhausted then the last response will continue to be returned.
The example uses the adapter style:
adapter.register_uri('GET', 'mock://test.com/4', [{'text': 'resp1', 'status_code': 300},
{'text': 'resp2', 'status_code': 200}])
What threw me off was that you have to call 'json'
as the key, in the list of dictionary responses.
In the case of JSON, you'd do the following for your code:
@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