Repository: OnroerendErfgoed/pyramid_urireferencer

Issue:
Error message when a backend application can't be reached
When a service is not reachable for the uriregistry.

AS IS:
HTTPInternalServerError: Urireferencer: Something went wrong while retrieving references of the uri https://id.erfgoed.net/besluiten/1

TO BE:
HTTP 503 Service Unavailable: Urireferencer: Something went wrong while retrieving references of the uri https://id.erfgoed.net/test/1. Application A not reachable. 


Discussion:

Patch:
diff --git a/CHANGES.rst b/CHANGES.rst
index 72b550b..195a2b5 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -5,6 +5,7 @@
 - Some minor doc fixes
 - Changed an edge case where `items` or `applications` response attributes could
   be `None` so that they are now always empty lists. (#6)
+- Updated error message and added JSON error message when a backend application can't be reached (#9) and when a resource can't be deleted (#10)
 
 0.4.0 (2015-07-10)
 ------------------
diff --git a/pyramid_urireferencer/models.py b/pyramid_urireferencer/models.py
index 067dd57..8ce334b 100644
--- a/pyramid_urireferencer/models.py
+++ b/pyramid_urireferencer/models.py
@@ -94,7 +94,7 @@ class ApplicationResponse:
             "success": self.success,
             "has_references": self.has_references,
             "count": self.count,
-            "items": [item.to_json() for item in self.items]
+            "items": [item.to_json() for item in self.items] if self.items else []
         }
 
 
diff --git a/pyramid_urireferencer/protected_resources.py b/pyramid_urireferencer/protected_resources.py
index db4556a..d54efaa 100644
--- a/pyramid_urireferencer/protected_resources.py
+++ b/pyramid_urireferencer/protected_resources.py
@@ -50,8 +50,8 @@ def protected_operation(fn):
                                     app_response.count,
                                     ', '.join([i.uri for i in app_response.items]))
                         response_json["errors"].append(error_string)
-                        response.json_body = response_json
-                        response.content_type = 'application/json'
+                    response.json_body = response_json
+                    response.content_type = 'application/json'
                 return response
             else:
                 raise HTTPConflict(
@@ -60,8 +60,26 @@ def protected_operation(fn):
                                    ', '.join([app_response.title for app_response in registery_response.applications
                                               if app_response.has_references])))
         elif not registery_response.success:
-            raise HTTPInternalServerError(
-                    detail="Urireferencer: Something went wrong while retrieving references of the uri {0}".format(uri))
+            if parent_object.request.headers.get("Accept", None) == "application/json":
+                response = Response()
+                response.status_code = 500
+                response_json = {
+                    "message": "Unable to verify the uri {0} is no longer being used.".format(uri),
+                    "errors": [],
+                    "registry_response": registery_response.to_json()
+                }
+                for app_response in registery_response.applications:
+                    if not app_response.success:
+                        response_json["errors"].append(
+                            "{}: Could not verify the uri is no longer being used.".format(app_response.uri))
+                response.json_body = response_json
+                response.content_type = 'application/json'
+                return response
+            else:
+                raise HTTPInternalServerError(
+                        detail="Urireferencer: Unable to verify the uri {0} is no longer being used. Could not verify with {1}".
+                            format(uri, ', '.join([app_response.uri for app_response
+                                                   in registery_response.applications if not app_response.success])))
         return fn(parent_object, *args, **kw)
 
     return advice


Test patch:
diff --git a/tests/test_protected_resources.py b/tests/test_protected_resources.py
index 1989235..81972ee 100644
--- a/tests/test_protected_resources.py
+++ b/tests/test_protected_resources.py
@@ -29,6 +29,18 @@ def get_app(nr):
     return a
 
 
+def get_app_500():
+    return ApplicationResponse(
+        title='App',
+        uri="https://dev-app.onroerenderfgoed.be/",
+        service_url="https://dev-app.onroerenderfgoed.be/references",
+        success=False,
+        has_references=None,
+        count=None,
+        items=None
+    )
+
+
 class DummyParent(object):
     def __init__(self):
         self.request = testing.DummyRequest()
@@ -96,7 +108,25 @@ class ProtectedTests(unittest.TestCase):
     def test_protected_operation_500(self, is_referenced_mock):
         dummy = DummyParent()
         is_referenced_mock.return_value = RegistryResponse('https://id.erfgoed.net/resources/1', False, None, None,
-                                                           None)
+                                                           [get_app_500()])
         self.assertRaises(HTTPInternalServerError, dummy.protected_dummy)
         is_referenced_call = is_referenced_mock.mock_calls[0]
         self.assertEqual('https://id.erfgoed.net/resources/1', is_referenced_call[1][0])
+
+    @patch('pyramid_urireferencer.protected_resources.pyramid_urireferencer.Referencer.is_referenced')
+    def test_protected_operation_500_json(self, is_referenced_mock):
+        dummy = DummyParent()
+        dummy.request.headers = {"Accept": "application/json"}
+        is_referenced_mock.return_value = RegistryResponse('https://id.erfgoed.net/resources/1', False, None, None,
+                                                           [get_app_500()])
+        res = dummy.protected_dummy()
+        self.assertEqual(500, res.status_code)
+        self.assertEqual(res.json_body["message"],
+                         "Unable to verify the uri https://id.erfgoed.net/resources/1 is no longer being used.")
+        self.assertListEqual(res.json_body["errors"],
+                             ["https://dev-app.onroerenderfgoed.be/: Could not verify the uri is no longer being used."])
+        self.assertEqual("application/json", res.content_type)
+
+        is_referenced_call = is_referenced_mock.mock_calls[0]
+        self.assertEqual('https://id.erfgoed.net/resources/1', is_referenced_call[1][0])
+