简体   繁体   中英

Unit tests for flask API routes

I'm building a simple flask API and i'm fairly new to it, I already have about 8 routes in /my_app_name/main/controllers.py and I would like to write unit tests for them. Some of these routes use json received in the body of the request to do something:

@main.route('/update_account', methods=['POST'])
def update_account():

    """Updates an account in the DB."""

    ##########################################
    # gets the item

    item = request.json

    # code to add to the DB

    return "Success!"

How do I write a unit test for this? Also what would be the right directory to put the tests on?

You can get the answer for Q1 in Flask's documentation for testing . To be specific, there is a chapter called Testing JSON APIs .

As of Q2, a typical structure may like this:

| my_app_pkg
| tests
| setup.py

There are many ways you can do that;

one could be creating a models file and include classes to contain all the data and 
logic you have included in the update route.So in your  unittests file you import 
those modals and test for the functions....In your routes you could just call for the 
results from the modals

Also you can just import your main into your tsts file and start with something like this

 res = self.client().post('/update_account', data={[the json your api takes]}
    self.assertEqual(res.status_code, 201)

@Christopher Kaggwa,我们应该如何在此处创建客户端..是我们的原始应用需要为此运行还是由unittest托管虚拟应用?

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