简体   繁体   中英

Flask jsonify boolean response cannot be decoded in unit tests

I am performing tests on my Flask application and I am expecting a json response built with jsonify . I use the ast library to decode the response. But I am getting the following error:

Traceback (most recent call last):
  File "test_index.py", line 177, in test_create_venue
    data = ast.literal_eval(rv.data)
  File "/Users/manuelgodoy/anaconda/lib/python2.7/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/Users/manuelgodoy/anaconda/lib/python2.7/ast.py", line 63, in _convert
    in zip(node.keys, node.values))
  File "/Users/manuelgodoy/anaconda/lib/python2.7/ast.py", line 62, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "/Users/manuelgodoy/anaconda/lib/python2.7/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string

My test function is as follows:

def test_create_venue(self):
    rv = self.app.get("/data_send")
    data = ast.literal_eval(rv.data)
    self.assertTrue(data["Sent"])

And the application's function is:

@app.route('/data_send', methods = ['GET'])
def data_send():
    usr = User.get_by_id(g.user.key.id())
    usr.get_last_order().set_as_posted()
    rest = usr.restaurant
    for c in rest.channel_set():
        try:
            channel.send_message(c.cid, 'ping')
        except:
            return jsonify(Sent = False)
    return jsonify(Sent = True)

Jsonify is sending the following response:

'{\n  "Sent": true\n}'

But ast does not recognize the lower case true as Boolean. Hence, it raises a ValueError .

Any idea how to transform jsonify 's response into a Dict that maintains the Boolean value so I can perform the Boolean assertion?

Don't use literal_eval to load JSON. Ever.

Use Flask's JSON decoder , or the app-specific decoder .

from flask import json
data = json.loads(rv.data)
# or
self.app.json_decoder.decode(rv.data)

Or if you're not using Flask, and need to load JSON, use the built-in module .

import json
data = json.loads(json_data)

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