在 werkzeug test_client get 方法的 header 中传递 JWT 令牌
Passing JWT token in the header of werkzeug test_client get method
我目前正在为我的 Flask REST API 编写单元测试。我正在测试的端点需要一个令牌,我成功地从另一个端点获取了该令牌。将此标记传递给 test_client.get()
方法时,出现无法解决的错误。
这是我的单元测试代码:
def test_get_all_users(self):
# encoding credentials of a user inserted in setup method of test class
credentials = b64encode(b"user1@mail.com: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
# ...
被测端点代码:
@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})
当我运行测试时,出现以下错误:
============================================================================= 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"user1@mail.com: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'
我很确定错误出在 get 方法的 headers 中,因为 result
似乎是空的。我尝试了几个不同的选项,例如 'x-access-token'、'X-Auth' 等。但是 none 似乎有效,因为我遇到了同样的错误。
你们知道我的代码有什么问题吗?有人可以给我在这个 get() 方法的 headers 中声明令牌的正确方法吗?我上网查了一下,但找不到适合我的东西...
提前致谢!
所以我找到了解决问题的方法。我使用 flask-jwt-extended 模块重写了端点。它使用 Bearer 令牌 headers 所以我的测试现在很容易编写并且全部通过!
我目前正在为我的 Flask REST API 编写单元测试。我正在测试的端点需要一个令牌,我成功地从另一个端点获取了该令牌。将此标记传递给 test_client.get()
方法时,出现无法解决的错误。
这是我的单元测试代码:
def test_get_all_users(self):
# encoding credentials of a user inserted in setup method of test class
credentials = b64encode(b"user1@mail.com: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
# ...
被测端点代码:
@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})
当我运行测试时,出现以下错误:
============================================================================= 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"user1@mail.com: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'
我很确定错误出在 get 方法的 headers 中,因为 result
似乎是空的。我尝试了几个不同的选项,例如 'x-access-token'、'X-Auth' 等。但是 none 似乎有效,因为我遇到了同样的错误。
你们知道我的代码有什么问题吗?有人可以给我在这个 get() 方法的 headers 中声明令牌的正确方法吗?我上网查了一下,但找不到适合我的东西...
提前致谢!
所以我找到了解决问题的方法。我使用 flask-jwt-extended 模块重写了端点。它使用 Bearer 令牌 headers 所以我的测试现在很容易编写并且全部通过!