I'm making an HTTP GET request (with the requests library) that includes basic authentication:
requests.get("https://httpbin.org/get", auth=("fake_username", "fake_password"))
How do I test for the existence of the correct username and password in the request?
Mock the request (with requests-mock), Base64 encode the username and password, and assert (with pytest) on the last_request.headers["Authorization"]
key. For example:
def test_make_request():
with requests_mock.Mocker() as mock_request:
mock_request.get(requests_mock.ANY, text="success!")
requests.get("https://httpbin.org/get", auth=("fake_username", "fake_password"))
encoded_auth = b64encode(b"fake_username:fake_password").decode("ascii")
assert mock_request.last_request.headers["Authorization"] == f"Basic {encoded_auth}"