Search code examples
pythonunit-testingrequests-mock

verify auth in python mock_requests lib


I'm creating a unit test making sure my http client is passing auth token correctly. I'm using requests_mock lib

with requests_mock.mock() as m:
    m.get(
        "https://my-endpoint",
        text="{}",
    )
history = m.request_history[0]
assert "Bearer test" == history._request.headers.get("Authorization")

But history._request is a protected member so I'd like to avoid binding to protected members in my code. Is there some more proper way to check Authorization header in requests_mock ?


Solution

  • Rather than using history._request.headers, you can use history.headers.

    For example:

    import requests
    import requests_mock
    
    with requests_mock.mock() as m:
        m.get(
            "https://my-endpoint",
            text="{}",
        )
    
        headers = {'Authorization': 'Bearer test'}
        requests.get('https://my-endpoint', headers=headers)
        history = m.request_history[0]
        assert "Bearer test" == history.headers.get("Authorization")