Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem when getting 'Authorization' header on test Flask application with FlaskClient

I'm testing my Flask application using FlaskClient, in order to avoid to run a Flask server always when I'm testing my application.

I've created a 'sign_in' view that returns an 'Authorization' header with a encrypted token when the user logs successfully in my front-end.

This view works normally in a normal environment, it returns the 'Authorization' header correctly, however when I'm testing this view, inside the test environment, it does not return the 'Authorization' header. The view returns None in 'Authorization' header.

I've already tried some solutions on the internet, such as to add self.app.config['TESTING'] = True in my test case, but the terminal raises an error 'FlaskClient' object has no attribute 'config' that I've already tried to look for a solution, but without success.

I would like to know what may be happening.

Does anyone know any solution for this question?

I send my code below for analysis.

Thank you in advance.

view.py

@app.route("/sign_in", methods = ["POST"])
def sign_in():
    ...

    username, password = ...

    try:
        encoded_jwt_token = auth_login(username, password)
    except UserDoesNotExistException as error:
        return str(error), error.status_code

    resp = Response("Returned Token")
    resp.headers['Authorization'] = encoded_jwt_token

    return resp

test.py

class TestAPIAuthLogin(TestCase):

    def setUp(self):
        self.app = catalog_app.test_client()
        # self.app.config['TESTING'] = True  # config does not exist

    def test_get_api_auth_login_user_test(self):
        username = "test"
        password = get_string_in_hash_sha512("test")
        authorization = 'Basic ' + get_string_in_base64(username + ":" + password)

        headers = {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Authorization': authorization
        }

        response = self.app.get('/sign_in', headers=headers)
        # it returns None 
        authorization = response.headers.get("Authorization")

        self.assertIsNotNone(authorization)
        self.assertNotEqual(authorization, "")
like image 536
rmmariano Avatar asked Sep 04 '26 10:09

rmmariano


1 Answers

I believe this may be to do with the way HTTP requests process headers, where they capitalise them and add HTTP_ as a prefix. Try changing your header to HTTP_AUTHORIZATION instead of just Authorization, since the test client will not be setting this properly.

like image 124
Kathy Rindhoops Avatar answered Sep 06 '26 23:09

Kathy Rindhoops



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!