I'm creating a Flask app with JWT Authorization and trying to test services with PyTest.
I successfully added tests to endpoints, but when I trying to add unit tests for certain function I can't access current user, because flask_jwt_extended.get_current_user()
returns None.
Here is simple example:
@api.route('/listings', methods=['POST'])
@jwt_required
def create_listing():
payload = request.json
listing = listing_svc.create(payload)
return listing
def create(payload):
listing = ListingSchema().load(payload, db.session).data
class ListingSchema(ModelSchema):
id = field_for(Project, 'id', dump_only=True)
creator_user_id = field_for(Project, 'creator_user_id')
# ...
@pre_load
def set_creator_id(self, data):
current_user = flask_jwt_extended.get_current_user()
data['creator_user_id'] = current_user.id
It works when I authorize and send a request using app_context:
with client.application.app_context():
rv = client.post('/listings',
# ...
)
But what I need is to test create
function without sending a request to client. In this case flask_jwt_extended.get_current_user()
returns None, so I think I should set request context some way before running this function.
I tried to do this...
fake_payload = {}
with client.application.test_request_context('/listings', headers={'Authorization': 'Bearer ' + access_token}):
create(fake_payload)
but still getting current_user
is None
This is how I get token:
def login(email, password):
user = get_by_email(email)
if user and check_password_hash(user.password, password):
return access_token = flask_jwt_extended.create_access_token(identity=email)