Last active
July 15, 2022 14:56
-
-
Save pgjones/763b6aa223433d06583f to your computer and use it in GitHub Desktop.
A replacement flask test client that allows easy JSON API testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not actual anymore since Flask has the same functionality now.