Merge "refactor vping"
[functest.git] / testcases / features / promise.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Maintainer : jose.lausuch@ericsson.com
11 #
12 import argparse
13 import json
14 import os
15 import subprocess
16 import time
17
18 import functest.utils.functest_logger as ft_logger
19 import functest.utils.functest_utils as functest_utils
20 import functest.utils.openstack_utils as openstack_utils
21 import keystoneclient.v2_0.client as ksclient
22 from neutronclient.v2_0 import client as ntclient
23 import novaclient.client as nvclient
24 import yaml
25
26
27 parser = argparse.ArgumentParser()
28
29 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
30 parser.add_argument("-r", "--report",
31                     help="Create json result file",
32                     action="store_true")
33 args = parser.parse_args()
34
35 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
36     functest_yaml = yaml.safe_load(f)
37
38 dirs = functest_yaml.get('general').get('directories')
39 FUNCTEST_REPO = dirs.get('dir_repo_functest')
40 PROMISE_REPO = dirs.get('dir_repo_promise')
41 TEST_DB = functest_yaml.get('results').get('test_db_url')
42
43 TENANT_NAME = functest_yaml.get('promise').get('general').get('tenant_name')
44 TENANT_DESCRIPTION = functest_yaml.get('promise').get(
45     'general').get('tenant_description')
46 USER_NAME = functest_yaml.get('promise').get('general').get('user_name')
47 USER_PWD = functest_yaml.get('promise').get('general').get('user_pwd')
48 IMAGE_NAME = functest_yaml.get('promise').get('general').get('image_name')
49 FLAVOR_NAME = functest_yaml.get('promise').get('general').get('flavor_name')
50 FLAVOR_VCPUS = functest_yaml.get('promise').get('general').get('flavor_vcpus')
51 FLAVOR_RAM = functest_yaml.get('promise').get('general').get('flavor_ram')
52 FLAVOR_DISK = functest_yaml.get('promise').get('general').get('flavor_disk')
53
54
55 GLANCE_IMAGE_FILENAME = functest_yaml.get('general').get('openstack').get(
56     'image_file_name')
57 GLANCE_IMAGE_FORMAT = functest_yaml.get('general').get('openstack').get(
58     'image_disk_format')
59 GLANCE_IMAGE_PATH = functest_yaml.get('general').get('directories').get(
60     'dir_functest_data') + "/" + GLANCE_IMAGE_FILENAME
61
62 NET_NAME = functest_yaml.get('promise').get('general').get('network_name')
63 SUBNET_NAME = functest_yaml.get('promise').get('general').get('subnet_name')
64 SUBNET_CIDR = functest_yaml.get('promise').get('general').get('subnet_cidr')
65 ROUTER_NAME = functest_yaml.get('promise').get('general').get('router_name')
66
67
68 """ logging configuration """
69 logger = ft_logger.Logger("promise").getLogger()
70
71
72 def main():
73     exit_code = -1
74     start_time = time.time()
75     ks_creds = openstack_utils.get_credentials("keystone")
76     nv_creds = openstack_utils.get_credentials("nova")
77     nt_creds = openstack_utils.get_credentials("neutron")
78
79     keystone = ksclient.Client(**ks_creds)
80
81     user_id = openstack_utils.get_user_id(keystone, ks_creds['username'])
82     if user_id == '':
83         logger.error("Error : Failed to get id of %s user" %
84                      ks_creds['username'])
85         exit(-1)
86
87     logger.info("Creating tenant '%s'..." % TENANT_NAME)
88     tenant_id = openstack_utils.create_tenant(
89         keystone, TENANT_NAME, TENANT_DESCRIPTION)
90     if tenant_id == '':
91         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
92         exit(-1)
93     logger.debug("Tenant '%s' created successfully." % TENANT_NAME)
94
95     roles_name = ["admin", "Admin"]
96     role_id = ''
97     for role_name in roles_name:
98         if role_id == '':
99             role_id = openstack_utils.get_role_id(keystone, role_name)
100
101     if role_id == '':
102         logger.error("Error : Failed to get id for %s role" % role_name)
103         exit(-1)
104
105     logger.info("Adding role '%s' to tenant '%s'..." % (role_id, TENANT_NAME))
106     if not openstack_utils.add_role_user(keystone, user_id,
107                                          role_id, tenant_id):
108         logger.error("Error : Failed to add %s on tenant %s" %
109                      (ks_creds['username'], TENANT_NAME))
110         exit(-1)
111     logger.debug("Role added successfully.")
112
113     logger.info("Creating user '%s'..." % USER_NAME)
114     user_id = openstack_utils.create_user(
115         keystone, USER_NAME, USER_PWD, None, tenant_id)
116
117     if user_id == '':
118         logger.error("Error : Failed to create %s user" % USER_NAME)
119         exit(-1)
120     logger.debug("User '%s' created successfully." % USER_NAME)
121
122     logger.info("Updating OpenStack credentials...")
123     ks_creds.update({
124         "username": TENANT_NAME,
125         "password": TENANT_NAME,
126         "tenant_name": TENANT_NAME,
127     })
128
129     nt_creds.update({
130         "tenant_name": TENANT_NAME,
131     })
132
133     nv_creds.update({
134         "project_id": TENANT_NAME,
135     })
136
137     glance = openstack_utils.get_glance_client()
138     nova = nvclient.Client("2", **nv_creds)
139
140     logger.info("Creating image '%s' from '%s'..." % (IMAGE_NAME,
141                                                       GLANCE_IMAGE_PATH))
142     image_id = openstack_utils.create_glance_image(glance,
143                                                    IMAGE_NAME,
144                                                    GLANCE_IMAGE_PATH)
145     if not image_id:
146         logger.error("Failed to create the Glance image...")
147         exit(-1)
148     logger.debug("Image '%s' with ID '%s' created successfully." % (IMAGE_NAME,
149                                                                     image_id))
150     flavor_id = openstack_utils.get_flavor_id(nova, FLAVOR_NAME)
151     if flavor_id == '':
152         logger.info("Creating flavor '%s'..." % FLAVOR_NAME)
153         flavor_id = openstack_utils.create_flavor(nova,
154                                                   FLAVOR_NAME,
155                                                   FLAVOR_RAM,
156                                                   FLAVOR_DISK,
157                                                   FLAVOR_VCPUS)
158         if not flavor_id:
159             logger.error("Failed to create the Flavor...")
160             exit(-1)
161         logger.debug("Flavor '%s' with ID '%s' created successfully." %
162                      (FLAVOR_NAME, flavor_id))
163     else:
164         logger.debug("Using existing flavor '%s' with ID '%s'..."
165                      % (FLAVOR_NAME, flavor_id))
166
167     neutron = ntclient.Client(**nt_creds)
168
169     network_dic = openstack_utils.create_network_full(neutron,
170                                                       NET_NAME,
171                                                       SUBNET_NAME,
172                                                       ROUTER_NAME,
173                                                       SUBNET_CIDR)
174     if network_dic is False:
175         logger.error("Failed to create the private network...")
176         exit(-1)
177
178     logger.info("Exporting environment variables...")
179     os.environ["NODE_ENV"] = "functest"
180     os.environ["OS_TENANT_NAME"] = TENANT_NAME
181     os.environ["OS_USERNAME"] = USER_NAME
182     os.environ["OS_PASSWORD"] = USER_PWD
183     os.environ["OS_TEST_IMAGE"] = image_id
184     os.environ["OS_TEST_FLAVOR"] = flavor_id
185     os.environ["OS_TEST_NETWORK"] = network_dic["net_id"]
186
187     os.chdir(PROMISE_REPO)
188     results_file_name = 'promise-results.json'
189     results_file = open(results_file_name, 'w+')
190     cmd = 'npm run -s test -- --reporter json'
191
192     logger.info("Running command: %s" % cmd)
193     ret = subprocess.call(cmd, shell=True, stdout=results_file,
194                           stderr=subprocess.STDOUT)
195     results_file.close()
196
197     if ret == 0:
198         logger.info("The test succeeded.")
199         # test_status = 'OK'
200     else:
201         logger.info("The command '%s' failed." % cmd)
202         # test_status = "Failed"
203
204     # Print output of file
205     with open(results_file_name, 'r') as results_file:
206         data = results_file.read()
207         logger.debug("\n%s" % data)
208         json_data = json.loads(data)
209
210         suites = json_data["stats"]["suites"]
211         tests = json_data["stats"]["tests"]
212         passes = json_data["stats"]["passes"]
213         pending = json_data["stats"]["pending"]
214         failures = json_data["stats"]["failures"]
215         start_time_json = json_data["stats"]["start"]
216         end_time = json_data["stats"]["end"]
217         duration = float(json_data["stats"]["duration"]) / float(1000)
218
219     logger.info("\n"
220                 "****************************************\n"
221                 "          Promise test report\n\n"
222                 "****************************************\n"
223                 " Suites:  \t%s\n"
224                 " Tests:   \t%s\n"
225                 " Passes:  \t%s\n"
226                 " Pending: \t%s\n"
227                 " Failures:\t%s\n"
228                 " Start:   \t%s\n"
229                 " End:     \t%s\n"
230                 " Duration:\t%s\n"
231                 "****************************************\n\n"
232                 % (suites, tests, passes, pending, failures,
233                    start_time_json, end_time, duration))
234
235     if args.report:
236         stop_time = time.time()
237         json_results = {"timestart": start_time, "duration": duration,
238                         "tests": int(tests), "failures": int(failures)}
239         logger.debug("Promise Results json: " + str(json_results))
240
241         # criteria for Promise in Release B was 100% of tests OK
242         status = "FAIL"
243         if int(tests) > 32 and int(failures) < 1:
244             status = "PASS"
245             exit_code = 0
246
247         functest_utils.push_results_to_db("promise",
248                                           "promise",
249                                           logger,
250                                           start_time,
251                                           stop_time,
252                                           status,
253                                           json_results)
254
255     exit(exit_code)
256
257
258 if __name__ == '__main__':
259     main()