Merge "CLI implementation"
[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 requests
16 import subprocess
17 import yaml
18
19 import keystoneclient.v2_0.client as ksclient
20 import glanceclient.client as glclient
21 import novaclient.client as nvclient
22 from neutronclient.v2_0 import client as ntclient
23
24 import functest.utils.functest_logger as ft_logger
25 import functest.utils.functest_utils as functest_utils
26 import functest.utils.openstack_utils as 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(os.environ["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 NET_NAME = functest_yaml.get('promise').get('general').get('network_name')
64 SUBNET_NAME = functest_yaml.get('promise').get('general').get('subnet_name')
65 SUBNET_CIDR = functest_yaml.get('promise').get('general').get('subnet_cidr')
66 ROUTER_NAME = functest_yaml.get('promise').get('general').get('router_name')
67
68
69 """ logging configuration """
70 logger = ft_logger.Logger("promise").getLogger()
71
72
73 def main():
74     ks_creds = openstack_utils.get_credentials("keystone")
75     nv_creds = openstack_utils.get_credentials("nova")
76     nt_creds = openstack_utils.get_credentials("neutron")
77
78     keystone = ksclient.Client(**ks_creds)
79
80     user_id = openstack_utils.get_user_id(keystone, ks_creds['username'])
81     if user_id == '':
82         logger.error("Error : Failed to get id of %s user" %
83                      ks_creds['username'])
84         exit(-1)
85
86     logger.info("Creating tenant '%s'..." % TENANT_NAME)
87     tenant_id = openstack_utils.create_tenant(
88         keystone, TENANT_NAME, TENANT_DESCRIPTION)
89     if tenant_id == '':
90         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
91         exit(-1)
92     logger.debug("Tenant '%s' created successfully." % TENANT_NAME)
93
94     roles_name = ["admin", "Admin"]
95     role_id = ''
96     for role_name in roles_name:
97         if role_id == '':
98             role_id = openstack_utils.get_role_id(keystone, role_name)
99
100     if role_id == '':
101         logger.error("Error : Failed to get id for %s role" % role_name)
102         exit(-1)
103
104     logger.info("Adding role '%s' to tenant '%s'..." % (role_id, TENANT_NAME))
105     if not openstack_utils.add_role_user(keystone, user_id,
106                                          role_id, tenant_id):
107         logger.error("Error : Failed to add %s on tenant %s" %
108                      (ks_creds['username'], TENANT_NAME))
109         exit(-1)
110     logger.debug("Role added successfully.")
111
112     logger.info("Creating user '%s'..." % USER_NAME)
113     user_id = openstack_utils.create_user(
114         keystone, USER_NAME, USER_PWD, None, tenant_id)
115
116     if user_id == '':
117         logger.error("Error : Failed to create %s user" % USER_NAME)
118         exit(-1)
119     logger.debug("User '%s' created successfully." % USER_NAME)
120
121     logger.info("Updating OpenStack credentials...")
122     ks_creds.update({
123         "username": TENANT_NAME,
124         "password": TENANT_NAME,
125         "tenant_name": TENANT_NAME,
126     })
127
128     nt_creds.update({
129         "tenant_name": TENANT_NAME,
130     })
131
132     nv_creds.update({
133         "project_id": TENANT_NAME,
134     })
135
136     glance_endpoint = keystone.service_catalog.url_for(
137         service_type='image', endpoint_type='publicURL')
138     glance = glclient.Client(1, glance_endpoint, token=keystone.auth_token)
139     nova = nvclient.Client("2", **nv_creds)
140
141     logger.info("Creating image '%s' from '%s'..." % (IMAGE_NAME,
142                                                       GLANCE_IMAGE_PATH))
143     image_id = openstack_utils.create_glance_image(glance,
144                                                    IMAGE_NAME,
145                                                    GLANCE_IMAGE_PATH)
146     if not image_id:
147         logger.error("Failed to create the Glance image...")
148         exit(-1)
149     logger.debug("Image '%s' with ID '%s' created successfully." % (IMAGE_NAME,
150                                                                     image_id))
151     flavor_id = openstack_utils.get_flavor_id(nova, FLAVOR_NAME)
152     if flavor_id == '':
153         logger.info("Creating flavor '%s'..." % FLAVOR_NAME)
154         flavor_id = openstack_utils.create_flavor(nova,
155                                                   FLAVOR_NAME,
156                                                   FLAVOR_RAM,
157                                                   FLAVOR_DISK,
158                                                   FLAVOR_VCPUS)
159         if not flavor_id:
160             logger.error("Failed to create the Flavor...")
161             exit(-1)
162         logger.debug("Flavor '%s' with ID '%s' created successfully." %
163                      (FLAVOR_NAME, flavor_id))
164     else:
165         logger.debug("Using existing flavor '%s' with ID '%s'..."
166                      % (FLAVOR_NAME, flavor_id))
167
168     neutron = ntclient.Client(**nt_creds)
169
170     network_dic = openstack_utils.create_network_full(logger,
171                                                       neutron,
172                                                       NET_NAME,
173                                                       SUBNET_NAME,
174                                                       ROUTER_NAME,
175                                                       SUBNET_CIDR)
176     if network_dic is False:
177         logger.error("Failed to create the private network...")
178         exit(-1)
179
180     logger.info("Exporting environment variables...")
181     os.environ["NODE_ENV"] = "functest"
182     os.environ["OS_TENANT_NAME"] = TENANT_NAME
183     os.environ["OS_USERNAME"] = USER_NAME
184     os.environ["OS_PASSWORD"] = USER_PWD
185     os.environ["OS_TEST_IMAGE"] = image_id
186     os.environ["OS_TEST_FLAVOR"] = flavor_id
187     os.environ["OS_TEST_NETWORK"] = network_dic["net_id"]
188
189     os.chdir(PROMISE_REPO)
190     results_file_name = 'promise-results.json'
191     results_file = open(results_file_name, 'w+')
192     cmd = 'npm run -s test -- --reporter json'
193
194     logger.info("Running command: %s" % cmd)
195     ret = subprocess.call(cmd, shell=True, stdout=results_file,
196                           stderr=subprocess.STDOUT)
197     results_file.close()
198
199     if ret == 0:
200         logger.info("The test succeeded.")
201         # test_status = 'OK'
202     else:
203         logger.info("The command '%s' failed." % cmd)
204         # test_status = "Failed"
205
206     # Print output of file
207     with open(results_file_name, 'r') as results_file:
208         data = results_file.read()
209         logger.debug("\n%s" % data)
210         json_data = json.loads(data)
211
212         suites = json_data["stats"]["suites"]
213         tests = json_data["stats"]["tests"]
214         passes = json_data["stats"]["passes"]
215         pending = json_data["stats"]["pending"]
216         failures = json_data["stats"]["failures"]
217         start_time = json_data["stats"]["start"]
218         end_time = json_data["stats"]["end"]
219         duration = float(json_data["stats"]["duration"]) / float(1000)
220
221     logger.info("\n"
222                 "****************************************\n"
223                 "          Promise test report\n\n"
224                 "****************************************\n"
225                 " Suites:  \t%s\n"
226                 " Tests:   \t%s\n"
227                 " Passes:  \t%s\n"
228                 " Pending: \t%s\n"
229                 " Failures:\t%s\n"
230                 " Start:   \t%s\n"
231                 " End:     \t%s\n"
232                 " Duration:\t%s\n"
233                 "****************************************\n\n"
234                 % (suites, tests, passes, pending, failures,
235                    start_time, end_time, duration))
236
237     if args.report:
238         pod_name = functest_utils.get_pod_name(logger)
239         installer = functest_utils.get_installer_type(logger)
240         scenario = functest_utils.get_scenario(logger)
241         version = functest_utils.get_version(logger)
242         build_tag = functest_utils.get_build_tag(logger)
243         # git_version = functest_utils.get_git_branch(PROMISE_REPO)
244         url = TEST_DB + "/results"
245
246         json_results = {"timestart": start_time, "duration": duration,
247                         "tests": int(tests), "failures": int(failures)}
248         logger.debug("Results json: " + str(json_results))
249
250         # criteria for Promise in Release B was 100% of tests OK
251         status = "failed"
252         if int(tests) > 32 and int(failures) < 1:
253             status = "passed"
254
255         params = {"project_name": "promise", "case_name": "promise",
256                   "pod_name": str(pod_name), 'installer': installer,
257                   "version": version, "scenario": scenario,
258                   "criteria": status, "build_tag": build_tag,
259                   'details': json_results}
260         headers = {'Content-Type': 'application/json'}
261
262         logger.info("Pushing results to DB...")
263         r = requests.post(url, data=json.dumps(params), headers=headers)
264         logger.debug(r)
265
266
267 if __name__ == '__main__':
268     main()