Skip to content
Myr

Merge pull request #3206 from pallets/test-client-json

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

don't push app context for test client json

authored by David Lord · committed by GitHub · parents f2c8540, a4f0f19 · Browse files · 4 files+95 added−39 removed
This commit

State

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

Diff stats

4 files+95 added−39 removed

  • tests:+27 added−0 removed
  • other:+68 added−39 removed

4 files+95 added−39 removed

modified:flask/json/__init__.py+62 added-32 removed
87 unmodified lines
88 functions of this module but also :attr:`~flask.Request`.89 """909192def _dump_arg_defaults(kwargs):92def _dump_arg_defaults(kwargs, app=None):93 """Inject default arguments for dump functions."""94 if app is None:95 app = current_app9694 if current_app:95 bp = current_app.blueprints.get(request.blueprint) if request else None97 if app:98 bp = app.blueprints.get(request.blueprint) if request else None99 kwargs.setdefault(97 'cls',98 bp.json_encoder if bp and bp.json_encoder99 else current_app.json_encoder100 'cls', bp.json_encoder if bp and bp.json_encoder else app.json_encoder101 )102102 if not current_app.config['JSON_AS_ASCII']:103 if not app.config['JSON_AS_ASCII']:104 kwargs.setdefault('ensure_ascii', False)105105 kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])106 kwargs.setdefault('sort_keys', app.config['JSON_SORT_KEYS'])107 else:108 kwargs.setdefault('sort_keys', True)109 kwargs.setdefault('cls', JSONEncoder)110111111def _load_arg_defaults(kwargs):112def _load_arg_defaults(kwargs, app=None):113 """Inject default arguments for load functions."""114 if app is None:115 app = current_app116113 if current_app:114 bp = current_app.blueprints.get(request.blueprint) if request else None117 if app:118 bp = app.blueprints.get(request.blueprint) if request else None119 kwargs.setdefault(120 'cls',121 bp.json_decoder if bp and bp.json_decoder118 else current_app.json_decoder122 else app.json_decoder123 )124 else:125 kwargs.setdefault('cls', JSONDecoder)126
40 unmodified lines
167168 return 'utf-8'169170167def dumps(obj, **kwargs):168 """Serialize ``obj`` to a JSON formatted ``str`` by using the application's169 configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an170 application on the stack.171def dumps(obj, app=None, **kwargs):172 """Serialize ``obj`` to a JSON-formatted string. If there is an173 app context pushed, use the current app's configured encoder174 (:attr:`~flask.Flask.json_encoder`), or fall back to the default175 :class:`JSONEncoder`.176172 This function can return ``unicode`` strings or ascii-only bytestrings by173 default which coerce into unicode strings automatically. That behavior by174 default is controlled by the ``JSON_AS_ASCII`` configuration variable175 and can be overridden by the simplejson ``ensure_ascii`` parameter.177 Takes the same arguments as the built-in :func:`json.dumps`, and178 does some extra configuration based on the application. If the179 simplejson package is installed, it is preferred.180181 :param obj: Object to serialize to JSON.182 :param app: App instance to use to configure the JSON encoder.183 Uses ``current_app`` if not given, and falls back to the default184 encoder when not in an app context.185 :param kwargs: Extra arguments passed to :func:`json.dumps`.186187 .. versionchanged:: 1.0.3188189 ``app`` can be passed directly, rather than requiring an app190 context for configuration.191 """177 _dump_arg_defaults(kwargs)192 _dump_arg_defaults(kwargs, app=app)193 encoding = kwargs.pop('encoding', None)194 rv = _json.dumps(obj, **kwargs)195 if encoding is not None and isinstance(rv, text_type):196 rv = rv.encode(encoding)197 return rv198199185def dump(obj, fp, **kwargs):200def dump(obj, fp, app=None, **kwargs):201 """Like :func:`dumps` but writes into a file object."""187 _dump_arg_defaults(kwargs)202 _dump_arg_defaults(kwargs, app=app)203 encoding = kwargs.pop('encoding', None)204 if encoding is not None:205 fp = _wrap_writer_for_text(fp, encoding)206 _json.dump(obj, fp, **kwargs)207208194def loads(s, **kwargs):195 """Unserialize a JSON object from a string ``s`` by using the application's196 configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an197 application on the stack.209def loads(s, app=None, **kwargs):210 """Deserialize an object from a JSON-formatted string ``s``. If211 there is an app context pushed, use the current app's configured212 decoder (:attr:`~flask.Flask.json_decoder`), or fall back to the213 default :class:`JSONDecoder`.214215 Takes the same arguments as the built-in :func:`json.loads`, and216 does some extra configuration based on the application. If the217 simplejson package is installed, it is preferred.218219 :param s: JSON string to deserialize.220 :param app: App instance to use to configure the JSON decoder.221 Uses ``current_app`` if not given, and falls back to the default222 encoder when not in an app context.223 :param kwargs: Extra arguments passed to :func:`json.dumps`.224225 .. versionchanged:: 1.0.3226227 ``app`` can be passed directly, rather than requiring an app228 context for configuration.229 """199 _load_arg_defaults(kwargs)230 _load_arg_defaults(kwargs, app=app)231 if isinstance(s, bytes):232 encoding = kwargs.pop('encoding', None)233 if encoding is None:234 encoding = detect_encoding(s)235 s = s.decode(encoding)236 return _json.loads(s, **kwargs)237238208def load(fp, **kwargs):209 """Like :func:`loads` but reads from a file object.210 """211 _load_arg_defaults(kwargs)239def load(fp, app=None, **kwargs):240 """Like :func:`loads` but reads from a file object."""241 _load_arg_defaults(kwargs, app=app)242 if not PY2:243 fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')244 return _json.load(fp, **kwargs)245
112 unmodified lines
modified:flask/testing.py+3 added-7 removed
71 unmodified lines
72 if url.query:73 sep = b'?' if isinstance(url.query, bytes) else '?'74 path += sep + url.query7576 # TODO use EnvironBuilder.json_dumps once we require Werkzeug 0.1577 if 'json' in kwargs:77 assert 'data' not in kwargs, (78 "Client cannot provide both 'json' and 'data'."79 )78 assert 'data' not in kwargs, "Client cannot provide both 'json' and 'data'."79 kwargs['data'] = json_dumps(kwargs.pop('json'), app=app)8081 # push a context so flask.json can use app's json attributes82 with app.app_context():83 kwargs['data'] = json_dumps(kwargs.pop('json'))8481 if 'content_type' not in kwargs:82 kwargs['content_type'] = 'application/json'8384 return EnvironBuilder(path, base_url, *args, **kwargs)
162 unmodified lines
modified:tests/test_testing.py+27 added
12 unmodified lines
1314import flask15import werkzeug1617from flask import appcontext_popped18from flask._compat import text_type19from flask.cli import ScriptInfo20from flask.json import jsonify21from flask.testing import make_test_environ_builder, FlaskCliRunner2223try:24 import blinker25except ImportError:26 blinker = None272829def test_environ_defaults_from_config(app, client):30 app.config['SERVER_NAME'] = 'example.com:1234'31 app.config['APPLICATION_ROOT'] = '/foo'32
278 unmodified lines
311 assert rv.is_json312 assert rv.get_json() == json_data313314315@pytest.mark.skipif(blinker is None, reason="blinker is not installed")316def test_client_json_no_app_context(app, client):317 @app.route("/hello", methods=["POST"])318 def hello():319 return "Hello, {}!".format(flask.request.json["name"])320321 class Namespace(object):322 count = 0323324 def add(self, app):325 self.count += 1326327 ns = Namespace()328329 with appcontext_popped.connected_to(ns.add, app):330 rv = client.post("/hello", json={"name": "Flask"})331332 assert rv.get_data(as_text=True) == "Hello, Flask!"333 assert ns.count == 1334335336def test_subdomain():337 app = flask.Flask(__name__, subdomain_matching=True)338 app.config['SERVER_NAME'] = 'example.com'339 client = app.test_client()
74 unmodified lines
modified:CHANGES.rst+3 added
21 unmodified lines
22- A catch-all error handler registered for ``HTTPException`` will not23 handle ``RoutingExcpetion``, which is used internally during24 routing. This fixes the unexpected behavior that had been introduced25 in 1.0. (`#2986`_)26- Passing the ``json`` argument to ``app.test_client`` does not27 push/pop an extra app context. (`#2900`_)2829.. _#2766: https://github.com/pallets/flask/issues/276630.. _#2765: https://github.com/pallets/flask/pull/276531.. _#2825: https://github.com/pallets/flask/pull/282532.. _#2900: https://github.com/pallets/flask/issues/290033.. _#2933: https://github.com/pallets/flask/issues/293334.. _#2986: https://github.com/pallets/flask/pull/29863536
898 unmodified lines