|
1 #!/usr/bin/python2.4 |
|
2 # |
|
3 # Unit tests for Mox. |
|
4 # |
|
5 # Copyright 2008 Google Inc. |
|
6 # |
|
7 # Licensed under the Apache License, Version 2.0 (the "License"); |
|
8 # you may not use this file except in compliance with the License. |
|
9 # You may obtain a copy of the License at |
|
10 # |
|
11 # http://www.apache.org/licenses/LICENSE-2.0 |
|
12 # |
|
13 # Unless required by applicable law or agreed to in writing, software |
|
14 # distributed under the License is distributed on an "AS IS" BASIS, |
|
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
16 # See the License for the specific language governing permissions and |
|
17 # limitations under the License. |
|
18 |
|
19 import cStringIO |
|
20 import unittest |
|
21 import re |
|
22 |
|
23 import mox |
|
24 |
|
25 import mox_test_helper |
|
26 |
|
27 |
|
28 class ExpectedMethodCallsErrorTest(unittest.TestCase): |
|
29 """Test creation and string conversion of ExpectedMethodCallsError.""" |
|
30 |
|
31 def testAtLeastOneMethod(self): |
|
32 self.assertRaises(ValueError, mox.ExpectedMethodCallsError, []) |
|
33 |
|
34 def testOneError(self): |
|
35 method = mox.MockMethod("testMethod", [], False) |
|
36 method(1, 2).AndReturn('output') |
|
37 e = mox.ExpectedMethodCallsError([method]) |
|
38 self.assertEqual( |
|
39 "Verify: Expected methods never called:\n" |
|
40 " 0. testMethod(1, 2) -> 'output'", |
|
41 str(e)) |
|
42 |
|
43 def testManyErrors(self): |
|
44 method1 = mox.MockMethod("testMethod", [], False) |
|
45 method1(1, 2).AndReturn('output') |
|
46 method2 = mox.MockMethod("testMethod", [], False) |
|
47 method2(a=1, b=2, c="only named") |
|
48 method3 = mox.MockMethod("testMethod2", [], False) |
|
49 method3().AndReturn(44) |
|
50 method4 = mox.MockMethod("testMethod", [], False) |
|
51 method4(1, 2).AndReturn('output') |
|
52 e = mox.ExpectedMethodCallsError([method1, method2, method3, method4]) |
|
53 self.assertEqual( |
|
54 "Verify: Expected methods never called:\n" |
|
55 " 0. testMethod(1, 2) -> 'output'\n" |
|
56 " 1. testMethod(a=1, b=2, c='only named') -> None\n" |
|
57 " 2. testMethod2() -> 44\n" |
|
58 " 3. testMethod(1, 2) -> 'output'", |
|
59 str(e)) |
|
60 |
|
61 |
|
62 class OrTest(unittest.TestCase): |
|
63 """Test Or correctly chains Comparators.""" |
|
64 |
|
65 def testValidOr(self): |
|
66 """Or should be True if either Comparator returns True.""" |
|
67 self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == {}) |
|
68 self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test') |
|
69 self.assert_(mox.Or(mox.IsA(str), mox.IsA(str)) == 'test') |
|
70 |
|
71 def testInvalidOr(self): |
|
72 """Or should be False if both Comparators return False.""" |
|
73 self.failIf(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0) |
|
74 |
|
75 |
|
76 class AndTest(unittest.TestCase): |
|
77 """Test And correctly chains Comparators.""" |
|
78 |
|
79 def testValidAnd(self): |
|
80 """And should be True if both Comparators return True.""" |
|
81 self.assert_(mox.And(mox.IsA(str), mox.IsA(str)) == '1') |
|
82 |
|
83 def testClauseOneFails(self): |
|
84 """And should be False if the first Comparator returns False.""" |
|
85 |
|
86 self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1') |
|
87 |
|
88 def testAdvancedUsage(self): |
|
89 """And should work with other Comparators. |
|
90 |
|
91 Note: this test is reliant on In and ContainsKeyValue. |
|
92 """ |
|
93 test_dict = {"mock" : "obj", "testing" : "isCOOL"} |
|
94 self.assert_(mox.And(mox.In("testing"), |
|
95 mox.ContainsKeyValue("mock", "obj")) == test_dict) |
|
96 |
|
97 def testAdvancedUsageFails(self): |
|
98 """Note: this test is reliant on In and ContainsKeyValue.""" |
|
99 test_dict = {"mock" : "obj", "testing" : "isCOOL"} |
|
100 self.failIf(mox.And(mox.In("NOTFOUND"), |
|
101 mox.ContainsKeyValue("mock", "obj")) == test_dict) |
|
102 |
|
103 |
|
104 class SameElementsAsTest(unittest.TestCase): |
|
105 """Test SameElementsAs correctly identifies sequences with same elements.""" |
|
106 |
|
107 def testSortedLists(self): |
|
108 """Should return True if two lists are exactly equal.""" |
|
109 self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c']) |
|
110 |
|
111 def testUnsortedLists(self): |
|
112 """Should return True if two lists are unequal but have same elements.""" |
|
113 self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1]) |
|
114 |
|
115 def testUnhashableLists(self): |
|
116 """Should return True if two lists have the same unhashable elements.""" |
|
117 self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == |
|
118 [{2: 'b'}, {'a': 1}]) |
|
119 |
|
120 def testEmptyLists(self): |
|
121 """Should return True for two empty lists.""" |
|
122 self.assert_(mox.SameElementsAs([]) == []) |
|
123 |
|
124 def testUnequalLists(self): |
|
125 """Should return False if the lists are not equal.""" |
|
126 self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c']) |
|
127 |
|
128 def testUnequalUnhashableLists(self): |
|
129 """Should return False if two lists with unhashable elements are unequal.""" |
|
130 self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}]) |
|
131 |
|
132 |
|
133 class ContainsKeyValueTest(unittest.TestCase): |
|
134 """Test ContainsKeyValue correctly identifies key/value pairs in a dict. |
|
135 """ |
|
136 |
|
137 def testValidPair(self): |
|
138 """Should return True if the key value is in the dict.""" |
|
139 self.assert_(mox.ContainsKeyValue("key", 1) == {"key": 1}) |
|
140 |
|
141 def testInvalidValue(self): |
|
142 """Should return False if the value is not correct.""" |
|
143 self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2}) |
|
144 |
|
145 def testInvalidKey(self): |
|
146 """Should return False if they key is not in the dict.""" |
|
147 self.failIf(mox.ContainsKeyValue("qux", 1) == {"key": 2}) |
|
148 |
|
149 |
|
150 class InTest(unittest.TestCase): |
|
151 """Test In correctly identifies a key in a list/dict""" |
|
152 |
|
153 def testItemInList(self): |
|
154 """Should return True if the item is in the list.""" |
|
155 self.assert_(mox.In(1) == [1, 2, 3]) |
|
156 |
|
157 def testKeyInDict(self): |
|
158 """Should return True if the item is a key in a dict.""" |
|
159 self.assert_(mox.In("test") == {"test" : "module"}) |
|
160 |
|
161 |
|
162 class NotTest(unittest.TestCase): |
|
163 """Test Not correctly identifies False predicates.""" |
|
164 |
|
165 def testItemInList(self): |
|
166 """Should return True if the item is NOT in the list.""" |
|
167 self.assert_(mox.Not(mox.In(42)) == [1, 2, 3]) |
|
168 |
|
169 def testKeyInDict(self): |
|
170 """Should return True if the item is NOT a key in a dict.""" |
|
171 self.assert_(mox.Not(mox.In("foo")) == {"key" : 42}) |
|
172 |
|
173 def testInvalidKeyWithNot(self): |
|
174 """Should return False if they key is NOT in the dict.""" |
|
175 self.assert_(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2}) |
|
176 |
|
177 |
|
178 class StrContainsTest(unittest.TestCase): |
|
179 """Test StrContains correctly checks for substring occurrence of a parameter. |
|
180 """ |
|
181 |
|
182 def testValidSubstringAtStart(self): |
|
183 """Should return True if the substring is at the start of the string.""" |
|
184 self.assert_(mox.StrContains("hello") == "hello world") |
|
185 |
|
186 def testValidSubstringInMiddle(self): |
|
187 """Should return True if the substring is in the middle of the string.""" |
|
188 self.assert_(mox.StrContains("lo wo") == "hello world") |
|
189 |
|
190 def testValidSubstringAtEnd(self): |
|
191 """Should return True if the substring is at the end of the string.""" |
|
192 self.assert_(mox.StrContains("ld") == "hello world") |
|
193 |
|
194 def testInvaildSubstring(self): |
|
195 """Should return False if the substring is not in the string.""" |
|
196 self.failIf(mox.StrContains("AAA") == "hello world") |
|
197 |
|
198 def testMultipleMatches(self): |
|
199 """Should return True if there are multiple occurances of substring.""" |
|
200 self.assert_(mox.StrContains("abc") == "ababcabcabcababc") |
|
201 |
|
202 |
|
203 class RegexTest(unittest.TestCase): |
|
204 """Test Regex correctly matches regular expressions.""" |
|
205 |
|
206 def testIdentifyBadSyntaxDuringInit(self): |
|
207 """The user should know immediately if a regex has bad syntax.""" |
|
208 self.assertRaises(re.error, mox.Regex, '(a|b') |
|
209 |
|
210 def testPatternInMiddle(self): |
|
211 """Should return True if the pattern matches at the middle of the string. |
|
212 |
|
213 This ensures that re.search is used (instead of re.find). |
|
214 """ |
|
215 self.assert_(mox.Regex(r"a\s+b") == "x y z a b c") |
|
216 |
|
217 def testNonMatchPattern(self): |
|
218 """Should return False if the pattern does not match the string.""" |
|
219 self.failIf(mox.Regex(r"a\s+b") == "x y z") |
|
220 |
|
221 def testFlagsPassedCorrectly(self): |
|
222 """Should return True as we pass IGNORECASE flag.""" |
|
223 self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a") |
|
224 |
|
225 def testReprWithoutFlags(self): |
|
226 """repr should return the regular expression pattern.""" |
|
227 self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>") |
|
228 |
|
229 def testReprWithFlags(self): |
|
230 """repr should return the regular expression pattern and flags.""" |
|
231 self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) == |
|
232 "<regular expression 'a\s+b', flags=4>") |
|
233 |
|
234 |
|
235 class IsATest(unittest.TestCase): |
|
236 """Verify IsA correctly checks equality based upon class type, not value.""" |
|
237 |
|
238 def testEqualityValid(self): |
|
239 """Verify that == correctly identifies objects of the same type.""" |
|
240 self.assert_(mox.IsA(str) == 'test') |
|
241 |
|
242 def testEqualityInvalid(self): |
|
243 """Verify that == correctly identifies objects of different types.""" |
|
244 self.failIf(mox.IsA(str) == 10) |
|
245 |
|
246 def testInequalityValid(self): |
|
247 """Verify that != identifies objects of different type.""" |
|
248 self.assert_(mox.IsA(str) != 10) |
|
249 |
|
250 def testInequalityInvalid(self): |
|
251 """Verify that != correctly identifies objects of the same type.""" |
|
252 self.failIf(mox.IsA(str) != "test") |
|
253 |
|
254 def testEqualityInListValid(self): |
|
255 """Verify list contents are properly compared.""" |
|
256 isa_list = [mox.IsA(str), mox.IsA(str)] |
|
257 str_list = ["abc", "def"] |
|
258 self.assert_(isa_list == str_list) |
|
259 |
|
260 def testEquailtyInListInvalid(self): |
|
261 """Verify list contents are properly compared.""" |
|
262 isa_list = [mox.IsA(str),mox.IsA(str)] |
|
263 mixed_list = ["abc", 123] |
|
264 self.failIf(isa_list == mixed_list) |
|
265 |
|
266 def testSpecialTypes(self): |
|
267 """Verify that IsA can handle objects like cStringIO.StringIO.""" |
|
268 isA = mox.IsA(cStringIO.StringIO()) |
|
269 stringIO = cStringIO.StringIO() |
|
270 self.assert_(isA == stringIO) |
|
271 |
|
272 class IsAlmostTest(unittest.TestCase): |
|
273 """Verify IsAlmost correctly checks equality of floating point numbers.""" |
|
274 |
|
275 def testEqualityValid(self): |
|
276 """Verify that == correctly identifies nearly equivalent floats.""" |
|
277 self.assertEquals(mox.IsAlmost(1.8999999999), 1.9) |
|
278 |
|
279 def testEqualityInvalid(self): |
|
280 """Verify that == correctly identifies non-equivalent floats.""" |
|
281 self.assertNotEquals(mox.IsAlmost(1.899), 1.9) |
|
282 |
|
283 def testEqualityWithPlaces(self): |
|
284 """Verify that specifying places has the desired effect.""" |
|
285 self.assertNotEquals(mox.IsAlmost(1.899), 1.9) |
|
286 self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9) |
|
287 |
|
288 def testNonNumericTypes(self): |
|
289 """Verify that IsAlmost handles non-numeric types properly.""" |
|
290 |
|
291 self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9') |
|
292 self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9) |
|
293 self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9') |
|
294 |
|
295 class MockMethodTest(unittest.TestCase): |
|
296 """Test class to verify that the MockMethod class is working correctly.""" |
|
297 |
|
298 def setUp(self): |
|
299 self.expected_method = mox.MockMethod("testMethod", [], False)(['original']) |
|
300 self.mock_method = mox.MockMethod("testMethod", [self.expected_method], |
|
301 True) |
|
302 |
|
303 def testAndReturnNoneByDefault(self): |
|
304 """Should return None by default.""" |
|
305 return_value = self.mock_method(['original']) |
|
306 self.assert_(return_value == None) |
|
307 |
|
308 def testAndReturnValue(self): |
|
309 """Should return a specificed return value.""" |
|
310 expected_return_value = "test" |
|
311 self.expected_method.AndReturn(expected_return_value) |
|
312 return_value = self.mock_method(['original']) |
|
313 self.assert_(return_value == expected_return_value) |
|
314 |
|
315 def testAndRaiseException(self): |
|
316 """Should raise a specified exception.""" |
|
317 expected_exception = Exception('test exception') |
|
318 self.expected_method.AndRaise(expected_exception) |
|
319 self.assertRaises(Exception, self.mock_method) |
|
320 |
|
321 def testWithSideEffects(self): |
|
322 """Should call state modifier.""" |
|
323 local_list = ['original'] |
|
324 def modifier(mutable_list): |
|
325 self.assertTrue(local_list is mutable_list) |
|
326 mutable_list[0] = 'mutation' |
|
327 self.expected_method.WithSideEffects(modifier).AndReturn(1) |
|
328 self.mock_method(local_list) |
|
329 self.assertEquals('mutation', local_list[0]) |
|
330 |
|
331 def testEqualityNoParamsEqual(self): |
|
332 """Methods with the same name and without params should be equal.""" |
|
333 expected_method = mox.MockMethod("testMethod", [], False) |
|
334 self.assertEqual(self.mock_method, expected_method) |
|
335 |
|
336 def testEqualityNoParamsNotEqual(self): |
|
337 """Methods with different names and without params should not be equal.""" |
|
338 expected_method = mox.MockMethod("otherMethod", [], False) |
|
339 self.failIfEqual(self.mock_method, expected_method) |
|
340 |
|
341 def testEqualityParamsEqual(self): |
|
342 """Methods with the same name and parameters should be equal.""" |
|
343 params = [1, 2, 3] |
|
344 expected_method = mox.MockMethod("testMethod", [], False) |
|
345 expected_method._params = params |
|
346 |
|
347 self.mock_method._params = params |
|
348 self.assertEqual(self.mock_method, expected_method) |
|
349 |
|
350 def testEqualityParamsNotEqual(self): |
|
351 """Methods with the same name and different params should not be equal.""" |
|
352 expected_method = mox.MockMethod("testMethod", [], False) |
|
353 expected_method._params = [1, 2, 3] |
|
354 |
|
355 self.mock_method._params = ['a', 'b', 'c'] |
|
356 self.failIfEqual(self.mock_method, expected_method) |
|
357 |
|
358 def testEqualityNamedParamsEqual(self): |
|
359 """Methods with the same name and same named params should be equal.""" |
|
360 named_params = {"input1": "test", "input2": "params"} |
|
361 expected_method = mox.MockMethod("testMethod", [], False) |
|
362 expected_method._named_params = named_params |
|
363 |
|
364 self.mock_method._named_params = named_params |
|
365 self.assertEqual(self.mock_method, expected_method) |
|
366 |
|
367 def testEqualityNamedParamsNotEqual(self): |
|
368 """Methods with the same name and diffnamed params should not be equal.""" |
|
369 expected_method = mox.MockMethod("testMethod", [], False) |
|
370 expected_method._named_params = {"input1": "test", "input2": "params"} |
|
371 |
|
372 self.mock_method._named_params = {"input1": "test2", "input2": "params2"} |
|
373 self.failIfEqual(self.mock_method, expected_method) |
|
374 |
|
375 def testEqualityWrongType(self): |
|
376 """Method should not be equal to an object of a different type.""" |
|
377 self.failIfEqual(self.mock_method, "string?") |
|
378 |
|
379 def testObjectEquality(self): |
|
380 """Equality of objects should work without a Comparator""" |
|
381 instA = TestClass(); |
|
382 instB = TestClass(); |
|
383 |
|
384 params = [instA, ] |
|
385 expected_method = mox.MockMethod("testMethod", [], False) |
|
386 expected_method._params = params |
|
387 |
|
388 self.mock_method._params = [instB, ] |
|
389 self.assertEqual(self.mock_method, expected_method) |
|
390 |
|
391 def testStrConversion(self): |
|
392 method = mox.MockMethod("f", [], False) |
|
393 method(1, 2, "st", n1=8, n2="st2") |
|
394 self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None")) |
|
395 |
|
396 method = mox.MockMethod("testMethod", [], False) |
|
397 method(1, 2, "only positional") |
|
398 self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None") |
|
399 |
|
400 method = mox.MockMethod("testMethod", [], False) |
|
401 method(a=1, b=2, c="only named") |
|
402 self.assertEqual(str(method), |
|
403 "testMethod(a=1, b=2, c='only named') -> None") |
|
404 |
|
405 method = mox.MockMethod("testMethod", [], False) |
|
406 method() |
|
407 self.assertEqual(str(method), "testMethod() -> None") |
|
408 |
|
409 method = mox.MockMethod("testMethod", [], False) |
|
410 method(x="only 1 parameter") |
|
411 self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None") |
|
412 |
|
413 method = mox.MockMethod("testMethod", [], False) |
|
414 method().AndReturn('return_value') |
|
415 self.assertEqual(str(method), "testMethod() -> 'return_value'") |
|
416 |
|
417 method = mox.MockMethod("testMethod", [], False) |
|
418 method().AndReturn(('a', {1: 2})) |
|
419 self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})") |
|
420 |
|
421 |
|
422 class MockAnythingTest(unittest.TestCase): |
|
423 """Verify that the MockAnything class works as expected.""" |
|
424 |
|
425 def setUp(self): |
|
426 self.mock_object = mox.MockAnything() |
|
427 |
|
428 def testSetupMode(self): |
|
429 """Verify the mock will accept any call.""" |
|
430 self.mock_object.NonsenseCall() |
|
431 self.assert_(len(self.mock_object._expected_calls_queue) == 1) |
|
432 |
|
433 def testReplayWithExpectedCall(self): |
|
434 """Verify the mock replays method calls as expected.""" |
|
435 self.mock_object.ValidCall() # setup method call |
|
436 self.mock_object._Replay() # start replay mode |
|
437 self.mock_object.ValidCall() # make method call |
|
438 |
|
439 def testReplayWithUnexpectedCall(self): |
|
440 """Unexpected method calls should raise UnexpectedMethodCallError.""" |
|
441 self.mock_object.ValidCall() # setup method call |
|
442 self.mock_object._Replay() # start replay mode |
|
443 self.assertRaises(mox.UnexpectedMethodCallError, |
|
444 self.mock_object.OtherValidCall) |
|
445 |
|
446 def testVerifyWithCompleteReplay(self): |
|
447 """Verify should not raise an exception for a valid replay.""" |
|
448 self.mock_object.ValidCall() # setup method call |
|
449 self.mock_object._Replay() # start replay mode |
|
450 self.mock_object.ValidCall() # make method call |
|
451 self.mock_object._Verify() |
|
452 |
|
453 def testVerifyWithIncompleteReplay(self): |
|
454 """Verify should raise an exception if the replay was not complete.""" |
|
455 self.mock_object.ValidCall() # setup method call |
|
456 self.mock_object._Replay() # start replay mode |
|
457 # ValidCall() is never made |
|
458 self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify) |
|
459 |
|
460 def testSpecialClassMethod(self): |
|
461 """Verify should not raise an exception when special methods are used.""" |
|
462 self.mock_object[1].AndReturn(True) |
|
463 self.mock_object._Replay() |
|
464 returned_val = self.mock_object[1] |
|
465 self.assert_(returned_val) |
|
466 self.mock_object._Verify() |
|
467 |
|
468 def testNonzero(self): |
|
469 """You should be able to use the mock object in an if.""" |
|
470 self.mock_object._Replay() |
|
471 if self.mock_object: |
|
472 pass |
|
473 |
|
474 def testNotNone(self): |
|
475 """Mock should be comparable to None.""" |
|
476 self.mock_object._Replay() |
|
477 if self.mock_object is not None: |
|
478 pass |
|
479 |
|
480 if self.mock_object is None: |
|
481 pass |
|
482 |
|
483 def testEquals(self): |
|
484 """A mock should be able to compare itself to another object.""" |
|
485 self.mock_object._Replay() |
|
486 self.assertEquals(self.mock_object, self.mock_object) |
|
487 |
|
488 def testEqualsMockFailure(self): |
|
489 """Verify equals identifies unequal objects.""" |
|
490 self.mock_object.SillyCall() |
|
491 self.mock_object._Replay() |
|
492 self.assertNotEquals(self.mock_object, mox.MockAnything()) |
|
493 |
|
494 def testEqualsInstanceFailure(self): |
|
495 """Verify equals identifies that objects are different instances.""" |
|
496 self.mock_object._Replay() |
|
497 self.assertNotEquals(self.mock_object, TestClass()) |
|
498 |
|
499 def testNotEquals(self): |
|
500 """Verify not equals works.""" |
|
501 self.mock_object._Replay() |
|
502 self.assertFalse(self.mock_object != self.mock_object) |
|
503 |
|
504 def testNestedMockCallsRecordedSerially(self): |
|
505 """Test that nested calls work when recorded serially.""" |
|
506 self.mock_object.CallInner().AndReturn(1) |
|
507 self.mock_object.CallOuter(1) |
|
508 self.mock_object._Replay() |
|
509 |
|
510 self.mock_object.CallOuter(self.mock_object.CallInner()) |
|
511 |
|
512 self.mock_object._Verify() |
|
513 |
|
514 def testNestedMockCallsRecordedNested(self): |
|
515 """Test that nested cals work when recorded in a nested fashion.""" |
|
516 self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1)) |
|
517 self.mock_object._Replay() |
|
518 |
|
519 self.mock_object.CallOuter(self.mock_object.CallInner()) |
|
520 |
|
521 self.mock_object._Verify() |
|
522 |
|
523 def testIsCallable(self): |
|
524 """Test that MockAnything can even mock a simple callable. |
|
525 |
|
526 This is handy for "stubbing out" a method in a module with a mock, and |
|
527 verifying that it was called. |
|
528 """ |
|
529 self.mock_object().AndReturn('mox0rd') |
|
530 self.mock_object._Replay() |
|
531 |
|
532 self.assertEquals('mox0rd', self.mock_object()) |
|
533 |
|
534 self.mock_object._Verify() |
|
535 |
|
536 |
|
537 class MethodCheckerTest(unittest.TestCase): |
|
538 """Tests MockMethod's use of MethodChecker method.""" |
|
539 |
|
540 def testNoParameters(self): |
|
541 method = mox.MockMethod('NoParameters', [], False, |
|
542 CheckCallTestClass.NoParameters) |
|
543 method() |
|
544 self.assertRaises(AttributeError, method, 1) |
|
545 self.assertRaises(AttributeError, method, 1, 2) |
|
546 self.assertRaises(AttributeError, method, a=1) |
|
547 self.assertRaises(AttributeError, method, 1, b=2) |
|
548 |
|
549 def testOneParameter(self): |
|
550 method = mox.MockMethod('OneParameter', [], False, |
|
551 CheckCallTestClass.OneParameter) |
|
552 self.assertRaises(AttributeError, method) |
|
553 method(1) |
|
554 method(a=1) |
|
555 self.assertRaises(AttributeError, method, b=1) |
|
556 self.assertRaises(AttributeError, method, 1, 2) |
|
557 self.assertRaises(AttributeError, method, 1, a=2) |
|
558 self.assertRaises(AttributeError, method, 1, b=2) |
|
559 |
|
560 def testTwoParameters(self): |
|
561 method = mox.MockMethod('TwoParameters', [], False, |
|
562 CheckCallTestClass.TwoParameters) |
|
563 self.assertRaises(AttributeError, method) |
|
564 self.assertRaises(AttributeError, method, 1) |
|
565 self.assertRaises(AttributeError, method, a=1) |
|
566 self.assertRaises(AttributeError, method, b=1) |
|
567 method(1, 2) |
|
568 method(1, b=2) |
|
569 method(a=1, b=2) |
|
570 method(b=2, a=1) |
|
571 self.assertRaises(AttributeError, method, b=2, c=3) |
|
572 self.assertRaises(AttributeError, method, a=1, b=2, c=3) |
|
573 self.assertRaises(AttributeError, method, 1, 2, 3) |
|
574 self.assertRaises(AttributeError, method, 1, 2, 3, 4) |
|
575 self.assertRaises(AttributeError, method, 3, a=1, b=2) |
|
576 |
|
577 def testOneDefaultValue(self): |
|
578 method = mox.MockMethod('OneDefaultValue', [], False, |
|
579 CheckCallTestClass.OneDefaultValue) |
|
580 method() |
|
581 method(1) |
|
582 method(a=1) |
|
583 self.assertRaises(AttributeError, method, b=1) |
|
584 self.assertRaises(AttributeError, method, 1, 2) |
|
585 self.assertRaises(AttributeError, method, 1, a=2) |
|
586 self.assertRaises(AttributeError, method, 1, b=2) |
|
587 |
|
588 def testTwoDefaultValues(self): |
|
589 method = mox.MockMethod('TwoDefaultValues', [], False, |
|
590 CheckCallTestClass.TwoDefaultValues) |
|
591 self.assertRaises(AttributeError, method) |
|
592 self.assertRaises(AttributeError, method, c=3) |
|
593 self.assertRaises(AttributeError, method, 1) |
|
594 self.assertRaises(AttributeError, method, 1, d=4) |
|
595 self.assertRaises(AttributeError, method, 1, d=4, c=3) |
|
596 method(1, 2) |
|
597 method(a=1, b=2) |
|
598 method(1, 2, 3) |
|
599 method(1, 2, 3, 4) |
|
600 method(1, 2, c=3) |
|
601 method(1, 2, c=3, d=4) |
|
602 method(1, 2, d=4, c=3) |
|
603 method(d=4, c=3, a=1, b=2) |
|
604 self.assertRaises(AttributeError, method, 1, 2, 3, 4, 5) |
|
605 self.assertRaises(AttributeError, method, 1, 2, e=9) |
|
606 self.assertRaises(AttributeError, method, a=1, b=2, e=9) |
|
607 |
|
608 def testArgs(self): |
|
609 method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args) |
|
610 self.assertRaises(AttributeError, method) |
|
611 self.assertRaises(AttributeError, method, 1) |
|
612 method(1, 2) |
|
613 method(a=1, b=2) |
|
614 method(1, 2, 3) |
|
615 method(1, 2, 3, 4) |
|
616 self.assertRaises(AttributeError, method, 1, 2, a=3) |
|
617 self.assertRaises(AttributeError, method, 1, 2, c=3) |
|
618 |
|
619 def testKwargs(self): |
|
620 method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs) |
|
621 self.assertRaises(AttributeError, method) |
|
622 method(1) |
|
623 method(1, 2) |
|
624 method(a=1, b=2) |
|
625 method(b=2, a=1) |
|
626 self.assertRaises(AttributeError, method, 1, 2, 3) |
|
627 self.assertRaises(AttributeError, method, 1, 2, a=3) |
|
628 method(1, 2, c=3) |
|
629 method(a=1, b=2, c=3) |
|
630 method(c=3, a=1, b=2) |
|
631 method(a=1, b=2, c=3, d=4) |
|
632 self.assertRaises(AttributeError, method, 1, 2, 3, 4) |
|
633 |
|
634 def testArgsAndKwargs(self): |
|
635 method = mox.MockMethod('ArgsAndKwargs', [], False, |
|
636 CheckCallTestClass.ArgsAndKwargs) |
|
637 self.assertRaises(AttributeError, method) |
|
638 method(1) |
|
639 method(1, 2) |
|
640 method(1, 2, 3) |
|
641 method(a=1) |
|
642 method(1, b=2) |
|
643 self.assertRaises(AttributeError, method, 1, a=2) |
|
644 method(b=2, a=1) |
|
645 method(c=3, b=2, a=1) |
|
646 method(1, 2, c=3) |
|
647 |
|
648 |
|
649 class CheckCallTestClass(object): |
|
650 def NoParameters(self): |
|
651 pass |
|
652 |
|
653 def OneParameter(self, a): |
|
654 pass |
|
655 |
|
656 def TwoParameters(self, a, b): |
|
657 pass |
|
658 |
|
659 def OneDefaultValue(self, a=1): |
|
660 pass |
|
661 |
|
662 def TwoDefaultValues(self, a, b, c=1, d=2): |
|
663 pass |
|
664 |
|
665 def Args(self, a, b, *args): |
|
666 pass |
|
667 |
|
668 def Kwargs(self, a, b=2, **kwargs): |
|
669 pass |
|
670 |
|
671 def ArgsAndKwargs(self, a, *args, **kwargs): |
|
672 pass |
|
673 |
|
674 |
|
675 class MockObjectTest(unittest.TestCase): |
|
676 """Verify that the MockObject class works as exepcted.""" |
|
677 |
|
678 def setUp(self): |
|
679 self.mock_object = mox.MockObject(TestClass) |
|
680 |
|
681 def testSetupModeWithValidCall(self): |
|
682 """Verify the mock object properly mocks a basic method call.""" |
|
683 self.mock_object.ValidCall() |
|
684 self.assert_(len(self.mock_object._expected_calls_queue) == 1) |
|
685 |
|
686 def testSetupModeWithInvalidCall(self): |
|
687 """UnknownMethodCallError should be raised if a non-member method is called. |
|
688 """ |
|
689 # Note: assertRaises does not catch exceptions thrown by MockObject's |
|
690 # __getattr__ |
|
691 try: |
|
692 self.mock_object.InvalidCall() |
|
693 self.fail("No exception thrown, expected UnknownMethodCallError") |
|
694 except mox.UnknownMethodCallError: |
|
695 pass |
|
696 except Exception: |
|
697 self.fail("Wrong exception type thrown, expected UnknownMethodCallError") |
|
698 |
|
699 def testReplayWithInvalidCall(self): |
|
700 """UnknownMethodCallError should be raised if a non-member method is called. |
|
701 """ |
|
702 self.mock_object.ValidCall() # setup method call |
|
703 self.mock_object._Replay() # start replay mode |
|
704 # Note: assertRaises does not catch exceptions thrown by MockObject's |
|
705 # __getattr__ |
|
706 try: |
|
707 self.mock_object.InvalidCall() |
|
708 self.fail("No exception thrown, expected UnknownMethodCallError") |
|
709 except mox.UnknownMethodCallError: |
|
710 pass |
|
711 except Exception: |
|
712 self.fail("Wrong exception type thrown, expected UnknownMethodCallError") |
|
713 |
|
714 def testIsInstance(self): |
|
715 """Mock should be able to pass as an instance of the mocked class.""" |
|
716 self.assert_(isinstance(self.mock_object, TestClass)) |
|
717 |
|
718 def testFindValidMethods(self): |
|
719 """Mock should be able to mock all public methods.""" |
|
720 self.assert_('ValidCall' in self.mock_object._known_methods) |
|
721 self.assert_('OtherValidCall' in self.mock_object._known_methods) |
|
722 self.assert_('MyClassMethod' in self.mock_object._known_methods) |
|
723 self.assert_('MyStaticMethod' in self.mock_object._known_methods) |
|
724 self.assert_('_ProtectedCall' in self.mock_object._known_methods) |
|
725 self.assert_('__PrivateCall' not in self.mock_object._known_methods) |
|
726 self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods) |
|
727 |
|
728 def testFindsSuperclassMethods(self): |
|
729 """Mock should be able to mock superclasses methods.""" |
|
730 self.mock_object = mox.MockObject(ChildClass) |
|
731 self.assert_('ValidCall' in self.mock_object._known_methods) |
|
732 self.assert_('OtherValidCall' in self.mock_object._known_methods) |
|
733 self.assert_('MyClassMethod' in self.mock_object._known_methods) |
|
734 self.assert_('ChildValidCall' in self.mock_object._known_methods) |
|
735 |
|
736 def testAccessClassVariables(self): |
|
737 """Class variables should be accessible through the mock.""" |
|
738 self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars) |
|
739 self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars) |
|
740 self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR) |
|
741 |
|
742 def testEquals(self): |
|
743 """A mock should be able to compare itself to another object.""" |
|
744 self.mock_object._Replay() |
|
745 self.assertEquals(self.mock_object, self.mock_object) |
|
746 |
|
747 def testEqualsMockFailure(self): |
|
748 """Verify equals identifies unequal objects.""" |
|
749 self.mock_object.ValidCall() |
|
750 self.mock_object._Replay() |
|
751 self.assertNotEquals(self.mock_object, mox.MockObject(TestClass)) |
|
752 |
|
753 def testEqualsInstanceFailure(self): |
|
754 """Verify equals identifies that objects are different instances.""" |
|
755 self.mock_object._Replay() |
|
756 self.assertNotEquals(self.mock_object, TestClass()) |
|
757 |
|
758 def testNotEquals(self): |
|
759 """Verify not equals works.""" |
|
760 self.mock_object._Replay() |
|
761 self.assertFalse(self.mock_object != self.mock_object) |
|
762 |
|
763 def testMockSetItem_ExpectedSetItem_Success(self): |
|
764 """Test that __setitem__() gets mocked in Dummy. |
|
765 |
|
766 In this test, _Verify() succeeds. |
|
767 """ |
|
768 dummy = mox.MockObject(TestClass) |
|
769 dummy['X'] = 'Y' |
|
770 |
|
771 dummy._Replay() |
|
772 |
|
773 dummy['X'] = 'Y' |
|
774 |
|
775 dummy._Verify() |
|
776 |
|
777 def testMockSetItem_ExpectedSetItem_NoSuccess(self): |
|
778 """Test that __setitem__() gets mocked in Dummy. |
|
779 |
|
780 In this test, _Verify() fails. |
|
781 """ |
|
782 dummy = mox.MockObject(TestClass) |
|
783 dummy['X'] = 'Y' |
|
784 |
|
785 dummy._Replay() |
|
786 |
|
787 # NOT doing dummy['X'] = 'Y' |
|
788 |
|
789 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify) |
|
790 |
|
791 def testMockSetItem_ExpectedNoSetItem_Success(self): |
|
792 """Test that __setitem__() gets mocked in Dummy. |
|
793 |
|
794 In this test, _Verify() succeeds. |
|
795 """ |
|
796 dummy = mox.MockObject(TestClass) |
|
797 # NOT doing dummy['X'] = 'Y' |
|
798 |
|
799 dummy._Replay() |
|
800 |
|
801 def call(): dummy['X'] = 'Y' |
|
802 self.assertRaises(mox.UnexpectedMethodCallError, call) |
|
803 |
|
804 dummy._Verify() |
|
805 |
|
806 def testMockSetItem_ExpectedNoSetItem_NoSuccess(self): |
|
807 """Test that __setitem__() gets mocked in Dummy. |
|
808 |
|
809 In this test, _Verify() fails. |
|
810 """ |
|
811 dummy = mox.MockObject(TestClass) |
|
812 # NOT doing dummy['X'] = 'Y' |
|
813 |
|
814 dummy._Replay() |
|
815 |
|
816 # NOT doing dummy['X'] = 'Y' |
|
817 |
|
818 dummy._Verify() |
|
819 |
|
820 def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self): |
|
821 """Test that __setitem__() fails if other parameters are expected.""" |
|
822 dummy = mox.MockObject(TestClass) |
|
823 dummy['X'] = 'Y' |
|
824 |
|
825 dummy._Replay() |
|
826 |
|
827 def call(): dummy['wrong'] = 'Y' |
|
828 |
|
829 self.assertRaises(mox.UnexpectedMethodCallError, call) |
|
830 |
|
831 dummy._Verify() |
|
832 |
|
833 def testMockGetItem_ExpectedGetItem_Success(self): |
|
834 """Test that __setitem__() gets mocked in Dummy. |
|
835 |
|
836 In this test, _Verify() succeeds. |
|
837 """ |
|
838 dummy = mox.MockObject(TestClass) |
|
839 dummy['X'].AndReturn('value') |
|
840 |
|
841 dummy._Replay() |
|
842 |
|
843 self.assertEqual(dummy['X'], 'value') |
|
844 |
|
845 dummy._Verify() |
|
846 |
|
847 def testMockGetItem_ExpectedGetItem_NoSuccess(self): |
|
848 """Test that __setitem__() gets mocked in Dummy. |
|
849 |
|
850 In this test, _Verify() fails. |
|
851 """ |
|
852 dummy = mox.MockObject(TestClass) |
|
853 dummy['X'].AndReturn('value') |
|
854 |
|
855 dummy._Replay() |
|
856 |
|
857 # NOT doing dummy['X'] |
|
858 |
|
859 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify) |
|
860 |
|
861 def testMockGetItem_ExpectedNoGetItem_NoSuccess(self): |
|
862 """Test that __setitem__() gets mocked in Dummy. |
|
863 |
|
864 In this test, _Verify() succeeds. |
|
865 """ |
|
866 dummy = mox.MockObject(TestClass) |
|
867 # NOT doing dummy['X'] |
|
868 |
|
869 dummy._Replay() |
|
870 |
|
871 def call(): return dummy['X'] |
|
872 self.assertRaises(mox.UnexpectedMethodCallError, call) |
|
873 |
|
874 dummy._Verify() |
|
875 |
|
876 def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self): |
|
877 """Test that __setitem__() fails if other parameters are expected.""" |
|
878 dummy = mox.MockObject(TestClass) |
|
879 dummy['X'].AndReturn('value') |
|
880 |
|
881 dummy._Replay() |
|
882 |
|
883 def call(): return dummy['wrong'] |
|
884 |
|
885 self.assertRaises(mox.UnexpectedMethodCallError, call) |
|
886 |
|
887 dummy._Verify() |
|
888 |
|
889 def testMockContains_ExpectedContains_Success(self): |
|
890 """Test that __contains__ gets mocked in Dummy. |
|
891 |
|
892 In this test, _Verify() succeeds. |
|
893 """ |
|
894 dummy = mox.MockObject(TestClass) |
|
895 dummy.__contains__('X').AndReturn(True) |
|
896 |
|
897 dummy._Replay() |
|
898 |
|
899 self.failUnless('X' in dummy) |
|
900 |
|
901 dummy._Verify() |
|
902 |
|
903 def testMockContains_ExpectedContains_NoSuccess(self): |
|
904 """Test that __contains__() gets mocked in Dummy. |
|
905 |
|
906 In this test, _Verify() fails. |
|
907 """ |
|
908 dummy = mox.MockObject(TestClass) |
|
909 dummy.__contains__('X').AndReturn('True') |
|
910 |
|
911 dummy._Replay() |
|
912 |
|
913 # NOT doing 'X' in dummy |
|
914 |
|
915 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify) |
|
916 |
|
917 def testMockContains_ExpectedContains_NonmatchingParameter(self): |
|
918 """Test that __contains__ fails if other parameters are expected.""" |
|
919 dummy = mox.MockObject(TestClass) |
|
920 dummy.__contains__('X').AndReturn(True) |
|
921 |
|
922 dummy._Replay() |
|
923 |
|
924 def call(): return 'Y' in dummy |
|
925 |
|
926 self.assertRaises(mox.UnexpectedMethodCallError, call) |
|
927 |
|
928 dummy._Verify() |
|
929 |
|
930 class MoxTest(unittest.TestCase): |
|
931 """Verify Mox works correctly.""" |
|
932 |
|
933 def setUp(self): |
|
934 self.mox = mox.Mox() |
|
935 |
|
936 def testCreateObject(self): |
|
937 """Mox should create a mock object.""" |
|
938 mock_obj = self.mox.CreateMock(TestClass) |
|
939 |
|
940 def testVerifyObjectWithCompleteReplay(self): |
|
941 """Mox should replay and verify all objects it created.""" |
|
942 mock_obj = self.mox.CreateMock(TestClass) |
|
943 mock_obj.ValidCall() |
|
944 mock_obj.ValidCallWithArgs(mox.IsA(TestClass)) |
|
945 self.mox.ReplayAll() |
|
946 mock_obj.ValidCall() |
|
947 mock_obj.ValidCallWithArgs(TestClass("some_value")) |
|
948 self.mox.VerifyAll() |
|
949 |
|
950 def testVerifyObjectWithIncompleteReplay(self): |
|
951 """Mox should raise an exception if a mock didn't replay completely.""" |
|
952 mock_obj = self.mox.CreateMock(TestClass) |
|
953 mock_obj.ValidCall() |
|
954 self.mox.ReplayAll() |
|
955 # ValidCall() is never made |
|
956 self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll) |
|
957 |
|
958 def testEntireWorkflow(self): |
|
959 """Test the whole work flow.""" |
|
960 mock_obj = self.mox.CreateMock(TestClass) |
|
961 mock_obj.ValidCall().AndReturn("yes") |
|
962 self.mox.ReplayAll() |
|
963 |
|
964 ret_val = mock_obj.ValidCall() |
|
965 self.assertEquals("yes", ret_val) |
|
966 self.mox.VerifyAll() |
|
967 |
|
968 def testCallableObject(self): |
|
969 """Test recording calls to a callable object works.""" |
|
970 mock_obj = self.mox.CreateMock(CallableClass) |
|
971 mock_obj("foo").AndReturn("qux") |
|
972 self.mox.ReplayAll() |
|
973 |
|
974 ret_val = mock_obj("foo") |
|
975 self.assertEquals("qux", ret_val) |
|
976 self.mox.VerifyAll() |
|
977 |
|
978 def testCallOnNonCallableObject(self): |
|
979 """Test that you cannot call a non-callable object.""" |
|
980 mock_obj = self.mox.CreateMock(TestClass) |
|
981 self.assertRaises(TypeError, mock_obj) |
|
982 |
|
983 def testCallableObjectWithBadCall(self): |
|
984 """Test verifying calls to a callable object works.""" |
|
985 mock_obj = self.mox.CreateMock(CallableClass) |
|
986 mock_obj("foo").AndReturn("qux") |
|
987 self.mox.ReplayAll() |
|
988 |
|
989 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, "ZOOBAZ") |
|
990 |
|
991 def testUnorderedGroup(self): |
|
992 """Test that using one unordered group works.""" |
|
993 mock_obj = self.mox.CreateMockAnything() |
|
994 mock_obj.Method(1).InAnyOrder() |
|
995 mock_obj.Method(2).InAnyOrder() |
|
996 self.mox.ReplayAll() |
|
997 |
|
998 mock_obj.Method(2) |
|
999 mock_obj.Method(1) |
|
1000 |
|
1001 self.mox.VerifyAll() |
|
1002 |
|
1003 def testUnorderedGroupsInline(self): |
|
1004 """Unordered groups should work in the context of ordered calls.""" |
|
1005 mock_obj = self.mox.CreateMockAnything() |
|
1006 mock_obj.Open() |
|
1007 mock_obj.Method(1).InAnyOrder() |
|
1008 mock_obj.Method(2).InAnyOrder() |
|
1009 mock_obj.Close() |
|
1010 self.mox.ReplayAll() |
|
1011 |
|
1012 mock_obj.Open() |
|
1013 mock_obj.Method(2) |
|
1014 mock_obj.Method(1) |
|
1015 mock_obj.Close() |
|
1016 |
|
1017 self.mox.VerifyAll() |
|
1018 |
|
1019 def testMultipleUnorderdGroups(self): |
|
1020 """Multiple unoreded groups should work.""" |
|
1021 mock_obj = self.mox.CreateMockAnything() |
|
1022 mock_obj.Method(1).InAnyOrder() |
|
1023 mock_obj.Method(2).InAnyOrder() |
|
1024 mock_obj.Foo().InAnyOrder('group2') |
|
1025 mock_obj.Bar().InAnyOrder('group2') |
|
1026 self.mox.ReplayAll() |
|
1027 |
|
1028 mock_obj.Method(2) |
|
1029 mock_obj.Method(1) |
|
1030 mock_obj.Bar() |
|
1031 mock_obj.Foo() |
|
1032 |
|
1033 self.mox.VerifyAll() |
|
1034 |
|
1035 def testMultipleUnorderdGroupsOutOfOrder(self): |
|
1036 """Multiple unordered groups should maintain external order""" |
|
1037 mock_obj = self.mox.CreateMockAnything() |
|
1038 mock_obj.Method(1).InAnyOrder() |
|
1039 mock_obj.Method(2).InAnyOrder() |
|
1040 mock_obj.Foo().InAnyOrder('group2') |
|
1041 mock_obj.Bar().InAnyOrder('group2') |
|
1042 self.mox.ReplayAll() |
|
1043 |
|
1044 mock_obj.Method(2) |
|
1045 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar) |
|
1046 |
|
1047 def testUnorderedGroupWithReturnValue(self): |
|
1048 """Unordered groups should work with return values.""" |
|
1049 mock_obj = self.mox.CreateMockAnything() |
|
1050 mock_obj.Open() |
|
1051 mock_obj.Method(1).InAnyOrder().AndReturn(9) |
|
1052 mock_obj.Method(2).InAnyOrder().AndReturn(10) |
|
1053 mock_obj.Close() |
|
1054 self.mox.ReplayAll() |
|
1055 |
|
1056 mock_obj.Open() |
|
1057 actual_two = mock_obj.Method(2) |
|
1058 actual_one = mock_obj.Method(1) |
|
1059 mock_obj.Close() |
|
1060 |
|
1061 self.assertEquals(9, actual_one) |
|
1062 self.assertEquals(10, actual_two) |
|
1063 |
|
1064 self.mox.VerifyAll() |
|
1065 |
|
1066 def testUnorderedGroupWithComparator(self): |
|
1067 """Unordered groups should work with comparators""" |
|
1068 |
|
1069 def VerifyOne(cmd): |
|
1070 if not isinstance(cmd, str): |
|
1071 self.fail('Unexpected type passed to comparator: ' + str(cmd)) |
|
1072 return cmd == 'test' |
|
1073 |
|
1074 def VerifyTwo(cmd): |
|
1075 return True |
|
1076 |
|
1077 mock_obj = self.mox.CreateMockAnything() |
|
1078 mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\ |
|
1079 AndReturn('yes test') |
|
1080 mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\ |
|
1081 AndReturn('anything') |
|
1082 |
|
1083 self.mox.ReplayAll() |
|
1084 |
|
1085 mock_obj.Foo(['test'], 'anything', bar=1) |
|
1086 mock_obj.Foo(['test'], 'test', bar=1) |
|
1087 |
|
1088 self.mox.VerifyAll() |
|
1089 |
|
1090 def testMultipleTimes(self): |
|
1091 """Test if MultipleTimesGroup works.""" |
|
1092 mock_obj = self.mox.CreateMockAnything() |
|
1093 mock_obj.Method(1).MultipleTimes().AndReturn(9) |
|
1094 mock_obj.Method(2).AndReturn(10) |
|
1095 mock_obj.Method(3).MultipleTimes().AndReturn(42) |
|
1096 self.mox.ReplayAll() |
|
1097 |
|
1098 actual_one = mock_obj.Method(1) |
|
1099 second_one = mock_obj.Method(1) # This tests MultipleTimes. |
|
1100 actual_two = mock_obj.Method(2) |
|
1101 actual_three = mock_obj.Method(3) |
|
1102 mock_obj.Method(3) |
|
1103 mock_obj.Method(3) |
|
1104 |
|
1105 self.assertEquals(9, actual_one) |
|
1106 self.assertEquals(9, second_one) # Repeated calls should return same number. |
|
1107 self.assertEquals(10, actual_two) |
|
1108 self.assertEquals(42, actual_three) |
|
1109 |
|
1110 self.mox.VerifyAll() |
|
1111 |
|
1112 def testMultipleTimesUsingIsAParameter(self): |
|
1113 """Test if MultipleTimesGroup works with a IsA parameter.""" |
|
1114 mock_obj = self.mox.CreateMockAnything() |
|
1115 mock_obj.Open() |
|
1116 mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9) |
|
1117 mock_obj.Close() |
|
1118 self.mox.ReplayAll() |
|
1119 |
|
1120 mock_obj.Open() |
|
1121 actual_one = mock_obj.Method("1") |
|
1122 second_one = mock_obj.Method("2") # This tests MultipleTimes. |
|
1123 mock_obj.Close() |
|
1124 |
|
1125 self.assertEquals(9, actual_one) |
|
1126 self.assertEquals(9, second_one) # Repeated calls should return same number. |
|
1127 |
|
1128 self.mox.VerifyAll() |
|
1129 |
|
1130 def testMultipleTimesThreeMethods(self): |
|
1131 """Test if MultipleTimesGroup works with three or more methods.""" |
|
1132 mock_obj = self.mox.CreateMockAnything() |
|
1133 mock_obj.Open() |
|
1134 mock_obj.Method(1).MultipleTimes().AndReturn(9) |
|
1135 mock_obj.Method(2).MultipleTimes().AndReturn(8) |
|
1136 mock_obj.Method(3).MultipleTimes().AndReturn(7) |
|
1137 mock_obj.Method(4).AndReturn(10) |
|
1138 mock_obj.Close() |
|
1139 self.mox.ReplayAll() |
|
1140 |
|
1141 mock_obj.Open() |
|
1142 actual_three = mock_obj.Method(3) |
|
1143 mock_obj.Method(1) |
|
1144 actual_two = mock_obj.Method(2) |
|
1145 mock_obj.Method(3) |
|
1146 actual_one = mock_obj.Method(1) |
|
1147 actual_four = mock_obj.Method(4) |
|
1148 mock_obj.Close() |
|
1149 |
|
1150 self.assertEquals(9, actual_one) |
|
1151 self.assertEquals(8, actual_two) |
|
1152 self.assertEquals(7, actual_three) |
|
1153 self.assertEquals(10, actual_four) |
|
1154 |
|
1155 self.mox.VerifyAll() |
|
1156 |
|
1157 def testMultipleTimesMissingOne(self): |
|
1158 """Test if MultipleTimesGroup fails if one method is missing.""" |
|
1159 mock_obj = self.mox.CreateMockAnything() |
|
1160 mock_obj.Open() |
|
1161 mock_obj.Method(1).MultipleTimes().AndReturn(9) |
|
1162 mock_obj.Method(2).MultipleTimes().AndReturn(8) |
|
1163 mock_obj.Method(3).MultipleTimes().AndReturn(7) |
|
1164 mock_obj.Method(4).AndReturn(10) |
|
1165 mock_obj.Close() |
|
1166 self.mox.ReplayAll() |
|
1167 |
|
1168 mock_obj.Open() |
|
1169 mock_obj.Method(3) |
|
1170 mock_obj.Method(2) |
|
1171 mock_obj.Method(3) |
|
1172 mock_obj.Method(3) |
|
1173 mock_obj.Method(2) |
|
1174 |
|
1175 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4) |
|
1176 |
|
1177 def testMultipleTimesTwoGroups(self): |
|
1178 """Test if MultipleTimesGroup works with a group after a |
|
1179 MultipleTimesGroup. |
|
1180 """ |
|
1181 mock_obj = self.mox.CreateMockAnything() |
|
1182 mock_obj.Open() |
|
1183 mock_obj.Method(1).MultipleTimes().AndReturn(9) |
|
1184 mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42) |
|
1185 mock_obj.Close() |
|
1186 self.mox.ReplayAll() |
|
1187 |
|
1188 mock_obj.Open() |
|
1189 actual_one = mock_obj.Method(1) |
|
1190 mock_obj.Method(1) |
|
1191 actual_three = mock_obj.Method(3) |
|
1192 mock_obj.Method(3) |
|
1193 mock_obj.Close() |
|
1194 |
|
1195 self.assertEquals(9, actual_one) |
|
1196 self.assertEquals(42, actual_three) |
|
1197 |
|
1198 self.mox.VerifyAll() |
|
1199 |
|
1200 def testMultipleTimesTwoGroupsFailure(self): |
|
1201 """Test if MultipleTimesGroup fails with a group after a |
|
1202 MultipleTimesGroup. |
|
1203 """ |
|
1204 mock_obj = self.mox.CreateMockAnything() |
|
1205 mock_obj.Open() |
|
1206 mock_obj.Method(1).MultipleTimes().AndReturn(9) |
|
1207 mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42) |
|
1208 mock_obj.Close() |
|
1209 self.mox.ReplayAll() |
|
1210 |
|
1211 mock_obj.Open() |
|
1212 actual_one = mock_obj.Method(1) |
|
1213 mock_obj.Method(1) |
|
1214 actual_three = mock_obj.Method(3) |
|
1215 |
|
1216 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1) |
|
1217 |
|
1218 def testWithSideEffects(self): |
|
1219 """Test side effect operations actually modify their target objects.""" |
|
1220 def modifier(mutable_list): |
|
1221 mutable_list[0] = 'mutated' |
|
1222 mock_obj = self.mox.CreateMockAnything() |
|
1223 mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier) |
|
1224 mock_obj.WorkWithParameter(['mutated']) |
|
1225 self.mox.ReplayAll() |
|
1226 |
|
1227 local_list = ['original'] |
|
1228 mock_obj.ConfigureInOutParameter(local_list) |
|
1229 mock_obj.WorkWithParameter(local_list) |
|
1230 |
|
1231 self.mox.VerifyAll() |
|
1232 |
|
1233 def testWithSideEffectsException(self): |
|
1234 """Test side effect operations actually modify their target objects.""" |
|
1235 def modifier(mutable_list): |
|
1236 mutable_list[0] = 'mutated' |
|
1237 mock_obj = self.mox.CreateMockAnything() |
|
1238 method = mock_obj.ConfigureInOutParameter(['original']) |
|
1239 method.WithSideEffects(modifier).AndRaise(Exception('exception')) |
|
1240 mock_obj.WorkWithParameter(['mutated']) |
|
1241 self.mox.ReplayAll() |
|
1242 |
|
1243 local_list = ['original'] |
|
1244 self.failUnlessRaises(Exception, |
|
1245 mock_obj.ConfigureInOutParameter, |
|
1246 local_list) |
|
1247 mock_obj.WorkWithParameter(local_list) |
|
1248 |
|
1249 self.mox.VerifyAll() |
|
1250 |
|
1251 def testStubOutMethod(self): |
|
1252 """Test that a method is replaced with a MockAnything.""" |
|
1253 test_obj = TestClass() |
|
1254 # Replace OtherValidCall with a mock. |
|
1255 self.mox.StubOutWithMock(test_obj, 'OtherValidCall') |
|
1256 self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything)) |
|
1257 test_obj.OtherValidCall().AndReturn('foo') |
|
1258 self.mox.ReplayAll() |
|
1259 |
|
1260 actual = test_obj.OtherValidCall() |
|
1261 |
|
1262 self.mox.VerifyAll() |
|
1263 self.mox.UnsetStubs() |
|
1264 self.assertEquals('foo', actual) |
|
1265 self.failIf(isinstance(test_obj.OtherValidCall, mox.MockAnything)) |
|
1266 |
|
1267 def testStubOutObject(self): |
|
1268 """Test than object is replaced with a Mock.""" |
|
1269 |
|
1270 class Foo(object): |
|
1271 def __init__(self): |
|
1272 self.obj = TestClass() |
|
1273 |
|
1274 foo = Foo() |
|
1275 self.mox.StubOutWithMock(foo, "obj") |
|
1276 self.assert_(isinstance(foo.obj, mox.MockObject)) |
|
1277 foo.obj.ValidCall() |
|
1278 self.mox.ReplayAll() |
|
1279 |
|
1280 foo.obj.ValidCall() |
|
1281 |
|
1282 self.mox.VerifyAll() |
|
1283 self.mox.UnsetStubs() |
|
1284 self.failIf(isinstance(foo.obj, mox.MockObject)) |
|
1285 |
|
1286 def testForgotReplayHelpfulMessage(self): |
|
1287 """If there is an AttributeError on a MockMethod, give users a helpful msg. |
|
1288 """ |
|
1289 foo = self.mox.CreateMockAnything() |
|
1290 bar = self.mox.CreateMockAnything() |
|
1291 foo.GetBar().AndReturn(bar) |
|
1292 bar.ShowMeTheMoney() |
|
1293 # Forgot to replay! |
|
1294 try: |
|
1295 foo.GetBar().ShowMeTheMoney() |
|
1296 except AttributeError, e: |
|
1297 self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". ' |
|
1298 'Did you remember to put your mocks in replay mode?', str(e)) |
|
1299 |
|
1300 class ReplayTest(unittest.TestCase): |
|
1301 """Verify Replay works properly.""" |
|
1302 |
|
1303 def testReplay(self): |
|
1304 """Replay should put objects into replay mode.""" |
|
1305 mock_obj = mox.MockObject(TestClass) |
|
1306 self.assertFalse(mock_obj._replay_mode) |
|
1307 mox.Replay(mock_obj) |
|
1308 self.assertTrue(mock_obj._replay_mode) |
|
1309 |
|
1310 class MoxTestBaseTest(unittest.TestCase): |
|
1311 """Verify that all tests in a class derived from MoxTestBase are wrapped.""" |
|
1312 |
|
1313 def setUp(self): |
|
1314 self.mox = mox.Mox() |
|
1315 self.test_mox = mox.Mox() |
|
1316 self.result = unittest.TestResult() |
|
1317 |
|
1318 def tearDown(self): |
|
1319 # In case one of our tests fail before UnsetStubs is called. |
|
1320 self.mox.UnsetStubs() |
|
1321 self.test_mox.UnsetStubs() |
|
1322 |
|
1323 def _setUpTestClass(self): |
|
1324 """Replacement for setUp in the test class instance. |
|
1325 |
|
1326 Assigns a mox.Mox instance as the mox attribute of the test class instance. |
|
1327 This replacement Mox instance is under our control before setUp is called |
|
1328 in the test class instance. |
|
1329 """ |
|
1330 self.test.mox = self.test_mox |
|
1331 |
|
1332 def _CreateTest(self, test_name): |
|
1333 """Create a test from our example mox class. |
|
1334 |
|
1335 The created test instance is assigned to this instances test attribute. |
|
1336 """ |
|
1337 self.test = mox_test_helper.ExampleMoxTest(test_name) |
|
1338 self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass) |
|
1339 |
|
1340 def _VerifySuccess(self): |
|
1341 """Run the checks to confirm test method completed successfully.""" |
|
1342 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') |
|
1343 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll') |
|
1344 self.test_mox.UnsetStubs() |
|
1345 self.test_mox.VerifyAll() |
|
1346 self.mox.ReplayAll() |
|
1347 self.test.run(result=self.result) |
|
1348 self.assertTrue(self.result.wasSuccessful()) |
|
1349 self.mox.UnsetStubs() |
|
1350 self.mox.VerifyAll() |
|
1351 self.test_mox.UnsetStubs() |
|
1352 self.test_mox.VerifyAll() |
|
1353 |
|
1354 def testSuccess(self): |
|
1355 """Successful test method execution test.""" |
|
1356 self._CreateTest('testSuccess') |
|
1357 self._VerifySuccess() |
|
1358 |
|
1359 def testExpectedNotCalled(self): |
|
1360 """Stubbed out method is not called.""" |
|
1361 self._CreateTest('testExpectedNotCalled') |
|
1362 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') |
|
1363 # Dont stub out VerifyAll - that's what causes the test to fail |
|
1364 self.test_mox.UnsetStubs() |
|
1365 self.test_mox.VerifyAll() |
|
1366 self.mox.ReplayAll() |
|
1367 self.test.run(result=self.result) |
|
1368 self.failIf(self.result.wasSuccessful()) |
|
1369 self.mox.UnsetStubs() |
|
1370 self.mox.VerifyAll() |
|
1371 self.test_mox.UnsetStubs() |
|
1372 |
|
1373 def testUnexpectedCall(self): |
|
1374 """Stubbed out method is called with unexpected arguments.""" |
|
1375 self._CreateTest('testUnexpectedCall') |
|
1376 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') |
|
1377 # Ensure no calls are made to VerifyAll() |
|
1378 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll') |
|
1379 self.test_mox.UnsetStubs() |
|
1380 self.mox.ReplayAll() |
|
1381 self.test.run(result=self.result) |
|
1382 self.failIf(self.result.wasSuccessful()) |
|
1383 self.mox.UnsetStubs() |
|
1384 self.mox.VerifyAll() |
|
1385 self.test_mox.UnsetStubs() |
|
1386 |
|
1387 def testFailure(self): |
|
1388 """Failing assertion in test method.""" |
|
1389 self._CreateTest('testFailure') |
|
1390 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs') |
|
1391 # Ensure no calls are made to VerifyAll() |
|
1392 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll') |
|
1393 self.test_mox.UnsetStubs() |
|
1394 self.mox.ReplayAll() |
|
1395 self.test.run(result=self.result) |
|
1396 self.failIf(self.result.wasSuccessful()) |
|
1397 self.mox.UnsetStubs() |
|
1398 self.mox.VerifyAll() |
|
1399 self.test_mox.UnsetStubs() |
|
1400 |
|
1401 def testMixin(self): |
|
1402 """Run test from mix-in test class, ensure it passes.""" |
|
1403 self._CreateTest('testStat') |
|
1404 self._VerifySuccess() |
|
1405 |
|
1406 def testMixinAgain(self): |
|
1407 """Run same test as above but from the current test class. |
|
1408 |
|
1409 This ensures metaclass properly wrapped test methods from all base classes. |
|
1410 If unsetting of stubs doesn't happen, this will fail. |
|
1411 """ |
|
1412 self._CreateTest('testStatOther') |
|
1413 self._VerifySuccess() |
|
1414 |
|
1415 |
|
1416 class VerifyTest(unittest.TestCase): |
|
1417 """Verify Verify works properly.""" |
|
1418 |
|
1419 def testVerify(self): |
|
1420 """Verify should be called for all objects. |
|
1421 |
|
1422 This should throw an exception because the expected behavior did not occur. |
|
1423 """ |
|
1424 mock_obj = mox.MockObject(TestClass) |
|
1425 mock_obj.ValidCall() |
|
1426 mock_obj._Replay() |
|
1427 self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj) |
|
1428 |
|
1429 |
|
1430 class ResetTest(unittest.TestCase): |
|
1431 """Verify Reset works properly.""" |
|
1432 |
|
1433 def testReset(self): |
|
1434 """Should empty all queues and put mocks in record mode.""" |
|
1435 mock_obj = mox.MockObject(TestClass) |
|
1436 mock_obj.ValidCall() |
|
1437 self.assertFalse(mock_obj._replay_mode) |
|
1438 mock_obj._Replay() |
|
1439 self.assertTrue(mock_obj._replay_mode) |
|
1440 self.assertEquals(1, len(mock_obj._expected_calls_queue)) |
|
1441 |
|
1442 mox.Reset(mock_obj) |
|
1443 self.assertFalse(mock_obj._replay_mode) |
|
1444 self.assertEquals(0, len(mock_obj._expected_calls_queue)) |
|
1445 |
|
1446 |
|
1447 class MyTestCase(unittest.TestCase): |
|
1448 """Simulate the use of a fake wrapper around Python's unittest library.""" |
|
1449 |
|
1450 def setUp(self): |
|
1451 super(MyTestCase, self).setUp() |
|
1452 self.critical_variable = 42 |
|
1453 |
|
1454 |
|
1455 class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase): |
|
1456 """Test that multiple inheritance can be used with MoxTestBase.""" |
|
1457 |
|
1458 def setUp(self): |
|
1459 super(MoxTestBaseMultipleInheritanceTest, self).setUp() |
|
1460 |
|
1461 def testMultipleInheritance(self): |
|
1462 """Should be able to access members created by all parent setUp().""" |
|
1463 self.assert_(isinstance(self.mox, mox.Mox)) |
|
1464 self.assertEquals(42, self.critical_variable) |
|
1465 |
|
1466 |
|
1467 class TestClass: |
|
1468 """This class is used only for testing the mock framework""" |
|
1469 |
|
1470 SOME_CLASS_VAR = "test_value" |
|
1471 _PROTECTED_CLASS_VAR = "protected value" |
|
1472 |
|
1473 def __init__(self, ivar=None): |
|
1474 self.__ivar = ivar |
|
1475 |
|
1476 def __eq__(self, rhs): |
|
1477 return self.__ivar == rhs |
|
1478 |
|
1479 def __ne__(self, rhs): |
|
1480 return not self.__eq__(rhs) |
|
1481 |
|
1482 def ValidCall(self): |
|
1483 pass |
|
1484 |
|
1485 def OtherValidCall(self): |
|
1486 pass |
|
1487 |
|
1488 def ValidCallWithArgs(self, *args, **kwargs): |
|
1489 pass |
|
1490 |
|
1491 @classmethod |
|
1492 def MyClassMethod(cls): |
|
1493 pass |
|
1494 |
|
1495 @staticmethod |
|
1496 def MyStaticMethod(): |
|
1497 pass |
|
1498 |
|
1499 def _ProtectedCall(self): |
|
1500 pass |
|
1501 |
|
1502 def __PrivateCall(self): |
|
1503 pass |
|
1504 |
|
1505 def __getitem__(self, key): |
|
1506 pass |
|
1507 |
|
1508 def __DoNotMock(self): |
|
1509 pass |
|
1510 |
|
1511 def __getitem__(self, key): |
|
1512 """Return the value for key.""" |
|
1513 return self.d[key] |
|
1514 |
|
1515 def __setitem__(self, key, value): |
|
1516 """Set the value for key to value.""" |
|
1517 self.d[key] = value |
|
1518 |
|
1519 def __contains__(self, key): |
|
1520 """Returns True if d contains the key.""" |
|
1521 return key in self.d |
|
1522 |
|
1523 |
|
1524 class ChildClass(TestClass): |
|
1525 """This inherits from TestClass.""" |
|
1526 def __init__(self): |
|
1527 TestClass.__init__(self) |
|
1528 |
|
1529 def ChildValidCall(self): |
|
1530 pass |
|
1531 |
|
1532 |
|
1533 class CallableClass(object): |
|
1534 """This class is callable, and that should be mockable!""" |
|
1535 |
|
1536 def __init__(self): |
|
1537 pass |
|
1538 |
|
1539 def __call__(self, param): |
|
1540 return param |
|
1541 |
|
1542 |
|
1543 if __name__ == '__main__': |
|
1544 unittest.main() |