Merge "Add combine_url test for restcall.py"
authorLiang Ke <lokyse@163.com>
Fri, 23 Mar 2018 02:19:55 +0000 (02:19 +0000)
committerGerrit Code Review <gerrit@onap.org>
Fri, 23 Mar 2018 02:19:55 +0000 (02:19 +0000)
multivimbroker/multivimbroker/api_v2/api_router/v0_controller.py
multivimbroker/multivimbroker/forwarder/views.py
multivimbroker/multivimbroker/tests/test_check_capacity.py

index 10922e5..83b4260 100644 (file)
 #    See the License for the specific language governing permissions and
 #    limitations under the License.
 
+import logging
 import pecan
 
 from multivimbroker.swagger import utils
+from multivimbroker.pub import exceptions
+from multivimbroker.pub.utils import restcall
+from multivimbroker.pub.utils import syscomm
+
+
+logger = logging.getLogger(__name__)
+
+# TODO: Move to a constant file.
+REGISTRY_URI = "registry"
+UNREGISTRY_URI = ""
+IDENTITY_URI = "identity/v3"
+IDENTITY_AUTH_URI = "identity/v3/auth/tokens"
 
 
 class V0_Controller(object):
@@ -20,3 +33,57 @@ class V0_Controller(object):
     @pecan.expose('json', route="swagger.json")
     def swagger_json(self):
         return utils.get_swagger_json_data()
+
+    def _filter_illegal_uri(self, uri, method):
+        """
+        Filter unsupported actions, so they can be stopped at begginning.
+        """
+
+        if uri == REGISTRY_URI and method != "POST":
+            pecan.abort(405)
+
+        if uri == UNREGISTRY_URI and method != "DELETE":
+            pecan.abort(405)
+
+        if (uri in (IDENTITY_URI, IDENTITY_AUTH_URI) and
+                method not in ("POST", "GET")):
+            pecan.abort(405)
+
+    @pecan.expose()
+    def _route(self, remainder, request):
+        uri = "/".join(remainder[1:])
+        method = request.method
+        self._filter_illegal_uri(uri, method)
+
+        return self.forwarder, remainder
+
+    @pecan.expose('json')
+    def forwarder(self, *remainder, **kwargs):
+        """ Forward any requests that don't have a specific match """
+
+        # TODO(xiaohhui): Add validator for vim_id.
+        vim_id = remainder[0]
+        request = pecan.request
+        try:
+            vim_url = syscomm.getMultivimDriver(vim_id,
+                                                full_path=request.path)
+
+            # NOTE: Not sure headers should be set here. According to original
+            # code, headers are discarded.
+            retcode, content, status_code, resp = restcall.req_by_msb(
+                vim_url, request.method, content=request.body)
+        except exceptions.NotFound as e:
+            pecan.abort(404, detail=str(e))
+        except Exception as e:
+            pecan.abort(500, detail=str(e))
+
+        if retcode:
+            # Execptions are handled within req_by_msb
+            logger.error("Status code is %s, detail is %s.",
+                         status_code, content)
+        response = pecan.Response(body=content, status=status_code)
+
+        for k in syscomm.getHeadersKeys(resp):
+            response.headers[k] = resp[k]
+
+        return response
index c77fe94..83d3172 100644 (file)
@@ -104,7 +104,7 @@ class CheckCapacity(BaseServer):
     def post(self, request):
         try:
             body = json.loads(request.body)
-        except json.JSONDecodeError as e:
+        except ValueError as e:
             return Response(
                 data={'error': 'Invalidate request body %s.' % e},
                 status=status.HTTP_400_BAD_REQUEST)
@@ -123,7 +123,7 @@ class CheckCapacity(BaseServer):
                 continue
             try:
                 resp_body = json.loads(resp.body)
-            except json.JSONDecodeError:
+            except ValueError:
                 continue
             if not resp_body.get("result", False):
                 continue
index 0a852e8..60035e0 100644 (file)
@@ -52,3 +52,42 @@ class CheckCapacityTest(unittest.TestCase):
             }
             self.assertEqual(status.HTTP_200_OK, resp.status_code)
             self.assertDictEqual(expect_body, resp.data)
+
+    def test_check_capacity_no_suitable_vim(self):
+        req = mock.Mock()
+        req.body = """
+        {
+            "vCPU": 1,
+            "Memory": 1,
+            "Storage": 500,
+            "VIMs": ["openstack_RegionOne"]
+        }"""
+        req.get_full_path.return_value = ("http://msb.onap.org/api/multicloud"
+                                          "/v0/check_vim_capacity")
+        with mock.patch.object(self.view, "send") as send:
+            plugin_resp = mock.Mock()
+            plugin_resp.body = """{
+                "result": false
+            }"""
+            plugin_resp.status_code = status.HTTP_200_OK
+            send.return_value = plugin_resp
+
+            resp = self.view.post(req)
+            expect_body = {
+                "VIMs": []
+            }
+            self.assertEqual(status.HTTP_200_OK, resp.status_code)
+            self.assertDictEqual(expect_body, resp.data)
+
+    def test_check_capacity_invalid_input(self):
+        req = mock.Mock()
+        req.body = "hello world"
+        req.get_full_path.return_value = ("http://msb.onap.org/api/multicloud"
+                                          "/v0/check_vim_capacity")
+        expect_body = {
+            "error": ("Invalidate request body "
+                      "No JSON object could be decoded.")
+        }
+        resp = self.view.post(req)
+        self.assertEqual(status.HTTP_400_BAD_REQUEST, resp.status_code)
+        self.assertDictEqual(expect_body, resp.data)