blob: ca626daca6a06f6e7c82ef3099c0c57421ff4322 [file] [log] [blame]
Jay Pipes051075a2012-04-28 17:39:37 -04001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
3# Copyright 2012 OpenStack, LLC
4# 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
Ian Wienand98c35f32013-07-23 20:34:23 +100019import os
Jay Pipes051075a2012-04-28 17:39:37 -040020import time
21
Matthew Treinish78561ad2013-07-26 11:41:56 -040022import fixtures
Chris Yeoh55530bb2013-02-08 16:04:27 +103023import nose.plugins.attrib
Attila Fazekasdc216422013-01-29 15:12:14 +010024import testresources
ivan-zhu1feeb382013-01-24 10:14:39 +080025import testtools
Jay Pipes051075a2012-04-28 17:39:37 -040026
Matthew Treinish3e046852013-07-23 16:00:24 -040027from tempest import clients
Attila Fazekasdc216422013-01-29 15:12:14 +010028from tempest import config
Matthew Treinishf4a9b0f2013-07-26 16:58:26 -040029from tempest.openstack.common import log as logging
Jay Pipes051075a2012-04-28 17:39:37 -040030
31LOG = logging.getLogger(__name__)
32
Samuel Merritt0d499bc2013-06-19 12:08:23 -070033# All the successful HTTP status codes from RFC 2616
34HTTP_SUCCESS = (200, 201, 202, 203, 204, 205, 206)
35
Jay Pipes051075a2012-04-28 17:39:37 -040036
Chris Yeoh55530bb2013-02-08 16:04:27 +103037def attr(*args, **kwargs):
38 """A decorator which applies the nose and testtools attr decorator
39
40 This decorator applies the nose attr decorator as well as the
41 the testtools.testcase.attr if it is in the list of attributes
Attila Fazekasb2902af2013-02-16 16:22:44 +010042 to testtools we want to apply.
43 """
Chris Yeoh55530bb2013-02-08 16:04:27 +103044
45 def decorator(f):
Giulio Fidente4946a052013-05-14 12:23:51 +020046 if 'type' in kwargs and isinstance(kwargs['type'], str):
47 f = testtools.testcase.attr(kwargs['type'])(f)
Chris Yeohcf3fb7c2013-05-19 15:59:00 +093048 if kwargs['type'] == 'smoke':
49 f = testtools.testcase.attr('gate')(f)
Giulio Fidente4946a052013-05-14 12:23:51 +020050 elif 'type' in kwargs and isinstance(kwargs['type'], list):
51 for attr in kwargs['type']:
52 f = testtools.testcase.attr(attr)(f)
Chris Yeohcf3fb7c2013-05-19 15:59:00 +093053 if attr == 'smoke':
54 f = testtools.testcase.attr('gate')(f)
Giulio Fidente4946a052013-05-14 12:23:51 +020055 return nose.plugins.attrib.attr(*args, **kwargs)(f)
Chris Yeoh55530bb2013-02-08 16:04:27 +103056
57 return decorator
58
59
Marc Koderer32221b8e2013-08-23 13:57:50 +020060def stresstest(*args, **kwargs):
61 """Add stress test decorator
62
63 For all functions with this decorator a attr stress will be
64 set automatically.
65
66 @param class_setup_per: allowed values are application, process, action
67 ``application``: once in the stress job lifetime
68 ``process``: once in the worker process lifetime
69 ``action``: on each action
70 """
71 def decorator(f):
72 if 'class_setup_per' in kwargs:
73 setattr(f, "st_class_setup_per", kwargs['class_setup_per'])
74 else:
75 setattr(f, "st_class_setup_per", 'process')
76 attr(type='stress')(f)
77 return f
78 return decorator
79
80
Ian Wienand98c35f32013-07-23 20:34:23 +100081# there is a mis-match between nose and testtools for older pythons.
82# testtools will set skipException to be either
83# unittest.case.SkipTest, unittest2.case.SkipTest or an internal skip
84# exception, depending on what it can find. Python <2.7 doesn't have
85# unittest.case.SkipTest; so if unittest2 is not installed it falls
86# back to the internal class.
87#
88# The current nose skip plugin will decide to raise either
89# unittest.case.SkipTest or its own internal exception; it does not
90# look for unittest2 or the internal unittest exception. Thus we must
91# monkey-patch testtools.TestCase.skipException to be the exception
92# the nose skip plugin expects.
93#
94# However, with the switch to testr nose may not be available, so we
95# require you to opt-in to this fix with an environment variable.
96#
97# This is temporary until upstream nose starts looking for unittest2
98# as testtools does; we can then remove this and ensure unittest2 is
99# available for older pythons; then nose and testtools will agree
100# unittest2.case.SkipTest is the one-true skip test exception.
101#
102# https://review.openstack.org/#/c/33056
103# https://github.com/nose-devs/nose/pull/699
104if 'TEMPEST_PY26_NOSE_COMPAT' in os.environ:
105 try:
106 import unittest.case.SkipTest
107 # convince pep8 we're using the import...
108 if unittest.case.SkipTest:
109 pass
110 raise RuntimeError("You have unittest.case.SkipTest; "
111 "no need to override")
112 except ImportError:
113 LOG.info("Overriding skipException to nose SkipTest")
114 testtools.TestCase.skipException = nose.plugins.skip.SkipTest
115
Attila Fazekasf86fa312013-07-30 19:56:39 +0200116at_exit_set = set()
117
118
119def validate_tearDownClass():
120 if at_exit_set:
Alex Gaynor94560d42013-08-23 05:41:23 -0700121 raise RuntimeError("tearDownClass does not calls the super's "
Attila Fazekasf86fa312013-07-30 19:56:39 +0200122 "tearDownClass in these classes: "
123 + str(at_exit_set))
124
125atexit.register(validate_tearDownClass)
126
Ian Wienand98c35f32013-07-23 20:34:23 +1000127
Attila Fazekasdc216422013-01-29 15:12:14 +0100128class BaseTestCase(testtools.TestCase,
129 testtools.testcase.WithAttributes,
130 testresources.ResourcedTestCase):
Attila Fazekasc43fec82013-04-09 23:17:52 +0200131
132 config = config.TempestConfig()
Attila Fazekasdc216422013-01-29 15:12:14 +0100133
Attila Fazekasf86fa312013-07-30 19:56:39 +0200134 setUpClassCalled = False
135
Pavel Sedlák1053bd32013-04-16 16:47:40 +0200136 @classmethod
137 def setUpClass(cls):
138 if hasattr(super(BaseTestCase, cls), 'setUpClass'):
139 super(BaseTestCase, cls).setUpClass()
Attila Fazekasf86fa312013-07-30 19:56:39 +0200140 cls.setUpClassCalled = True
Pavel Sedlák1053bd32013-04-16 16:47:40 +0200141
Attila Fazekasf86fa312013-07-30 19:56:39 +0200142 @classmethod
143 def tearDownClass(cls):
Attila Fazekas5d275302013-08-29 12:35:12 +0200144 at_exit_set.discard(cls)
Attila Fazekasf86fa312013-07-30 19:56:39 +0200145 if hasattr(super(BaseTestCase, cls), 'tearDownClass'):
146 super(BaseTestCase, cls).tearDownClass()
147
148 def setUp(self):
149 super(BaseTestCase, self).setUp()
150 if not self.setUpClassCalled:
151 raise RuntimeError("setUpClass does not calls the super's"
152 "setUpClass in the "
153 + self.__class__.__name__)
154 at_exit_set.add(self.__class__)
Matthew Treinish78561ad2013-07-26 11:41:56 -0400155 test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
156 try:
157 test_timeout = int(test_timeout)
158 except ValueError:
159 test_timeout = 0
160 if test_timeout > 0:
Attila Fazekasf86fa312013-07-30 19:56:39 +0200161 self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
Matthew Treinish78561ad2013-07-26 11:41:56 -0400162
163 if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or
164 os.environ.get('OS_STDOUT_CAPTURE') == '1'):
Attila Fazekasf86fa312013-07-30 19:56:39 +0200165 stdout = self.useFixture(fixtures.StringStream('stdout')).stream
166 self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
Matthew Treinish78561ad2013-07-26 11:41:56 -0400167 if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or
168 os.environ.get('OS_STDERR_CAPTURE') == '1'):
Attila Fazekasf86fa312013-07-30 19:56:39 +0200169 stderr = self.useFixture(fixtures.StringStream('stderr')).stream
170 self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
Attila Fazekas31388072013-08-15 08:58:07 +0200171 if (os.environ.get('OS_LOG_CAPTURE') != 'False' and
172 os.environ.get('OS_LOG_CAPTURE') != '0'):
173 log_format = '%(asctime)-15s %(message)s'
174 self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
175 format=log_format))
Matthew Treinish78561ad2013-07-26 11:41:56 -0400176
Matthew Treinish3e046852013-07-23 16:00:24 -0400177 @classmethod
178 def _get_identity_admin_client(cls):
179 """
180 Returns an instance of the Identity Admin API client
181 """
182 os = clients.AdminManager(interface=cls._interface)
183 admin_client = os.identity_client
184 return admin_client
185
186 @classmethod
187 def _get_client_args(cls):
188
189 return (
190 cls.config,
191 cls.config.identity.admin_username,
192 cls.config.identity.admin_password,
193 cls.config.identity.uri
194 )
195
Attila Fazekasdc216422013-01-29 15:12:14 +0100196
Sean Dague35a7caf2013-05-10 10:38:22 -0400197def call_until_true(func, duration, sleep_for):
198 """
199 Call the given function until it returns True (and return True) or
200 until the specified duration (in seconds) elapses (and return
201 False).
202
203 :param func: A zero argument callable that returns True on success.
204 :param duration: The number of seconds for which to attempt a
205 successful call of the function.
206 :param sleep_for: The number of seconds to sleep after an unsuccessful
207 invocation of the function.
208 """
209 now = time.time()
210 timeout = now + duration
211 while now < timeout:
212 if func():
213 return True
214 LOG.debug("Sleeping for %d seconds", sleep_for)
215 time.sleep(sleep_for)
216 now = time.time()
217 return False