python - Flask test_client() doesn't have request.authorization with pytest

The credentials for HTTP Basic authentication must have a username and a password separated by a colon. If you're still using python 2, try this:

def test_index(test_client):
    credentials = b64encode(b"test_user:test_password")
    res = test_client.get("/", headers={"Authorization": "Basic {}".format(credentials)})
    assert res.status_code == 200

Python 3 is a little stricter about data sanity, so you have to make sure that the bytes are properly decoded before sending them to the server:

def test_index(test_client):
    credentials = b64encode(b"test_user:test_password").decode('utf-8')
    res = test_client.get("/", headers={"Authorization": f"Basic {credentials}"})
    assert res.status_code == 200

I found this solution. Maybe it can help someone:

from requests.auth import _basic_auth_str
headers = {
   'Authorization': _basic_auth_str(username, password),
}

You just have to use the library 'requests'


from requests.auth import _basic_auth_str
headers = {
   'Authorization': _basic_auth_str(username, password)
}

This works for me on both python 3.6 and 2.7 whereas the following only works for me on 2.7:

res = test_client.get("/", headers={"Authorization": "Basic {user}".format(user=b64encode(b"test_user:test_password"))})