在werkzeug test_client get方法的标头中传递JWT令牌

时间:2020-09-16 17:04:58

标签: python flask jwt werkzeug

我目前正在为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()方法的标头中声明令牌吗?我检查了互联网,但找不到适合我的任何东西...

提前谢谢!

1 个答案:

答案 0 :(得分:1)

因此,我找到了解决问题的方法。我使用flask-jwt-extended模块重写了端点。它使用Bearer令牌标头,因此我的测试现在易于编写并且全部通过!