9

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

SpaceMonkey
  • 93
  • 1
  • 1
  • 3

2 Answers2

24

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.

bakkal
  • 54,350
  • 12
  • 131
  • 107
  • in mine the `app` does not have a get attribute, how do I do a test response in unittest, this is my project structure ` ├───.idea │ └───inspectionProfiles ├───project │ └───__pycache__ └───tests ` – perymerdeka Mar 04 '21 at 05:44
-2

You should return a string, not a dictionary object!

@app.route("/dummy")
def dummy(): 
    return flask.jsonify(dummy="dummy-value")

And in your test, parse the JSON using json.loads(..) and then assert.

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104