From 19e2114634c322d5a58f3dd282a3a3cfd0f5aa24 Mon Sep 17 00:00:00 2001 From: Adam Chainz Date: Mon, 21 Nov 2016 13:14:03 +0000 Subject: [PATCH] Fixed #27516 -- Made test client's response.json() cache the parsed JSON. --- django/test/client.py | 14 ++++++++------ tests/test_client_regress/tests.py | 4 ++++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/django/test/client.py b/django/test/client.py index be5b6198bf..d27d462689 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -683,12 +683,14 @@ class Client(RequestFactory): self.cookies = SimpleCookie() def _parse_json(self, response, **extra): - if 'application/json' not in response.get('Content-Type'): - raise ValueError( - 'Content-Type header is "{0}", not "application/json"' - .format(response.get('Content-Type')) - ) - return json.loads(response.content.decode(), **extra) + if not hasattr(response, '_json'): + if 'application/json' not in response.get('Content-Type'): + raise ValueError( + 'Content-Type header is "{0}", not "application/json"' + .format(response.get('Content-Type')) + ) + response._json = json.loads(response.content.decode(), **extra) + return response._json def _handle_redirects(self, response, **extra): "Follows any redirects by requesting responses from the server using GET." diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index 48ce51b091..7a633ee7a3 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -1209,6 +1209,10 @@ class RequestMethodStringDataTests(SimpleTestCase): response = self.client.get('/json_response/') self.assertEqual(response.json(), {'key': 'value'}) + def test_json_multiple_access(self): + response = self.client.get('/json_response/') + self.assertIs(response.json(), response.json()) + def test_json_wrong_header(self): response = self.client.get('/body/') msg = 'Content-Type header is "text/html; charset=utf-8", not "application/json"'