Reputation: 136
I am currently writing unit tests for my Flask REST API. The endpoint I am testing requires a token which I successfully fetch from another endpoint. When passing this token to the test_client.get()
method, I get an error that I can't solve.
Here is the code of my unit test:
def test_get_all_users(self):
# encoding credentials of a user inserted in setup method of test class
credentials = b64encode(b"[email protected]:1234").decode('utf-8')
# fetch the token using test_client().get()
# note: self.test_api is my werkzeug test_client() instantiated beforehand
result = json.loads(self.test_api.get("/users/api/v1/token", headers={"Authorization": f"Basic {credentials}"}).data)
# encode the token so I can pass it to the get method
token_encoded = b64encode(bytes(result['token'], 'utf-8')).decode('utf-8')
# error happens at the next line because of headers?
result = json.loads(self.test_api.get("/users/api/v1/user", headers={"Authorization": f"JWT {token_encoded}"}).data)
assert result.status_code == 200
# ...
The code of the tested endpoint:
@api.route("/users/api/v1/user", methods=['GET'])
@token_required
def get_all_users(token):
""" Function for retrieving all users in db """
# checking if current user role is valid
output = []
# fetching all users
users = User.query.all()
# building output dict
for user in users:
output.append(dict(user))
return jsonify({'users' : output})
When I run the test, I get the following error:
============================================================================= FAILURES ==============================================================================
____________________________________________________________________ TestUser.test_get_all_users ____________________________________________________________________
self = <api.tests.test_users.TestUser testMethod=test_get_all_users>
def test_get_all_users(self):
# nominal test
credentials = b64encode(b"[email protected]:1234").decode('utf-8')
result = json.loads(self.test_api.get("/users/api/v1/token", headers={"Authorization": f"Basic {credentials}"}).data)
print(result['token'])
#token_encoded = bytes(result['token'], 'utf-8')
token_encoded = b64encode(bytes(result['token'], 'utf-8')).decode('utf-8')
result = json.loads(self.test_api.get("/users/api/v1/user", headers={"Authorization": f"JWT {token_encoded}"}).data)
> assert result.status_code == 200
E AttributeError: 'dict' object has no attribute 'status_code'
api/tests/test_users.py:83: AttributeError
====================================================================== short test summary info ======================================================================
FAILED api/tests/test_users.py::TestUser::test_get_all_users - AttributeError: 'dict' object has no attribute 'status_code'
I'm pretty sure the error is in the headers of the get method because result
seems to be empty. I tried a few different options such as 'x-access-token', 'X-Auth', etc.. but none seemed to work as I got the same error.
Do you guys have any idea about what's wrong in my code? Could someone give me the correct way of declaring a token in the headers of this get() method? I checked on the internet but couldn't find anything that worked for me...
Thank you in advance!
Upvotes: 0
Views: 669
Reputation: 136
So I kind of found a way to address my problem. I rewrote the endpoints using flask-jwt-extended module. It uses Bearer token headers so my tests are now easy to write and all passing!
Upvotes: 1