0e2e30134b284cf5ed46f69449ca59afa0ba2c9b
[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 time
14 import uuid
15
16 import functest.core.testcase as base
17 from functest.utils.constants import CONST
18 from snaps.config.user import UserConfig
19 from snaps.config.project import ProjectConfig
20 from snaps.openstack.create_user import OpenStackUser
21 from snaps.openstack.create_project import OpenStackProject
22 from snaps.openstack.tests import openstack_tests
23
24 __author__ = ("Morgan Richomme <morgan.richomme@orange.com>, "
25               "Valentin Boucher <valentin.boucher@orange.com>")
26
27
28 class VnfPreparationException(Exception):
29     """Raise when VNF preparation cannot be executed."""
30
31
32 class OrchestratorDeploymentException(Exception):
33     """Raise when orchestrator cannot be deployed."""
34
35
36 class VnfDeploymentException(Exception):
37     """Raise when VNF cannot be deployed."""
38
39
40 class VnfTestException(Exception):
41     """Raise when VNF cannot be tested."""
42
43
44 class VnfOnBoarding(base.TestCase):
45     """Base model for VNF test cases."""
46
47     __logger = logging.getLogger(__name__)
48
49     def __init__(self, **kwargs):
50         super(VnfOnBoarding, self).__init__(**kwargs)
51         self.tenant_name = CONST.__getattribute__(
52             'vnf_{}_tenant_name'.format(self.case_name))
53         self.snaps_creds = {}
54         self.created_object = []
55         self.os_project = None
56
57     def run(self, **kwargs):
58         """
59         Run of the VNF test case:
60
61             * Deploy an orchestrator if needed (e.g. heat, cloudify, ONAP,...),
62             * Deploy the VNF,
63             * Perform tests on the VNF
64
65           A VNF test case is successfull when the 3 steps are PASS
66           If one of the step is FAIL, the test case is FAIL
67
68         Returns:
69           TestCase.EX_OK if result is 'PASS'.
70           TestCase.EX_TESTCASE_FAILED otherwise.
71         """
72         self.start_time = time.time()
73
74         try:
75             self.prepare()
76             if (self.deploy_orchestrator() and
77                     self.deploy_vnf() and
78                     self.test_vnf()):
79                 self.stop_time = time.time()
80                 # Calculation with different weight depending on the steps TODO
81                 self.result = 100
82                 return base.TestCase.EX_OK
83             else:
84                 self.result = 0
85                 self.stop_time = time.time()
86                 return base.TestCase.EX_TESTCASE_FAILED
87         except Exception:  # pylint: disable=broad-except
88             self.stop_time = time.time()
89             self.__logger.exception("Exception on VNF testing")
90             return base.TestCase.EX_TESTCASE_FAILED
91
92     def prepare(self):
93         """
94         Prepare the environment for VNF testing:
95
96             * Creation of a user,
97             * Creation of a tenant,
98             * Allocation admin role to the user on this tenant
99
100         Returns base.TestCase.EX_OK if preparation is successfull
101
102         Raise VnfPreparationException in case of problem
103         """
104         try:
105             tenant_description = CONST.__getattribute__(
106                 'vnf_{}_tenant_description'.format(self.case_name))
107             self.__logger.info("Prepare VNF: %s, description: %s",
108                                self.tenant_name, tenant_description)
109             snaps_creds = openstack_tests.get_credentials(
110                 os_env_file=CONST.__getattribute__('env_file'))
111
112             project_creator = OpenStackProject(
113                 snaps_creds,
114                 ProjectConfig(
115                     name=self.tenant_name,
116                     description=tenant_description
117                 ))
118             project_creator.create()
119             self.created_object.append(project_creator)
120             self.os_project = project_creator
121
122             user_creator = OpenStackUser(
123                 snaps_creds,
124                 UserConfig(
125                     name=self.tenant_name,
126                     password=str(uuid.uuid4()),
127                     roles={'admin': self.tenant_name}))
128
129             user_creator.create()
130             self.created_object.append(user_creator)
131
132             self.snaps_creds = user_creator.get_os_creds(self.tenant_name)
133
134             return base.TestCase.EX_OK
135         except Exception:  # pylint: disable=broad-except
136             self.__logger.exception("Exception raised during VNF preparation")
137             raise VnfPreparationException
138
139     def deploy_orchestrator(self):
140         """
141         Deploy an orchestrator (optional).
142
143         If this method is overriden then raise orchestratorDeploymentException
144         if error during orchestrator deployment
145         """
146         self.__logger.info("Deploy orchestrator (if necessary)")
147         return True
148
149     def deploy_vnf(self):
150         """
151         Deploy 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         The deployment can be executed via a specific orchestrator
157         or using build-in orchestrators such as heat, OpenBaton, cloudify,
158         juju, onap, ...
159
160         Returns:
161             True if the VNF is properly deployed
162             False if the VNF is not deployed
163
164         Raise VnfDeploymentException if error during VNF deployment
165         """
166         self.__logger.error("VNF must be deployed")
167         raise VnfDeploymentException
168
169     def test_vnf(self):
170         """
171         Test the VNF
172
173         This function MUST be implemented by vnf test cases.
174         The details section MAY be updated in the vnf test cases.
175
176         Once a VNF is deployed, it is assumed that specific test suite can be
177         run to validate the VNF.
178         Please note that the same test suite can be used on several test case
179         (e.g. clearwater test suite can be used whatever the orchestrator used
180         for the deployment)
181
182         Returns:
183             True if VNF tests are PASS
184             False if test suite is FAIL
185
186         Raise VnfTestException if error during VNF test
187         """
188         self.__logger.error("VNF must be tested")
189         raise VnfTestException
190
191     def clean(self):
192         """
193         Clean VNF test case.
194
195         It is up to the test providers to delete resources used for the tests.
196         By default we clean:
197
198             * the user,
199             * the tenant
200         """
201         self.__logger.info('Removing the VNF resources ..')
202         for creator in reversed(self.created_object):
203             try:
204                 creator.clean()
205             except Exception as exc:  # pylint: disable=broad-except
206                 self.__logger.error('Unexpected error cleaning - %s', exc)