Merge "Refactor OSCreds to leverage kwargs instead of named parameters."
[snaps.git] / snaps / 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 json
17 import logging
18 import unittest
19
20 from snaps import test_suite_builder, file_utils
21 from snaps.openstack.tests import openstack_tests
22
23 __author__ = 'spisarski'
24
25 logger = logging.getLogger('test_runner')
26
27 ARG_NOT_SET = "argument not set"
28 LOG_LEVELS = {'FATAL': logging.FATAL, 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARN': logging.WARN,
29               'INFO': logging.INFO, 'DEBUG': logging.DEBUG}
30
31
32 def __create_test_suite(source_filename, ext_net_name, proxy_settings, ssh_proxy_cmd, run_unit_tests,
33                         run_connection_tests, run_api_tests, run_integration_tests, run_staging_tests, flavor_metadata,
34                         image_metadata, use_keystone, use_floating_ips, log_level):
35     """
36     Compiles the tests that should run
37     :param source_filename: the OpenStack credentials file (required)
38     :param ext_net_name: the name of the external network to use for floating IPs (required)
39     :param run_unit_tests: when true, the tests not requiring OpenStack will be added to the test suite
40     :param run_connection_tests: when true, the tests that perform simple connections to OpenStack are executed
41     :param run_api_tests: when true, the tests that perform simple API calls to OpenStack are executed
42     :param run_integration_tests: when true, the integration tests are executed
43     :param run_staging_tests: when true, the staging tests are executed
44     :param proxy_settings: <host>:<port> of the proxy server (optional)
45     :param ssh_proxy_cmd: the command used to connect via SSH over some proxy server (optional)
46     :param flavor_metadata: dict() object containing the metadata for flavors created for test VM instance
47     :param image_metadata: dict() object containing the metadata for overriding default images within the tests
48     :param use_keystone: when true, tests creating users and projects will be exercised and must be run on a host that
49                          has access to the cloud's administrative network
50     :param use_floating_ips: when true, tests requiring floating IPs will be executed
51     :param log_level: the logging level
52     :return:
53     """
54     suite = unittest.TestSuite()
55
56     os_creds = openstack_tests.get_credentials(os_env_file=source_filename, proxy_settings_str=proxy_settings,
57                                                ssh_proxy_cmd=ssh_proxy_cmd)
58
59     # Tests that do not require a remote connection to an OpenStack cloud
60     if run_unit_tests:
61         test_suite_builder.add_unit_tests(suite)
62
63     # Basic connection tests
64     if run_connection_tests:
65         test_suite_builder.add_openstack_client_tests(
66             suite=suite, os_creds=os_creds, ext_net_name=ext_net_name, use_keystone=use_keystone, log_level=log_level)
67
68     # Tests the OpenStack API calls
69     if run_api_tests:
70         test_suite_builder.add_openstack_api_tests(
71             suite=suite, os_creds=os_creds, ext_net_name=ext_net_name, use_keystone=use_keystone,
72             image_metadata=image_metadata, log_level=log_level)
73
74     # Long running integration type tests
75     if run_integration_tests:
76         test_suite_builder.add_openstack_integration_tests(
77             suite=suite, os_creds=os_creds, ext_net_name=ext_net_name, use_keystone=use_keystone,
78             flavor_metadata=flavor_metadata, image_metadata=image_metadata, use_floating_ips=use_floating_ips,
79             log_level=log_level)
80
81     if run_staging_tests:
82         test_suite_builder.add_openstack_staging_tests(
83             suite=suite, os_creds=os_creds, ext_net_name=ext_net_name, log_level=log_level)
84     return suite
85
86
87 def main(arguments):
88     """
89     Begins running unit tests.
90     argv[1] if used must be the source filename else os_env.yaml will be leveraged instead
91     argv[2] if used must be the proxy server <host>:<port>
92     """
93     logger.info('Starting test suite')
94
95     log_level = LOG_LEVELS.get(arguments.log_level, logging.DEBUG)
96
97     flavor_metadata = None
98     if arguments.flavor_metadata:
99         flavor_metadata = json.loads(arguments.flavor_metadata)
100
101     image_metadata = None
102     if arguments.image_metadata_file:
103         image_metadata = file_utils.read_yaml(arguments.image_metadata_file)
104
105     suite = None
106     if arguments.env and arguments.ext_net:
107         unit = arguments.include_unit != ARG_NOT_SET
108         connection = arguments.include_connection != ARG_NOT_SET
109         api = arguments.include_api != ARG_NOT_SET
110         integration = arguments.include_integration != ARG_NOT_SET
111         staging = arguments.include_staging != ARG_NOT_SET
112         if not unit and not connection and not api and not integration and not staging:
113             unit = True
114             connection = True
115             api = True
116             integration = True
117
118         suite = __create_test_suite(arguments.env, arguments.ext_net, arguments.proxy, arguments.ssh_proxy_cmd,
119                                     unit, connection, api, integration, staging, flavor_metadata, image_metadata,
120                                     arguments.use_keystone != ARG_NOT_SET,
121                                     arguments.floating_ips != ARG_NOT_SET, log_level)
122     else:
123         logger.error('Environment file or external network not defined')
124         exit(1)
125
126     i = 0
127     while i < int(arguments.num_runs):
128         result = unittest.TextTestRunner(verbosity=2).run(suite)
129         i += 1
130
131         if result.errors:
132             logger.error('Number of errors in test suite - ' + str(len(result.errors)))
133             for test, message in result.errors:
134                 logger.error(str(test) + " ERROR with " + message)
135
136         if result.failures:
137             logger.error('Number of failures in test suite - ' + str(len(result.failures)))
138             for test, message in result.failures:
139                 logger.error(str(test) + " FAILED with " + message)
140
141         if (result.errors and len(result.errors) > 0) or (result.failures and len(result.failures) > 0):
142             logger.error('See above for test failures')
143             exit(1)
144         else:
145             logger.info('All tests completed successfully in run #' + str(i))
146
147     logger.info('Successful completion of ' + str(i) + ' test runs')
148     exit(0)
149
150
151 if __name__ == '__main__':
152     parser = argparse.ArgumentParser()
153     parser.add_argument('-e', '--env', dest='env', required=True, help='OpenStack credentials file')
154     parser.add_argument('-n', '--net', dest='ext_net', required=True, help='External network name')
155     parser.add_argument('-p', '--proxy', dest='proxy', nargs='?', default=None,
156                         help='Optonal HTTP proxy socket (<host>:<port>)')
157     parser.add_argument('-s', '--ssh-proxy-cmd', dest='ssh_proxy_cmd', nargs='?', default=None,
158                         help='Optonal SSH proxy command value')
159     parser.add_argument('-l', '--log-level', dest='log_level', default='INFO',
160                         help='Logging Level (FATAL|CRITICAL|ERROR|WARN|INFO|DEBUG)')
161     parser.add_argument('-u', '--unit-tests', dest='include_unit', default=ARG_NOT_SET, nargs='?',
162                         help='When argument is set, all tests not requiring OpenStack will be executed')
163     parser.add_argument('-c', '--connection-tests', dest='include_connection', default=ARG_NOT_SET, nargs='?',
164                         help='When argument is set, simple OpenStack connection tests will be executed')
165     parser.add_argument('-a', '--api-tests', dest='include_api', default=ARG_NOT_SET, nargs='?',
166                         help='When argument is set, OpenStack API tests will be executed')
167     parser.add_argument('-i', '--integration-tests', dest='include_integration', default=ARG_NOT_SET, nargs='?',
168                         help='When argument is set, OpenStack integrations tests will be executed')
169     parser.add_argument('-st', '--staging-tests', dest='include_staging', default=ARG_NOT_SET, nargs='?',
170                         help='When argument is set, OpenStack staging tests will be executed')
171     parser.add_argument('-f', '--floating-ips', dest='floating_ips', default=ARG_NOT_SET, nargs='?',
172                         help='When argument is set, all integration tests requiring Floating IPs will be executed')
173     parser.add_argument('-k', '--use-keystone', dest='use_keystone', default=ARG_NOT_SET, nargs='?',
174                         help='When argument is set, the tests will exercise the keystone APIs and must be run on a ' +
175                              'machine that has access to the admin network' +
176                              ' and is able to create users and groups')
177     parser.add_argument('-fm', '--flavor-meta', dest='flavor_metadata',
178                         default='{\"hw:mem_page_size\": \"any\"}',
179                         help='JSON string to be used as flavor metadata for all test instances created')
180     parser.add_argument('-im', '--image-meta', dest='image_metadata_file',
181                         default=None,
182                         help='Location of YAML file containing the image metadata')
183     parser.add_argument('-r', '--num-runs', dest='num_runs', default=1,
184                         help='Number of test runs to execute (default 1)')
185
186     args = parser.parse_args()
187
188     main(args)