Add criteria and version when pushing the results into test DB
[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
64 """ logging configuration """
65 logger = logging.getLogger('Promise')
66 logger.setLevel(logging.DEBUG)
67
68 ch = logging.StreamHandler()
69
70 if args.debug:
71     ch.setLevel(logging.DEBUG)
72 else:
73     ch.setLevel(logging.INFO)
74
75 formatter = logging.Formatter('%(asctime)s - %(name)s'
76                               '- %(levelname)s - %(message)s')
77
78 ch.setFormatter(formatter)
79 logger.addHandler(ch)
80
81
82 def create_image(glance_client, name):
83
84     return image_id
85
86
87 def main():
88     ks_creds = functest_utils.get_credentials("keystone")
89     nv_creds = functest_utils.get_credentials("nova")
90     nt_creds = functest_utils.get_credentials("neutron")
91
92     keystone = ksclient.Client(**ks_creds)
93
94     user_id = functest_utils.get_user_id(keystone, ks_creds['username'])
95     if user_id == '':
96         logger.error("Error : Failed to get id of %s user" %
97                      ks_creds['username'])
98         exit(-1)
99
100     logger.info("Creating tenant '%s'..." % TENANT_NAME)
101     tenant_id = functest_utils.create_tenant(
102         keystone, TENANT_NAME, TENANT_DESCRIPTION)
103     if tenant_id == '':
104         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
105         exit(-1)
106     logger.debug("Tenant '%s' created successfully." % TENANT_NAME)
107
108     roles_name = ["admin", "Admin"]
109     role_id = ''
110     for role_name in roles_name:
111         if role_id == '':
112             role_id = functest_utils.get_role_id(keystone, role_name)
113
114     if role_id == '':
115         logger.error("Error : Failed to get id for %s role" % role_name)
116         exit(-1)
117
118     logger.info("Adding role '%s' to tenant '%s'..." % (role_id, TENANT_NAME))
119     if not functest_utils.add_role_user(keystone, user_id, role_id, tenant_id):
120         logger.error("Error : Failed to add %s on tenant %s" %
121                      (ks_creds['username'], TENANT_NAME))
122         exit(-1)
123     logger.debug("Role added successfully.")
124
125     logger.info("Creating user '%s'..." % USER_NAME)
126     user_id = functest_utils.create_user(
127         keystone, USER_NAME, USER_PWD, None, tenant_id)
128
129     if user_id == '':
130         logger.error("Error : Failed to create %s user" % USER_NAME)
131         exit(-1)
132     logger.debug("User '%s' created successfully." % USER_NAME)
133
134     logger.info("Updating OpenStack credentials...")
135     ks_creds.update({
136         "username": TENANT_NAME,
137         "password": TENANT_NAME,
138         "tenant_name": TENANT_NAME,
139     })
140
141     nt_creds.update({
142         "tenant_name": TENANT_NAME,
143     })
144
145     nv_creds.update({
146         "project_id": TENANT_NAME,
147     })
148
149     glance_endpoint = keystone.service_catalog.url_for(service_type='image',
150                                                        endpoint_type='publicURL')
151     glance = glclient.Client(1, glance_endpoint, token=keystone.auth_token)
152     nova = nvclient.Client("2", **nv_creds)
153
154     logger.info("Creating image '%s' from '%s'..." % (IMAGE_NAME,
155                                                       GLANCE_IMAGE_PATH))
156     image_id = functest_utils.create_glance_image(glance,
157                                                   IMAGE_NAME,
158                                                   GLANCE_IMAGE_PATH)
159     if not image_id:
160         logger.error("Failed to create the Glance image...")
161         exit(-1)
162     logger.debug("Image '%s' with ID '%s' created successfully." % (IMAGE_NAME,
163                                                                     image_id))
164     flavor_id = functest_utils.get_flavor_id(nova, FLAVOR_NAME)
165     if flavor_id == '':
166         logger.info("Creating flavor '%s'..." % FLAVOR_NAME)
167         flavor_id = functest_utils.create_flavor(nova,
168                                                  FLAVOR_NAME,
169                                                  FLAVOR_RAM,
170                                                  FLAVOR_DISK,
171                                                  FLAVOR_VCPUS)
172         if not flavor_id:
173             logger.error("Failed to create the Flavor...")
174             exit(-1)
175         logger.debug("Flavor '%s' with ID '%s' created successfully." %
176                      (FLAVOR_NAME, flavor_id))
177     else:
178         logger.debug("Using existing flavor '%s' with ID '%s'..." % (FLAVOR_NAME,
179                                                                      flavor_id))
180
181     neutron = ntclient.Client(**nt_creds)
182     private_net = functest_utils.get_private_net(neutron)
183     if private_net is None:
184         logger.error("There is no private network in the deployment. Aborting...")
185         exit(-1)
186     logger.debug("Using private network '%s' (%s)." % (private_net['name'],
187                                                        private_net['id']))
188
189     logger.info("Exporting environment variables...")
190     os.environ["NODE_ENV"] = "functest"
191     os.environ["OS_TENANT_NAME"] = TENANT_NAME
192     os.environ["OS_USERNAME"] = USER_NAME
193     os.environ["OS_PASSWORD"] = USER_PWD
194     os.environ["OS_TEST_IMAGE"] = image_id
195     os.environ["OS_TEST_FLAVOR"] = flavor_id
196     os.environ["OS_TEST_NETWORK"] = private_net['id']
197
198     os.chdir(PROMISE_REPO)
199     results_file_name = 'promise-results.json'
200     results_file = open(results_file_name, 'w+')
201     cmd = 'npm run -s test -- --reporter json'
202
203     logger.info("Running command: %s" % cmd)
204     ret = subprocess.call(cmd, shell=True, stdout=results_file, \
205                           stderr=subprocess.STDOUT)
206     results_file.close()
207
208     if ret == 0:
209         logger.info("The test succeeded.")
210         test_status = 'OK'
211     else:
212         logger.info("The command '%s' failed." % cmd)
213         test_status = "Failed"
214
215     # Print output of file
216     with open(results_file_name, 'r') as results_file:
217         data = results_file.read()
218         logger.debug("\n%s" % data)
219         json_data = json.loads(data)
220
221         suites = json_data["stats"]["suites"]
222         tests = json_data["stats"]["tests"]
223         passes = json_data["stats"]["passes"]
224         pending = json_data["stats"]["pending"]
225         failures = json_data["stats"]["failures"]
226         start_time = json_data["stats"]["start"]
227         end_time = json_data["stats"]["end"]
228         duration = float(json_data["stats"]["duration"])/float(1000)
229
230     logger.info("\n" \
231                 "****************************************\n"\
232                 "          Promise test report\n\n"\
233                 "****************************************\n"\
234                 " Suites:  \t%s\n"\
235                 " Tests:   \t%s\n"\
236                 " Passes:  \t%s\n"\
237                 " Pending: \t%s\n"\
238                 " Failures:\t%s\n"\
239                 " Start:   \t%s\n"\
240                 " End:     \t%s\n"\
241                 " Duration:\t%s\n"\
242                 "****************************************\n\n"\
243                 % (suites, tests, passes, pending, failures, 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()