Colin-b / pytest_httpx

pytest fixture to mock HTTPX
https://colin-b.github.io/pytest_httpx/
MIT License
358 stars 30 forks source link

Matching the `Authorization` header correctly while another parameter doesn't match causes a very confusing error message #106

Closed dolfandringa closed 1 year ago

dolfandringa commented 1 year ago

With the following test, which correctly matches the Authorization header, but with an incorrect url in this case, the non-matching request causes a very confusing error message that seems to suggest the headers are wrong (besides the url also being wrong):

from pytest_httpx import HTTPXMock
import httpx

def test_something(httpx_mock: HTTPXMock):
    httpx_mock.add_response(
        method="GET",
        url="http://www.google.com?q=b",
        match_headers={"Authorization": "Bearer: Something"},
    )
    with httpx.Client() as client:
        client.get(
            "http://www.google.com", headers={"Authorization": "Bearer: Something"}
        )

Running this with pytest results in the following error:

E       httpx.TimeoutException: No response can be found for GET request on http://www.google.com with {} headers amongst:
E       Match GET requests on http://www.google.com?q=b with {'Authorization': 'Bearer: Something'} headers

I was expecting it to fail, but it says with {} header as if no headers were passed in, while they were.

I found out what the issue is: In _explain_that_no_response_was_found it includes if name in expect_headers}. The issue is that in the request, the Authorization header is turned into lowercase. So this ends up on that line as "authorization" not in {"Authorization": "Bearer: Something"}, so it won't display the header.

Colin-b commented 1 year ago

This is actually a more complex issue to tackle, we should match with respect to case. And this is not the case atm. It should be handled in next release.

Colin-b commented 1 year ago

Release 0.24.0 handling headers matching a bit more strictly (and with a better error message) is now available on pypi.