Merge "Leverage on Xtesting"
[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
114             return vnf.VnfOnBoarding.EX_OK
115         except Exception:  # pylint: disable=broad-except
116             self.__logger.exception("Exception raised during VNF preparation")
117             raise VnfPreparationException
118
119     def deploy_orchestrator(self):
120         """
121         Deploy an orchestrator (optional).
122
123         If this method is overriden then raise orchestratorDeploymentException
124         if error during orchestrator deployment
125         """
126         self.__logger.info("Deploy orchestrator (if necessary)")
127         return True
128
129     def deploy_vnf(self):
130         """
131         Deploy the VNF
132
133         This function MUST be implemented by vnf test cases.
134         The details section MAY be updated in the vnf test cases.
135
136         The deployment can be executed via a specific orchestrator
137         or using build-in orchestrators such as heat, OpenBaton, cloudify,
138         juju, onap, ...
139
140         Returns:
141             True if the VNF is properly deployed
142             False if the VNF is not deployed
143
144         Raise VnfDeploymentException if error during VNF deployment
145         """
146         self.__logger.error("VNF must be deployed")
147         raise VnfDeploymentException
148
149     def test_vnf(self):
150         """
151         Test the VNF
152
153         This function MUST be implemented by vnf test cases.
154         The details section MAY be updated in the vnf test cases.
155
156         Once a VNF is deployed, it is assumed that specific test suite can be
157         run to validate the VNF.
158         Please note that the same test suite can be used on several test case
159         (e.g. clearwater test suite can be used whatever the orchestrator used
160         for the deployment)
161
162         Returns:
163             True if VNF tests are PASS
164             False if test suite is FAIL
165
166         Raise VnfTestException if error during VNF test
167         """
168         self.__logger.error("VNF must be tested")
169         raise VnfTestException
170
171     def clean(self):
172         """
173         Clean VNF test case.
174
175         It is up to the test providers to delete resources used for the tests.
176         By default we clean:
177
178             * the user,
179             * the tenant
180         """
181         self.__logger.info('Removing the VNF resources ..')
182         for creator in reversed(self.created_object):
183             try:
184                 creator.clean()
185             except Exception as exc:  # pylint: disable=broad-except
186                 self.__logger.error('Unexpected error cleaning - %s', exc)