How to send requests with JSON in unit tests

Question:

I have code within a Flask application that uses JSONs in the request, and I can get the JSON object like so:

Request = request.get_json()

This has been working fine, however I am trying to create unit tests using Python’s unittest module and I’m having difficulty finding a way to send a JSON with the request.

response=self.app.post('/test_function', 
                       data=json.dumps(dict(foo = 'bar')))

This gives me:

>>> request.get_data()
'{"foo": "bar"}'
>>> request.get_json()
None

Flask seems to have a JSON argument where you can set json=dict(foo=’bar’) within the post request, but I don’t know how to do that with the unittest module.

Asked By: Sepehr Nazari

||

Answers:

Changing the post to

response=self.app.post('/test_function', 
                       data=json.dumps(dict(foo='bar')),
                       content_type='application/json')

fixed it.

Thanks to user3012759.

Answered By: Sepehr Nazari

Since Flask 1.0 release flask.testing.FlaskClient methods accepts json argument and Response.get_json method added, see pull request

    with app.test_client() as c:
        rv = c.post('/api/auth', json={
            'username': 'flask', 'password': 'secret'
        })
        json_data = rv.get_json()

For Flask 0.x compatibility you may use receipt below:

    from flask import Flask, Response as BaseResponse, json
    from flask.testing import FlaskClient
    
    
    class Response(BaseResponse):
        def get_json(self):
            return json.loads(self.data)
    
    
    class TestClient(FlaskClient):
        def open(self, *args, **kwargs):
            if 'json' in kwargs:
                kwargs['data'] = json.dumps(kwargs.pop('json'))
                kwargs['content_type'] = 'application/json'
            return super(TestClient, self).open(*args, **kwargs)
    

    app = Flask(__name__)
    app.response_class = Response
    app.test_client_class = TestClient
    app.testing = True
Answered By: Victor Gavro
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.