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