assert_all_mocked wrongly reports a route as not mocked?
ecwootten opened this issue · 4 comments
I'm using respx to mock various http get/post requests for testing, and my tests are all behaving as expected. But when I set assert_all_mocked=True, it asserts that a route is not mocked when I believe it is.
This test demonstrates an equivalent problem:
@respx.mock(assert_all_mocked=True)
def test_me():
myurl = 'http://example.com/test'
myroute = respx.post(myurl)
mocked_response ={ "a": 1 }
myroute.return_value = Response(200, json=mocked_response)
httpx.post(myurl)
It fails with:
respx.models.AllMockedAssertionError: RESPX: <Request('POST', 'http://example.com/test')> not mocked!
However, this test passes:
@respx.mock
def test_me2():
myurl = 'http://example.com/test'
myroute = respx.post(myurl)
mocked_response = {"a": 1}
myroute.return_value = Response(200, json=mocked_response)
response = httpx.post(myurl)
assert response.json() == {"a": 1}
suggesting that the call is mocked.
This test:
@respx.mock(assert_all_mocked=False)
def test_me3():
myurl = 'http://example.com/test'
myroute = respx.post(myurl)
mocked_response = {"a": 1}
myroute.return_value = Response(200, json=mocked_response)
response = httpx.post(myurl)
assert response.json() == {"a": 1}
fails, because assert_all_mocked's automock gets involved, and the POST request returns a Response[200] with no JSON-able data.
Ah, I think this is my misuse of the decorator? My test ought to be:
@respx.mock(assert_all_mocked=True)
def test_me(respx_mock):
myurl = 'http://example.com/test'
myroute = respx_mock.post(myurl)
mocked_response = {"a": 1}
myroute.return_value = Response(200, json=mocked_response)
httpx.post(myurl)
which passes as expected.
Ah, I think this is my misuse of the decorator?
Yep, you spot the issue! When passing args (configuring) to the decorator, you need to add the mocked routes to that router, i.e. using the respx_mock
router given via arg to your test function.
Thanks for bringing up the issue anyways, it can help others bumping in to the same "problem".
Maybe RESPX should fire a warning when the test function is missing the respx_mock
arg.
Thanks - I then fell over this issue https://pythonissues.com/issues/1027354, but switched to the pytest.mark.respx decorator instead and all is well now. A warning could certainly be helpful.
Happy for this to be closed, depending on what you decide about the warning.
I'll open a new issue about the warning, thanks.