Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a unit test to check the response of an API made in Flask? [duplicate]

Tags:

python

flask

I'm trying to test a JSON API I implemented in Flask

Here's my view function

@app.route("/dummy")
def dummy(): 
    return {"dummy":"dummy-value"}

And in my Unittest I'm testing using

def setUp(self):
    self.app = my_app.app.test_client()

def test_dummy(self):
     response = self.app.get("/dummy")
     self.assertEqual(response['dummy'], "dummy-value")

However, when I ran it, I get the error TypeError: 'dict' object is not callable

like image 915
SpaceMonkey Avatar asked Jul 07 '16 23:07

SpaceMonkey


1 Answers

Using jsonify() fixes the error 'dict' object is not callable

from flask import jsonify
@app.route("/dummy")
def dummy(): 
    return jsonify({"dummy":"dummy-value"})

And for the test, you'll have to pull the JSON out of the HTTP response

import json

class MyAppCase(unittest.TestCase):
    def setUp(self):
        my_app.app.config['TESTING'] = True
        self.app = my_app.app.test_client()

    def test_dummy(self):
        response = self.app.get("/dummy")
        data = json.loads(response.get_data(as_text=True))

        self.assertEqual(data['dummy'], "dummy-value")

This now runs for me.

like image 52
bakkal Avatar answered Sep 30 '22 21:09

bakkal