Fix Flake8 Violations in the Functest scripts
[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 logging
15 import os
16 import requests
17 import subprocess
18 import sys
19 import yaml
20
21 import keystoneclient.v2_0.client as ksclient
22 import glanceclient.client as glclient
23 import novaclient.client as nvclient
24 from neutronclient.v2_0 import client as ntclient
25
26 parser = argparse.ArgumentParser()
27
28 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
29 parser.add_argument("-r", "--report",
30                     help="Create json result file",
31                     action="store_true")
32 args = parser.parse_args()
33
34 with open('/home/opnfv/functest/conf/config_functest.yaml') as f:
35     functest_yaml = yaml.safe_load(f)
36
37 dirs = functest_yaml.get('general').get('directories')
38 FUNCTEST_REPO = dirs.get('dir_repo_functest')
39 PROMISE_REPO = dirs.get('dir_repo_promise')
40 TEST_DB = functest_yaml.get('results').get('test_db_url')
41
42 TENANT_NAME = functest_yaml.get('promise').get('general').get('tenant_name')
43 TENANT_DESCRIPTION = functest_yaml.get('promise').get(
44     'general').get('tenant_description')
45 USER_NAME = functest_yaml.get('promise').get('general').get('user_name')
46 USER_PWD = functest_yaml.get('promise').get('general').get('user_pwd')
47 IMAGE_NAME = functest_yaml.get('promise').get('general').get('image_name')
48 FLAVOR_NAME = functest_yaml.get('promise').get('general').get('flavor_name')
49 FLAVOR_VCPUS = functest_yaml.get('promise').get('general').get('flavor_vcpus')
50 FLAVOR_RAM = functest_yaml.get('promise').get('general').get('flavor_ram')
51 FLAVOR_DISK = functest_yaml.get('promise').get('general').get('flavor_disk')
52
53
54 GLANCE_IMAGE_FILENAME = functest_yaml.get('general'). \
55     get('openstack').get('image_file_name')
56 GLANCE_IMAGE_FORMAT = functest_yaml.get('general'). \
57     get('openstack').get('image_disk_format')
58 GLANCE_IMAGE_PATH = functest_yaml.get('general'). \
59     get('directories').get('dir_functest_data') + "/" + GLANCE_IMAGE_FILENAME
60
61 sys.path.append('%s/testcases' % FUNCTEST_REPO)
62 import functest_utils
63 import openstack_utils
64
65 """ logging configuration """
66 logger = logging.getLogger('Promise')
67 logger.setLevel(logging.DEBUG)
68
69 ch = logging.StreamHandler()
70
71 if args.debug:
72     ch.setLevel(logging.DEBUG)
73 else:
74     ch.setLevel(logging.INFO)
75
76 formatter = logging.Formatter('%(asctime)s - %(name)s'
77                               '- %(levelname)s - %(message)s')
78
79 ch.setFormatter(formatter)
80 logger.addHandler(ch)
81
82
83 def main():
84     ks_creds = openstack_utils.get_credentials("keystone")
85     nv_creds = openstack_utils.get_credentials("nova")
86     nt_creds = openstack_utils.get_credentials("neutron")
87
88     keystone = ksclient.Client(**ks_creds)
89
90     user_id = openstack_utils.get_user_id(keystone, ks_creds['username'])
91     if user_id == '':
92         logger.error("Error : Failed to get id of %s user" %
93                      ks_creds['username'])
94         exit(-1)
95
96     logger.info("Creating tenant '%s'..." % TENANT_NAME)
97     tenant_id = openstack_utils.create_tenant(
98         keystone, TENANT_NAME, TENANT_DESCRIPTION)
99     if tenant_id == '':
100         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
101         exit(-1)
102     logger.debug("Tenant '%s' created successfully." % TENANT_NAME)
103
104     roles_name = ["admin", "Admin"]
105     role_id = ''
106     for role_name in roles_name:
107         if role_id == '':
108             role_id = openstack_utils.get_role_id(keystone, role_name)
109
110     if role_id == '':
111         logger.error("Error : Failed to get id for %s role" % role_name)
112         exit(-1)
113
114     logger.info("Adding role '%s' to tenant '%s'..." % (role_id, TENANT_NAME))
115     if not openstack_utils.add_role_user(keystone, user_id,
116                                          role_id, tenant_id):
117         logger.error("Error : Failed to add %s on tenant %s" %
118                      (ks_creds['username'], TENANT_NAME))
119         exit(-1)
120     logger.debug("Role added successfully.")
121
122     logger.info("Creating user '%s'..." % USER_NAME)
123     user_id = openstack_utils.create_user(
124         keystone, USER_NAME, USER_PWD, None, tenant_id)
125
126     if user_id == '':
127         logger.error("Error : Failed to create %s user" % USER_NAME)
128         exit(-1)
129     logger.debug("User '%s' created successfully." % USER_NAME)
130
131     logger.info("Updating OpenStack credentials...")
132     ks_creds.update({
133         "username": TENANT_NAME,
134         "password": TENANT_NAME,
135         "tenant_name": TENANT_NAME,
136     })
137
138     nt_creds.update({
139         "tenant_name": TENANT_NAME,
140     })
141
142     nv_creds.update({
143         "project_id": TENANT_NAME,
144     })
145
146     glance_endpoint = keystone.\
147         service_catalog.url_for(service_type='image',
148                                 endpoint_type='publicURL')
149     glance = glclient.Client(1, glance_endpoint, token=keystone.auth_token)
150     nova = nvclient.Client("2", **nv_creds)
151
152     logger.info("Creating image '%s' from '%s'..." % (IMAGE_NAME,
153                                                       GLANCE_IMAGE_PATH))
154     image_id = openstack_utils.create_glance_image(glance,
155                                                    IMAGE_NAME,
156                                                    GLANCE_IMAGE_PATH)
157     if not image_id:
158         logger.error("Failed to create the Glance image...")
159         exit(-1)
160     logger.debug("Image '%s' with ID '%s' created successfully." % (IMAGE_NAME,
161                                                                     image_id))
162     flavor_id = openstack_utils.get_flavor_id(nova, FLAVOR_NAME)
163     if flavor_id == '':
164         logger.info("Creating flavor '%s'..." % FLAVOR_NAME)
165         flavor_id = openstack_utils.create_flavor(nova,
166                                                   FLAVOR_NAME,
167                                                   FLAVOR_RAM,
168                                                   FLAVOR_DISK,
169                                                   FLAVOR_VCPUS)
170         if not flavor_id:
171             logger.error("Failed to create the Flavor...")
172             exit(-1)
173         logger.debug("Flavor '%s' with ID '%s' created successfully." %
174                      (FLAVOR_NAME, flavor_id))
175     else:
176         logger.debug("Using existing flavor '%s' with ID '%s'..."
177                      % (FLAVOR_NAME, flavor_id))
178
179     neutron = ntclient.Client(**nt_creds)
180     private_net = openstack_utils.get_private_net(neutron)
181     if private_net is None:
182         logger.error("There is no private network in the deployment."
183                      "Aborting...")
184         exit(-1)
185     logger.debug("Using private network '%s' (%s)." % (private_net['name'],
186                                                        private_net['id']))
187
188     logger.info("Exporting environment variables...")
189     os.environ["NODE_ENV"] = "functest"
190     os.environ["OS_TENANT_NAME"] = TENANT_NAME
191     os.environ["OS_USERNAME"] = USER_NAME
192     os.environ["OS_PASSWORD"] = USER_PWD
193     os.environ["OS_TEST_IMAGE"] = image_id
194     os.environ["OS_TEST_FLAVOR"] = flavor_id
195     os.environ["OS_TEST_NETWORK"] = private_net['id']
196
197     os.chdir(PROMISE_REPO)
198     results_file_name = 'promise-results.json'
199     results_file = open(results_file_name, 'w+')
200     cmd = 'npm run -s test -- --reporter json'
201
202     logger.info("Running command: %s" % cmd)
203     ret = subprocess.call(cmd, shell=True, stdout=results_file,
204                           stderr=subprocess.STDOUT)
205     results_file.close()
206
207     if ret == 0:
208         logger.info("The test succeeded.")
209         # test_status = 'OK'
210     else:
211         logger.info("The command '%s' failed." % cmd)
212         # test_status = "Failed"
213
214     # Print output of file
215     with open(results_file_name, 'r') as results_file:
216         data = results_file.read()
217         logger.debug("\n%s" % data)
218         json_data = json.loads(data)
219
220         suites = json_data["stats"]["suites"]
221         tests = json_data["stats"]["tests"]
222         passes = json_data["stats"]["passes"]
223         pending = json_data["stats"]["pending"]
224         failures = json_data["stats"]["failures"]
225         start_time = json_data["stats"]["start"]
226         end_time = json_data["stats"]["end"]
227         duration = float(json_data["stats"]["duration"]) / float(1000)
228
229     logger.info("\n"
230                 "****************************************\n"
231                 "          Promise test report\n\n"
232                 "****************************************\n"
233                 " Suites:  \t%s\n"
234                 " Tests:   \t%s\n"
235                 " Passes:  \t%s\n"
236                 " Pending: \t%s\n"
237                 " Failures:\t%s\n"
238                 " Start:   \t%s\n"
239                 " End:     \t%s\n"
240                 " Duration:\t%s\n"
241                 "****************************************\n\n"
242                 % (suites, tests, passes, pending, failures,
243                    start_time, end_time, duration))
244
245     if args.report:
246         pod_name = functest_utils.get_pod_name(logger)
247         installer = functest_utils.get_installer_type(logger)
248         scenario = functest_utils.get_scenario(logger)
249         build_tag = functest_utils.get_build_tag(logger)
250         # git_version = functest_utils.get_git_branch(PROMISE_REPO)
251         url = TEST_DB + "/results"
252
253         json_results = {"timestart": start_time, "duration": duration,
254                         "tests": int(tests), "failures": int(failures)}
255         logger.debug("Results json: " + str(json_results))
256
257         # criteria for Promise in Release B was 100% of tests OK
258         status = "failed"
259         if int(tests) > 32 and int(failures) < 1:
260             status = "passed"
261
262         params = {"project_name": "promise", "case_name": "promise",
263                   "pod_name": str(pod_name), 'installer': installer,
264                   "version": scenario, "scenario": scenario,
265                   "criteria": status, "build_tag": build_tag,
266                   'details': json_results}
267         headers = {'Content-Type': 'application/json'}
268
269         logger.info("Pushing results to DB...")
270         r = requests.post(url, data=json.dumps(params), headers=headers)
271         logger.debug(r)
272
273
274 if __name__ == '__main__':
275     main()