Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python 3.x - Python3 PyTest Flask JWT throws HTTP 422 Unprocessable Entity

I am using Python 3.9 and the Flask-JWT-Extended PyPi package in my application. I am writing some test cases and when I POST to the endpoint I am testing with a proper-looking Bearer token, I get an HTTP 422 'Unprocessable Entity'. Google is not turning up an answer. How can I fix this?

# Do the Bearer login
data = {
    'username': app.username,
    'password': app.password,
}
tokenResponse = client.post("/login", json=data)
assert tokenResponse.content_type == 'application/json'
assert tokenResponse.json['access_token']

And shortly after, in the same test method, I try to POST to the actual endpoint:

print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print({"Authorization": f"JWT {tokenResponse.json['access_token']}"})
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

response = client.post(endpoint, buffered=False,
                               content_type='multipart/form-data',
                               data=data,headers={"Authorization": f"JWT {tokenResponse.json['access_token']}"})

Here is the token printout:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{'Authorization': 'JWT eyJ0eXAiOiJKV1QilCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MTI0Nzk5NzAsIm5iZiI6MTYxMjQ3OTk3MCwianRpIjoiYTQyZjU1NmUtYjQ2MS00NTNiLThkM2ItYjk1MmIzYzAwZjc0IiwiZXhwIjoxNjeyNDgwMDMwLCJpZGVudGl0eSI6IlNlbnNvbml4QXBpVXNlciIsImZyZXNoIjpmYWxzZSwidHlwZSI6ImFjY2VzcyJ9.IYrgg2e9VxhLFH0_kwQbmoHKI1wKsKfm3cpK3XZmqyY'}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the traceback.

            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
            print({"Authorization": f"JWT {tokenResponse.json['access_token']}"})
            print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    
            response = client.post(endpoint, buffered=False,
                                       content_type='multipart/form-data',
                                       data=data,headers={"Authorization": f"JWT {tokenResponse.json['access_token']}"})
>           assert response.status_code == 200
E           assert 422 == 200
E            +  where 422 = <Response streamed [422 UNPROCESSABLE ENTITY]>.status_code

../tests/test_endpoints.py:153: AssertionError
question from:https://stackoverflow.com/questions/66055485/python3-pytest-flask-jwt-throws-http-422-unprocessable-entity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First suggestion, if you look at the response.get_json() it should give you a helpful error message for why the 422 was thrown (invalid audience, jwt verification failed, etc). That might help point you in the right direction.

Here is an example of a working spec that creates and passes a JWT in via headers if it helps:

import pytest

from flask import Flask
from flask import  jsonify

from flask_jwt_extended import JWTManager
from flask_jwt_extended import jwt_required
from flask_jwt_extended import create_access_token


@pytest.fixture(scope="function")
def app():
    app = Flask(__name__)
    app.config["JWT_SECRET_KEY"] = "foobarbaz"
    JWTManager(app)

    @app.route("/login", methods=["POST"])
    def login():
        return jsonify(access_token=create_access_token("test_user"))

    @app.route("/protected", methods=["GET"])
    @jwt_required
    def access_protected():
        return jsonify(foo="bar")

    return app


def test_default_headers(app):
    test_client = app.test_client()

    response = test_client.post("/login")
    access_token = response.get_json()["access_token"]

    access_headers = {"Authorization": "Bearer {}".format(access_token)}
    response = test_client.get("/protected", headers=access_headers)
    assert response.status_code == 200
    assert response.get_json() == {"foo": "bar"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...