How to send requests with JSONs in unit tests

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.


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