简体   繁体   English

如何使用REST API + Flask JWT Extended正确测试应用程序?

[英]How to properly test an app with REST API + Flask JWT extended?

Assuming that I have an API endpoint, whose resources are accessible to authorised users only who possess a valid access token, similar with this: 假设我有一个API端点,只有拥有有效访问令牌的授权用户才能访问其资源,类似于以下内容:

from flask_restful import Resource
from flask_jwt_extended import jwt_required

class Collection(Resource):

    @jwt_required
    def get(self):
        """
        GET response implementation here.
        """
        # Queries and logic here
        data = 10
        if(is_everythig_ok()):
            return {"data": data}, 200
        else:
            return {"message":"Failed to get data."}, 400

And assuming that there is a LoginUser endpoint which returns a valid access_token, how can I write some unit tests to reproduce the two status codes (200 for success and 400 for failure) while user HAS a valid access token AND also the case when the user DOES NOT have a valid access_token. 并假设有一个LoginUser端点返回一个有效的access_token,那么当用户具有有效的访问令牌时,我该如何编写一些单元测试来重现两个状态代码(成功的200和失败的400)以及用户的情况。没有有效的access_token。

I have test my endpoints with POSTMAN and it seems ok, but I also need to write some unit tests for proof. 我已经用POSTMAN测试了端点,这似乎还可以,但是我还需要编写一些单元测试来证明。 So, what is the proper way of doing that? 那么,这样做的正确方法是什么?

Since this is an API, what you really want are integration tests. 由于这是一个API,因此您真正想要的是集成测试。 The way I do this, is like this: 我这样做的方式是这样的:

  1. create a test user 创建一个测试用户
  2. request a valid token 要求有效的令牌
  3. access a protected resource with the valid token 使用有效令牌访问受保护的资源
  4. access the resource with an invalid token 使用无效令牌访问资源
  5. any other tests making sure you cover every method in every controller. 确保您涵盖每个控制器中的每个方法的任何其他测试。
  6. remove the test user 删除测试用户

You will end up with a lot of integration tests which you can automate, postman is great at this, you can build collections for every endpoint and run them easily. 您将最终获得许多可以自动化的集成测试,postman擅长于此,您可以为每个端点构建集合并轻松运行它们。

More than this, you can start measuring how long each request takes to execute and can start looking at those which take too long. 不仅如此,您还可以开始衡量每个请求执行的时间,并开始查看花费太长时间的请求。

Unit test the logic inside your methods, but not your authorization system, not your endpoints and not your controllers. 对方法内部的逻辑进行单元测试,但不对授权系统,对端点和控制器进行逻辑单元测试。 Those you integration test. 那些您进行集成测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM