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