Alex M981
Alex M981

Reputation: 2374

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 ?

Upvotes: 2

Views: 1843

Answers (1)

Adam Dangoor
Adam Dangoor

Reputation: 436

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")

Upvotes: 1

Related Questions