blob: 56c0554119ffd1aadcbc4353f75e610196e00581 [file] [log] [blame]
Jay Pipes051075a2012-04-28 17:39:37 -04001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
ZhiQiang Fan39f97222013-09-20 04:49:44 +08003# Copyright 2012 OpenStack Foundation
Jay Pipes051075a2012-04-28 17:39:37 -04004# All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17
Attila Fazekasf86fa312013-07-30 19:56:39 +020018import atexit
Masayuki Igawa80c1b9f2013-10-07 17:19:11 +090019import functools
Ian Wienand98c35f32013-07-23 20:34:23 +100020import os
Jay Pipes051075a2012-04-28 17:39:37 -040021import time
22
Matthew Treinish78561ad2013-07-26 11:41:56 -040023import fixtures
Chris Yeoh55530bb2013-02-08 16:04:27 +103024import nose.plugins.attrib
Attila Fazekasdc216422013-01-29 15:12:14 +010025import testresources
ivan-zhu1feeb382013-01-24 10:14:39 +080026import testtools
Jay Pipes051075a2012-04-28 17:39:37 -040027
Matthew Treinish3e046852013-07-23 16:00:24 -040028from tempest import clients
Ryan Hsu6c4bb3d2013-10-21 21:22:50 -070029from tempest.common import isolated_creds
Attila Fazekasdc216422013-01-29 15:12:14 +010030from tempest import config
Matthew Treinish16c43792013-09-09 19:55:23 +000031from tempest import exceptions
Matthew Treinishf4a9b0f2013-07-26 16:58:26 -040032from tempest.openstack.common import log as logging
Jay Pipes051075a2012-04-28 17:39:37 -040033
34LOG = logging.getLogger(__name__)
35
Sean Dague86bd8422013-12-20 09:56:44 -050036CONF = config.CONF
37
Samuel Merritt0d499bc2013-06-19 12:08:23 -070038# All the successful HTTP status codes from RFC 2616
39HTTP_SUCCESS = (200, 201, 202, 203, 204, 205, 206)
40
Jay Pipes051075a2012-04-28 17:39:37 -040041
Chris Yeoh55530bb2013-02-08 16:04:27 +103042def attr(*args, **kwargs):
43 """A decorator which applies the nose and testtools attr decorator
44
45 This decorator applies the nose attr decorator as well as the
46 the testtools.testcase.attr if it is in the list of attributes
Attila Fazekasb2902af2013-02-16 16:22:44 +010047 to testtools we want to apply.
48 """
Chris Yeoh55530bb2013-02-08 16:04:27 +103049
50 def decorator(f):
Giulio Fidente4946a052013-05-14 12:23:51 +020051 if 'type' in kwargs and isinstance(kwargs['type'], str):
52 f = testtools.testcase.attr(kwargs['type'])(f)
Chris Yeohcf3fb7c2013-05-19 15:59:00 +093053 if kwargs['type'] == 'smoke':
54 f = testtools.testcase.attr('gate')(f)
Giulio Fidente4946a052013-05-14 12:23:51 +020055 elif 'type' in kwargs and isinstance(kwargs['type'], list):
56 for attr in kwargs['type']:
57 f = testtools.testcase.attr(attr)(f)
Chris Yeohcf3fb7c2013-05-19 15:59:00 +093058 if attr == 'smoke':
59 f = testtools.testcase.attr('gate')(f)
Giulio Fidente4946a052013-05-14 12:23:51 +020060 return nose.plugins.attrib.attr(*args, **kwargs)(f)
Chris Yeoh55530bb2013-02-08 16:04:27 +103061
62 return decorator
63
64
Matthew Treinish16c43792013-09-09 19:55:23 +000065def services(*args, **kwargs):
66 """A decorator used to set an attr for each service used in a test case
67
68 This decorator applies a testtools attr for each service that gets
69 exercised by a test case.
70 """
71 valid_service_list = ['compute', 'image', 'volume', 'orchestration',
72 'network', 'identity', 'object', 'dashboard']
73
74 def decorator(f):
75 for service in args:
76 if service not in valid_service_list:
77 raise exceptions.InvalidServiceTag('%s is not a valid service'
78 % service)
79 attr(type=list(args))(f)
80 return f
81 return decorator
82
83
Marc Koderer32221b8e2013-08-23 13:57:50 +020084def stresstest(*args, **kwargs):
85 """Add stress test decorator
86
87 For all functions with this decorator a attr stress will be
88 set automatically.
89
90 @param class_setup_per: allowed values are application, process, action
91 ``application``: once in the stress job lifetime
92 ``process``: once in the worker process lifetime
93 ``action``: on each action
Marc Kodererb0604412013-09-02 09:43:40 +020094 @param allow_inheritance: allows inheritance of this attribute
Marc Koderer32221b8e2013-08-23 13:57:50 +020095 """
96 def decorator(f):
97 if 'class_setup_per' in kwargs:
98 setattr(f, "st_class_setup_per", kwargs['class_setup_per'])
99 else:
100 setattr(f, "st_class_setup_per", 'process')
Marc Kodererb0604412013-09-02 09:43:40 +0200101 if 'allow_inheritance' in kwargs:
102 setattr(f, "st_allow_inheritance", kwargs['allow_inheritance'])
103 else:
104 setattr(f, "st_allow_inheritance", False)
Marc Koderer32221b8e2013-08-23 13:57:50 +0200105 attr(type='stress')(f)
106 return f
107 return decorator
108
109
Giulio Fidente83181a92013-10-01 06:02:24 +0200110def skip_because(*args, **kwargs):
111 """A decorator useful to skip tests hitting known bugs
112
113 @param bug: bug number causing the test to skip
114 @param condition: optional condition to be True for the skip to have place
115 """
116 def decorator(f):
Masayuki Igawa80c1b9f2013-10-07 17:19:11 +0900117 @functools.wraps(f)
118 def wrapper(*func_args, **func_kwargs):
119 if "bug" in kwargs:
120 if "condition" not in kwargs or kwargs["condition"] is True:
121 msg = "Skipped until Bug: %s is resolved." % kwargs["bug"]
122 raise testtools.TestCase.skipException(msg)
123 return f(*func_args, **func_kwargs)
124 return wrapper
Giulio Fidente83181a92013-10-01 06:02:24 +0200125 return decorator
126
127
Matthew Treinishe3d26142013-11-26 19:14:58 +0000128def requires_ext(*args, **kwargs):
129 """A decorator to skip tests if an extension is not enabled
130
131 @param extension
132 @param service
133 """
134 def decorator(func):
135 @functools.wraps(func)
136 def wrapper(*func_args, **func_kwargs):
137 if not is_extension_enabled(kwargs['extension'],
138 kwargs['service']):
139 msg = "Skipped because %s extension: %s is not enabled" % (
140 kwargs['service'], kwargs['extension'])
141 raise testtools.TestCase.skipException(msg)
142 return func(*func_args, **func_kwargs)
143 return wrapper
144 return decorator
145
146
147def is_extension_enabled(extension_name, service):
148 """A function that will check the list of enabled extensions from config
149
150 """
Sean Dague86bd8422013-12-20 09:56:44 -0500151 configs = CONF
Matthew Treinishe3d26142013-11-26 19:14:58 +0000152 config_dict = {
153 'compute': configs.compute_feature_enabled.api_extensions,
154 'compute_v3': configs.compute_feature_enabled.api_v3_extensions,
155 'volume': configs.volume_feature_enabled.api_extensions,
156 'network': configs.network_feature_enabled.api_extensions,
157 }
158 if config_dict[service][0] == 'all':
159 return True
160 if extension_name in config_dict[service]:
161 return True
162 return False
163
Ian Wienand98c35f32013-07-23 20:34:23 +1000164# there is a mis-match between nose and testtools for older pythons.
165# testtools will set skipException to be either
166# unittest.case.SkipTest, unittest2.case.SkipTest or an internal skip
167# exception, depending on what it can find. Python <2.7 doesn't have
168# unittest.case.SkipTest; so if unittest2 is not installed it falls
169# back to the internal class.
170#
171# The current nose skip plugin will decide to raise either
172# unittest.case.SkipTest or its own internal exception; it does not
173# look for unittest2 or the internal unittest exception. Thus we must
174# monkey-patch testtools.TestCase.skipException to be the exception
175# the nose skip plugin expects.
176#
177# However, with the switch to testr nose may not be available, so we
178# require you to opt-in to this fix with an environment variable.
179#
180# This is temporary until upstream nose starts looking for unittest2
181# as testtools does; we can then remove this and ensure unittest2 is
182# available for older pythons; then nose and testtools will agree
183# unittest2.case.SkipTest is the one-true skip test exception.
184#
185# https://review.openstack.org/#/c/33056
186# https://github.com/nose-devs/nose/pull/699
187if 'TEMPEST_PY26_NOSE_COMPAT' in os.environ:
188 try:
189 import unittest.case.SkipTest
190 # convince pep8 we're using the import...
191 if unittest.case.SkipTest:
192 pass
193 raise RuntimeError("You have unittest.case.SkipTest; "
194 "no need to override")
195 except ImportError:
196 LOG.info("Overriding skipException to nose SkipTest")
197 testtools.TestCase.skipException = nose.plugins.skip.SkipTest
198
Attila Fazekasf86fa312013-07-30 19:56:39 +0200199at_exit_set = set()
200
201
202def validate_tearDownClass():
203 if at_exit_set:
Alex Gaynor94560d42013-08-23 05:41:23 -0700204 raise RuntimeError("tearDownClass does not calls the super's "
Attila Fazekasf86fa312013-07-30 19:56:39 +0200205 "tearDownClass in these classes: "
Attila Fazekasd5d43b82013-10-09 16:02:19 +0200206 + str(at_exit_set) + "\n"
207 "If you see the exception, with another "
208 "exception please do not report this one!"
209 "If you are changing tempest code, make sure you",
210 "are calling the super class's tearDownClass!")
Attila Fazekasf86fa312013-07-30 19:56:39 +0200211
212atexit.register(validate_tearDownClass)
213
Ian Wienand98c35f32013-07-23 20:34:23 +1000214
Attila Fazekasdc216422013-01-29 15:12:14 +0100215class BaseTestCase(testtools.TestCase,
216 testtools.testcase.WithAttributes,
217 testresources.ResourcedTestCase):
Attila Fazekasc43fec82013-04-09 23:17:52 +0200218
Sean Dague86bd8422013-12-20 09:56:44 -0500219 config = CONF
Attila Fazekasdc216422013-01-29 15:12:14 +0100220
Attila Fazekasf86fa312013-07-30 19:56:39 +0200221 setUpClassCalled = False
222
Pavel Sedlák1053bd32013-04-16 16:47:40 +0200223 @classmethod
224 def setUpClass(cls):
225 if hasattr(super(BaseTestCase, cls), 'setUpClass'):
226 super(BaseTestCase, cls).setUpClass()
Attila Fazekasf86fa312013-07-30 19:56:39 +0200227 cls.setUpClassCalled = True
Pavel Sedlák1053bd32013-04-16 16:47:40 +0200228
Attila Fazekasf86fa312013-07-30 19:56:39 +0200229 @classmethod
230 def tearDownClass(cls):
Attila Fazekas5d275302013-08-29 12:35:12 +0200231 at_exit_set.discard(cls)
Attila Fazekasf86fa312013-07-30 19:56:39 +0200232 if hasattr(super(BaseTestCase, cls), 'tearDownClass'):
233 super(BaseTestCase, cls).tearDownClass()
234
235 def setUp(self):
236 super(BaseTestCase, self).setUp()
237 if not self.setUpClassCalled:
238 raise RuntimeError("setUpClass does not calls the super's"
239 "setUpClass in the "
240 + self.__class__.__name__)
241 at_exit_set.add(self.__class__)
Matthew Treinish78561ad2013-07-26 11:41:56 -0400242 test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
243 try:
244 test_timeout = int(test_timeout)
245 except ValueError:
246 test_timeout = 0
247 if test_timeout > 0:
Attila Fazekasf86fa312013-07-30 19:56:39 +0200248 self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
Matthew Treinish78561ad2013-07-26 11:41:56 -0400249
250 if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or
251 os.environ.get('OS_STDOUT_CAPTURE') == '1'):
Attila Fazekasf86fa312013-07-30 19:56:39 +0200252 stdout = self.useFixture(fixtures.StringStream('stdout')).stream
253 self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
Matthew Treinish78561ad2013-07-26 11:41:56 -0400254 if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or
255 os.environ.get('OS_STDERR_CAPTURE') == '1'):
Attila Fazekasf86fa312013-07-30 19:56:39 +0200256 stderr = self.useFixture(fixtures.StringStream('stderr')).stream
257 self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
Attila Fazekas31388072013-08-15 08:58:07 +0200258 if (os.environ.get('OS_LOG_CAPTURE') != 'False' and
259 os.environ.get('OS_LOG_CAPTURE') != '0'):
260 log_format = '%(asctime)-15s %(message)s'
261 self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
Attila Fazekas90445be2013-10-24 16:46:03 +0200262 format=log_format,
263 level=None))
Matthew Treinish78561ad2013-07-26 11:41:56 -0400264
Matthew Treinish3e046852013-07-23 16:00:24 -0400265 @classmethod
Ryan Hsu6c4bb3d2013-10-21 21:22:50 -0700266 def get_client_manager(cls):
267 """
268 Returns an Openstack client manager
269 """
270 cls.isolated_creds = isolated_creds.IsolatedCreds(cls.__name__)
271
272 force_tenant_isolation = getattr(cls, 'force_tenant_isolation', None)
273 if (cls.config.compute.allow_tenant_isolation or
274 force_tenant_isolation):
275 creds = cls.isolated_creds.get_primary_creds()
276 username, tenant_name, password = creds
277 os = clients.Manager(username=username,
278 password=password,
279 tenant_name=tenant_name,
280 interface=cls._interface)
281 else:
282 os = clients.Manager(interface=cls._interface)
283 return os
284
285 @classmethod
286 def clear_isolated_creds(cls):
287 """
288 Clears isolated creds if set
289 """
290 if getattr(cls, 'isolated_creds'):
291 cls.isolated_creds.clear_isolated_creds()
292
293 @classmethod
Matthew Treinish3e046852013-07-23 16:00:24 -0400294 def _get_identity_admin_client(cls):
295 """
296 Returns an instance of the Identity Admin API client
297 """
298 os = clients.AdminManager(interface=cls._interface)
299 admin_client = os.identity_client
300 return admin_client
301
302 @classmethod
303 def _get_client_args(cls):
304
305 return (
306 cls.config,
307 cls.config.identity.admin_username,
308 cls.config.identity.admin_password,
309 cls.config.identity.uri
310 )
311
Attila Fazekasdc216422013-01-29 15:12:14 +0100312
Sean Dague35a7caf2013-05-10 10:38:22 -0400313def call_until_true(func, duration, sleep_for):
314 """
315 Call the given function until it returns True (and return True) or
316 until the specified duration (in seconds) elapses (and return
317 False).
318
319 :param func: A zero argument callable that returns True on success.
320 :param duration: The number of seconds for which to attempt a
321 successful call of the function.
322 :param sleep_for: The number of seconds to sleep after an unsuccessful
323 invocation of the function.
324 """
325 now = time.time()
326 timeout = now + duration
327 while now < timeout:
328 if func():
329 return True
330 LOG.debug("Sleeping for %d seconds", sleep_for)
331 time.sleep(sleep_for)
332 now = time.time()
333 return False