diff --git a/docs/docs/guides/testing.md b/docs/docs/guides/testing.md index 8d9f203c..9686cb05 100644 --- a/docs/docs/guides/testing.md +++ b/docs/docs/guides/testing.md @@ -33,6 +33,11 @@ class HelloTest(TestCase): self.assertEqual(response.json(), {"msg": "Hello World"}) ``` +It is also possible to access the deserialized data using the `data` property: +```python + self.assertEqual(response.data, {"msg": "Hello World"}) +``` + Arbitrary attributes can be added to the request object by passing keyword arguments to the client request methods: ```python class HelloTest(TestCase): diff --git a/ninja/testing/client.py b/ninja/testing/client.py index 88291122..8a3cbcd7 100644 --- a/ninja/testing/client.py +++ b/ninja/testing/client.py @@ -189,10 +189,17 @@ def __init__(self, http_response: Union[HttpResponse, StreamingHttpResponse]): self.content = b"".join(http_response.streaming_content) # type: ignore else: self.content = http_response.content # type: ignore[union-attr] + self._data = None def json(self) -> Any: return json_loads(self.content) + @property + def data(self) -> Any: + if self._data is None: # Recomputes if json() is None but cheap then + self._data = self.json() + return self._data + def __getitem__(self, key: str) -> Any: return self._response[key] diff --git a/tests/test_response.py b/tests/test_response.py index 5504e51e..6b234a6c 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -117,6 +117,7 @@ def test_responses(path, expected_response): response = client.get(path) assert response.status_code == 200, response.content assert response.json() == expected_response + assert response.data == response.data == expected_response # Ensures cache works def test_validates():