Skip to content

Instantly share code, notes, and snippets.

@pgjones
Last active July 15, 2022 14:56
Show Gist options
  • Save pgjones/763b6aa223433d06583f to your computer and use it in GitHub Desktop.
Save pgjones/763b6aa223433d06583f to your computer and use it in GitHub Desktop.
A replacement flask test client that allows easy JSON API testing
import json
from flask.testing import FlaskClient
from flask.wrappers import Response
class JSONResponseWrapper(Response):
"""Extends the BaseResponse to add a get_json method.
This should be used as the response wrapper in the TestClient.
"""
def get_json(self):
"""Return the json decoded content."""
return json.loads(self.get_data(as_text=True))
class JSONTestClient(FlaskClient):
"""Extends the FlaskClient request methods by adding json support.
This should be used like so::
app.test_client_class = JSONTestClient
client = app.test_client()
client.post(url, json=data)
Note that this class will override any response_wrapper you wish to use.
"""
def __init__(self, *args, **kwargs):
"""This ensures the response_wrapper is JSONResponseWrapper."""
super(JSONTestClient, self).__init__(args[0], response_wrapper=JSONResponseWrapper, **kwargs)
def open(self, *args, **kwargs):
json_data = kwargs.pop('json', None)
if json_data is not None:
if 'data' in kwargs:
raise ValueError('Use either `json` or `data`, not both.')
if 'content_type' not in kwargs:
kwargs['content_type'] = 'application/json'
kwargs['data'] = json.dumps(json_data)
return super(JSONTestClient, self).open(*args, **kwargs)
@belkka
Copy link

belkka commented Aug 26, 2018

This is not actual anymore since Flask has the same functionality now.

json – If given, this is serialized as JSON and passed as data. Also defaults content_type to application/json.
http://flask.pocoo.org/docs/1.0/api/#flask.Flask.test_request_context

Changed in version 1.0: JSON support is added to the response, like the request. This is useful when testing to get the test client response data as JSON.
http://flask.pocoo.org/docs/1.0/api/#flask.Response

@erm3nda
Copy link

erm3nda commented Oct 12, 2020

flask.pocoo.org domain not working anymore, the new one is https://flask.palletsprojects.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment