From: Mark McLoughlin Date: Wed, 12 Sep 2012 11:51:23 +0000 (+0100) Subject: Add entity body validation helper X-Git-Url: https://review.fuel-infra.org/gitweb?a=commitdiff_plain;h=3dcb3fdba791639ab3fe7ab20b3398babcd27512;p=openstack-build%2Fcinder-build.git Add entity body validation helper Add a _valid_body() helper for the to avoid repeating the same tests in multiple methods. Include a check that the entity itself is actually a dict. (Cherry-picks part of commit d1ad73ee from Nova) Change-Id: If8114cc76d68567005c85c803f29e30e034db89a --- diff --git a/cinder/api/openstack/wsgi.py b/cinder/api/openstack/wsgi.py index 6463f03fc..fa0baead6 100644 --- a/cinder/api/openstack/wsgi.py +++ b/cinder/api/openstack/wsgi.py @@ -1016,6 +1016,23 @@ class Controller(object): else: self._view_builder = None + @staticmethod + def is_valid_body(body, entity_name): + if not (body and entity_name in body): + return False + + def is_dict(d): + try: + d.get(None) + return True + except AttributeError: + return False + + if not is_dict(body[entity_name]): + return False + + return True + class Fault(webob.exc.HTTPException): """Wrap webob.exc.HTTPException to provide API friendly response.""" diff --git a/cinder/tests/api/openstack/test_wsgi.py b/cinder/tests/api/openstack/test_wsgi.py index 22bf8691e..8792984f9 100644 --- a/cinder/tests/api/openstack/test_wsgi.py +++ b/cinder/tests/api/openstack/test_wsgi.py @@ -828,3 +828,32 @@ class ResponseObjectTest(test.TestCase): self.assertEqual(response.headers['X-header2'], 'header2') self.assertEqual(response.status_int, 202) self.assertEqual(response.body, mtype) + + +class ValidBodyTest(test.TestCase): + + def setUp(self): + super(ValidBodyTest, self).setUp() + self.controller = wsgi.Controller() + + def test_is_valid_body(self): + body = {'foo': {}} + self.assertTrue(self.controller.is_valid_body(body, 'foo')) + + def test_is_valid_body_none(self): + resource = wsgi.Resource(controller=None) + self.assertFalse(self.controller.is_valid_body(None, 'foo')) + + def test_is_valid_body_empty(self): + resource = wsgi.Resource(controller=None) + self.assertFalse(self.controller.is_valid_body({}, 'foo')) + + def test_is_valid_body_no_entity(self): + resource = wsgi.Resource(controller=None) + body = {'bar': {}} + self.assertFalse(self.controller.is_valid_body(body, 'foo')) + + def test_is_valid_body_malformed_entity(self): + resource = wsgi.Resource(controller=None) + body = {'foo': 'bar'} + self.assertFalse(self.controller.is_valid_body(body, 'foo'))