Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert test client data to JSON

I'm building an app and I want to make some tests. I need to convert the response data from the test client to JSON.

The app:

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }
]

app = Flask(__name__, static_url_path="")

@app.route('/myapp/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': [task for task in tasks]})

if __name__ == '__main__':
    app.run(debug=True)

The tests:

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

    def test_empty_url(self):
        response = self.app.get('/myapp/api/v1.0/tasks')
        resp = json.loads(response.data)
        print(resp)

if __name__ == '__main__':
    unittest.main()

When I try to convert response.data to JSON, I get the following error:

TypeError: the JSON object must be str, not 'bytes'

How can I fix this error and get the JSON data?

like image 929
ben-hx Avatar asked Mar 05 '15 15:03

ben-hx


People also ask

What is JSON dump?

The json. dumps() method allows us to convert a python object into an equivalent JSON object. Or in other words to send the data from python to json. The json. dump() method allows us to convert a python object into an equivalent JSON object and store the result into a JSON file at the working directory.

What does Response JSON () do Python?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.


1 Answers

Flask 1.0 adds the get_json method to the response object, similar to the request object. It handles parsing the response data as JSON, or raises an error if it can't.

data = response.get_json()

Prior to that, and prior to Python 3.6, json.loads expects text, but data is bytes. The response object provides the method get_data, with the as_text parameter to control this.

data = json.loads(response.get_data(as_text=True))
like image 57
davidism Avatar answered Sep 22 '22 12:09

davidism