How to send requests with JSONs in unit tests

前端 未结 2 602
挽巷
挽巷 2020-12-04 22:59

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()

相关标签:
2条回答
  • 2020-12-04 23:32

    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.

    0 讨论(0)
  • 2020-12-04 23:33

    UPDATE: Since Flask 1.0 released flask.testing.FlaskClient methods accepts json argument and Response.get_json method added, see example.

    for Flask 0.x you may use receipt below:

    from flask import Flask, Response as BaseResponse, json
    from flask.testing import FlaskClient
    from werkzeug.utils import cached_property
    
    
    class Response(BaseResponse):
        @cached_property
        def 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
    
    0 讨论(0)
提交回复
热议问题