Fix an invalid filter attribute when listing floating ips
[snaps.git] / snaps / custom_image_test_runner.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 import argparse
16 import logging
17 import unittest
18
19 from snaps import test_suite_builder
20 from snaps.openstack.create_image import OpenStackImage
21 from snaps.openstack.tests import openstack_tests
22 from snaps.openstack.tests.os_source_file_test import OSComponentTestCase
23 from snaps.openstack.utils.tests.glance_utils_tests import GlanceUtilsTests
24
25 __author__ = 'spisarski'
26
27 logger = logging.getLogger('custom_image_test_runner')
28
29 ARG_NOT_SET = "argument not set"
30 LOG_LEVELS = {'FATAL': logging.FATAL, 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARN': logging.WARN,
31               'INFO': logging.INFO, 'DEBUG': logging.DEBUG}
32
33
34 def __run_tests(source_filename, ext_net_name, proxy_settings, ssh_proxy_cmd, use_keystone, use_floating_ips,
35                 log_level):
36     """
37     Compiles the tests that should run
38     :param source_filename: the OpenStack credentials file (required)
39     :param ext_net_name: the name of the external network to use for floating IPs (required)
40     :param proxy_settings: <host>:<port> of the proxy server (optional)
41     :param ssh_proxy_cmd: the command used to connect via SSH over some proxy server (optional)
42     :param use_keystone: when true, tests creating users and projects will be exercised and must be run on a host that
43                          has access to the cloud's administrative network
44     :param use_floating_ips: when true, tests requiring floating IPs will be executed
45     :param log_level: the logging level
46     :return:
47     """
48     os_creds = openstack_tests.get_credentials(os_env_file=source_filename, proxy_settings_str=proxy_settings,
49                                                ssh_proxy_cmd=ssh_proxy_cmd)
50     image_creators = __create_images(os_creds)
51
52     meta_list = list()
53
54     # Create images from default
55     meta_list.append(None)
56
57     # Create images from specified URL
58     meta_list.append(
59         {'glance_tests': {'disk_url': openstack_tests.CIRROS_DEFAULT_IMAGE_URL},
60          'cirros': {'disk_url': openstack_tests.CIRROS_DEFAULT_IMAGE_URL},
61          'centos': {'disk_url': openstack_tests.CENTOS_DEFAULT_IMAGE_URL},
62          'ubuntu': {'disk_url': openstack_tests.UBUNTU_DEFAULT_IMAGE_URL}})
63
64     # Create images from file
65     meta_list.append(
66         {'glance_tests': {'disk_file': '../images/cirros-0.3.4-x86_64-disk.img'},
67          'cirros': {'disk_file': '../images/cirros-0.3.4-x86_64-disk.img'},
68          'centos': {'disk_file': '../images/CentOS-7-x86_64-GenericCloud.qcow2'},
69          'ubuntu': {'disk_file': '../images/ubuntu-14.04-server-cloudimg-amd64-disk1.img'}})
70
71     # Create images from Existing
72     meta_list.append(
73         {'glance_tests': {'disk_file': '../images/cirros-0.3.4-x86_64-disk.img'},
74          'cirros': {'config': {'name': image_creators['cirros'].image_settings.name,
75                                'exists': True, 'image_user': 'cirros'}},
76          'centos': {'config': {'name': image_creators['centos'].image_settings.name,
77                                'exists': True, 'image_user': 'centos'}},
78          'ubuntu': {'config': {'name': image_creators['ubuntu'].image_settings.name,
79                                'exists': True, 'image_user': 'ubuntu'}}})
80
81     failure_count = 0
82     error_count = 0
83
84     try:
85         for metadata in meta_list:
86             logger.info('Starting tests with image metadata of - ' + str(metadata))
87             suite = unittest.TestSuite()
88
89             # Long running integration type tests
90             suite.addTest(OSComponentTestCase.parameterize(
91                 GlanceUtilsTests, os_creds=os_creds, ext_net_name=ext_net_name, image_metadata=metadata,
92                 log_level=log_level))
93
94             test_suite_builder.add_openstack_integration_tests(
95                 suite=suite, os_creds=os_creds, ext_net_name=ext_net_name, use_keystone=use_keystone,
96                 image_metadata=metadata, use_floating_ips=use_floating_ips, log_level=log_level)
97
98             result = unittest.TextTestRunner(verbosity=2).run(suite)
99             if result.errors:
100                 logger.error('Number of errors in test suite - ' + str(len(result.errors)))
101                 for test, message in result.errors:
102                     logger.error(str(test) + " ERROR with " + message)
103                     error_count += 1
104
105             if result.failures:
106                 logger.error('Number of failures in test suite - ' + str(len(result.failures)))
107                 for test, message in result.failures:
108                     logger.error(str(test) + " FAILED with " + message)
109                     failure_count += 1
110
111             if (result.errors and len(result.errors) > 0) or (result.failures and len(result.failures) > 0):
112                 logger.error('See above for test failures')
113             else:
114                 logger.info('All tests completed successfully in run')
115
116         logger.info('Total number of errors = ' + str(error_count))
117         logger.info('Total number of failures = ' + str(failure_count))
118
119         if error_count + failure_count > 0:
120             exit(1)
121     except Exception as e:
122         logger.warn('Unexpected error running tests - %s', e)
123         pass
124     finally:
125         for image_creator in image_creators.values():
126             try:
127                 image_creator.clean()
128             except Exception as e:
129                 logger.error('Exception thrown while cleaning image - %s', e)
130
131
132 def __create_images(os_creds):
133     """
134     Returns a dictionary of 
135     :param os_creds: 
136     :return: 
137     """
138     image_meta = {'cirros': {'disk_url': openstack_tests.CIRROS_DEFAULT_IMAGE_URL,
139                              'kernel_url': openstack_tests.CIRROS_DEFAULT_KERNEL_IMAGE_URL,
140                              'ramdisk_url': openstack_tests.CIRROS_DEFAULT_RAMDISK_IMAGE_URL},
141                   'centos': {'disk_file': '../images/CentOS-7-x86_64-GenericCloud.qcow2'},
142                   'ubuntu': {'disk_file': '../images/ubuntu-14.04-server-cloudimg-amd64-disk1.img'}}
143     cirros_image_settings = openstack_tests.cirros_image_settings(name='static_image_test-cirros',
144                                                                   image_metadata=image_meta, public=True)
145     centos_image_settings = openstack_tests.centos_image_settings(name='static_image_test-centos',
146                                                                   image_metadata=image_meta, public=True)
147     ubuntu_image_settings = openstack_tests.ubuntu_image_settings(name='static_image_test-ubuntu',
148                                                                   image_metadata=image_meta, public=True)
149
150     out = dict()
151     out['cirros'] = OpenStackImage(os_creds, cirros_image_settings)
152     out['cirros'].create()
153     out['centos'] = OpenStackImage(os_creds, centos_image_settings)
154     out['centos'].create()
155     out['ubuntu'] = OpenStackImage(os_creds, ubuntu_image_settings)
156     out['ubuntu'].create()
157
158     return out
159
160
161 def main(arguments):
162     """
163     Begins running tests with different image_metadata configuration.
164     argv[1] if used must be the source filename else os_env.yaml will be leveraged instead
165     argv[2] if used must be the proxy server <host>:<port>
166     """
167     log_level = LOG_LEVELS.get(arguments.log_level, logging.DEBUG)
168     logging.basicConfig(level=log_level)
169     logger.info('Starting test suite')
170
171     __run_tests(arguments.env, arguments.ext_net, arguments.proxy, arguments.ssh_proxy_cmd,
172                 arguments.use_keystone != ARG_NOT_SET, arguments.floating_ips != ARG_NOT_SET, log_level)
173
174     exit(0)
175
176
177 if __name__ == '__main__':
178     parser = argparse.ArgumentParser()
179     parser.add_argument('-e', '--env', dest='env', required=True, help='OpenStack credentials file')
180     parser.add_argument('-n', '--net', dest='ext_net', required=True, help='External network name')
181     parser.add_argument('-p', '--proxy', dest='proxy', nargs='?', default=None,
182                         help='Optonal HTTP proxy socket (<host>:<port>)')
183     parser.add_argument('-s', '--ssh-proxy-cmd', dest='ssh_proxy_cmd', nargs='?', default=None,
184                         help='Optonal SSH proxy command value')
185     parser.add_argument('-l', '--log-level', dest='log_level', default='INFO',
186                         help='Logging Level (FATAL|CRITICAL|ERROR|WARN|INFO|DEBUG)')
187     parser.add_argument('-f', '--floating-ips', dest='floating_ips', default=ARG_NOT_SET, nargs='?',
188                         help='When argument is set, all integration tests requiring Floating IPs will be executed')
189     parser.add_argument('-k', '--use-keystone', dest='use_keystone', default=ARG_NOT_SET, nargs='?',
190                         help='When argument is set, the tests will exercise the keystone APIs and must be run on a ' +
191                              'machine that has access to the admin network' +
192                              ' and is able to create users and groups')
193
194     args = parser.parse_args()
195
196     main(args)