Skip to content

Commit

Permalink
Merge pull request #1260 from c4ffein/test-response-data
Browse files Browse the repository at this point in the history
DRF-style data property for responses in tests
  • Loading branch information
vitalik authored Aug 12, 2024
2 parents 6de2bdc + a4f9b6c commit d7d25a6
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions docs/docs/guides/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
7 changes: 7 additions & 0 deletions ninja/testing/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down
1 change: 1 addition & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down

0 comments on commit d7d25a6

Please sign in to comment.