Merge "Add support for Promise test cases"
[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 logging
14 import os
15 import time
16 import sys
17 import yaml
18 import keystoneclient.v2_0.client as ksclient
19 import glanceclient.client as glclient
20 import novaclient.client as nvclient
21
22 parser = argparse.ArgumentParser()
23
24 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
25 parser.add_argument("-r", "--report",
26                     help="Create json result file",
27                     action="store_true")
28 args = parser.parse_args()
29
30 with open('/home/opnfv/functest/conf/config_functest.yaml') as f:
31     functest_yaml = yaml.safe_load(f)
32
33 dirs = functest_yaml.get('general').get('directories')
34 FUNCTEST_REPO = dirs.get('dir_repo_functest')
35 PROMISE_REPO = dirs.get('dir_repo_promise')
36 TEST_DB_URL = functest_yaml.get('results').get('test_db_url')
37
38 TENANT_NAME = functest_yaml.get('promise').get('general').get('tenant_name')
39 TENANT_DESCRIPTION = functest_yaml.get('promise').get(
40     'general').get('tenant_description')
41 USER_NAME = functest_yaml.get('promise').get('general').get('user_name')
42 USER_PWD = functest_yaml.get('promise').get('general').get('user_pwd')
43 IMAGE_NAME = functest_yaml.get('promise').get('general').get('image_name')
44 FLAVOR_NAME = functest_yaml.get('promise').get('general').get('flavor_name')
45 FLAVOR_VCPUS = functest_yaml.get('promise').get('general').get('flavor_vcpus')
46 FLAVOR_RAM = functest_yaml.get('promise').get('general').get('flavor_ram')
47 FLAVOR_DISK = functest_yaml.get('promise').get('general').get('flavor_disk')
48
49
50 GLANCE_IMAGE_FILENAME = functest_yaml.get('general'). \
51     get('openstack').get('image_file_name')
52 GLANCE_IMAGE_FORMAT = functest_yaml.get('general'). \
53     get('openstack').get('image_disk_format')
54 GLANCE_IMAGE_PATH = functest_yaml.get('general'). \
55     get('directories').get('dir_functest_data') + "/" + GLANCE_IMAGE_FILENAME
56
57 sys.path.append('%s/testcases' % FUNCTEST_REPO)
58 import functest_utils
59
60 """ logging configuration """
61 logger = logging.getLogger('Promise')
62 logger.setLevel(logging.DEBUG)
63
64 ch = logging.StreamHandler()
65
66 if args.debug:
67     ch.setLevel(logging.DEBUG)
68 else:
69     ch.setLevel(logging.INFO)
70
71 formatter = logging.Formatter('%(asctime)s - %(name)s'
72                               '- %(levelname)s - %(message)s')
73
74 ch.setFormatter(formatter)
75 logger.addHandler(ch)
76
77
78
79 def create_image(glance_client, name):
80
81     return image_id
82
83
84 def main():
85     ks_creds = functest_utils.get_credentials("keystone")
86     nv_creds = functest_utils.get_credentials("nova")
87     nt_creds = functest_utils.get_credentials("neutron")
88
89     keystone = ksclient.Client(**ks_creds)
90
91     user_id = functest_utils.get_user_id(keystone, ks_creds['username'])
92     if user_id == '':
93         logger.error("Error : Failed to get id of %s user" %
94                      ks_creds['username'])
95         exit(-1)
96
97     logger.info("Creating tenant '%s'..." % TENANT_NAME)
98     tenant_id = functest_utils.create_tenant(
99         keystone, TENANT_NAME, TENANT_DESCRIPTION)
100     if tenant_id == '':
101         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
102         exit(-1)
103     logger.debug("Tenant '%s' created successfully." % TENANT_NAME)
104
105     roles_name = ["admin", "Admin"]
106     role_id = ''
107     for role_name in roles_name:
108         if role_id == '':
109             role_id = functest_utils.get_role_id(keystone, role_name)
110
111     if role_id == '':
112         logger.error("Error : Failed to get id for %s role" % role_name)
113         exit(-1)
114
115     logger.info("Adding role '%s' to tenant '%s'..." % (role_id,TENANT_NAME))
116     if not functest_utils.add_role_user(keystone, user_id, 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 = functest_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.service_catalog.url_for(service_type='image',
147                                                        endpoint_type='publicURL')
148     glance = glclient.Client(1, glance_endpoint, token=keystone.auth_token)
149     nova = nvclient.Client("2", **nv_creds)
150
151
152     logger.info("Creating image '%s' from '%s'..." % (IMAGE_NAME,
153                                                        GLANCE_IMAGE_PATH))
154     image_id = functest_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
163     flavor_id = functest_utils.create_flavor(nova,
164                                              FLAVOR_NAME,
165                                              FLAVOR_RAM,
166                                              FLAVOR_DISK,
167                                              FLAVOR_VCPUS)
168     if not flavor_id:
169         logger.error("Failed to create the Flavor...")
170         exit(-1)
171     logger.debug("Flavor '%s' with ID '%s' created successfully." % (FLAVOR_NAME,
172                                                                     flavor_id))
173
174     logger.info("Exporting environment variables...")
175     os.environ["NODE_ENV"] = "functest"
176     os.environ["OS_TENANT_NAME"] = TENANT_NAME
177     os.environ["OS_USERNAME"] = USER_NAME
178     os.environ["OS_PASSWORD"] = USER_PWD
179     os.environ["OS_TEST_IMAGE"] = image_id
180     os.environ["OS_TEST_FLAVOR"] = flavor_id
181
182     cmd = 'DEBUG=1 npm run -s test'
183     start_time_ts = time.time()
184
185     logger.info("Running command: %s" % cmd)
186     os.chdir(PROMISE_REPO)
187     ret = functest_utils.execute_command(cmd, exit_on_error=False)
188
189     end_time_ts = time.time()
190     duration = round(end_time_ts - start_time_ts, 1)
191     test_status = 'Failed'
192     if ret:
193         test_status = 'OK'
194
195     logger.info("Test status: %s" % test_status)
196     details = {
197         'timestart': start_time_ts,
198         'duration': duration,
199         'status': test_status,
200     }
201     pod_name = functest_utils.get_pod_name()
202     git_version = functest_utils.get_git_branch(PROMISE_REPO)
203     #functest_utils.push_results_to_db(TEST_DB_URL,
204     #                                  'promise',
205     #                                  None,
206     #                                  pod_name,
207     #                                  git_version,
208     #                                  details)
209     #
210
211 if __name__ == '__main__':
212     main()