【发布时间】:2020-10-26 02:35:59
【问题描述】:
我目前正在为我的 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 方法的标头中,因为 result 似乎是空的。我尝试了一些不同的选项,例如“x-access-token”、“X-Auth”等。但似乎都没有,因为我遇到了同样的错误。
你们知道我的代码有什么问题吗?有人能给我在这个 get() 方法的标头中声明令牌的正确方法吗?我在互联网上查了一下,但找不到任何对我有用的东西......
提前谢谢你!
【问题讨论】: