Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 297 lines (244 sloc) 9.814 kb
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
1 # vim: tabstop=4 shiftwidth=4 softtabstop=4
caeece6 Updated licenses
Devin Carlen authored
2
3 # Copyright 2010 United States Government as represented by the
4ba6802 @vishvananda Removed trailing whitespace from header
vishvananda authored
4 # Administrator of the National Aeronautics and Space Administration.
caeece6 Updated licenses
Devin Carlen authored
5 # All Rights Reserved.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License"); you may
8 # not use this file except in compliance with the License. You may obtain
9 # a copy of the License at
3dcc46b @vishvananda fix fakeldap so it can use redis keeper
vishvananda authored
10 #
caeece6 Updated licenses
Devin Carlen authored
11 # http://www.apache.org/licenses/LICENSE-2.0
3dcc46b @vishvananda fix fakeldap so it can use redis keeper
vishvananda authored
12 #
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
13 # Unless required by applicable law or agreed to in writing, software
caeece6 Updated licenses
Devin Carlen authored
14 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16 # License for the specific language governing permissions and limitations
17 # under the License.
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
18
f69600e @termie docstring cleanup, nova dir
termie authored
19 """Base classes for our unit tests.
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
20
f69600e @termie docstring cleanup, nova dir
termie authored
21 Allows overriding of flags for use of fakes, and some black magic for
22 inline callbacks.
23
24 """
3c09d48 @vishvananda use flags for sqlite db names and fix flags in dhcpbridge
vishvananda authored
25
0deaa85 @termie update test base class to monkey patch wsgi
termie authored
26 import functools
3c09d48 @vishvananda use flags for sqlite db names and fix flags in dhcpbridge
vishvananda authored
27 import os
28 import shutil
3c85f1b intermediate commit to checkpoint progress
Andy Smith authored
29 import unittest
6cb7801 @jogo Alphabetize imports
jogo authored
30 import uuid
a31fe61 pylint fixes for /nova/test.py
jaypipes@gmail.com authored
31
d508418 @termie rather comprehensive style fixes
termie authored
32 import mox
8464533 @Cerberus98 Added test skipper class
Cerberus98 authored
33 import nose.plugins.skip
d508418 @termie rather comprehensive style fixes
termie authored
34 import stubout
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
35
36 from nova import flags
d73a004 Clean up pylint errors in top-level files
Brian Waldon authored
37 import nova.image.fake
c9ca372 @jkoelker Standardize logging delaration and use
jkoelker authored
38 from nova import log as logging
9871c5f @markmc Move cfg to nova.openstack.common
markmc authored
39 from nova.openstack.common import cfg
ab73d72 @termie add a start_service method to our test baseclass
termie authored
40 from nova import service
07bbe57 @YorikSar Run tools/hacking.py instead of pep8 mandatory.
YorikSar authored
41 from nova import tests
b858108 @markmc Use cfg's new behavior of reset() clearing overrides
markmc authored
42 from nova.tests import fake_flags
6cb7801 @jogo Alphabetize imports
jogo authored
43 from nova import utils
c9b21b0 @vishvananda lots of fixes for rpc and extra imports
vishvananda authored
44 from nova.virt import fake
7eab72b @vishvananda get rid of initialized flag
vishvananda authored
45
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
46
82049af @markmc Refactor away the flags.DEFINE_* helpers
markmc authored
47 test_opts = [
48 cfg.StrOpt('sqlite_clean_db',
49 default='clean.sqlite',
50 help='File name of clean sqlite db'),
51 cfg.BoolOpt('fake_tests',
52 default=True,
53 help='should we use everything for testing'),
54 ]
55
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
56 FLAGS = flags.FLAGS
d1888a3 @markmc Remove the last of the gflags shim layer
markmc authored
57 FLAGS.register_opts(test_opts)
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
58
c9ca372 @jkoelker Standardize logging delaration and use
jkoelker authored
59 LOG = logging.getLogger(__name__)
b3b2863 @Cerberus98 Fixing divergence
Cerberus98 authored
60
ba530da @jkoelker merge with dietz
jkoelker authored
61
8464533 @Cerberus98 Added test skipper class
Cerberus98 authored
62 class skip_test(object):
749eac4 @tr3buchet bunch of docstring changes
tr3buchet authored
63 """Decorator that skips a test."""
15b2a3b @tr3buchet moved floating ip db access and sanity checking from network api into ne...
tr3buchet authored
64 # TODO(tr3buchet): remember forever what comstud did here
8464533 @Cerberus98 Added test skipper class
Cerberus98 authored
65 def __init__(self, msg):
66 self.message = msg
36c9396 @jkoelker pep8 fixes
jkoelker authored
67
8464533 @Cerberus98 Added test skipper class
Cerberus98 authored
68 def __call__(self, func):
625330b @galstrom21 utilized functools.wraps
galstrom21 authored
69 @functools.wraps(func)
8464533 @Cerberus98 Added test skipper class
Cerberus98 authored
70 def _skipper(*args, **kw):
749eac4 @tr3buchet bunch of docstring changes
tr3buchet authored
71 """Wrapped skipper function."""
8464533 @Cerberus98 Added test skipper class
Cerberus98 authored
72 raise nose.SkipTest(self.message)
73 return _skipper
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
74
836c394 @galstrom21 Resolved pep8 errors
galstrom21 authored
75
883095f @galstrom21 Added @test.skip_unless and @test.skip_if functionality. Also created no...
galstrom21 authored
76 class skip_if(object):
d7b9ee3 @jogo More spelling fixes inside of nova
jogo authored
77 """Decorator that skips a test if condition is true."""
883095f @galstrom21 Added @test.skip_unless and @test.skip_if functionality. Also created no...
galstrom21 authored
78 def __init__(self, condition, msg):
79 self.condition = condition
80 self.message = msg
81
82 def __call__(self, func):
625330b @galstrom21 utilized functools.wraps
galstrom21 authored
83 @functools.wraps(func)
883095f @galstrom21 Added @test.skip_unless and @test.skip_if functionality. Also created no...
galstrom21 authored
84 def _skipper(*args, **kw):
85 """Wrapped skipper function."""
86 if self.condition:
87 raise nose.SkipTest(self.message)
27392e9 @galstrom21 Conditionals were not actually runing the tests when they were supposed ...
galstrom21 authored
88 func(*args, **kw)
883095f @galstrom21 Added @test.skip_unless and @test.skip_if functionality. Also created no...
galstrom21 authored
89 return _skipper
90
91
92 class skip_unless(object):
836c394 @galstrom21 Resolved pep8 errors
galstrom21 authored
93 """Decorator that skips a test if condition is not true."""
883095f @galstrom21 Added @test.skip_unless and @test.skip_if functionality. Also created no...
galstrom21 authored
94 def __init__(self, condition, msg):
95 self.condition = condition
96 self.message = msg
97
98 def __call__(self, func):
625330b @galstrom21 utilized functools.wraps
galstrom21 authored
99 @functools.wraps(func)
883095f @galstrom21 Added @test.skip_unless and @test.skip_if functionality. Also created no...
galstrom21 authored
100 def _skipper(*args, **kw):
101 """Wrapped skipper function."""
102 if not self.condition:
103 raise nose.SkipTest(self.message)
27392e9 @galstrom21 Conditionals were not actually runing the tests when they were supposed ...
galstrom21 authored
104 func(*args, **kw)
8464533 @Cerberus98 Added test skipper class
Cerberus98 authored
105 return _skipper
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
106
107
a31fe61 pylint fixes for /nova/test.py
jaypipes@gmail.com authored
108 def skip_if_fake(func):
f69600e @termie docstring cleanup, nova dir
termie authored
109 """Decorator that skips a test if running in fake mode."""
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
110 def _skipper(*args, **kw):
f69600e @termie docstring cleanup, nova dir
termie authored
111 """Wrapped skipper function."""
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
112 if FLAGS.fake_tests:
a31fe61 pylint fixes for /nova/test.py
jaypipes@gmail.com authored
113 raise unittest.SkipTest('Test cannot be run in fake mode')
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
114 else:
a31fe61 pylint fixes for /nova/test.py
jaypipes@gmail.com authored
115 return func(*args, **kw)
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
116 return _skipper
117
118
8813ab1 @jerdfelt assertRaises(Exception, ...) considered harmful
jerdfelt authored
119 class TestingException(Exception):
120 pass
121
122
a1640f3 formatting and naming cleanup
Andy Smith authored
123 class TestCase(unittest.TestCase):
f69600e @termie docstring cleanup, nova dir
termie authored
124 """Test case base class for all unit tests."""
125
e012a2b PEP8 and pylint cleanup. There should be no functional changes here, jus...
Eric Day authored
126 def setUp(self):
f69600e @termie docstring cleanup, nova dir
termie authored
127 """Run before each test method to initialize test environment."""
a1640f3 formatting and naming cleanup
Andy Smith authored
128 super(TestCase, self).setUp()
b858108 @markmc Use cfg's new behavior of reset() clearing overrides
markmc authored
129
130 fake_flags.set_defaults(FLAGS)
131
e4cb0d3 @vishvananda get rid of network indexes and make networks into a pool
vishvananda authored
132 # NOTE(vish): We need a better method for creating fixtures for tests
133 # now that we have some required db setup for the system
134 # to work properly.
b2fb173 @vishvananda make all uses of utcnow use our testable utils.utcnow
vishvananda authored
135 self.start = utils.utcnow()
07bbe57 @YorikSar Run tools/hacking.py instead of pep8 mandatory.
YorikSar authored
136 tests.reset_db()
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
137
138 # emulate some of the mox stuff, we can't use the metaclass
139 # because it screws with our generators
140 self.mox = mox.Mox()
141 self.stubs = stubout.StubOutForTesting()
9df460a @termie Remove tornado-related code from almost everything.
termie authored
142 self.injected = []
ab73d72 @termie add a start_service method to our test baseclass
termie authored
143 self._services = []
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
144
e012a2b PEP8 and pylint cleanup. There should be no functional changes here, jus...
Eric Day authored
145 def tearDown(self):
f69600e @termie docstring cleanup, nova dir
termie authored
146 """Runs after each test method to tear down test environment."""
e0ae19c prevent leakage of FLAGS changes across tests
Andy Smith authored
147 try:
148 self.mox.UnsetStubs()
149 self.stubs.UnsetAll()
150 self.stubs.SmartUnsetAll()
151 self.mox.VerifyAll()
ab73d72 @termie add a start_service method to our test baseclass
termie authored
152 super(TestCase, self).tearDown()
153 finally:
c9b21b0 @vishvananda lots of fixes for rpc and extra imports
vishvananda authored
154 if FLAGS.connection_type == 'fake':
155 if hasattr(fake.FakeConnection, '_instance'):
156 del fake.FakeConnection._instance
157
d5307a2 @yamahata image/fake: added teardown method
yamahata authored
158 if FLAGS.image_service == 'nova.image.fake.FakeImageService':
159 nova.image.fake.FakeImageService_reset()
160
d7b9ee3 @jogo More spelling fixes inside of nova
jogo authored
161 # Reset any overridden flags
b858108 @markmc Use cfg's new behavior of reset() clearing overrides
markmc authored
162 FLAGS.reset()
ab73d72 @termie add a start_service method to our test baseclass
termie authored
163
164 # Stop any timers
e0ae19c prevent leakage of FLAGS changes across tests
Andy Smith authored
165 for x in self.injected:
166 try:
167 x.stop()
168 except AssertionError:
169 pass
170
ab73d72 @termie add a start_service method to our test baseclass
termie authored
171 # Kill any services
172 for x in self._services:
173 try:
174 x.kill()
175 except Exception:
176 pass
387671f @termie Tests turn things into inlineCallbacks.
termie authored
177
fb7d1fb @jerdfelt Clear created attributes when tearing down tests
jerdfelt authored
178 # Delete attributes that don't start with _ so they don't pin
179 # memory around unnecessarily for the duration of the test
180 # suite
181 for key in [k for k in self.__dict__.keys() if k[0] != '_']:
182 del self.__dict__[key]
183
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
184 def flags(self, **kw):
f69600e @termie docstring cleanup, nova dir
termie authored
185 """Override flag variables for a test."""
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
186 for k, v in kw.iteritems():
d1888a3 @markmc Remove the last of the gflags shim layer
markmc authored
187 FLAGS.set_override(k, v)
bf6e6e7 @anotherjesse initial commit
anotherjesse authored
188
83e4dcb @termie remove keyword argument, per review
termie authored
189 def start_service(self, name, host=None, **kwargs):
ab73d72 @termie add a start_service method to our test baseclass
termie authored
190 host = host and host or uuid.uuid4().hex
191 kwargs.setdefault('host', host)
192 kwargs.setdefault('binary', 'nova-%s' % name)
193 svc = service.Service.create(**kwargs)
194 svc.start()
195 self._services.append(svc)
196 return svc
197
7fe5052 @rconradharris Adding instance_id as Glance image_property
rconradharris authored
198 # Useful assertions
a4035df @rconradharris Adding fill first cost function
rconradharris authored
199 def assertDictMatch(self, d1, d2, approx_equal=False, tolerance=0.001):
7fe5052 @rconradharris Adding instance_id as Glance image_property
rconradharris authored
200 """Assert two dicts are equivalent.
201
202 This is a 'deep' match in the sense that it handles nested
203 dictionaries appropriately.
a56a973 @rconradharris Fixing API per spec, to get unit-tests to pass
rconradharris authored
204
205 NOTE:
206
207 If you don't care (or don't know) a given value, you can specify
208 the string DONTCARE as the value. This will cause that dict-item
209 to be skipped.
f69600e @termie docstring cleanup, nova dir
termie authored
210
7fe5052 @rconradharris Adding instance_id as Glance image_property
rconradharris authored
211 """
212 def raise_assertion(msg):
213 d1str = str(d1)
214 d2str = str(d2)
f69600e @termie docstring cleanup, nova dir
termie authored
215 base_msg = ('Dictionaries do not match. %(msg)s d1: %(d1str)s '
216 'd2: %(d2str)s' % locals())
7fe5052 @rconradharris Adding instance_id as Glance image_property
rconradharris authored
217 raise AssertionError(base_msg)
218
219 d1keys = set(d1.keys())
220 d2keys = set(d2.keys())
221 if d1keys != d2keys:
222 d1only = d1keys - d2keys
223 d2only = d2keys - d1keys
f69600e @termie docstring cleanup, nova dir
termie authored
224 raise_assertion('Keys in d1 and not d2: %(d1only)s. '
225 'Keys in d2 and not d1: %(d2only)s' % locals())
7fe5052 @rconradharris Adding instance_id as Glance image_property
rconradharris authored
226
227 for key in d1keys:
228 d1value = d1[key]
229 d2value = d2[key]
a4035df @rconradharris Adding fill first cost function
rconradharris authored
230 try:
439787e @rconradharris Pep8 fixes
rconradharris authored
231 error = abs(float(d1value) - float(d2value))
232 within_tolerance = error <= tolerance
b4845fa @rconradharris Resolving conflict and finish test_images
rconradharris authored
233 except (ValueError, TypeError):
a4035df @rconradharris Adding fill first cost function
rconradharris authored
234 # If both values aren't convertable to float, just ignore
b4845fa @rconradharris Resolving conflict and finish test_images
rconradharris authored
235 # ValueError if arg is a str, TypeError if it's something else
236 # (like None)
a4035df @rconradharris Adding fill first cost function
rconradharris authored
237 within_tolerance = False
238
7fe5052 @rconradharris Adding instance_id as Glance image_property
rconradharris authored
239 if hasattr(d1value, 'keys') and hasattr(d2value, 'keys'):
240 self.assertDictMatch(d1value, d2value)
a56a973 @rconradharris Fixing API per spec, to get unit-tests to pass
rconradharris authored
241 elif 'DONTCARE' in (d1value, d2value):
242 continue
a4035df @rconradharris Adding fill first cost function
rconradharris authored
243 elif approx_equal and within_tolerance:
244 continue
7fe5052 @rconradharris Adding instance_id as Glance image_property
rconradharris authored
245 elif d1value != d2value:
246 raise_assertion("d1['%(key)s']=%(d1value)s != "
247 "d2['%(key)s']=%(d2value)s" % locals())
a56a973 @rconradharris Fixing API per spec, to get unit-tests to pass
rconradharris authored
248
a4035df @rconradharris Adding fill first cost function
rconradharris authored
249 def assertDictListMatch(self, L1, L2, approx_equal=False, tolerance=0.001):
f69600e @termie docstring cleanup, nova dir
termie authored
250 """Assert a list of dicts are equivalent."""
a56a973 @rconradharris Fixing API per spec, to get unit-tests to pass
rconradharris authored
251 def raise_assertion(msg):
252 L1str = str(L1)
253 L2str = str(L2)
f69600e @termie docstring cleanup, nova dir
termie authored
254 base_msg = ('List of dictionaries do not match: %(msg)s '
255 'L1: %(L1str)s L2: %(L2str)s' % locals())
a56a973 @rconradharris Fixing API per spec, to get unit-tests to pass
rconradharris authored
256 raise AssertionError(base_msg)
257
258 L1count = len(L1)
259 L2count = len(L2)
260 if L1count != L2count:
f69600e @termie docstring cleanup, nova dir
termie authored
261 raise_assertion('Length mismatch: len(L1)=%(L1count)d != '
262 'len(L2)=%(L2count)d' % locals())
a56a973 @rconradharris Fixing API per spec, to get unit-tests to pass
rconradharris authored
263
264 for d1, d2 in zip(L1, L2):
a4035df @rconradharris Adding fill first cost function
rconradharris authored
265 self.assertDictMatch(d1, d2, approx_equal=approx_equal,
266 tolerance=tolerance)
5276e80 @yamahata api/ec2, boot-from-volume: an unit test for describe instances
yamahata authored
267
268 def assertSubDictMatch(self, sub_dict, super_dict):
269 """Assert a sub_dict is subset of super_dict."""
270 self.assertTrue(set(sub_dict.keys()).issubset(set(super_dict.keys())))
271 for k, sub_value in sub_dict.items():
272 super_value = super_dict[k]
273 if isinstance(sub_value, dict):
274 self.assertSubDictMatch(sub_value, super_value)
275 elif 'DONTCARE' in (sub_value, super_value):
276 continue
277 else:
278 self.assertEqual(sub_value, super_value)
5994671 @comstud fix for assertIn and assertNotIn use which was added in python 2.7. thi...
comstud authored
279
8bfa5e2 @comstud support the extra optional arguments for msg to assertIn and assertNotIn
comstud authored
280 def assertIn(self, a, b, *args, **kwargs):
5994671 @comstud fix for assertIn and assertNotIn use which was added in python 2.7. thi...
comstud authored
281 """Python < v2.7 compatibility. Assert 'a' in 'b'"""
282 try:
283 f = super(TestCase, self).assertIn
284 except AttributeError:
8bfa5e2 @comstud support the extra optional arguments for msg to assertIn and assertNotIn
comstud authored
285 self.assertTrue(a in b, *args, **kwargs)
5994671 @comstud fix for assertIn and assertNotIn use which was added in python 2.7. thi...
comstud authored
286 else:
8bfa5e2 @comstud support the extra optional arguments for msg to assertIn and assertNotIn
comstud authored
287 f(a, b, *args, **kwargs)
5994671 @comstud fix for assertIn and assertNotIn use which was added in python 2.7. thi...
comstud authored
288
8bfa5e2 @comstud support the extra optional arguments for msg to assertIn and assertNotIn
comstud authored
289 def assertNotIn(self, a, b, *args, **kwargs):
5994671 @comstud fix for assertIn and assertNotIn use which was added in python 2.7. thi...
comstud authored
290 """Python < v2.7 compatibility. Assert 'a' NOT in 'b'"""
291 try:
292 f = super(TestCase, self).assertNotIn
293 except AttributeError:
8bfa5e2 @comstud support the extra optional arguments for msg to assertIn and assertNotIn
comstud authored
294 self.assertFalse(a in b, *args, **kwargs)
5994671 @comstud fix for assertIn and assertNotIn use which was added in python 2.7. thi...
comstud authored
295 else:
8bfa5e2 @comstud support the extra optional arguments for msg to assertIn and assertNotIn
comstud authored
296 f(a, b, *args, **kwargs)
Something went wrong with that request. Please try again.