简体   繁体   中英

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:

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.

I have test my endpoints with POSTMAN and it seems ok, but I also need to write some unit tests for proof. So, what is the proper way of doing that?

Since this is an API, what you really want are integration tests. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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