Mock os.makedirs() in test_odl.py
[functest.git] / functest / core / vnf.py
index bbdd80a..a6afd4e 100644 (file)
 """Define the parent class of all VNF TestCases."""
 
 import logging
-import time
+import uuid
 
-import functest.core.testcase as base
-from functest.utils.constants import CONST
-from snaps.openstack.create_user import UserSettings, OpenStackUser
-from snaps.openstack.create_project import ProjectSettings, OpenStackProject
+from snaps.config.user import UserConfig
+from snaps.config.project import ProjectConfig
+from snaps.openstack.create_user import OpenStackUser
+from snaps.openstack.create_project import OpenStackProject
+from snaps.openstack.utils import keystone_utils
 from snaps.openstack.tests import openstack_tests
 
+from xtesting.core import vnf
+from functest.utils import constants
+
 __author__ = ("Morgan Richomme <morgan.richomme@orange.com>, "
               "Valentin Boucher <valentin.boucher@orange.com>")
 
 
-class VnfPreparationException(Exception):
+class VnfPreparationException(vnf.VnfPreparationException):
     """Raise when VNF preparation cannot be executed."""
 
 
-class OrchestratorDeploymentException(Exception):
+class OrchestratorDeploymentException(vnf.OrchestratorDeploymentException):
     """Raise when orchestrator cannot be deployed."""
 
 
-class VnfDeploymentException(Exception):
+class VnfDeploymentException(vnf.VnfDeploymentException):
     """Raise when VNF cannot be deployed."""
 
 
-class VnfTestException(Exception):
+class VnfTestException(vnf.VnfTestException):
     """Raise when VNF cannot be tested."""
 
 
-class VnfOnBoarding(base.TestCase):
-    """Base model for VNF test cases."""
+class VnfOnBoarding(vnf.VnfOnBoarding):
+    # pylint: disable=too-many-instance-attributes
+    """Base model for OpenStack VNF test cases."""
 
     __logger = logging.getLogger(__name__)
 
     def __init__(self, **kwargs):
         super(VnfOnBoarding, self).__init__(**kwargs)
-        self.tenant_name = CONST.__getattribute__(
-            'vnf_{}_tenant_name'.format(self.case_name))
+        self.uuid = uuid.uuid4()
+        self.user_name = "{}-{}".format(self.case_name, self.uuid)
+        self.tenant_name = "{}-{}".format(self.case_name, self.uuid)
         self.snaps_creds = {}
         self.created_object = []
         self.os_project = None
-
-    def run(self, **kwargs):
-        """
-        Run of the VNF test case:
-
-            * Deploy an orchestrator if needed (e.g. heat, cloudify, ONAP),
-            * Deploy the VNF,
-            * Perform tests on the VNF
-
-          A VNF test case is successfull when the 3 steps are PASS
-          If one of the step is FAIL, the test case is FAIL
-
-          Returns:
-            TestCase.EX_OK if result is 'PASS'.
-            TestCase.EX_TESTCASE_FAILED otherwise.
-        """
-        self.start_time = time.time()
-
-        try:
-            self.prepare()
-            if (self.deploy_orchestrator() and
-                    self.deploy_vnf() and
-                    self.test_vnf()):
-                self.stop_time = time.time()
-                # Calculation with different weight depending on the steps TODO
-                self.result = 100
-                return base.TestCase.EX_OK
-            else:
-                self.result = 0
-                self.stop_time = time.time()
-                return base.TestCase.EX_TESTCASE_FAILED
-        except Exception:  # pylint: disable=broad-except
-            self.stop_time = time.time()
-            self.__logger.exception("Exception on VNF testing")
-            return base.TestCase.EX_TESTCASE_FAILED
+        self.tenant_description = "Created by OPNFV Functest: {}".format(
+            self.case_name)
 
     def prepare(self):
         """
@@ -99,35 +72,47 @@ class VnfOnBoarding(base.TestCase):
         Raise VnfPreparationException in case of problem
         """
         try:
-            tenant_description = CONST.__getattribute__(
-                'vnf_{}_tenant_description'.format(self.case_name))
-            self.__logger.info("Prepare VNF: %s, description: %s",
-                               self.tenant_name, tenant_description)
+            self.__logger.info(
+                "Prepare VNF: %s, description: %s", self.case_name,
+                self.tenant_description)
             snaps_creds = openstack_tests.get_credentials(
-                os_env_file=CONST.__getattribute__('openstack_creds'))
+                os_env_file=constants.ENV_FILE)
 
-            project_creator = OpenStackProject(
+            self.os_project = OpenStackProject(
                 snaps_creds,
-                ProjectSettings(
+                ProjectConfig(
                     name=self.tenant_name,
-                    description=tenant_description
+                    description=self.tenant_description,
+                    domain=snaps_creds.project_domain_name
                 ))
-            project_creator.create()
-            self.created_object.append(project_creator)
-            self.os_project = project_creator
-
-            user_creator = OpenStackUser(snaps_creds,
-                                         UserSettings(
-                                             name=self.tenant_name,
-                                             password=self.tenant_name))
-            user_creator.create()
-            self.created_object.append(user_creator)
+            self.os_project.create()
+            self.created_object.append(self.os_project)
+
+            snaps_creds.project_domain_id = \
+                self.os_project.get_project().domain_id
+            snaps_creds.user_domain_id = \
+                self.os_project.get_project().domain_id
 
-            project_creator.assoc_user(user_creator.user_settings)
+            for role in ['admin', 'Admin']:
+                if keystone_utils.get_role_by_name(
+                        keystone_utils.keystone_client(snaps_creds), role):
+                    admin_role = role
+                    break
 
+            user_creator = OpenStackUser(
+                snaps_creds,
+                UserConfig(
+                    name=self.user_name,
+                    password=str(uuid.uuid4()),
+                    project_name=self.tenant_name,
+                    domain_name=snaps_creds.user_domain_name,
+                    roles={admin_role: self.tenant_name}))
+            user_creator.create()
+            self.created_object.append(user_creator)
             self.snaps_creds = user_creator.get_os_creds(self.tenant_name)
+            self.__logger.debug("snaps creds: %s", self.snaps_creds)
 
-            return base.TestCase.EX_OK
+            return vnf.VnfOnBoarding.EX_OK
         except Exception:  # pylint: disable=broad-except
             self.__logger.exception("Exception raised during VNF preparation")
             raise VnfPreparationException
@@ -136,9 +121,8 @@ class VnfOnBoarding(base.TestCase):
         """
         Deploy an orchestrator (optional).
 
-        If function overwritten
-        raise orchestratorDeploymentException if error during orchestrator
-        deployment
+        If this method is overriden then raise orchestratorDeploymentException
+        if error during orchestrator deployment
         """
         self.__logger.info("Deploy orchestrator (if necessary)")
         return True
@@ -151,10 +135,8 @@ class VnfOnBoarding(base.TestCase):
         The details section MAY be updated in the vnf test cases.
 
         The deployment can be executed via a specific orchestrator
-        or using nuild-in orchestrators such as:
-
-            * heat, openbaton, cloudify (available on all scenario),
-            * open-o (on open-o scenarios)
+        or using build-in orchestrators such as heat, OpenBaton, cloudify,
+        juju, onap, ...
 
         Returns:
             True if the VNF is properly deployed
@@ -197,8 +179,7 @@ class VnfOnBoarding(base.TestCase):
             * the user,
             * the tenant
         """
-        self.__logger.info("test cleaning")
-        self.__logger.info('Remove the cloudify manager OS object ..')
+        self.__logger.info('Removing the VNF resources ..')
         for creator in reversed(self.created_object):
             try:
                 creator.clean()