Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(120)

Side by Side Diff: tests/pymox/mox_test.py

Issue 562031: Fix licensing headers and move most third party code to third_party/... (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/tools/depot_tools/
Patch Set: '' Created 10 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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
273 class IsAlmostTest(unittest.TestCase):
274 """Verify IsAlmost correctly checks equality of floating point numbers."""
275
276 def testEqualityValid(self):
277 """Verify that == correctly identifies nearly equivalent floats."""
278 self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
279
280 def testEqualityInvalid(self):
281 """Verify that == correctly identifies non-equivalent floats."""
282 self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
283
284 def testEqualityWithPlaces(self):
285 """Verify that specifying places has the desired effect."""
286 self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
287 self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
288
289 def testNonNumericTypes(self):
290 """Verify that IsAlmost handles non-numeric types properly."""
291
292 self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9')
293 self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9)
294 self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
295
296
297 class MockMethodTest(unittest.TestCase):
298 """Test class to verify that the MockMethod class is working correctly."""
299
300 def setUp(self):
301 self.expected_method = mox.MockMethod("testMethod", [], False)(['original'])
302 self.mock_method = mox.MockMethod("testMethod", [self.expected_method],
303 True)
304
305 def testAndReturnNoneByDefault(self):
306 """Should return None by default."""
307 return_value = self.mock_method(['original'])
308 self.assert_(return_value == None)
309
310 def testAndReturnValue(self):
311 """Should return a specificed return value."""
312 expected_return_value = "test"
313 self.expected_method.AndReturn(expected_return_value)
314 return_value = self.mock_method(['original'])
315 self.assert_(return_value == expected_return_value)
316
317 def testAndRaiseException(self):
318 """Should raise a specified exception."""
319 expected_exception = Exception('test exception')
320 self.expected_method.AndRaise(expected_exception)
321 self.assertRaises(Exception, self.mock_method)
322
323 def testWithSideEffects(self):
324 """Should call state modifier."""
325 local_list = ['original']
326 def modifier(mutable_list):
327 self.assertTrue(local_list is mutable_list)
328 mutable_list[0] = 'mutation'
329 self.expected_method.WithSideEffects(modifier).AndReturn(1)
330 self.mock_method(local_list)
331 self.assertEquals('mutation', local_list[0])
332
333 def testEqualityNoParamsEqual(self):
334 """Methods with the same name and without params should be equal."""
335 expected_method = mox.MockMethod("testMethod", [], False)
336 self.assertEqual(self.mock_method, expected_method)
337
338 def testEqualityNoParamsNotEqual(self):
339 """Methods with different names and without params should not be equal."""
340 expected_method = mox.MockMethod("otherMethod", [], False)
341 self.failIfEqual(self.mock_method, expected_method)
342
343 def testEqualityParamsEqual(self):
344 """Methods with the same name and parameters should be equal."""
345 params = [1, 2, 3]
346 expected_method = mox.MockMethod("testMethod", [], False)
347 expected_method._params = params
348
349 self.mock_method._params = params
350 self.assertEqual(self.mock_method, expected_method)
351
352 def testEqualityParamsNotEqual(self):
353 """Methods with the same name and different params should not be equal."""
354 expected_method = mox.MockMethod("testMethod", [], False)
355 expected_method._params = [1, 2, 3]
356
357 self.mock_method._params = ['a', 'b', 'c']
358 self.failIfEqual(self.mock_method, expected_method)
359
360 def testEqualityNamedParamsEqual(self):
361 """Methods with the same name and same named params should be equal."""
362 named_params = {"input1": "test", "input2": "params"}
363 expected_method = mox.MockMethod("testMethod", [], False)
364 expected_method._named_params = named_params
365
366 self.mock_method._named_params = named_params
367 self.assertEqual(self.mock_method, expected_method)
368
369 def testEqualityNamedParamsNotEqual(self):
370 """Methods with the same name and diffnamed params should not be equal."""
371 expected_method = mox.MockMethod("testMethod", [], False)
372 expected_method._named_params = {"input1": "test", "input2": "params"}
373
374 self.mock_method._named_params = {"input1": "test2", "input2": "params2"}
375 self.failIfEqual(self.mock_method, expected_method)
376
377 def testEqualityWrongType(self):
378 """Method should not be equal to an object of a different type."""
379 self.failIfEqual(self.mock_method, "string?")
380
381 def testObjectEquality(self):
382 """Equality of objects should work without a Comparator"""
383 instA = TestClass();
384 instB = TestClass();
385
386 params = [instA, ]
387 expected_method = mox.MockMethod("testMethod", [], False)
388 expected_method._params = params
389
390 self.mock_method._params = [instB, ]
391 self.assertEqual(self.mock_method, expected_method)
392
393 def testStrConversion(self):
394 method = mox.MockMethod("f", [], False)
395 method(1, 2, "st", n1=8, n2="st2")
396 self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None"))
397
398 method = mox.MockMethod("testMethod", [], False)
399 method(1, 2, "only positional")
400 self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None")
401
402 method = mox.MockMethod("testMethod", [], False)
403 method(a=1, b=2, c="only named")
404 self.assertEqual(str(method),
405 "testMethod(a=1, b=2, c='only named') -> None")
406
407 method = mox.MockMethod("testMethod", [], False)
408 method()
409 self.assertEqual(str(method), "testMethod() -> None")
410
411 method = mox.MockMethod("testMethod", [], False)
412 method(x="only 1 parameter")
413 self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None")
414
415 method = mox.MockMethod("testMethod", [], False)
416 method().AndReturn('return_value')
417 self.assertEqual(str(method), "testMethod() -> 'return_value'")
418
419 method = mox.MockMethod("testMethod", [], False)
420 method().AndReturn(('a', {1: 2}))
421 self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})")
422
423
424 class MockAnythingTest(unittest.TestCase):
425 """Verify that the MockAnything class works as expected."""
426
427 def setUp(self):
428 self.mock_object = mox.MockAnything()
429
430 def testRepr(self):
431 """Calling repr on a MockAnything instance must work."""
432 self.assertEqual('<MockAnything instance>', repr(self.mock_object))
433
434 def testSetupMode(self):
435 """Verify the mock will accept any call."""
436 self.mock_object.NonsenseCall()
437 self.assert_(len(self.mock_object._expected_calls_queue) == 1)
438
439 def testReplayWithExpectedCall(self):
440 """Verify the mock replays method calls as expected."""
441 self.mock_object.ValidCall() # setup method call
442 self.mock_object._Replay() # start replay mode
443 self.mock_object.ValidCall() # make method call
444
445 def testReplayWithUnexpectedCall(self):
446 """Unexpected method calls should raise UnexpectedMethodCallError."""
447 self.mock_object.ValidCall() # setup method call
448 self.mock_object._Replay() # start replay mode
449 self.assertRaises(mox.UnexpectedMethodCallError,
450 self.mock_object.OtherValidCall)
451
452 def testVerifyWithCompleteReplay(self):
453 """Verify should not raise an exception for a valid replay."""
454 self.mock_object.ValidCall() # setup method call
455 self.mock_object._Replay() # start replay mode
456 self.mock_object.ValidCall() # make method call
457 self.mock_object._Verify()
458
459 def testVerifyWithIncompleteReplay(self):
460 """Verify should raise an exception if the replay was not complete."""
461 self.mock_object.ValidCall() # setup method call
462 self.mock_object._Replay() # start replay mode
463 # ValidCall() is never made
464 self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify)
465
466 def testSpecialClassMethod(self):
467 """Verify should not raise an exception when special methods are used."""
468 self.mock_object[1].AndReturn(True)
469 self.mock_object._Replay()
470 returned_val = self.mock_object[1]
471 self.assert_(returned_val)
472 self.mock_object._Verify()
473
474 def testNonzero(self):
475 """You should be able to use the mock object in an if."""
476 self.mock_object._Replay()
477 if self.mock_object:
478 pass
479
480 def testNotNone(self):
481 """Mock should be comparable to None."""
482 self.mock_object._Replay()
483 if self.mock_object is not None:
484 pass
485
486 if self.mock_object is None:
487 pass
488
489 def testEquals(self):
490 """A mock should be able to compare itself to another object."""
491 self.mock_object._Replay()
492 self.assertEquals(self.mock_object, self.mock_object)
493
494 def testEqualsMockFailure(self):
495 """Verify equals identifies unequal objects."""
496 self.mock_object.SillyCall()
497 self.mock_object._Replay()
498 self.assertNotEquals(self.mock_object, mox.MockAnything())
499
500 def testEqualsInstanceFailure(self):
501 """Verify equals identifies that objects are different instances."""
502 self.mock_object._Replay()
503 self.assertNotEquals(self.mock_object, TestClass())
504
505 def testNotEquals(self):
506 """Verify not equals works."""
507 self.mock_object._Replay()
508 self.assertFalse(self.mock_object != self.mock_object)
509
510 def testNestedMockCallsRecordedSerially(self):
511 """Test that nested calls work when recorded serially."""
512 self.mock_object.CallInner().AndReturn(1)
513 self.mock_object.CallOuter(1)
514 self.mock_object._Replay()
515
516 self.mock_object.CallOuter(self.mock_object.CallInner())
517
518 self.mock_object._Verify()
519
520 def testNestedMockCallsRecordedNested(self):
521 """Test that nested cals work when recorded in a nested fashion."""
522 self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1))
523 self.mock_object._Replay()
524
525 self.mock_object.CallOuter(self.mock_object.CallInner())
526
527 self.mock_object._Verify()
528
529 def testIsCallable(self):
530 """Test that MockAnything can even mock a simple callable.
531
532 This is handy for "stubbing out" a method in a module with a mock, and
533 verifying that it was called.
534 """
535 self.mock_object().AndReturn('mox0rd')
536 self.mock_object._Replay()
537
538 self.assertEquals('mox0rd', self.mock_object())
539
540 self.mock_object._Verify()
541
542 def testIsReprable(self):
543 """Test that MockAnythings can be repr'd without causing a failure."""
544 self.failUnless('MockAnything' in repr(self.mock_object))
545
546
547 class MethodCheckerTest(unittest.TestCase):
548 """Tests MockMethod's use of MethodChecker method."""
549
550 def testNoParameters(self):
551 method = mox.MockMethod('NoParameters', [], False,
552 CheckCallTestClass.NoParameters)
553 method()
554 self.assertRaises(AttributeError, method, 1)
555 self.assertRaises(AttributeError, method, 1, 2)
556 self.assertRaises(AttributeError, method, a=1)
557 self.assertRaises(AttributeError, method, 1, b=2)
558
559 def testOneParameter(self):
560 method = mox.MockMethod('OneParameter', [], False,
561 CheckCallTestClass.OneParameter)
562 self.assertRaises(AttributeError, method)
563 method(1)
564 method(a=1)
565 self.assertRaises(AttributeError, method, b=1)
566 self.assertRaises(AttributeError, method, 1, 2)
567 self.assertRaises(AttributeError, method, 1, a=2)
568 self.assertRaises(AttributeError, method, 1, b=2)
569
570 def testTwoParameters(self):
571 method = mox.MockMethod('TwoParameters', [], False,
572 CheckCallTestClass.TwoParameters)
573 self.assertRaises(AttributeError, method)
574 self.assertRaises(AttributeError, method, 1)
575 self.assertRaises(AttributeError, method, a=1)
576 self.assertRaises(AttributeError, method, b=1)
577 method(1, 2)
578 method(1, b=2)
579 method(a=1, b=2)
580 method(b=2, a=1)
581 self.assertRaises(AttributeError, method, b=2, c=3)
582 self.assertRaises(AttributeError, method, a=1, b=2, c=3)
583 self.assertRaises(AttributeError, method, 1, 2, 3)
584 self.assertRaises(AttributeError, method, 1, 2, 3, 4)
585 self.assertRaises(AttributeError, method, 3, a=1, b=2)
586
587 def testOneDefaultValue(self):
588 method = mox.MockMethod('OneDefaultValue', [], False,
589 CheckCallTestClass.OneDefaultValue)
590 method()
591 method(1)
592 method(a=1)
593 self.assertRaises(AttributeError, method, b=1)
594 self.assertRaises(AttributeError, method, 1, 2)
595 self.assertRaises(AttributeError, method, 1, a=2)
596 self.assertRaises(AttributeError, method, 1, b=2)
597
598 def testTwoDefaultValues(self):
599 method = mox.MockMethod('TwoDefaultValues', [], False,
600 CheckCallTestClass.TwoDefaultValues)
601 self.assertRaises(AttributeError, method)
602 self.assertRaises(AttributeError, method, c=3)
603 self.assertRaises(AttributeError, method, 1)
604 self.assertRaises(AttributeError, method, 1, d=4)
605 self.assertRaises(AttributeError, method, 1, d=4, c=3)
606 method(1, 2)
607 method(a=1, b=2)
608 method(1, 2, 3)
609 method(1, 2, 3, 4)
610 method(1, 2, c=3)
611 method(1, 2, c=3, d=4)
612 method(1, 2, d=4, c=3)
613 method(d=4, c=3, a=1, b=2)
614 self.assertRaises(AttributeError, method, 1, 2, 3, 4, 5)
615 self.assertRaises(AttributeError, method, 1, 2, e=9)
616 self.assertRaises(AttributeError, method, a=1, b=2, e=9)
617
618 def testArgs(self):
619 method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args)
620 self.assertRaises(AttributeError, method)
621 self.assertRaises(AttributeError, method, 1)
622 method(1, 2)
623 method(a=1, b=2)
624 method(1, 2, 3)
625 method(1, 2, 3, 4)
626 self.assertRaises(AttributeError, method, 1, 2, a=3)
627 self.assertRaises(AttributeError, method, 1, 2, c=3)
628
629 def testKwargs(self):
630 method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs)
631 self.assertRaises(AttributeError, method)
632 method(1)
633 method(1, 2)
634 method(a=1, b=2)
635 method(b=2, a=1)
636 self.assertRaises(AttributeError, method, 1, 2, 3)
637 self.assertRaises(AttributeError, method, 1, 2, a=3)
638 method(1, 2, c=3)
639 method(a=1, b=2, c=3)
640 method(c=3, a=1, b=2)
641 method(a=1, b=2, c=3, d=4)
642 self.assertRaises(AttributeError, method, 1, 2, 3, 4)
643
644 def testArgsAndKwargs(self):
645 method = mox.MockMethod('ArgsAndKwargs', [], False,
646 CheckCallTestClass.ArgsAndKwargs)
647 self.assertRaises(AttributeError, method)
648 method(1)
649 method(1, 2)
650 method(1, 2, 3)
651 method(a=1)
652 method(1, b=2)
653 self.assertRaises(AttributeError, method, 1, a=2)
654 method(b=2, a=1)
655 method(c=3, b=2, a=1)
656 method(1, 2, c=3)
657
658
659 class CheckCallTestClass(object):
660 def NoParameters(self):
661 pass
662
663 def OneParameter(self, a):
664 pass
665
666 def TwoParameters(self, a, b):
667 pass
668
669 def OneDefaultValue(self, a=1):
670 pass
671
672 def TwoDefaultValues(self, a, b, c=1, d=2):
673 pass
674
675 def Args(self, a, b, *args):
676 pass
677
678 def Kwargs(self, a, b=2, **kwargs):
679 pass
680
681 def ArgsAndKwargs(self, a, *args, **kwargs):
682 pass
683
684
685 class MockObjectTest(unittest.TestCase):
686 """Verify that the MockObject class works as exepcted."""
687
688 def setUp(self):
689 self.mock_object = mox.MockObject(TestClass)
690
691 def testSetupModeWithValidCall(self):
692 """Verify the mock object properly mocks a basic method call."""
693 self.mock_object.ValidCall()
694 self.assert_(len(self.mock_object._expected_calls_queue) == 1)
695
696 def testSetupModeWithInvalidCall(self):
697 """UnknownMethodCallError should be raised if a non-member method is called.
698 """
699 # Note: assertRaises does not catch exceptions thrown by MockObject's
700 # __getattr__
701 try:
702 self.mock_object.InvalidCall()
703 self.fail("No exception thrown, expected UnknownMethodCallError")
704 except mox.UnknownMethodCallError:
705 pass
706 except Exception:
707 self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
708
709 def testReplayWithInvalidCall(self):
710 """UnknownMethodCallError should be raised if a non-member method is called.
711 """
712 self.mock_object.ValidCall() # setup method call
713 self.mock_object._Replay() # start replay mode
714 # Note: assertRaises does not catch exceptions thrown by MockObject's
715 # __getattr__
716 try:
717 self.mock_object.InvalidCall()
718 self.fail("No exception thrown, expected UnknownMethodCallError")
719 except mox.UnknownMethodCallError:
720 pass
721 except Exception:
722 self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
723
724 def testIsInstance(self):
725 """Mock should be able to pass as an instance of the mocked class."""
726 self.assert_(isinstance(self.mock_object, TestClass))
727
728 def testFindValidMethods(self):
729 """Mock should be able to mock all public methods."""
730 self.assert_('ValidCall' in self.mock_object._known_methods)
731 self.assert_('OtherValidCall' in self.mock_object._known_methods)
732 self.assert_('MyClassMethod' in self.mock_object._known_methods)
733 self.assert_('MyStaticMethod' in self.mock_object._known_methods)
734 self.assert_('_ProtectedCall' in self.mock_object._known_methods)
735 self.assert_('__PrivateCall' not in self.mock_object._known_methods)
736 self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods)
737
738 def testFindsSuperclassMethods(self):
739 """Mock should be able to mock superclasses methods."""
740 self.mock_object = mox.MockObject(ChildClass)
741 self.assert_('ValidCall' in self.mock_object._known_methods)
742 self.assert_('OtherValidCall' in self.mock_object._known_methods)
743 self.assert_('MyClassMethod' in self.mock_object._known_methods)
744 self.assert_('ChildValidCall' in self.mock_object._known_methods)
745
746 def testAccessClassVariables(self):
747 """Class variables should be accessible through the mock."""
748 self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars)
749 self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)
750 self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR)
751
752 def testEquals(self):
753 """A mock should be able to compare itself to another object."""
754 self.mock_object._Replay()
755 self.assertEquals(self.mock_object, self.mock_object)
756
757 def testEqualsMockFailure(self):
758 """Verify equals identifies unequal objects."""
759 self.mock_object.ValidCall()
760 self.mock_object._Replay()
761 self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
762
763 def testEqualsInstanceFailure(self):
764 """Verify equals identifies that objects are different instances."""
765 self.mock_object._Replay()
766 self.assertNotEquals(self.mock_object, TestClass())
767
768 def testNotEquals(self):
769 """Verify not equals works."""
770 self.mock_object._Replay()
771 self.assertFalse(self.mock_object != self.mock_object)
772
773 def testMockSetItem_ExpectedSetItem_Success(self):
774 """Test that __setitem__() gets mocked in Dummy.
775
776 In this test, _Verify() succeeds.
777 """
778 dummy = mox.MockObject(TestClass)
779 dummy['X'] = 'Y'
780
781 dummy._Replay()
782
783 dummy['X'] = 'Y'
784
785 dummy._Verify()
786
787 def testMockSetItem_ExpectedSetItem_NoSuccess(self):
788 """Test that __setitem__() gets mocked in Dummy.
789
790 In this test, _Verify() fails.
791 """
792 dummy = mox.MockObject(TestClass)
793 dummy['X'] = 'Y'
794
795 dummy._Replay()
796
797 # NOT doing dummy['X'] = 'Y'
798
799 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
800
801 def testMockSetItem_ExpectedNoSetItem_Success(self):
802 """Test that __setitem__() gets mocked in Dummy."""
803 dummy = mox.MockObject(TestClass)
804 # NOT doing dummy['X'] = 'Y'
805
806 dummy._Replay()
807
808 def call(): dummy['X'] = 'Y'
809 self.assertRaises(mox.UnexpectedMethodCallError, call)
810
811 def testMockSetItem_ExpectedNoSetItem_NoSuccess(self):
812 """Test that __setitem__() gets mocked in Dummy.
813
814 In this test, _Verify() fails.
815 """
816 dummy = mox.MockObject(TestClass)
817 # NOT doing dummy['X'] = 'Y'
818
819 dummy._Replay()
820
821 # NOT doing dummy['X'] = 'Y'
822
823 dummy._Verify()
824
825 def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self):
826 """Test that __setitem__() fails if other parameters are expected."""
827 dummy = mox.MockObject(TestClass)
828 dummy['X'] = 'Y'
829
830 dummy._Replay()
831
832 def call(): dummy['wrong'] = 'Y'
833
834 self.assertRaises(mox.UnexpectedMethodCallError, call)
835
836 dummy._Verify()
837
838 def testMockSetItem_WithSubClassOfNewStyleClass(self):
839 class NewStyleTestClass(object):
840 def __init__(self):
841 self.my_dict = {}
842
843 def __setitem__(self, key, value):
844 self.my_dict[key], value
845
846 class TestSubClass(NewStyleTestClass):
847 pass
848
849 dummy = mox.MockObject(TestSubClass)
850 dummy[1] = 2
851 dummy._Replay()
852 dummy[1] = 2
853 dummy._Verify()
854
855 def testMockGetItem_ExpectedGetItem_Success(self):
856 """Test that __getitem__() gets mocked in Dummy.
857
858 In this test, _Verify() succeeds.
859 """
860 dummy = mox.MockObject(TestClass)
861 dummy['X'].AndReturn('value')
862
863 dummy._Replay()
864
865 self.assertEqual(dummy['X'], 'value')
866
867 dummy._Verify()
868
869 def testMockGetItem_ExpectedGetItem_NoSuccess(self):
870 """Test that __getitem__() gets mocked in Dummy.
871
872 In this test, _Verify() fails.
873 """
874 dummy = mox.MockObject(TestClass)
875 dummy['X'].AndReturn('value')
876
877 dummy._Replay()
878
879 # NOT doing dummy['X']
880
881 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
882
883 def testMockGetItem_ExpectedNoGetItem_NoSuccess(self):
884 """Test that __getitem__() gets mocked in Dummy."""
885 dummy = mox.MockObject(TestClass)
886 # NOT doing dummy['X']
887
888 dummy._Replay()
889
890 def call(): return dummy['X']
891 self.assertRaises(mox.UnexpectedMethodCallError, call)
892
893 def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self):
894 """Test that __getitem__() fails if other parameters are expected."""
895 dummy = mox.MockObject(TestClass)
896 dummy['X'].AndReturn('value')
897
898 dummy._Replay()
899
900 def call(): return dummy['wrong']
901
902 self.assertRaises(mox.UnexpectedMethodCallError, call)
903
904 dummy._Verify()
905
906 def testMockGetItem_WithSubClassOfNewStyleClass(self):
907 class NewStyleTestClass(object):
908 def __getitem__(self, key):
909 return {1: '1', 2: '2'}[key]
910
911 class TestSubClass(NewStyleTestClass):
912 pass
913
914 dummy = mox.MockObject(TestSubClass)
915 dummy[1].AndReturn('3')
916
917 dummy._Replay()
918 self.assertEquals('3', dummy.__getitem__(1))
919 dummy._Verify()
920
921 def testMockIter_ExpectedIter_Success(self):
922 """Test that __iter__() gets mocked in Dummy.
923
924 In this test, _Verify() succeeds.
925 """
926 dummy = mox.MockObject(TestClass)
927 iter(dummy).AndReturn(iter(['X', 'Y']))
928
929 dummy._Replay()
930
931 self.assertEqual([x for x in dummy], ['X', 'Y'])
932
933 dummy._Verify()
934 def testMockContains_ExpectedContains_Success(self):
935 """Test that __contains__ gets mocked in Dummy.
936
937 In this test, _Verify() succeeds.
938 """
939 dummy = mox.MockObject(TestClass)
940 dummy.__contains__('X').AndReturn(True)
941
942 dummy._Replay()
943
944 self.failUnless('X' in dummy)
945
946 dummy._Verify()
947
948 def testMockContains_ExpectedContains_NoSuccess(self):
949 """Test that __contains__() gets mocked in Dummy.
950
951 In this test, _Verify() fails.
952 """
953 dummy = mox.MockObject(TestClass)
954 dummy.__contains__('X').AndReturn('True')
955
956 dummy._Replay()
957
958 # NOT doing 'X' in dummy
959
960 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
961
962 def testMockContains_ExpectedContains_NonmatchingParameter(self):
963 """Test that __contains__ fails if other parameters are expected."""
964 dummy = mox.MockObject(TestClass)
965 dummy.__contains__('X').AndReturn(True)
966
967 dummy._Replay()
968
969 def call(): return 'Y' in dummy
970
971 self.assertRaises(mox.UnexpectedMethodCallError, call)
972
973 dummy._Verify()
974
975 def testMockIter_ExpectedIter_NoSuccess(self):
976 """Test that __iter__() gets mocked in Dummy.
977
978 In this test, _Verify() fails.
979 """
980 dummy = mox.MockObject(TestClass)
981 iter(dummy).AndReturn(iter(['X', 'Y']))
982
983 dummy._Replay()
984
985 # NOT doing self.assertEqual([x for x in dummy], ['X', 'Y'])
986
987 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
988
989 def testMockIter_ExpectedNoIter_NoSuccess(self):
990 """Test that __iter__() gets mocked in Dummy."""
991 dummy = mox.MockObject(TestClass)
992 # NOT doing iter(dummy)
993
994 dummy._Replay()
995
996 def call(): return [x for x in dummy]
997 self.assertRaises(mox.UnexpectedMethodCallError, call)
998
999 def testMockIter_ExpectedGetItem_Success(self):
1000 """Test that __iter__() gets mocked in Dummy using getitem."""
1001 dummy = mox.MockObject(SubscribtableNonIterableClass)
1002 dummy[0].AndReturn('a')
1003 dummy[1].AndReturn('b')
1004 dummy[2].AndRaise(IndexError)
1005
1006 dummy._Replay()
1007 self.assertEquals(['a', 'b'], [x for x in dummy])
1008 dummy._Verify()
1009
1010 def testMockIter_ExpectedNoGetItem_NoSuccess(self):
1011 """Test that __iter__() gets mocked in Dummy using getitem."""
1012 dummy = mox.MockObject(SubscribtableNonIterableClass)
1013 # NOT doing dummy[index]
1014
1015 dummy._Replay()
1016 function = lambda: [x for x in dummy]
1017 self.assertRaises(mox.UnexpectedMethodCallError, function)
1018
1019 def testMockGetIter_WithSubClassOfNewStyleClass(self):
1020 class NewStyleTestClass(object):
1021 def __iter__(self):
1022 return iter([1, 2, 3])
1023
1024 class TestSubClass(NewStyleTestClass):
1025 pass
1026
1027 dummy = mox.MockObject(TestSubClass)
1028 iter(dummy).AndReturn(iter(['a', 'b']))
1029 dummy._Replay()
1030 self.assertEquals(['a', 'b'], [x for x in dummy])
1031 dummy._Verify()
1032
1033
1034 class MoxTest(unittest.TestCase):
1035 """Verify Mox works correctly."""
1036
1037 def setUp(self):
1038 self.mox = mox.Mox()
1039
1040 def testCreateObject(self):
1041 """Mox should create a mock object."""
1042 mock_obj = self.mox.CreateMock(TestClass)
1043
1044 def testVerifyObjectWithCompleteReplay(self):
1045 """Mox should replay and verify all objects it created."""
1046 mock_obj = self.mox.CreateMock(TestClass)
1047 mock_obj.ValidCall()
1048 mock_obj.ValidCallWithArgs(mox.IsA(TestClass))
1049 self.mox.ReplayAll()
1050 mock_obj.ValidCall()
1051 mock_obj.ValidCallWithArgs(TestClass("some_value"))
1052 self.mox.VerifyAll()
1053
1054 def testVerifyObjectWithIncompleteReplay(self):
1055 """Mox should raise an exception if a mock didn't replay completely."""
1056 mock_obj = self.mox.CreateMock(TestClass)
1057 mock_obj.ValidCall()
1058 self.mox.ReplayAll()
1059 # ValidCall() is never made
1060 self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll)
1061
1062 def testEntireWorkflow(self):
1063 """Test the whole work flow."""
1064 mock_obj = self.mox.CreateMock(TestClass)
1065 mock_obj.ValidCall().AndReturn("yes")
1066 self.mox.ReplayAll()
1067
1068 ret_val = mock_obj.ValidCall()
1069 self.assertEquals("yes", ret_val)
1070 self.mox.VerifyAll()
1071
1072 def testCallableObject(self):
1073 """Test recording calls to a callable object works."""
1074 mock_obj = self.mox.CreateMock(CallableClass)
1075 mock_obj("foo").AndReturn("qux")
1076 self.mox.ReplayAll()
1077
1078 ret_val = mock_obj("foo")
1079 self.assertEquals("qux", ret_val)
1080 self.mox.VerifyAll()
1081
1082 def testInheritedCallableObject(self):
1083 """Test recording calls to an object inheriting from a callable object."""
1084 mock_obj = self.mox.CreateMock(InheritsFromCallable)
1085 mock_obj("foo").AndReturn("qux")
1086 self.mox.ReplayAll()
1087
1088 ret_val = mock_obj("foo")
1089 self.assertEquals("qux", ret_val)
1090 self.mox.VerifyAll()
1091
1092 def testCallOnNonCallableObject(self):
1093 """Test that you cannot call a non-callable object."""
1094 mock_obj = self.mox.CreateMock(TestClass)
1095 self.assertRaises(TypeError, mock_obj)
1096
1097 def testCallableObjectWithBadCall(self):
1098 """Test verifying calls to a callable object works."""
1099 mock_obj = self.mox.CreateMock(CallableClass)
1100 mock_obj("foo").AndReturn("qux")
1101 self.mox.ReplayAll()
1102
1103 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, "ZOOBAZ")
1104
1105 def testUnorderedGroup(self):
1106 """Test that using one unordered group works."""
1107 mock_obj = self.mox.CreateMockAnything()
1108 mock_obj.Method(1).InAnyOrder()
1109 mock_obj.Method(2).InAnyOrder()
1110 self.mox.ReplayAll()
1111
1112 mock_obj.Method(2)
1113 mock_obj.Method(1)
1114
1115 self.mox.VerifyAll()
1116
1117 def testUnorderedGroupsInline(self):
1118 """Unordered groups should work in the context of ordered calls."""
1119 mock_obj = self.mox.CreateMockAnything()
1120 mock_obj.Open()
1121 mock_obj.Method(1).InAnyOrder()
1122 mock_obj.Method(2).InAnyOrder()
1123 mock_obj.Close()
1124 self.mox.ReplayAll()
1125
1126 mock_obj.Open()
1127 mock_obj.Method(2)
1128 mock_obj.Method(1)
1129 mock_obj.Close()
1130
1131 self.mox.VerifyAll()
1132
1133 def testMultipleUnorderdGroups(self):
1134 """Multiple unoreded groups should work."""
1135 mock_obj = self.mox.CreateMockAnything()
1136 mock_obj.Method(1).InAnyOrder()
1137 mock_obj.Method(2).InAnyOrder()
1138 mock_obj.Foo().InAnyOrder('group2')
1139 mock_obj.Bar().InAnyOrder('group2')
1140 self.mox.ReplayAll()
1141
1142 mock_obj.Method(2)
1143 mock_obj.Method(1)
1144 mock_obj.Bar()
1145 mock_obj.Foo()
1146
1147 self.mox.VerifyAll()
1148
1149 def testMultipleUnorderdGroupsOutOfOrder(self):
1150 """Multiple unordered groups should maintain external order"""
1151 mock_obj = self.mox.CreateMockAnything()
1152 mock_obj.Method(1).InAnyOrder()
1153 mock_obj.Method(2).InAnyOrder()
1154 mock_obj.Foo().InAnyOrder('group2')
1155 mock_obj.Bar().InAnyOrder('group2')
1156 self.mox.ReplayAll()
1157
1158 mock_obj.Method(2)
1159 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar)
1160
1161 def testUnorderedGroupWithReturnValue(self):
1162 """Unordered groups should work with return values."""
1163 mock_obj = self.mox.CreateMockAnything()
1164 mock_obj.Open()
1165 mock_obj.Method(1).InAnyOrder().AndReturn(9)
1166 mock_obj.Method(2).InAnyOrder().AndReturn(10)
1167 mock_obj.Close()
1168 self.mox.ReplayAll()
1169
1170 mock_obj.Open()
1171 actual_two = mock_obj.Method(2)
1172 actual_one = mock_obj.Method(1)
1173 mock_obj.Close()
1174
1175 self.assertEquals(9, actual_one)
1176 self.assertEquals(10, actual_two)
1177
1178 self.mox.VerifyAll()
1179
1180 def testUnorderedGroupWithComparator(self):
1181 """Unordered groups should work with comparators"""
1182
1183 def VerifyOne(cmd):
1184 if not isinstance(cmd, str):
1185 self.fail('Unexpected type passed to comparator: ' + str(cmd))
1186 return cmd == 'test'
1187
1188 def VerifyTwo(cmd):
1189 return True
1190
1191 mock_obj = self.mox.CreateMockAnything()
1192 mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\
1193 AndReturn('yes test')
1194 mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\
1195 AndReturn('anything')
1196
1197 self.mox.ReplayAll()
1198
1199 mock_obj.Foo(['test'], 'anything', bar=1)
1200 mock_obj.Foo(['test'], 'test', bar=1)
1201
1202 self.mox.VerifyAll()
1203
1204 def testMultipleTimes(self):
1205 """Test if MultipleTimesGroup works."""
1206 mock_obj = self.mox.CreateMockAnything()
1207 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1208 mock_obj.Method(2).AndReturn(10)
1209 mock_obj.Method(3).MultipleTimes().AndReturn(42)
1210 self.mox.ReplayAll()
1211
1212 actual_one = mock_obj.Method(1)
1213 second_one = mock_obj.Method(1) # This tests MultipleTimes.
1214 actual_two = mock_obj.Method(2)
1215 actual_three = mock_obj.Method(3)
1216 mock_obj.Method(3)
1217 mock_obj.Method(3)
1218
1219 self.mox.VerifyAll()
1220
1221 self.assertEquals(9, actual_one)
1222 self.assertEquals(9, second_one) # Repeated calls should return same number.
1223 self.assertEquals(10, actual_two)
1224 self.assertEquals(42, actual_three)
1225
1226 def testMultipleTimesUsingIsAParameter(self):
1227 """Test if MultipleTimesGroup works with a IsA parameter."""
1228 mock_obj = self.mox.CreateMockAnything()
1229 mock_obj.Open()
1230 mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9)
1231 mock_obj.Close()
1232 self.mox.ReplayAll()
1233
1234 mock_obj.Open()
1235 actual_one = mock_obj.Method("1")
1236 second_one = mock_obj.Method("2") # This tests MultipleTimes.
1237 mock_obj.Close()
1238
1239 self.mox.VerifyAll()
1240
1241 self.assertEquals(9, actual_one)
1242 self.assertEquals(9, second_one) # Repeated calls should return same number.
1243
1244 def testMutlipleTimesUsingFunc(self):
1245 """Test that the Func is not evaluated more times than necessary.
1246
1247 If a Func() has side effects, it can cause a passing test to fail.
1248 """
1249
1250 self.counter = 0
1251 def MyFunc(actual_str):
1252 """Increment the counter if actual_str == 'foo'."""
1253 if actual_str == 'foo':
1254 self.counter += 1
1255 return True
1256
1257 mock_obj = self.mox.CreateMockAnything()
1258 mock_obj.Open()
1259 mock_obj.Method(mox.Func(MyFunc)).MultipleTimes()
1260 mock_obj.Close()
1261 self.mox.ReplayAll()
1262
1263 mock_obj.Open()
1264 mock_obj.Method('foo')
1265 mock_obj.Method('foo')
1266 mock_obj.Method('not-foo')
1267 mock_obj.Close()
1268
1269 self.mox.VerifyAll()
1270
1271 self.assertEquals(2, self.counter)
1272
1273 def testMultipleTimesThreeMethods(self):
1274 """Test if MultipleTimesGroup works with three or more methods."""
1275 mock_obj = self.mox.CreateMockAnything()
1276 mock_obj.Open()
1277 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1278 mock_obj.Method(2).MultipleTimes().AndReturn(8)
1279 mock_obj.Method(3).MultipleTimes().AndReturn(7)
1280 mock_obj.Method(4).AndReturn(10)
1281 mock_obj.Close()
1282 self.mox.ReplayAll()
1283
1284 mock_obj.Open()
1285 actual_three = mock_obj.Method(3)
1286 mock_obj.Method(1)
1287 actual_two = mock_obj.Method(2)
1288 mock_obj.Method(3)
1289 actual_one = mock_obj.Method(1)
1290 actual_four = mock_obj.Method(4)
1291 mock_obj.Close()
1292
1293 self.assertEquals(9, actual_one)
1294 self.assertEquals(8, actual_two)
1295 self.assertEquals(7, actual_three)
1296 self.assertEquals(10, actual_four)
1297
1298 self.mox.VerifyAll()
1299
1300 def testMultipleTimesMissingOne(self):
1301 """Test if MultipleTimesGroup fails if one method is missing."""
1302 mock_obj = self.mox.CreateMockAnything()
1303 mock_obj.Open()
1304 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1305 mock_obj.Method(2).MultipleTimes().AndReturn(8)
1306 mock_obj.Method(3).MultipleTimes().AndReturn(7)
1307 mock_obj.Method(4).AndReturn(10)
1308 mock_obj.Close()
1309 self.mox.ReplayAll()
1310
1311 mock_obj.Open()
1312 mock_obj.Method(3)
1313 mock_obj.Method(2)
1314 mock_obj.Method(3)
1315 mock_obj.Method(3)
1316 mock_obj.Method(2)
1317
1318 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4)
1319
1320 def testMultipleTimesTwoGroups(self):
1321 """Test if MultipleTimesGroup works with a group after a
1322 MultipleTimesGroup.
1323 """
1324 mock_obj = self.mox.CreateMockAnything()
1325 mock_obj.Open()
1326 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1327 mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1328 mock_obj.Close()
1329 self.mox.ReplayAll()
1330
1331 mock_obj.Open()
1332 actual_one = mock_obj.Method(1)
1333 mock_obj.Method(1)
1334 actual_three = mock_obj.Method(3)
1335 mock_obj.Method(3)
1336 mock_obj.Close()
1337
1338 self.assertEquals(9, actual_one)
1339 self.assertEquals(42, actual_three)
1340
1341 self.mox.VerifyAll()
1342
1343 def testMultipleTimesTwoGroupsFailure(self):
1344 """Test if MultipleTimesGroup fails with a group after a
1345 MultipleTimesGroup.
1346 """
1347 mock_obj = self.mox.CreateMockAnything()
1348 mock_obj.Open()
1349 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1350 mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1351 mock_obj.Close()
1352 self.mox.ReplayAll()
1353
1354 mock_obj.Open()
1355 actual_one = mock_obj.Method(1)
1356 mock_obj.Method(1)
1357 actual_three = mock_obj.Method(3)
1358
1359 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1)
1360
1361 def testWithSideEffects(self):
1362 """Test side effect operations actually modify their target objects."""
1363 def modifier(mutable_list):
1364 mutable_list[0] = 'mutated'
1365 mock_obj = self.mox.CreateMockAnything()
1366 mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier)
1367 mock_obj.WorkWithParameter(['mutated'])
1368 self.mox.ReplayAll()
1369
1370 local_list = ['original']
1371 mock_obj.ConfigureInOutParameter(local_list)
1372 mock_obj.WorkWithParameter(local_list)
1373
1374 self.mox.VerifyAll()
1375
1376 def testWithSideEffectsException(self):
1377 """Test side effect operations actually modify their target objects."""
1378 def modifier(mutable_list):
1379 mutable_list[0] = 'mutated'
1380 mock_obj = self.mox.CreateMockAnything()
1381 method = mock_obj.ConfigureInOutParameter(['original'])
1382 method.WithSideEffects(modifier).AndRaise(Exception('exception'))
1383 mock_obj.WorkWithParameter(['mutated'])
1384 self.mox.ReplayAll()
1385
1386 local_list = ['original']
1387 self.failUnlessRaises(Exception,
1388 mock_obj.ConfigureInOutParameter,
1389 local_list)
1390 mock_obj.WorkWithParameter(local_list)
1391
1392 self.mox.VerifyAll()
1393
1394 def testStubOutMethod(self):
1395 """Test that a method is replaced with a MockAnything."""
1396 test_obj = TestClass()
1397 # Replace OtherValidCall with a mock.
1398 self.mox.StubOutWithMock(test_obj, 'OtherValidCall')
1399 self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything))
1400 test_obj.OtherValidCall().AndReturn('foo')
1401 self.mox.ReplayAll()
1402
1403 actual = test_obj.OtherValidCall()
1404
1405 self.mox.VerifyAll()
1406 self.mox.UnsetStubs()
1407 self.assertEquals('foo', actual)
1408 self.failIf(isinstance(test_obj.OtherValidCall, mox.MockAnything))
1409
1410 def testWarnsUserIfMockingMock(self):
1411 """Test that user is warned if they try to stub out a MockAnything."""
1412 self.mox.StubOutWithMock(TestClass, 'MyStaticMethod')
1413 self.assertRaises(TypeError, self.mox.StubOutWithMock, TestClass,
1414 'MyStaticMethod')
1415
1416 def testStubOutObject(self):
1417 """Test than object is replaced with a Mock."""
1418
1419 class Foo(object):
1420 def __init__(self):
1421 self.obj = TestClass()
1422
1423 foo = Foo()
1424 self.mox.StubOutWithMock(foo, "obj")
1425 self.assert_(isinstance(foo.obj, mox.MockObject))
1426 foo.obj.ValidCall()
1427 self.mox.ReplayAll()
1428
1429 foo.obj.ValidCall()
1430
1431 self.mox.VerifyAll()
1432 self.mox.UnsetStubs()
1433 self.failIf(isinstance(foo.obj, mox.MockObject))
1434
1435 def testForgotReplayHelpfulMessage(self):
1436 """If there is an AttributeError on a MockMethod, give users a helpful msg.
1437 """
1438 foo = self.mox.CreateMockAnything()
1439 bar = self.mox.CreateMockAnything()
1440 foo.GetBar().AndReturn(bar)
1441 bar.ShowMeTheMoney()
1442 # Forgot to replay!
1443 try:
1444 foo.GetBar().ShowMeTheMoney()
1445 except AttributeError, e:
1446 self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". '
1447 'Did you remember to put your mocks in replay mode?', str(e))
1448
1449
1450 class ReplayTest(unittest.TestCase):
1451 """Verify Replay works properly."""
1452
1453 def testReplay(self):
1454 """Replay should put objects into replay mode."""
1455 mock_obj = mox.MockObject(TestClass)
1456 self.assertFalse(mock_obj._replay_mode)
1457 mox.Replay(mock_obj)
1458 self.assertTrue(mock_obj._replay_mode)
1459
1460
1461 class MoxTestBaseTest(unittest.TestCase):
1462 """Verify that all tests in a class derived from MoxTestBase are wrapped."""
1463
1464 def setUp(self):
1465 self.mox = mox.Mox()
1466 self.test_mox = mox.Mox()
1467 self.result = unittest.TestResult()
1468
1469 def tearDown(self):
1470 # In case one of our tests fail before UnsetStubs is called.
1471 self.mox.UnsetStubs()
1472 self.test_mox.UnsetStubs()
1473
1474 def _setUpTestClass(self):
1475 """Replacement for setUp in the test class instance.
1476
1477 Assigns a mox.Mox instance as the mox attribute of the test class instance.
1478 This replacement Mox instance is under our control before setUp is called
1479 in the test class instance.
1480 """
1481 self.test.mox = self.test_mox
1482
1483 def _CreateTest(self, test_name):
1484 """Create a test from our example mox class.
1485
1486 The created test instance is assigned to this instances test attribute.
1487 """
1488 self.test = mox_test_helper.ExampleMoxTest(test_name)
1489 self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass)
1490
1491 def _VerifySuccess(self):
1492 """Run the checks to confirm test method completed successfully."""
1493 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1494 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1495 self.test_mox.UnsetStubs()
1496 self.test_mox.VerifyAll()
1497 self.mox.ReplayAll()
1498 self.test.run(result=self.result)
1499 self.assertTrue(self.result.wasSuccessful())
1500 self.mox.UnsetStubs()
1501 self.mox.VerifyAll()
1502 self.test_mox.UnsetStubs()
1503 self.test_mox.VerifyAll()
1504
1505 def testSuccess(self):
1506 """Successful test method execution test."""
1507 self._CreateTest('testSuccess')
1508 self._VerifySuccess()
1509
1510 def testExpectedNotCalled(self):
1511 """Stubbed out method is not called."""
1512 self._CreateTest('testExpectedNotCalled')
1513 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1514 # Dont stub out VerifyAll - that's what causes the test to fail
1515 self.test_mox.UnsetStubs()
1516 self.test_mox.VerifyAll()
1517 self.mox.ReplayAll()
1518 self.test.run(result=self.result)
1519 self.failIf(self.result.wasSuccessful())
1520 self.mox.UnsetStubs()
1521 self.mox.VerifyAll()
1522 self.test_mox.UnsetStubs()
1523
1524 def testUnexpectedCall(self):
1525 """Stubbed out method is called with unexpected arguments."""
1526 self._CreateTest('testUnexpectedCall')
1527 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1528 # Ensure no calls are made to VerifyAll()
1529 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1530 self.test_mox.UnsetStubs()
1531 self.mox.ReplayAll()
1532 self.test.run(result=self.result)
1533 self.failIf(self.result.wasSuccessful())
1534 self.mox.UnsetStubs()
1535 self.mox.VerifyAll()
1536 self.test_mox.UnsetStubs()
1537
1538 def testFailure(self):
1539 """Failing assertion in test method."""
1540 self._CreateTest('testFailure')
1541 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1542 # Ensure no calls are made to VerifyAll()
1543 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1544 self.test_mox.UnsetStubs()
1545 self.mox.ReplayAll()
1546 self.test.run(result=self.result)
1547 self.failIf(self.result.wasSuccessful())
1548 self.mox.UnsetStubs()
1549 self.mox.VerifyAll()
1550 self.test_mox.UnsetStubs()
1551
1552 def testMixin(self):
1553 """Run test from mix-in test class, ensure it passes."""
1554 self._CreateTest('testStat')
1555 self._VerifySuccess()
1556
1557 def testMixinAgain(self):
1558 """Run same test as above but from the current test class.
1559
1560 This ensures metaclass properly wrapped test methods from all base classes.
1561 If unsetting of stubs doesn't happen, this will fail.
1562 """
1563 self._CreateTest('testStatOther')
1564 self._VerifySuccess()
1565
1566
1567 class VerifyTest(unittest.TestCase):
1568 """Verify Verify works properly."""
1569
1570 def testVerify(self):
1571 """Verify should be called for all objects.
1572
1573 This should throw an exception because the expected behavior did not occur.
1574 """
1575 mock_obj = mox.MockObject(TestClass)
1576 mock_obj.ValidCall()
1577 mock_obj._Replay()
1578 self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
1579
1580
1581 class ResetTest(unittest.TestCase):
1582 """Verify Reset works properly."""
1583
1584 def testReset(self):
1585 """Should empty all queues and put mocks in record mode."""
1586 mock_obj = mox.MockObject(TestClass)
1587 mock_obj.ValidCall()
1588 self.assertFalse(mock_obj._replay_mode)
1589 mock_obj._Replay()
1590 self.assertTrue(mock_obj._replay_mode)
1591 self.assertEquals(1, len(mock_obj._expected_calls_queue))
1592
1593 mox.Reset(mock_obj)
1594 self.assertFalse(mock_obj._replay_mode)
1595 self.assertEquals(0, len(mock_obj._expected_calls_queue))
1596
1597
1598 class MyTestCase(unittest.TestCase):
1599 """Simulate the use of a fake wrapper around Python's unittest library."""
1600
1601 def setUp(self):
1602 super(MyTestCase, self).setUp()
1603 self.critical_variable = 42
1604
1605
1606 class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase):
1607 """Test that multiple inheritance can be used with MoxTestBase."""
1608
1609 def setUp(self):
1610 super(MoxTestBaseMultipleInheritanceTest, self).setUp()
1611
1612 def testMultipleInheritance(self):
1613 """Should be able to access members created by all parent setUp()."""
1614 self.assert_(isinstance(self.mox, mox.Mox))
1615 self.assertEquals(42, self.critical_variable)
1616
1617
1618 class TestClass:
1619 """This class is used only for testing the mock framework"""
1620
1621 SOME_CLASS_VAR = "test_value"
1622 _PROTECTED_CLASS_VAR = "protected value"
1623
1624 def __init__(self, ivar=None):
1625 self.__ivar = ivar
1626
1627 def __eq__(self, rhs):
1628 return self.__ivar == rhs
1629
1630 def __ne__(self, rhs):
1631 return not self.__eq__(rhs)
1632
1633 def ValidCall(self):
1634 pass
1635
1636 def OtherValidCall(self):
1637 pass
1638
1639 def ValidCallWithArgs(self, *args, **kwargs):
1640 pass
1641
1642 @classmethod
1643 def MyClassMethod(cls):
1644 pass
1645
1646 @staticmethod
1647 def MyStaticMethod():
1648 pass
1649
1650 def _ProtectedCall(self):
1651 pass
1652
1653 def __PrivateCall(self):
1654 pass
1655
1656 def __getitem__(self, key):
1657 pass
1658
1659 def __DoNotMock(self):
1660 pass
1661
1662 def __getitem__(self, key):
1663 """Return the value for key."""
1664 return self.d[key]
1665
1666 def __setitem__(self, key, value):
1667 """Set the value for key to value."""
1668 self.d[key] = value
1669
1670 def __contains__(self, key):
1671 """Returns True if d contains the key."""
1672 return key in self.d
1673
1674 def __iter__(self):
1675 pass
1676
1677 class ChildClass(TestClass):
1678 """This inherits from TestClass."""
1679 def __init__(self):
1680 TestClass.__init__(self)
1681
1682 def ChildValidCall(self):
1683 pass
1684
1685
1686 class CallableClass(object):
1687 """This class is callable, and that should be mockable!"""
1688
1689 def __init__(self):
1690 pass
1691
1692 def __call__(self, param):
1693 return param
1694
1695
1696 class SubscribtableNonIterableClass(object):
1697 def __getitem__(self, index):
1698 raise IndexError
1699
1700
1701 class InheritsFromCallable(CallableClass):
1702 """This class should also be mockable; it inherits from a callable class."""
1703
1704 pass
1705
1706
1707 if __name__ == '__main__':
1708 unittest.main()
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698