Set project_name arg when creating users
[functest.git] / functest / core / vnf.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 Orange and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """Define the parent class of all VNF TestCases."""
11
12 import logging
13 import uuid
14
15 from snaps.config.user import UserConfig
16 from snaps.config.project import ProjectConfig
17 from snaps.openstack.create_user import OpenStackUser
18 from snaps.openstack.create_project import OpenStackProject
19 from snaps.openstack.utils import keystone_utils
20 from snaps.openstack.tests import openstack_tests
21
22 from xtesting.core import vnf
23 from functest.utils import constants
24
25 __author__ = ("Morgan Richomme <morgan.richomme@orange.com>, "
26               "Valentin Boucher <valentin.boucher@orange.com>")
27
28
29 class VnfPreparationException(vnf.VnfPreparationException):
30     """Raise when VNF preparation cannot be executed."""
31
32
33 class OrchestratorDeploymentException(vnf.OrchestratorDeploymentException):
34     """Raise when orchestrator cannot be deployed."""
35
36
37 class VnfDeploymentException(vnf.VnfDeploymentException):
38     """Raise when VNF cannot be deployed."""
39
40
41 class VnfTestException(vnf.VnfTestException):
42     """Raise when VNF cannot be tested."""
43
44
45 class VnfOnBoarding(vnf.VnfOnBoarding):
46     # pylint: disable=too-many-instance-attributes
47     """Base model for OpenStack VNF test cases."""
48
49     __logger = logging.getLogger(__name__)
50
51     def __init__(self, **kwargs):
52         super(VnfOnBoarding, self).__init__(**kwargs)
53         self.uuid = uuid.uuid4()
54         self.user_name = "{}-{}".format(self.case_name, self.uuid)
55         self.tenant_name = "{}-{}".format(self.case_name, self.uuid)
56         self.snaps_creds = {}
57         self.created_object = []
58         self.os_project = None
59         self.tenant_description = "Created by OPNFV Functest: {}".format(
60             self.case_name)
61
62     def prepare(self):
63         """
64         Prepare the environment for VNF testing:
65
66             * Creation of a user,
67             * Creation of a tenant,
68             * Allocation admin role to the user on this tenant
69
70         Returns base.TestCase.EX_OK if preparation is successfull
71
72         Raise VnfPreparationException in case of problem
73         """
74         try:
75             self.__logger.info(
76                 "Prepare VNF: %s, description: %s", self.case_name,
77                 self.tenant_description)
78             snaps_creds = openstack_tests.get_credentials(
79                 os_env_file=constants.ENV_FILE)
80
81             self.os_project = OpenStackProject(
82                 snaps_creds,
83                 ProjectConfig(
84                     name=self.tenant_name,
85                     description=self.tenant_description,
86                     domain=snaps_creds.project_domain_name
87                 ))
88             self.os_project.create()
89             self.created_object.append(self.os_project)
90
91             snaps_creds.project_domain_id = \
92                 self.os_project.get_project().domain_id
93             snaps_creds.user_domain_id = \
94                 self.os_project.get_project().domain_id
95
96             for role in ['admin', 'Admin']:
97                 if keystone_utils.get_role_by_name(
98                         keystone_utils.keystone_client(snaps_creds), role):
99                     admin_role = role
100                     break
101
102             user_creator = OpenStackUser(
103                 snaps_creds,
104                 UserConfig(
105                     name=self.user_name,
106                     password=str(uuid.uuid4()),
107                     project_name=self.tenant_name,
108                     domain_name=snaps_creds.user_domain_name,
109                     roles={admin_role: self.tenant_name}))
110             user_creator.create()
111             self.created_object.append(user_creator)
112             self.snaps_creds = user_creator.get_os_creds(self.tenant_name)
113             self.__logger.debug("snaps creds: %s", self.snaps_creds)
114
115             return vnf.VnfOnBoarding.EX_OK
116         except Exception:  # pylint: disable=broad-except
117             self.__logger.exception("Exception raised during VNF preparation")
118             raise VnfPreparationException
119
120     def deploy_orchestrator(self):
121         """
122         Deploy an orchestrator (optional).
123
124         If this method is overriden then raise orchestratorDeploymentException
125         if error during orchestrator deployment
126         """
127         self.__logger.info("Deploy orchestrator (if necessary)")
128         return True
129
130     def deploy_vnf(self):
131         """
132         Deploy the VNF
133
134         This function MUST be implemented by vnf test cases.
135         The details section MAY be updated in the vnf test cases.
136
137         The deployment can be executed via a specific orchestrator
138         or using build-in orchestrators such as heat, OpenBaton, cloudify,
139         juju, onap, ...
140
141         Returns:
142             True if the VNF is properly deployed
143             False if the VNF is not deployed
144
145         Raise VnfDeploymentException if error during VNF deployment
146         """
147         self.__logger.error("VNF must be deployed")
148         raise VnfDeploymentException
149
150     def test_vnf(self):
151         """
152         Test the VNF
153
154         This function MUST be implemented by vnf test cases.
155         The details section MAY be updated in the vnf test cases.
156
157         Once a VNF is deployed, it is assumed that specific test suite can be
158         run to validate the VNF.
159         Please note that the same test suite can be used on several test case
160         (e.g. clearwater test suite can be used whatever the orchestrator used
161         for the deployment)
162
163         Returns:
164             True if VNF tests are PASS
165             False if test suite is FAIL
166
167         Raise VnfTestException if error during VNF test
168         """
169         self.__logger.error("VNF must be tested")
170         raise VnfTestException
171
172     def clean(self):
173         """
174         Clean VNF test case.
175
176         It is up to the test providers to delete resources used for the tests.
177         By default we clean:
178
179             * the user,
180             * the tenant
181         """
182         self.__logger.info('Removing the VNF resources ..')
183         for creator in reversed(self.created_object):
184             try:
185                 creator.clean()
186             except Exception as exc:  # pylint: disable=broad-except
187                 self.__logger.error('Unexpected error cleaning - %s', exc)