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