MCPcopy
hub / github.com/pallets/flask / test_json_customization

Function test_json_customization

tests/test_json.py:223–257  ·  view source on GitHub ↗
(app, client)

Source from the content-addressed store, hash-verified

221
222
223def test_json_customization(app, client):
224 class X: # noqa: B903, for Python2 compatibility
225 def __init__(self, val):
226 self.val = val
227
228 def default(o):
229 if isinstance(o, X):
230 return f"<{o.val}>"
231
232 return DefaultJSONProvider.default(o)
233
234 class CustomProvider(DefaultJSONProvider):
235 def object_hook(self, obj):
236 if len(obj) == 1 and "_foo" in obj:
237 return X(obj["_foo"])
238
239 return obj
240
241 def loads(self, s, **kwargs):
242 kwargs.setdefault("object_hook", self.object_hook)
243 return super().loads(s, **kwargs)
244
245 app.json = CustomProvider(app)
246 app.json.default = default
247
248 @app.route("/", methods=["POST"])
249 def index():
250 return flask.json.dumps(flask.request.get_json()["x"])
251
252 rv = client.post(
253 "/",
254 data=flask.json.dumps({"x": {"_foo": 42}}),
255 content_type="application/json",
256 )
257 assert rv.data == b'"<42>"'
258
259
260def _has_encoding(name):

Callers

nothing calls this directly

Calls 3

CustomProviderClass · 0.85
postMethod · 0.45
dumpsMethod · 0.45

Tested by

no test coverage detected