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
Provenance
- Commit
3dc84ec- Tree
620ed60- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
f2c8540- Parent 2
a4f0f19
4 files changed+95 added−39 removed
modified:flask/json/__init__.py+62 added-32 removed
87 unmodified lines88 functions of this module but also :attr:`~flask.Request`.89 """90 91 92-def _dump_arg_defaults(kwargs):92+def _dump_arg_defaults(kwargs, app=None):93 """Inject default arguments for dump functions."""94+ if app is None:95+ app = current_app96+94- 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 )102 102- if not current_app.config['JSON_AS_ASCII']:103+ if not app.config['JSON_AS_ASCII']:104 kwargs.setdefault('ensure_ascii', False)105 105- 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)110 111 111-def _load_arg_defaults(kwargs):112+def _load_arg_defaults(kwargs, app=None):113 """Inject default arguments for load functions."""114+ if app is None:115+ app = current_app116+113- 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 lines167 168 return 'utf-8'169 170 167-def 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.171+def 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`.176 172- 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.180+181+ :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`.186+187+ .. versionchanged:: 1.0.3188+189+ ``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 rv198 199 185-def dump(obj, fp, **kwargs):200+def 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)207 208 194-def 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.209+def 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`.214+215+ 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.218+219+ :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`.224+225+ .. versionchanged:: 1.0.3226+227+ ``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)237 238 208-def load(fp, **kwargs):209- """Like :func:`loads` but reads from a file object.210- """211- _load_arg_defaults(kwargs)239+def 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 linesmodified:flask/testing.py+3 added-7 removed
71 unmodified lines72 if url.query:73 sep = b'?' if isinstance(url.query, bytes) else '?'74 path += sep + url.query75 76+ # 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)80 81- # push a context so flask.json can use app's json attributes82- with app.app_context():83- kwargs['data'] = json_dumps(kwargs.pop('json'))84-81 if 'content_type' not in kwargs:82 kwargs['content_type'] = 'application/json'83 84 return EnvironBuilder(path, base_url, *args, **kwargs)162 unmodified linesmodified:tests/test_testing.py+27 added
12 unmodified lines13 14 import flask15 import werkzeug16 17+from flask import appcontext_popped18 from flask._compat import text_type19 from flask.cli import ScriptInfo20 from flask.json import jsonify21 from flask.testing import make_test_environ_builder, FlaskCliRunner22 23+try:24+ import blinker25+except ImportError:26+ blinker = None27 28+29 def test_environ_defaults_from_config(app, client):30 app.config['SERVER_NAME'] = 'example.com:1234'31 app.config['APPLICATION_ROOT'] = '/foo'32 278 unmodified lines311 assert rv.is_json312 assert rv.get_json() == json_data313 314 315+@pytest.mark.skipif(blinker is None, reason="blinker is not installed")316+def 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"])320+321+ class Namespace(object):322+ count = 0323+324+ def add(self, app):325+ self.count += 1326+327+ ns = Namespace()328+329+ with appcontext_popped.connected_to(ns.add, app):330+ rv = client.post("/hello", json={"name": "Flask"})331+332+ assert rv.get_data(as_text=True) == "Hello, Flask!"333+ assert ns.count == 1334+335+336 def test_subdomain():337 app = flask.Flask(__name__, subdomain_matching=True)338 app.config['SERVER_NAME'] = 'example.com'339 client = app.test_client()74 unmodified linesmodified:CHANGES.rst+3 added
21 unmodified lines22 - 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`_)28 29 .. _#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/298635 36 898 unmodified lines