diff --git a/durga/collection.py b/durga/collection.py index aa88028..d6e5036 100755 --- a/durga/collection.py +++ b/durga/collection.py @@ -78,7 +78,7 @@ def get(self, **kwargs): if count > 1: raise exceptions.MultipleObjectsReturnedError elif count == 0: - raise exceptions.ObjectNotFoundError + raise exceptions.ObjectNotFoundError(self.request, self.response) element = self.elements[0] self._reset_request() return element @@ -133,12 +133,16 @@ def _reset_request(self): def elements(self): if not self._elements: self.response = self.resource.dispatch(self.request) - self.data = self.resource.extract(self.response) - self.validated_data = self.resource.validate(self.data) - if self.as_dict or self.as_list: - self._elements = [self.get_values(data) for data in self.validated_data] + if self.response.status_code == 404: + self._elements = [] else: - self._elements = [self.get_element(data) for data in self.validated_data] + self.data = self.resource.extract(self.response) + self.validated_data = self.resource.validate(self.data) + if self.as_dict or self.as_list: + element_func = self.get_values + else: + element_func = self.get_element + self._elements = [element_func(data) for data in self.validated_data] return self._elements def get_element(self, data): diff --git a/durga/exceptions.py b/durga/exceptions.py index c4b7b9d..b387a18 100644 --- a/durga/exceptions.py +++ b/durga/exceptions.py @@ -5,7 +5,9 @@ class DurgaError(Exception): class ObjectNotFoundError(DurgaError): """The requested object does not exist.""" - pass + def __init__(self, request, response): + self.request = request + self.response = response class MultipleObjectsReturnedError(DurgaError): diff --git a/tests/test_collection.py b/tests/test_collection.py index 04fd916..58833a2 100644 --- a/tests/test_collection.py +++ b/tests/test_collection.py @@ -8,12 +8,21 @@ @pytest.mark.httpretty -@pytest.mark.parametrize('content', ['{}', '[]']) -def test_get_object_not_found(content, resource): - httpretty.register_uri(httpretty.GET, resource.url, body=content, - content_type='application/json') - with pytest.raises(exceptions.ObjectNotFoundError): +@pytest.mark.parametrize('content, content_type, status', [ + ('{}', 'application/json', 200), + ('[]', 'application/json', 200), + ('{"status_code": 404, "message": "Page not found"}', 'application/json', 404), + ("Page not found", 'text/plain', 404), +]) +def test_get_object_not_found(content, content_type, status, resource): + httpretty.register_uri(httpretty.GET, resource.url, body=content, content_type=content_type, + status=status) + with pytest.raises(exceptions.ObjectNotFoundError) as excinfo: resource.collection.get(year=1900) + assert excinfo.value.request.url == resource.url + assert excinfo.value.response.text == content + if content_type.endswith('json') and status == 200: + assert excinfo.value.response.json() == resource.collection.data @pytest.mark.httpretty