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