Skip to content
Myr

JSON support for the Flask test client

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Adam Byrtek · committed by Markus Unterwaditzer · parent 0f1cf50 · Browse files · 2 files+28 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+28 added−1 removed

  • tests:+14 added−0 removed
  • other:+14 added−1 removed

2 files+28 added−1 removed

modified:flask/testing.py+14 added-1 removed
11 unmodified lines
1213from contextlib import contextmanager14from werkzeug.test import Client, EnvironBuilder15from flask import _request_ctx_stack16from flask.json import dumps as json_dumps1718try:19 from werkzeug.urls import url_parse20except ImportError:21 from urlparse import urlsplit as url_parse222323def make_test_environ_builder(app, path='/', base_url=None, *args, **kwargs):24def make_test_environ_builder(app, path='/', base_url=None, json=None, *args, **kwargs):25 """Creates a new test builder with some application defaults thrown in."""26 http_host = app.config.get('SERVER_NAME')27 app_root = app.config.get('APPLICATION_ROOT')28 if base_url is None:
4 unmodified lines
33 if url.netloc:34 path = url.path35 if url.query:36 path += '?' + url.query3738 if json:39 if 'data' in kwargs:40 raise RuntimeError('Client cannot provide both `json` and `data`')41 kwargs['data'] = json_dumps(json)4243 # Only set Content-Type when not explicitly provided44 if 'Content-Type' not in kwargs.get('headers', {}):45 new_headers = kwargs.get('headers', {}).copy()46 new_headers['Content-Type'] = 'application/json'47 kwargs['headers'] = new_headers4849 return EnvironBuilder(path, base_url, *args, **kwargs)505152class FlaskClient(Client):
90 unmodified lines
modified:tests/test_testing.py+14 added
201 unmodified lines
202 assert rv.status_code == 200203 assert 'gin' in flask.request.form204 assert 'vodka' in flask.request.args205206def test_json_request():207 app = flask.Flask(__name__)208 app.testing = True209210 @app.route('/api', methods=['POST'])211 def api():212 return ''213214 with app.test_client() as c:215 json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}216 rv = c.post('/api', json=json_data)217 assert rv.status_code == 200218 assert flask.request.get_json() == json_data219220def test_subdomain():221 app = flask.Flask(__name__)222 app.config['SERVER_NAME'] = 'example.com'223 @app.route('/', subdomain='<company_id>')
27 unmodified lines