From 505b8c16d7859b9a771ff60a631db1a186354e76 Mon Sep 17 00:00:00 2001 From: Satellite QE <115476073+Satellite-QE@users.noreply.github.com> Date: Thu, 30 May 2024 04:42:12 -0400 Subject: [PATCH] Add json response to entity creation error message (#1134) * Makes the error message information more detailed and informative * Possibility to write more precise assertions Signed-off-by: dosas (cherry picked from commit 95b3ce10125cfbc8d9a6d8a8e2b38a5007dd1b16) Co-authored-by: dosas --- nailgun/entity_mixins.py | 8 +++++++- tests/test_entity_mixins.py | 23 ++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/nailgun/entity_mixins.py b/nailgun/entity_mixins.py index d83cc1e0..06c1a1ea 100644 --- a/nailgun/entity_mixins.py +++ b/nailgun/entity_mixins.py @@ -11,6 +11,7 @@ from fauxfactory import gen_choice from inflection import pluralize +from requests.exceptions import HTTPError, JSONDecodeError from nailgun import client, config from nailgun.entity_fields import IntegerField, ListField, OneToManyField, OneToOneField @@ -949,7 +950,12 @@ def create_json(self, create_missing=None): """ response = self.create_raw(create_missing) - response.raise_for_status() + try: + response.raise_for_status() + except HTTPError as e: + with contextlib.suppress(JSONDecodeError): + e.args += (response.json(),) + raise e return response.json() def create(self, create_missing=None): diff --git a/tests/test_entity_mixins.py b/tests/test_entity_mixins.py index 97f8a8bd..2776c0f5 100644 --- a/tests/test_entity_mixins.py +++ b/tests/test_entity_mixins.py @@ -3,7 +3,7 @@ from unittest import TestCase, mock from fauxfactory import gen_integer -from requests.exceptions import HTTPError +from requests.exceptions import HTTPError, JSONDecodeError from nailgun import client, config, entity_mixins from nailgun.entity_fields import ( @@ -621,6 +621,27 @@ def test_create_json(self): self.assertEqual(response.raise_for_status.call_count, 1) self.assertEqual(response.json.call_count, 1) + def test_create_json_with_exception(self): + """Check what happens if the server returns an error HTTP status code for :meth:`nailgun.entity_mixins.EntityCreateMixin.create_json`.""" + for valid_json in (True, False): + response = mock.Mock() + return_value = {"a": "b"} + response.raise_for_status.side_effect = HTTPError("foo") + if valid_json: + response.json.return_value = return_value + else: + response.json.side_effect = JSONDecodeError("msg", "foo", 2) + with mock.patch.object( + self.entity, 'create_raw', return_value=response + ), self.assertRaises(HTTPError) as error: + self.entity.create_json() + self.assertEqual(response.raise_for_status.call_count, 1) + self.assertEqual(response.json.call_count, 1) + if valid_json: + self.assertEqual(error.exception.args[1], return_value) + else: + self.assertEqual(len(error.exception.args), 1) + def test_create(self): """Test :meth:`nailgun.entity_mixins.EntityCreateMixin.create`."""