App Engine Python SDK version 1.9.9
[gae.git] / python / lib / mox / mox_test.py
blobaccabf4ac102312b7ab0c2f2eda2d8f9df9f5490
1 #!/usr/bin/python2.4
3 # Unit tests for Mox.
5 # Copyright 2008 Google Inc.
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
11 # http://www.apache.org/licenses/LICENSE-2.0
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.
19 import cStringIO
20 import unittest
21 import re
23 import mox
25 import mox_test_helper
27 OS_LISTDIR = mox_test_helper.os.listdir
29 class ExpectedMethodCallsErrorTest(unittest.TestCase):
30 """Test creation and string conversion of ExpectedMethodCallsError."""
32 def testAtLeastOneMethod(self):
33 self.assertRaises(ValueError, mox.ExpectedMethodCallsError, [])
35 def testOneError(self):
36 method = mox.MockMethod("testMethod", [], False)
37 method(1, 2).AndReturn('output')
38 e = mox.ExpectedMethodCallsError([method])
39 self.assertEqual(
40 "Verify: Expected methods never called:\n"
41 " 0. testMethod(1, 2) -> 'output'",
42 str(e))
44 def testManyErrors(self):
45 method1 = mox.MockMethod("testMethod", [], False)
46 method1(1, 2).AndReturn('output')
47 method2 = mox.MockMethod("testMethod", [], False)
48 method2(a=1, b=2, c="only named")
49 method3 = mox.MockMethod("testMethod2", [], False)
50 method3().AndReturn(44)
51 method4 = mox.MockMethod("testMethod", [], False)
52 method4(1, 2).AndReturn('output')
53 e = mox.ExpectedMethodCallsError([method1, method2, method3, method4])
54 self.assertEqual(
55 "Verify: Expected methods never called:\n"
56 " 0. testMethod(1, 2) -> 'output'\n"
57 " 1. testMethod(a=1, b=2, c='only named') -> None\n"
58 " 2. testMethod2() -> 44\n"
59 " 3. testMethod(1, 2) -> 'output'",
60 str(e))
63 class OrTest(unittest.TestCase):
64 """Test Or correctly chains Comparators."""
66 def testValidOr(self):
67 """Or should be True if either Comparator returns True."""
68 self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == {})
69 self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test')
70 self.assert_(mox.Or(mox.IsA(str), mox.IsA(str)) == 'test')
72 def testInvalidOr(self):
73 """Or should be False if both Comparators return False."""
74 self.failIf(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0)
77 class AndTest(unittest.TestCase):
78 """Test And correctly chains Comparators."""
80 def testValidAnd(self):
81 """And should be True if both Comparators return True."""
82 self.assert_(mox.And(mox.IsA(str), mox.IsA(str)) == '1')
84 def testClauseOneFails(self):
85 """And should be False if the first Comparator returns False."""
87 self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1')
89 def testAdvancedUsage(self):
90 """And should work with other Comparators.
92 Note: this test is reliant on In and ContainsKeyValue.
93 """
94 test_dict = {"mock" : "obj", "testing" : "isCOOL"}
95 self.assert_(mox.And(mox.In("testing"),
96 mox.ContainsKeyValue("mock", "obj")) == test_dict)
98 def testAdvancedUsageFails(self):
99 """Note: this test is reliant on In and ContainsKeyValue."""
100 test_dict = {"mock" : "obj", "testing" : "isCOOL"}
101 self.failIf(mox.And(mox.In("NOTFOUND"),
102 mox.ContainsKeyValue("mock", "obj")) == test_dict)
105 class SameElementsAsTest(unittest.TestCase):
106 """Test SameElementsAs correctly identifies sequences with same elements."""
108 def testSortedLists(self):
109 """Should return True if two lists are exactly equal."""
110 self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c'])
112 def testUnsortedLists(self):
113 """Should return True if two lists are unequal but have same elements."""
114 self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1])
116 def testUnhashableLists(self):
117 """Should return True if two lists have the same unhashable elements."""
118 self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) ==
119 [{2: 'b'}, {'a': 1}])
121 def testEmptyLists(self):
122 """Should return True for two empty lists."""
123 self.assert_(mox.SameElementsAs([]) == [])
125 def testUnequalLists(self):
126 """Should return False if the lists are not equal."""
127 self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c'])
129 def testUnequalUnhashableLists(self):
130 """Should return False if two lists with unhashable elements are unequal."""
131 self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])
134 class ContainsKeyValueTest(unittest.TestCase):
135 """Test ContainsKeyValue correctly identifies key/value pairs in a dict.
138 def testValidPair(self):
139 """Should return True if the key value is in the dict."""
140 self.assert_(mox.ContainsKeyValue("key", 1) == {"key": 1})
142 def testInvalidValue(self):
143 """Should return False if the value is not correct."""
144 self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2})
146 def testInvalidKey(self):
147 """Should return False if they key is not in the dict."""
148 self.failIf(mox.ContainsKeyValue("qux", 1) == {"key": 2})
151 class ContainsAttributeValueTest(unittest.TestCase):
152 """Test ContainsAttributeValue correctly identifies properties in an object.
155 def setUp(self):
156 """Create an object to test with."""
159 class TestObject(object):
160 key = 1
162 self.test_object = TestObject()
164 def testValidPair(self):
165 """Should return True if the object has the key attribute and it matches."""
166 self.assert_(mox.ContainsAttributeValue("key", 1) == self.test_object)
168 def testInvalidValue(self):
169 """Should return False if the value is not correct."""
170 self.failIf(mox.ContainsKeyValue("key", 2) == self.test_object)
172 def testInvalidKey(self):
173 """Should return False if they the object doesn't have the property."""
174 self.failIf(mox.ContainsKeyValue("qux", 1) == self.test_object)
177 class InTest(unittest.TestCase):
178 """Test In correctly identifies a key in a list/dict"""
180 def testItemInList(self):
181 """Should return True if the item is in the list."""
182 self.assert_(mox.In(1) == [1, 2, 3])
184 def testKeyInDict(self):
185 """Should return True if the item is a key in a dict."""
186 self.assert_(mox.In("test") == {"test" : "module"})
189 class NotTest(unittest.TestCase):
190 """Test Not correctly identifies False predicates."""
192 def testItemInList(self):
193 """Should return True if the item is NOT in the list."""
194 self.assert_(mox.Not(mox.In(42)) == [1, 2, 3])
196 def testKeyInDict(self):
197 """Should return True if the item is NOT a key in a dict."""
198 self.assert_(mox.Not(mox.In("foo")) == {"key" : 42})
200 def testInvalidKeyWithNot(self):
201 """Should return False if they key is NOT in the dict."""
202 self.assert_(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2})
205 class StrContainsTest(unittest.TestCase):
206 """Test StrContains correctly checks for substring occurrence of a parameter.
209 def testValidSubstringAtStart(self):
210 """Should return True if the substring is at the start of the string."""
211 self.assert_(mox.StrContains("hello") == "hello world")
213 def testValidSubstringInMiddle(self):
214 """Should return True if the substring is in the middle of the string."""
215 self.assert_(mox.StrContains("lo wo") == "hello world")
217 def testValidSubstringAtEnd(self):
218 """Should return True if the substring is at the end of the string."""
219 self.assert_(mox.StrContains("ld") == "hello world")
221 def testInvaildSubstring(self):
222 """Should return False if the substring is not in the string."""
223 self.failIf(mox.StrContains("AAA") == "hello world")
225 def testMultipleMatches(self):
226 """Should return True if there are multiple occurances of substring."""
227 self.assert_(mox.StrContains("abc") == "ababcabcabcababc")
230 class RegexTest(unittest.TestCase):
231 """Test Regex correctly matches regular expressions."""
233 def testIdentifyBadSyntaxDuringInit(self):
234 """The user should know immediately if a regex has bad syntax."""
235 self.assertRaises(re.error, mox.Regex, '(a|b')
237 def testPatternInMiddle(self):
238 """Should return True if the pattern matches at the middle of the string.
240 This ensures that re.search is used (instead of re.find).
242 self.assert_(mox.Regex(r"a\s+b") == "x y z a b c")
244 def testNonMatchPattern(self):
245 """Should return False if the pattern does not match the string."""
246 self.failIf(mox.Regex(r"a\s+b") == "x y z")
248 def testFlagsPassedCorrectly(self):
249 """Should return True as we pass IGNORECASE flag."""
250 self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a")
252 def testReprWithoutFlags(self):
253 """repr should return the regular expression pattern."""
254 self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>")
256 def testReprWithFlags(self):
257 """repr should return the regular expression pattern and flags."""
258 self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) ==
259 "<regular expression 'a\s+b', flags=4>")
262 class IsATest(unittest.TestCase):
263 """Verify IsA correctly checks equality based upon class type, not value."""
265 def testEqualityValid(self):
266 """Verify that == correctly identifies objects of the same type."""
267 self.assert_(mox.IsA(str) == 'test')
269 def testEqualityInvalid(self):
270 """Verify that == correctly identifies objects of different types."""
271 self.failIf(mox.IsA(str) == 10)
273 def testInequalityValid(self):
274 """Verify that != identifies objects of different type."""
275 self.assert_(mox.IsA(str) != 10)
277 def testInequalityInvalid(self):
278 """Verify that != correctly identifies objects of the same type."""
279 self.failIf(mox.IsA(str) != "test")
281 def testEqualityInListValid(self):
282 """Verify list contents are properly compared."""
283 isa_list = [mox.IsA(str), mox.IsA(str)]
284 str_list = ["abc", "def"]
285 self.assert_(isa_list == str_list)
287 def testEqualityInListInvalid(self):
288 """Verify list contents are properly compared."""
289 isa_list = [mox.IsA(str),mox.IsA(str)]
290 mixed_list = ["abc", 123]
291 self.failIf(isa_list == mixed_list)
293 def testSpecialTypes(self):
294 """Verify that IsA can handle objects like cStringIO.StringIO."""
295 isA = mox.IsA(cStringIO.StringIO())
296 stringIO = cStringIO.StringIO()
297 self.assert_(isA == stringIO)
300 class IsAlmostTest(unittest.TestCase):
301 """Verify IsAlmost correctly checks equality of floating point numbers."""
303 def testEqualityValid(self):
304 """Verify that == correctly identifies nearly equivalent floats."""
305 self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
307 def testEqualityInvalid(self):
308 """Verify that == correctly identifies non-equivalent floats."""
309 self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
311 def testEqualityWithPlaces(self):
312 """Verify that specifying places has the desired effect."""
313 self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
314 self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
316 def testNonNumericTypes(self):
317 """Verify that IsAlmost handles non-numeric types properly."""
319 self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9')
320 self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9)
321 self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
324 class MockMethodTest(unittest.TestCase):
325 """Test class to verify that the MockMethod class is working correctly."""
327 def setUp(self):
328 self.expected_method = mox.MockMethod("testMethod", [], False)(['original'])
329 self.mock_method = mox.MockMethod("testMethod", [self.expected_method],
330 True)
332 def testNameAttribute(self):
333 """Should provide a __name__ attribute."""
334 self.assertEquals('testMethod', self.mock_method.__name__)
336 def testAndReturnNoneByDefault(self):
337 """Should return None by default."""
338 return_value = self.mock_method(['original'])
339 self.assert_(return_value == None)
341 def testAndReturnValue(self):
342 """Should return a specificed return value."""
343 expected_return_value = "test"
344 self.expected_method.AndReturn(expected_return_value)
345 return_value = self.mock_method(['original'])
346 self.assert_(return_value == expected_return_value)
348 def testAndRaiseException(self):
349 """Should raise a specified exception."""
350 expected_exception = Exception('test exception')
351 self.expected_method.AndRaise(expected_exception)
352 self.assertRaises(Exception, self.mock_method)
354 def testWithSideEffects(self):
355 """Should call state modifier."""
356 local_list = ['original']
357 def modifier(mutable_list):
358 self.assertTrue(local_list is mutable_list)
359 mutable_list[0] = 'mutation'
360 self.expected_method.WithSideEffects(modifier).AndReturn(1)
361 self.mock_method(local_list)
362 self.assertEquals('mutation', local_list[0])
364 def testWithReturningSideEffects(self):
365 """Should call state modifier and propagate its return value."""
366 local_list = ['original']
367 expected_return = 'expected_return'
368 def modifier_with_return(mutable_list):
369 self.assertTrue(local_list is mutable_list)
370 mutable_list[0] = 'mutation'
371 return expected_return
372 self.expected_method.WithSideEffects(modifier_with_return)
373 actual_return = self.mock_method(local_list)
374 self.assertEquals('mutation', local_list[0])
375 self.assertEquals(expected_return, actual_return)
377 def testWithReturningSideEffectsWithAndReturn(self):
378 """Should call state modifier and ignore its return value."""
379 local_list = ['original']
380 expected_return = 'expected_return'
381 unexpected_return = 'unexpected_return'
382 def modifier_with_return(mutable_list):
383 self.assertTrue(local_list is mutable_list)
384 mutable_list[0] = 'mutation'
385 return unexpected_return
386 self.expected_method.WithSideEffects(modifier_with_return).AndReturn(
387 expected_return)
388 actual_return = self.mock_method(local_list)
389 self.assertEquals('mutation', local_list[0])
390 self.assertEquals(expected_return, actual_return)
392 def testEqualityNoParamsEqual(self):
393 """Methods with the same name and without params should be equal."""
394 expected_method = mox.MockMethod("testMethod", [], False)
395 self.assertEqual(self.mock_method, expected_method)
397 def testEqualityNoParamsNotEqual(self):
398 """Methods with different names and without params should not be equal."""
399 expected_method = mox.MockMethod("otherMethod", [], False)
400 self.failIfEqual(self.mock_method, expected_method)
402 def testEqualityParamsEqual(self):
403 """Methods with the same name and parameters should be equal."""
404 params = [1, 2, 3]
405 expected_method = mox.MockMethod("testMethod", [], False)
406 expected_method._params = params
408 self.mock_method._params = params
409 self.assertEqual(self.mock_method, expected_method)
411 def testEqualityParamsNotEqual(self):
412 """Methods with the same name and different params should not be equal."""
413 expected_method = mox.MockMethod("testMethod", [], False)
414 expected_method._params = [1, 2, 3]
416 self.mock_method._params = ['a', 'b', 'c']
417 self.failIfEqual(self.mock_method, expected_method)
419 def testEqualityNamedParamsEqual(self):
420 """Methods with the same name and same named params should be equal."""
421 named_params = {"input1": "test", "input2": "params"}
422 expected_method = mox.MockMethod("testMethod", [], False)
423 expected_method._named_params = named_params
425 self.mock_method._named_params = named_params
426 self.assertEqual(self.mock_method, expected_method)
428 def testEqualityNamedParamsNotEqual(self):
429 """Methods with the same name and diffnamed params should not be equal."""
430 expected_method = mox.MockMethod("testMethod", [], False)
431 expected_method._named_params = {"input1": "test", "input2": "params"}
433 self.mock_method._named_params = {"input1": "test2", "input2": "params2"}
434 self.failIfEqual(self.mock_method, expected_method)
436 def testEqualityWrongType(self):
437 """Method should not be equal to an object of a different type."""
438 self.failIfEqual(self.mock_method, "string?")
440 def testObjectEquality(self):
441 """Equality of objects should work without a Comparator"""
442 instA = TestClass();
443 instB = TestClass();
445 params = [instA, ]
446 expected_method = mox.MockMethod("testMethod", [], False)
447 expected_method._params = params
449 self.mock_method._params = [instB, ]
450 self.assertEqual(self.mock_method, expected_method)
452 def testStrConversion(self):
453 method = mox.MockMethod("f", [], False)
454 method(1, 2, "st", n1=8, n2="st2")
455 self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None"))
457 method = mox.MockMethod("testMethod", [], False)
458 method(1, 2, "only positional")
459 self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None")
461 method = mox.MockMethod("testMethod", [], False)
462 method(a=1, b=2, c="only named")
463 self.assertEqual(str(method),
464 "testMethod(a=1, b=2, c='only named') -> None")
466 method = mox.MockMethod("testMethod", [], False)
467 method()
468 self.assertEqual(str(method), "testMethod() -> None")
470 method = mox.MockMethod("testMethod", [], False)
471 method(x="only 1 parameter")
472 self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None")
474 method = mox.MockMethod("testMethod", [], False)
475 method().AndReturn('return_value')
476 self.assertEqual(str(method), "testMethod() -> 'return_value'")
478 method = mox.MockMethod("testMethod", [], False)
479 method().AndReturn(('a', {1: 2}))
480 self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})")
483 class MockAnythingTest(unittest.TestCase):
484 """Verify that the MockAnything class works as expected."""
486 def setUp(self):
487 self.mock_object = mox.MockAnything()
489 def testRepr(self):
490 """Calling repr on a MockAnything instance must work."""
491 self.assertEqual('<MockAnything instance>', repr(self.mock_object))
493 def testSetupMode(self):
494 """Verify the mock will accept any call."""
495 self.mock_object.NonsenseCall()
496 self.assert_(len(self.mock_object._expected_calls_queue) == 1)
498 def testReplayWithExpectedCall(self):
499 """Verify the mock replays method calls as expected."""
500 self.mock_object.ValidCall() # setup method call
501 self.mock_object._Replay() # start replay mode
502 self.mock_object.ValidCall() # make method call
504 def testReplayWithUnexpectedCall(self):
505 """Unexpected method calls should raise UnexpectedMethodCallError."""
506 self.mock_object.ValidCall() # setup method call
507 self.mock_object._Replay() # start replay mode
508 self.assertRaises(mox.UnexpectedMethodCallError,
509 self.mock_object.OtherValidCall)
511 def testVerifyWithCompleteReplay(self):
512 """Verify should not raise an exception for a valid replay."""
513 self.mock_object.ValidCall() # setup method call
514 self.mock_object._Replay() # start replay mode
515 self.mock_object.ValidCall() # make method call
516 self.mock_object._Verify()
518 def testVerifyWithIncompleteReplay(self):
519 """Verify should raise an exception if the replay was not complete."""
520 self.mock_object.ValidCall() # setup method call
521 self.mock_object._Replay() # start replay mode
522 # ValidCall() is never made
523 self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify)
525 def testSpecialClassMethod(self):
526 """Verify should not raise an exception when special methods are used."""
527 self.mock_object[1].AndReturn(True)
528 self.mock_object._Replay()
529 returned_val = self.mock_object[1]
530 self.assert_(returned_val)
531 self.mock_object._Verify()
533 def testNonzero(self):
534 """You should be able to use the mock object in an if."""
535 self.mock_object._Replay()
536 if self.mock_object:
537 pass
539 def testNotNone(self):
540 """Mock should be comparable to None."""
541 self.mock_object._Replay()
542 if self.mock_object is not None:
543 pass
545 if self.mock_object is None:
546 pass
548 def testEquals(self):
549 """A mock should be able to compare itself to another object."""
550 self.mock_object._Replay()
551 self.assertEquals(self.mock_object, self.mock_object)
553 def testEqualsMockFailure(self):
554 """Verify equals identifies unequal objects."""
555 self.mock_object.SillyCall()
556 self.mock_object._Replay()
557 self.assertNotEquals(self.mock_object, mox.MockAnything())
559 def testEqualsInstanceFailure(self):
560 """Verify equals identifies that objects are different instances."""
561 self.mock_object._Replay()
562 self.assertNotEquals(self.mock_object, TestClass())
564 def testNotEquals(self):
565 """Verify not equals works."""
566 self.mock_object._Replay()
567 self.assertFalse(self.mock_object != self.mock_object)
569 def testNestedMockCallsRecordedSerially(self):
570 """Test that nested calls work when recorded serially."""
571 self.mock_object.CallInner().AndReturn(1)
572 self.mock_object.CallOuter(1)
573 self.mock_object._Replay()
575 self.mock_object.CallOuter(self.mock_object.CallInner())
577 self.mock_object._Verify()
579 def testNestedMockCallsRecordedNested(self):
580 """Test that nested cals work when recorded in a nested fashion."""
581 self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1))
582 self.mock_object._Replay()
584 self.mock_object.CallOuter(self.mock_object.CallInner())
586 self.mock_object._Verify()
588 def testIsCallable(self):
589 """Test that MockAnything can even mock a simple callable.
591 This is handy for "stubbing out" a method in a module with a mock, and
592 verifying that it was called.
594 self.mock_object().AndReturn('mox0rd')
595 self.mock_object._Replay()
597 self.assertEquals('mox0rd', self.mock_object())
599 self.mock_object._Verify()
601 def testIsReprable(self):
602 """Test that MockAnythings can be repr'd without causing a failure."""
603 self.failUnless('MockAnything' in repr(self.mock_object))
606 class MethodCheckerTest(unittest.TestCase):
607 """Tests MockMethod's use of MethodChecker method."""
609 def testNoParameters(self):
610 method = mox.MockMethod('NoParameters', [], False,
611 CheckCallTestClass.NoParameters)
612 method()
613 self.assertRaises(AttributeError, method, 1)
614 self.assertRaises(AttributeError, method, 1, 2)
615 self.assertRaises(AttributeError, method, a=1)
616 self.assertRaises(AttributeError, method, 1, b=2)
618 def testOneParameter(self):
619 method = mox.MockMethod('OneParameter', [], False,
620 CheckCallTestClass.OneParameter)
621 self.assertRaises(AttributeError, method)
622 method(1)
623 method(a=1)
624 self.assertRaises(AttributeError, method, b=1)
625 self.assertRaises(AttributeError, method, 1, 2)
626 self.assertRaises(AttributeError, method, 1, a=2)
627 self.assertRaises(AttributeError, method, 1, b=2)
629 def testTwoParameters(self):
630 method = mox.MockMethod('TwoParameters', [], False,
631 CheckCallTestClass.TwoParameters)
632 self.assertRaises(AttributeError, method)
633 self.assertRaises(AttributeError, method, 1)
634 self.assertRaises(AttributeError, method, a=1)
635 self.assertRaises(AttributeError, method, b=1)
636 method(1, 2)
637 method(1, b=2)
638 method(a=1, b=2)
639 method(b=2, a=1)
640 self.assertRaises(AttributeError, method, b=2, c=3)
641 self.assertRaises(AttributeError, method, a=1, b=2, c=3)
642 self.assertRaises(AttributeError, method, 1, 2, 3)
643 self.assertRaises(AttributeError, method, 1, 2, 3, 4)
644 self.assertRaises(AttributeError, method, 3, a=1, b=2)
646 def testOneDefaultValue(self):
647 method = mox.MockMethod('OneDefaultValue', [], False,
648 CheckCallTestClass.OneDefaultValue)
649 method()
650 method(1)
651 method(a=1)
652 self.assertRaises(AttributeError, method, b=1)
653 self.assertRaises(AttributeError, method, 1, 2)
654 self.assertRaises(AttributeError, method, 1, a=2)
655 self.assertRaises(AttributeError, method, 1, b=2)
657 def testTwoDefaultValues(self):
658 method = mox.MockMethod('TwoDefaultValues', [], False,
659 CheckCallTestClass.TwoDefaultValues)
660 self.assertRaises(AttributeError, method)
661 self.assertRaises(AttributeError, method, c=3)
662 self.assertRaises(AttributeError, method, 1)
663 self.assertRaises(AttributeError, method, 1, d=4)
664 self.assertRaises(AttributeError, method, 1, d=4, c=3)
665 method(1, 2)
666 method(a=1, b=2)
667 method(1, 2, 3)
668 method(1, 2, 3, 4)
669 method(1, 2, c=3)
670 method(1, 2, c=3, d=4)
671 method(1, 2, d=4, c=3)
672 method(d=4, c=3, a=1, b=2)
673 self.assertRaises(AttributeError, method, 1, 2, 3, 4, 5)
674 self.assertRaises(AttributeError, method, 1, 2, e=9)
675 self.assertRaises(AttributeError, method, a=1, b=2, e=9)
677 def testArgs(self):
678 method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args)
679 self.assertRaises(AttributeError, method)
680 self.assertRaises(AttributeError, method, 1)
681 method(1, 2)
682 method(a=1, b=2)
683 method(1, 2, 3)
684 method(1, 2, 3, 4)
685 self.assertRaises(AttributeError, method, 1, 2, a=3)
686 self.assertRaises(AttributeError, method, 1, 2, c=3)
688 def testKwargs(self):
689 method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs)
690 self.assertRaises(AttributeError, method)
691 method(1)
692 method(1, 2)
693 method(a=1, b=2)
694 method(b=2, a=1)
695 self.assertRaises(AttributeError, method, 1, 2, 3)
696 self.assertRaises(AttributeError, method, 1, 2, a=3)
697 method(1, 2, c=3)
698 method(a=1, b=2, c=3)
699 method(c=3, a=1, b=2)
700 method(a=1, b=2, c=3, d=4)
701 self.assertRaises(AttributeError, method, 1, 2, 3, 4)
703 def testArgsAndKwargs(self):
704 method = mox.MockMethod('ArgsAndKwargs', [], False,
705 CheckCallTestClass.ArgsAndKwargs)
706 self.assertRaises(AttributeError, method)
707 method(1)
708 method(1, 2)
709 method(1, 2, 3)
710 method(a=1)
711 method(1, b=2)
712 self.assertRaises(AttributeError, method, 1, a=2)
713 method(b=2, a=1)
714 method(c=3, b=2, a=1)
715 method(1, 2, c=3)
718 class CheckCallTestClass(object):
719 def NoParameters(self):
720 pass
722 def OneParameter(self, a):
723 pass
725 def TwoParameters(self, a, b):
726 pass
728 def OneDefaultValue(self, a=1):
729 pass
731 def TwoDefaultValues(self, a, b, c=1, d=2):
732 pass
734 def Args(self, a, b, *args):
735 pass
737 def Kwargs(self, a, b=2, **kwargs):
738 pass
740 def ArgsAndKwargs(self, a, *args, **kwargs):
741 pass
744 class MockObjectTest(unittest.TestCase):
745 """Verify that the MockObject class works as exepcted."""
747 def setUp(self):
748 self.mock_object = mox.MockObject(TestClass)
750 def testSetupModeWithValidCall(self):
751 """Verify the mock object properly mocks a basic method call."""
752 self.mock_object.ValidCall()
753 self.assert_(len(self.mock_object._expected_calls_queue) == 1)
755 def testSetupModeWithInvalidCall(self):
756 """UnknownMethodCallError should be raised if a non-member method is called.
758 # Note: assertRaises does not catch exceptions thrown by MockObject's
759 # __getattr__
760 try:
761 self.mock_object.InvalidCall()
762 self.fail("No exception thrown, expected UnknownMethodCallError")
763 except mox.UnknownMethodCallError:
764 pass
765 except Exception:
766 self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
768 def testReplayWithInvalidCall(self):
769 """UnknownMethodCallError should be raised if a non-member method is called.
771 self.mock_object.ValidCall() # setup method call
772 self.mock_object._Replay() # start replay mode
773 # Note: assertRaises does not catch exceptions thrown by MockObject's
774 # __getattr__
775 try:
776 self.mock_object.InvalidCall()
777 self.fail("No exception thrown, expected UnknownMethodCallError")
778 except mox.UnknownMethodCallError:
779 pass
780 except Exception:
781 self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
783 def testIsInstance(self):
784 """Mock should be able to pass as an instance of the mocked class."""
785 self.assert_(isinstance(self.mock_object, TestClass))
787 def testFindValidMethods(self):
788 """Mock should be able to mock all public methods."""
789 self.assert_('ValidCall' in self.mock_object._known_methods)
790 self.assert_('OtherValidCall' in self.mock_object._known_methods)
791 self.assert_('MyClassMethod' in self.mock_object._known_methods)
792 self.assert_('MyStaticMethod' in self.mock_object._known_methods)
793 self.assert_('_ProtectedCall' in self.mock_object._known_methods)
794 self.assert_('__PrivateCall' not in self.mock_object._known_methods)
795 self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods)
797 def testFindsSuperclassMethods(self):
798 """Mock should be able to mock superclasses methods."""
799 self.mock_object = mox.MockObject(ChildClass)
800 self.assert_('ValidCall' in self.mock_object._known_methods)
801 self.assert_('OtherValidCall' in self.mock_object._known_methods)
802 self.assert_('MyClassMethod' in self.mock_object._known_methods)
803 self.assert_('ChildValidCall' in self.mock_object._known_methods)
805 def testAccessClassVariables(self):
806 """Class variables should be accessible through the mock."""
807 self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars)
808 self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)
809 self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR)
811 def testEquals(self):
812 """A mock should be able to compare itself to another object."""
813 self.mock_object._Replay()
814 self.assertEquals(self.mock_object, self.mock_object)
816 def testEqualsMockFailure(self):
817 """Verify equals identifies unequal objects."""
818 self.mock_object.ValidCall()
819 self.mock_object._Replay()
820 self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
822 def testEqualsInstanceFailure(self):
823 """Verify equals identifies that objects are different instances."""
824 self.mock_object._Replay()
825 self.assertNotEquals(self.mock_object, TestClass())
827 def testNotEquals(self):
828 """Verify not equals works."""
829 self.mock_object._Replay()
830 self.assertFalse(self.mock_object != self.mock_object)
832 def testMockSetItem_ExpectedSetItem_Success(self):
833 """Test that __setitem__() gets mocked in Dummy.
835 In this test, _Verify() succeeds.
837 dummy = mox.MockObject(TestClass)
838 dummy['X'] = 'Y'
840 dummy._Replay()
842 dummy['X'] = 'Y'
844 dummy._Verify()
846 def testMockSetItem_ExpectedSetItem_NoSuccess(self):
847 """Test that __setitem__() gets mocked in Dummy.
849 In this test, _Verify() fails.
851 dummy = mox.MockObject(TestClass)
852 dummy['X'] = 'Y'
854 dummy._Replay()
856 # NOT doing dummy['X'] = 'Y'
858 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
860 def testMockSetItem_ExpectedNoSetItem_Success(self):
861 """Test that __setitem__() gets mocked in Dummy."""
862 dummy = mox.MockObject(TestClass)
863 # NOT doing dummy['X'] = 'Y'
865 dummy._Replay()
867 def call(): dummy['X'] = 'Y'
868 self.assertRaises(mox.UnexpectedMethodCallError, call)
870 def testMockSetItem_ExpectedNoSetItem_NoSuccess(self):
871 """Test that __setitem__() gets mocked in Dummy.
873 In this test, _Verify() fails.
875 dummy = mox.MockObject(TestClass)
876 # NOT doing dummy['X'] = 'Y'
878 dummy._Replay()
880 # NOT doing dummy['X'] = 'Y'
882 dummy._Verify()
884 def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self):
885 """Test that __setitem__() fails if other parameters are expected."""
886 dummy = mox.MockObject(TestClass)
887 dummy['X'] = 'Y'
889 dummy._Replay()
891 def call(): dummy['wrong'] = 'Y'
893 self.assertRaises(mox.UnexpectedMethodCallError, call)
895 dummy._Verify()
897 def testMockSetItem_WithSubClassOfNewStyleClass(self):
898 class NewStyleTestClass(object):
899 def __init__(self):
900 self.my_dict = {}
902 def __setitem__(self, key, value):
903 self.my_dict[key], value
905 class TestSubClass(NewStyleTestClass):
906 pass
908 dummy = mox.MockObject(TestSubClass)
909 dummy[1] = 2
910 dummy._Replay()
911 dummy[1] = 2
912 dummy._Verify()
914 def testMockGetItem_ExpectedGetItem_Success(self):
915 """Test that __getitem__() gets mocked in Dummy.
917 In this test, _Verify() succeeds.
919 dummy = mox.MockObject(TestClass)
920 dummy['X'].AndReturn('value')
922 dummy._Replay()
924 self.assertEqual(dummy['X'], 'value')
926 dummy._Verify()
928 def testMockGetItem_ExpectedGetItem_NoSuccess(self):
929 """Test that __getitem__() gets mocked in Dummy.
931 In this test, _Verify() fails.
933 dummy = mox.MockObject(TestClass)
934 dummy['X'].AndReturn('value')
936 dummy._Replay()
938 # NOT doing dummy['X']
940 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
942 def testMockGetItem_ExpectedNoGetItem_NoSuccess(self):
943 """Test that __getitem__() gets mocked in Dummy."""
944 dummy = mox.MockObject(TestClass)
945 # NOT doing dummy['X']
947 dummy._Replay()
949 def call(): return dummy['X']
950 self.assertRaises(mox.UnexpectedMethodCallError, call)
952 def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self):
953 """Test that __getitem__() fails if other parameters are expected."""
954 dummy = mox.MockObject(TestClass)
955 dummy['X'].AndReturn('value')
957 dummy._Replay()
959 def call(): return dummy['wrong']
961 self.assertRaises(mox.UnexpectedMethodCallError, call)
963 dummy._Verify()
965 def testMockGetItem_WithSubClassOfNewStyleClass(self):
966 class NewStyleTestClass(object):
967 def __getitem__(self, key):
968 return {1: '1', 2: '2'}[key]
970 class TestSubClass(NewStyleTestClass):
971 pass
973 dummy = mox.MockObject(TestSubClass)
974 dummy[1].AndReturn('3')
976 dummy._Replay()
977 self.assertEquals('3', dummy.__getitem__(1))
978 dummy._Verify()
980 def testMockIter_ExpectedIter_Success(self):
981 """Test that __iter__() gets mocked in Dummy.
983 In this test, _Verify() succeeds.
985 dummy = mox.MockObject(TestClass)
986 iter(dummy).AndReturn(iter(['X', 'Y']))
988 dummy._Replay()
990 self.assertEqual([x for x in dummy], ['X', 'Y'])
992 dummy._Verify()
994 def testMockContains_ExpectedContains_Success(self):
995 """Test that __contains__ gets mocked in Dummy.
997 In this test, _Verify() succeeds.
999 dummy = mox.MockObject(TestClass)
1000 dummy.__contains__('X').AndReturn(True)
1002 dummy._Replay()
1004 self.failUnless('X' in dummy)
1006 dummy._Verify()
1008 def testMockContains_ExpectedContains_NoSuccess(self):
1009 """Test that __contains__() gets mocked in Dummy.
1011 In this test, _Verify() fails.
1013 dummy = mox.MockObject(TestClass)
1014 dummy.__contains__('X').AndReturn('True')
1016 dummy._Replay()
1018 # NOT doing 'X' in dummy
1020 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
1022 def testMockContains_ExpectedContains_NonmatchingParameter(self):
1023 """Test that __contains__ fails if other parameters are expected."""
1024 dummy = mox.MockObject(TestClass)
1025 dummy.__contains__('X').AndReturn(True)
1027 dummy._Replay()
1029 def call(): return 'Y' in dummy
1031 self.assertRaises(mox.UnexpectedMethodCallError, call)
1033 dummy._Verify()
1035 def testMockIter_ExpectedIter_NoSuccess(self):
1036 """Test that __iter__() gets mocked in Dummy.
1038 In this test, _Verify() fails.
1040 dummy = mox.MockObject(TestClass)
1041 iter(dummy).AndReturn(iter(['X', 'Y']))
1043 dummy._Replay()
1045 # NOT doing self.assertEqual([x for x in dummy], ['X', 'Y'])
1047 self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
1049 def testMockIter_ExpectedNoIter_NoSuccess(self):
1050 """Test that __iter__() gets mocked in Dummy."""
1051 dummy = mox.MockObject(TestClass)
1052 # NOT doing iter(dummy)
1054 dummy._Replay()
1056 def call(): return [x for x in dummy]
1057 self.assertRaises(mox.UnexpectedMethodCallError, call)
1059 def testMockIter_ExpectedGetItem_Success(self):
1060 """Test that __iter__() gets mocked in Dummy using getitem."""
1061 dummy = mox.MockObject(SubscribtableNonIterableClass)
1062 dummy[0].AndReturn('a')
1063 dummy[1].AndReturn('b')
1064 dummy[2].AndRaise(IndexError)
1066 dummy._Replay()
1067 self.assertEquals(['a', 'b'], [x for x in dummy])
1068 dummy._Verify()
1070 def testMockIter_ExpectedNoGetItem_NoSuccess(self):
1071 """Test that __iter__() gets mocked in Dummy using getitem."""
1072 dummy = mox.MockObject(SubscribtableNonIterableClass)
1073 # NOT doing dummy[index]
1075 dummy._Replay()
1076 function = lambda: [x for x in dummy]
1077 self.assertRaises(mox.UnexpectedMethodCallError, function)
1079 def testMockGetIter_WithSubClassOfNewStyleClass(self):
1080 class NewStyleTestClass(object):
1081 def __iter__(self):
1082 return iter([1, 2, 3])
1084 class TestSubClass(NewStyleTestClass):
1085 pass
1087 dummy = mox.MockObject(TestSubClass)
1088 iter(dummy).AndReturn(iter(['a', 'b']))
1089 dummy._Replay()
1090 self.assertEquals(['a', 'b'], [x for x in dummy])
1091 dummy._Verify()
1093 def testInstantiationWithAdditionalAttributes(self):
1094 mock_object = mox.MockObject(TestClass, attrs={"attr1": "value"})
1095 self.assertEquals(mock_object.attr1, "value")
1097 def testCantOverrideMethodsWithAttributes(self):
1098 self.assertRaises(ValueError, mox.MockObject, TestClass,
1099 attrs={"ValidCall": "value"})
1101 def testCantMockNonPublicAttributes(self):
1102 self.assertRaises(mox.PrivateAttributeError, mox.MockObject, TestClass,
1103 attrs={"_protected": "value"})
1104 self.assertRaises(mox.PrivateAttributeError, mox.MockObject, TestClass,
1105 attrs={"__private": "value"})
1108 class MoxTest(unittest.TestCase):
1109 """Verify Mox works correctly."""
1111 def setUp(self):
1112 self.mox = mox.Mox()
1114 def testCreateObject(self):
1115 """Mox should create a mock object."""
1116 mock_obj = self.mox.CreateMock(TestClass)
1118 def testVerifyObjectWithCompleteReplay(self):
1119 """Mox should replay and verify all objects it created."""
1120 mock_obj = self.mox.CreateMock(TestClass)
1121 mock_obj.ValidCall()
1122 mock_obj.ValidCallWithArgs(mox.IsA(TestClass))
1123 self.mox.ReplayAll()
1124 mock_obj.ValidCall()
1125 mock_obj.ValidCallWithArgs(TestClass("some_value"))
1126 self.mox.VerifyAll()
1128 def testVerifyObjectWithIncompleteReplay(self):
1129 """Mox should raise an exception if a mock didn't replay completely."""
1130 mock_obj = self.mox.CreateMock(TestClass)
1131 mock_obj.ValidCall()
1132 self.mox.ReplayAll()
1133 # ValidCall() is never made
1134 self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll)
1136 def testEntireWorkflow(self):
1137 """Test the whole work flow."""
1138 mock_obj = self.mox.CreateMock(TestClass)
1139 mock_obj.ValidCall().AndReturn("yes")
1140 self.mox.ReplayAll()
1142 ret_val = mock_obj.ValidCall()
1143 self.assertEquals("yes", ret_val)
1144 self.mox.VerifyAll()
1146 def testCallableObject(self):
1147 """Test recording calls to a callable object works."""
1148 mock_obj = self.mox.CreateMock(CallableClass)
1149 mock_obj("foo").AndReturn("qux")
1150 self.mox.ReplayAll()
1152 ret_val = mock_obj("foo")
1153 self.assertEquals("qux", ret_val)
1154 self.mox.VerifyAll()
1156 def testInheritedCallableObject(self):
1157 """Test recording calls to an object inheriting from a callable object."""
1158 mock_obj = self.mox.CreateMock(InheritsFromCallable)
1159 mock_obj("foo").AndReturn("qux")
1160 self.mox.ReplayAll()
1162 ret_val = mock_obj("foo")
1163 self.assertEquals("qux", ret_val)
1164 self.mox.VerifyAll()
1166 def testCallOnNonCallableObject(self):
1167 """Test that you cannot call a non-callable object."""
1168 mock_obj = self.mox.CreateMock(TestClass)
1169 self.assertRaises(TypeError, mock_obj)
1171 def testCallableObjectWithBadCall(self):
1172 """Test verifying calls to a callable object works."""
1173 mock_obj = self.mox.CreateMock(CallableClass)
1174 mock_obj("foo").AndReturn("qux")
1175 self.mox.ReplayAll()
1177 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, "ZOOBAZ")
1179 def testCallableObjectVerifiesSignature(self):
1180 mock_obj = self.mox.CreateMock(CallableClass)
1181 # Too many arguments
1182 self.assertRaises(AttributeError, mock_obj, "foo", "bar")
1184 def testUnorderedGroup(self):
1185 """Test that using one unordered group works."""
1186 mock_obj = self.mox.CreateMockAnything()
1187 mock_obj.Method(1).InAnyOrder()
1188 mock_obj.Method(2).InAnyOrder()
1189 self.mox.ReplayAll()
1191 mock_obj.Method(2)
1192 mock_obj.Method(1)
1194 self.mox.VerifyAll()
1196 def testUnorderedGroupsInline(self):
1197 """Unordered groups should work in the context of ordered calls."""
1198 mock_obj = self.mox.CreateMockAnything()
1199 mock_obj.Open()
1200 mock_obj.Method(1).InAnyOrder()
1201 mock_obj.Method(2).InAnyOrder()
1202 mock_obj.Close()
1203 self.mox.ReplayAll()
1205 mock_obj.Open()
1206 mock_obj.Method(2)
1207 mock_obj.Method(1)
1208 mock_obj.Close()
1210 self.mox.VerifyAll()
1212 def testMultipleUnorderdGroups(self):
1213 """Multiple unoreded groups should work."""
1214 mock_obj = self.mox.CreateMockAnything()
1215 mock_obj.Method(1).InAnyOrder()
1216 mock_obj.Method(2).InAnyOrder()
1217 mock_obj.Foo().InAnyOrder('group2')
1218 mock_obj.Bar().InAnyOrder('group2')
1219 self.mox.ReplayAll()
1221 mock_obj.Method(2)
1222 mock_obj.Method(1)
1223 mock_obj.Bar()
1224 mock_obj.Foo()
1226 self.mox.VerifyAll()
1228 def testMultipleUnorderdGroupsOutOfOrder(self):
1229 """Multiple unordered groups should maintain external order"""
1230 mock_obj = self.mox.CreateMockAnything()
1231 mock_obj.Method(1).InAnyOrder()
1232 mock_obj.Method(2).InAnyOrder()
1233 mock_obj.Foo().InAnyOrder('group2')
1234 mock_obj.Bar().InAnyOrder('group2')
1235 self.mox.ReplayAll()
1237 mock_obj.Method(2)
1238 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar)
1240 def testUnorderedGroupWithReturnValue(self):
1241 """Unordered groups should work with return values."""
1242 mock_obj = self.mox.CreateMockAnything()
1243 mock_obj.Open()
1244 mock_obj.Method(1).InAnyOrder().AndReturn(9)
1245 mock_obj.Method(2).InAnyOrder().AndReturn(10)
1246 mock_obj.Close()
1247 self.mox.ReplayAll()
1249 mock_obj.Open()
1250 actual_two = mock_obj.Method(2)
1251 actual_one = mock_obj.Method(1)
1252 mock_obj.Close()
1254 self.assertEquals(9, actual_one)
1255 self.assertEquals(10, actual_two)
1257 self.mox.VerifyAll()
1259 def testUnorderedGroupWithComparator(self):
1260 """Unordered groups should work with comparators"""
1262 def VerifyOne(cmd):
1263 if not isinstance(cmd, str):
1264 self.fail('Unexpected type passed to comparator: ' + str(cmd))
1265 return cmd == 'test'
1267 def VerifyTwo(cmd):
1268 return True
1270 mock_obj = self.mox.CreateMockAnything()
1271 mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\
1272 AndReturn('yes test')
1273 mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\
1274 AndReturn('anything')
1276 self.mox.ReplayAll()
1278 mock_obj.Foo(['test'], 'anything', bar=1)
1279 mock_obj.Foo(['test'], 'test', bar=1)
1281 self.mox.VerifyAll()
1283 def testMultipleTimes(self):
1284 """Test if MultipleTimesGroup works."""
1285 mock_obj = self.mox.CreateMockAnything()
1286 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1287 mock_obj.Method(2).AndReturn(10)
1288 mock_obj.Method(3).MultipleTimes().AndReturn(42)
1289 self.mox.ReplayAll()
1291 actual_one = mock_obj.Method(1)
1292 second_one = mock_obj.Method(1) # This tests MultipleTimes.
1293 actual_two = mock_obj.Method(2)
1294 actual_three = mock_obj.Method(3)
1295 mock_obj.Method(3)
1296 mock_obj.Method(3)
1298 self.mox.VerifyAll()
1300 self.assertEquals(9, actual_one)
1301 self.assertEquals(9, second_one) # Repeated calls should return same number.
1302 self.assertEquals(10, actual_two)
1303 self.assertEquals(42, actual_three)
1305 def testMultipleTimesUsingIsAParameter(self):
1306 """Test if MultipleTimesGroup works with a IsA parameter."""
1307 mock_obj = self.mox.CreateMockAnything()
1308 mock_obj.Open()
1309 mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9)
1310 mock_obj.Close()
1311 self.mox.ReplayAll()
1313 mock_obj.Open()
1314 actual_one = mock_obj.Method("1")
1315 second_one = mock_obj.Method("2") # This tests MultipleTimes.
1316 mock_obj.Close()
1318 self.mox.VerifyAll()
1320 self.assertEquals(9, actual_one)
1321 self.assertEquals(9, second_one) # Repeated calls should return same number.
1323 def testMutlipleTimesUsingFunc(self):
1324 """Test that the Func is not evaluated more times than necessary.
1326 If a Func() has side effects, it can cause a passing test to fail.
1329 self.counter = 0
1330 def MyFunc(actual_str):
1331 """Increment the counter if actual_str == 'foo'."""
1332 if actual_str == 'foo':
1333 self.counter += 1
1334 return True
1336 mock_obj = self.mox.CreateMockAnything()
1337 mock_obj.Open()
1338 mock_obj.Method(mox.Func(MyFunc)).MultipleTimes()
1339 mock_obj.Close()
1340 self.mox.ReplayAll()
1342 mock_obj.Open()
1343 mock_obj.Method('foo')
1344 mock_obj.Method('foo')
1345 mock_obj.Method('not-foo')
1346 mock_obj.Close()
1348 self.mox.VerifyAll()
1350 self.assertEquals(2, self.counter)
1352 def testMultipleTimesThreeMethods(self):
1353 """Test if MultipleTimesGroup works with three or more methods."""
1354 mock_obj = self.mox.CreateMockAnything()
1355 mock_obj.Open()
1356 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1357 mock_obj.Method(2).MultipleTimes().AndReturn(8)
1358 mock_obj.Method(3).MultipleTimes().AndReturn(7)
1359 mock_obj.Method(4).AndReturn(10)
1360 mock_obj.Close()
1361 self.mox.ReplayAll()
1363 mock_obj.Open()
1364 actual_three = mock_obj.Method(3)
1365 mock_obj.Method(1)
1366 actual_two = mock_obj.Method(2)
1367 mock_obj.Method(3)
1368 actual_one = mock_obj.Method(1)
1369 actual_four = mock_obj.Method(4)
1370 mock_obj.Close()
1372 self.assertEquals(9, actual_one)
1373 self.assertEquals(8, actual_two)
1374 self.assertEquals(7, actual_three)
1375 self.assertEquals(10, actual_four)
1377 self.mox.VerifyAll()
1379 def testMultipleTimesMissingOne(self):
1380 """Test if MultipleTimesGroup fails if one method is missing."""
1381 mock_obj = self.mox.CreateMockAnything()
1382 mock_obj.Open()
1383 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1384 mock_obj.Method(2).MultipleTimes().AndReturn(8)
1385 mock_obj.Method(3).MultipleTimes().AndReturn(7)
1386 mock_obj.Method(4).AndReturn(10)
1387 mock_obj.Close()
1388 self.mox.ReplayAll()
1390 mock_obj.Open()
1391 mock_obj.Method(3)
1392 mock_obj.Method(2)
1393 mock_obj.Method(3)
1394 mock_obj.Method(3)
1395 mock_obj.Method(2)
1397 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4)
1399 def testMultipleTimesTwoGroups(self):
1400 """Test if MultipleTimesGroup works with a group after a
1401 MultipleTimesGroup.
1403 mock_obj = self.mox.CreateMockAnything()
1404 mock_obj.Open()
1405 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1406 mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1407 mock_obj.Close()
1408 self.mox.ReplayAll()
1410 mock_obj.Open()
1411 actual_one = mock_obj.Method(1)
1412 mock_obj.Method(1)
1413 actual_three = mock_obj.Method(3)
1414 mock_obj.Method(3)
1415 mock_obj.Close()
1417 self.assertEquals(9, actual_one)
1418 self.assertEquals(42, actual_three)
1420 self.mox.VerifyAll()
1422 def testMultipleTimesTwoGroupsFailure(self):
1423 """Test if MultipleTimesGroup fails with a group after a
1424 MultipleTimesGroup.
1426 mock_obj = self.mox.CreateMockAnything()
1427 mock_obj.Open()
1428 mock_obj.Method(1).MultipleTimes().AndReturn(9)
1429 mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1430 mock_obj.Close()
1431 self.mox.ReplayAll()
1433 mock_obj.Open()
1434 actual_one = mock_obj.Method(1)
1435 mock_obj.Method(1)
1436 actual_three = mock_obj.Method(3)
1438 self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1)
1440 def testWithSideEffects(self):
1441 """Test side effect operations actually modify their target objects."""
1442 def modifier(mutable_list):
1443 mutable_list[0] = 'mutated'
1444 mock_obj = self.mox.CreateMockAnything()
1445 mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier)
1446 mock_obj.WorkWithParameter(['mutated'])
1447 self.mox.ReplayAll()
1449 local_list = ['original']
1450 mock_obj.ConfigureInOutParameter(local_list)
1451 mock_obj.WorkWithParameter(local_list)
1453 self.mox.VerifyAll()
1455 def testWithSideEffectsException(self):
1456 """Test side effect operations actually modify their target objects."""
1457 def modifier(mutable_list):
1458 mutable_list[0] = 'mutated'
1459 mock_obj = self.mox.CreateMockAnything()
1460 method = mock_obj.ConfigureInOutParameter(['original'])
1461 method.WithSideEffects(modifier).AndRaise(Exception('exception'))
1462 mock_obj.WorkWithParameter(['mutated'])
1463 self.mox.ReplayAll()
1465 local_list = ['original']
1466 self.failUnlessRaises(Exception,
1467 mock_obj.ConfigureInOutParameter,
1468 local_list)
1469 mock_obj.WorkWithParameter(local_list)
1471 self.mox.VerifyAll()
1473 def testStubOutMethod(self):
1474 """Test that a method is replaced with a MockAnything."""
1475 test_obj = TestClass()
1476 # Replace OtherValidCall with a mock.
1477 self.mox.StubOutWithMock(test_obj, 'OtherValidCall')
1478 self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything))
1479 test_obj.OtherValidCall().AndReturn('foo')
1480 self.mox.ReplayAll()
1482 actual = test_obj.OtherValidCall()
1484 self.mox.VerifyAll()
1485 self.mox.UnsetStubs()
1486 self.assertEquals('foo', actual)
1487 self.failIf(isinstance(test_obj.OtherValidCall, mox.MockAnything))
1489 def testStubOutClass_OldStyle(self):
1490 """Test a mocked class whose __init__ returns a Mock."""
1491 self.mox.StubOutWithMock(mox_test_helper, 'TestClassFromAnotherModule')
1492 self.assert_(isinstance(mox_test_helper.TestClassFromAnotherModule,
1493 mox.MockObject))
1495 mock_instance = self.mox.CreateMock(
1496 mox_test_helper.TestClassFromAnotherModule)
1497 mox_test_helper.TestClassFromAnotherModule().AndReturn(mock_instance)
1498 mock_instance.Value().AndReturn('mock instance')
1500 self.mox.ReplayAll()
1502 a_mock = mox_test_helper.TestClassFromAnotherModule()
1503 actual = a_mock.Value()
1505 self.mox.VerifyAll()
1506 self.mox.UnsetStubs()
1507 self.assertEquals('mock instance', actual)
1509 def testStubOutClass(self):
1510 self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1512 # Instance one
1513 mock_one = mox_test_helper.CallableClass(1, 2)
1514 mock_one.Value().AndReturn('mock')
1516 # Instance two
1517 mock_two = mox_test_helper.CallableClass(8, 9)
1518 mock_two('one').AndReturn('called mock')
1520 self.mox.ReplayAll()
1522 one = mox_test_helper.CallableClass(1, 2)
1523 actual_one = one.Value()
1525 two = mox_test_helper.CallableClass(8, 9)
1526 actual_two = two('one')
1528 self.mox.VerifyAll()
1529 self.mox.UnsetStubs()
1531 # Verify the correct mocks were returned
1532 self.assertEquals(mock_one, one)
1533 self.assertEquals(mock_two, two)
1535 # Verify
1536 self.assertEquals('mock', actual_one)
1537 self.assertEquals('called mock', actual_two)
1539 def testStubOutClass_NotAClass(self):
1540 self.assertRaises(TypeError, self.mox.StubOutClassWithMocks,
1541 mox_test_helper, 'MyTestFunction')
1543 def testStubOutClassNotEnoughCreated(self):
1544 self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1546 mox_test_helper.CallableClass(1, 2)
1547 mox_test_helper.CallableClass(8, 9)
1549 self.mox.ReplayAll()
1550 mox_test_helper.CallableClass(1, 2)
1552 self.assertRaises(mox.ExpectedMockCreationError, self.mox.VerifyAll)
1553 self.mox.UnsetStubs()
1555 def testStubOutClassWrongSignature(self):
1556 self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1558 self.assertRaises(AttributeError, mox_test_helper.CallableClass)
1560 self.mox.UnsetStubs()
1562 def testStubOutClassWrongParameters(self):
1563 self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1565 mox_test_helper.CallableClass(1, 2)
1567 self.mox.ReplayAll()
1569 self.assertRaises(mox.UnexpectedMethodCallError,
1570 mox_test_helper.CallableClass, 8, 9)
1571 self.mox.UnsetStubs()
1573 def testStubOutClassTooManyCreated(self):
1574 self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1576 mox_test_helper.CallableClass(1, 2)
1578 self.mox.ReplayAll()
1579 mox_test_helper.CallableClass(1, 2)
1580 self.assertRaises(mox.UnexpectedMockCreationError,
1581 mox_test_helper.CallableClass, 8, 9)
1583 self.mox.UnsetStubs()
1585 def testWarnsUserIfMockingMock(self):
1586 """Test that user is warned if they try to stub out a MockAnything."""
1587 self.mox.StubOutWithMock(TestClass, 'MyStaticMethod')
1588 self.assertRaises(TypeError, self.mox.StubOutWithMock, TestClass,
1589 'MyStaticMethod')
1591 def testStubOutFirstClassMethodVerifiesSignature(self):
1592 self.mox.StubOutWithMock(mox_test_helper, 'MyTestFunction')
1594 # Wrong number of arguments
1595 self.assertRaises(AttributeError, mox_test_helper.MyTestFunction, 1)
1596 self.mox.UnsetStubs()
1598 def testStubOutObject(self):
1599 """Test than object is replaced with a Mock."""
1601 class Foo(object):
1602 def __init__(self):
1603 self.obj = TestClass()
1605 foo = Foo()
1606 self.mox.StubOutWithMock(foo, "obj")
1607 self.assert_(isinstance(foo.obj, mox.MockObject))
1608 foo.obj.ValidCall()
1609 self.mox.ReplayAll()
1611 foo.obj.ValidCall()
1613 self.mox.VerifyAll()
1614 self.mox.UnsetStubs()
1615 self.failIf(isinstance(foo.obj, mox.MockObject))
1617 def testForgotReplayHelpfulMessage(self):
1618 """If there is an AttributeError on a MockMethod, give users a helpful msg.
1620 foo = self.mox.CreateMockAnything()
1621 bar = self.mox.CreateMockAnything()
1622 foo.GetBar().AndReturn(bar)
1623 bar.ShowMeTheMoney()
1624 # Forgot to replay!
1625 try:
1626 foo.GetBar().ShowMeTheMoney()
1627 except AttributeError, e:
1628 self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". '
1629 'Did you remember to put your mocks in replay mode?', str(e))
1632 class ReplayTest(unittest.TestCase):
1633 """Verify Replay works properly."""
1635 def testReplay(self):
1636 """Replay should put objects into replay mode."""
1637 mock_obj = mox.MockObject(TestClass)
1638 self.assertFalse(mock_obj._replay_mode)
1639 mox.Replay(mock_obj)
1640 self.assertTrue(mock_obj._replay_mode)
1643 class MoxTestBaseTest(unittest.TestCase):
1644 """Verify that all tests in a class derived from MoxTestBase are wrapped."""
1646 def setUp(self):
1647 self.mox = mox.Mox()
1648 self.test_mox = mox.Mox()
1649 self.test_stubs = mox.stubout.StubOutForTesting()
1650 self.result = unittest.TestResult()
1652 def tearDown(self):
1653 self.mox.UnsetStubs()
1654 self.test_mox.UnsetStubs()
1655 self.test_stubs.UnsetAll()
1656 self.test_stubs.SmartUnsetAll()
1658 def _setUpTestClass(self):
1659 """Replacement for setUp in the test class instance.
1661 Assigns a mox.Mox instance as the mox attribute of the test class instance.
1662 This replacement Mox instance is under our control before setUp is called
1663 in the test class instance.
1665 self.test.mox = self.test_mox
1666 self.test.stubs = self.test_stubs
1668 def _CreateTest(self, test_name):
1669 """Create a test from our example mox class.
1671 The created test instance is assigned to this instances test attribute.
1673 self.test = mox_test_helper.ExampleMoxTest(test_name)
1674 self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass)
1676 def _VerifySuccess(self):
1677 """Run the checks to confirm test method completed successfully."""
1678 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1679 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1680 self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1681 self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1682 self.test_mox.UnsetStubs()
1683 self.test_mox.VerifyAll()
1684 self.test_stubs.UnsetAll()
1685 self.test_stubs.SmartUnsetAll()
1686 self.mox.ReplayAll()
1687 self.test.run(result=self.result)
1688 self.assertTrue(self.result.wasSuccessful())
1689 self.mox.VerifyAll()
1690 self.mox.UnsetStubs() # Needed to call the real VerifyAll() below.
1691 self.test_mox.VerifyAll()
1693 def testSuccess(self):
1694 """Successful test method execution test."""
1695 self._CreateTest('testSuccess')
1696 self._VerifySuccess()
1698 def testSuccessNoMocks(self):
1699 """Let testSuccess() unset all the mocks, and verify they've been unset."""
1700 self._CreateTest('testSuccess')
1701 self.test.run(result=self.result)
1702 self.assertTrue(self.result.wasSuccessful())
1703 self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1705 def testStubs(self):
1706 """Test that "self.stubs" is provided as is useful."""
1707 self._CreateTest('testHasStubs')
1708 self._VerifySuccess()
1710 def testStubsNoMocks(self):
1711 """Let testHasStubs() unset the stubs by itself."""
1712 self._CreateTest('testHasStubs')
1713 self.test.run(result=self.result)
1714 self.assertTrue(self.result.wasSuccessful())
1715 self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1717 def testExpectedNotCalled(self):
1718 """Stubbed out method is not called."""
1719 self._CreateTest('testExpectedNotCalled')
1720 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1721 self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1722 self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1723 # Don't stub out VerifyAll - that's what causes the test to fail
1724 self.test_mox.UnsetStubs()
1725 self.test_stubs.UnsetAll()
1726 self.test_stubs.SmartUnsetAll()
1727 self.mox.ReplayAll()
1728 self.test.run(result=self.result)
1729 self.failIf(self.result.wasSuccessful())
1730 self.mox.VerifyAll()
1732 def testExpectedNotCalledNoMocks(self):
1733 """Let testExpectedNotCalled() unset all the mocks by itself."""
1734 self._CreateTest('testExpectedNotCalled')
1735 self.test.run(result=self.result)
1736 self.failIf(self.result.wasSuccessful())
1737 self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1739 def testUnexpectedCall(self):
1740 """Stubbed out method is called with unexpected arguments."""
1741 self._CreateTest('testUnexpectedCall')
1742 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1743 self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1744 self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1745 # Ensure no calls are made to VerifyAll()
1746 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1747 self.test_mox.UnsetStubs()
1748 self.test_stubs.UnsetAll()
1749 self.test_stubs.SmartUnsetAll()
1750 self.mox.ReplayAll()
1751 self.test.run(result=self.result)
1752 self.failIf(self.result.wasSuccessful())
1753 self.mox.VerifyAll()
1755 def testFailure(self):
1756 """Failing assertion in test method."""
1757 self._CreateTest('testFailure')
1758 self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1759 self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1760 self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1761 # Ensure no calls are made to VerifyAll()
1762 self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1763 self.test_mox.UnsetStubs()
1764 self.test_stubs.UnsetAll()
1765 self.test_stubs.SmartUnsetAll()
1766 self.mox.ReplayAll()
1767 self.test.run(result=self.result)
1768 self.failIf(self.result.wasSuccessful())
1769 self.mox.VerifyAll()
1771 def testMixin(self):
1772 """Run test from mix-in test class, ensure it passes."""
1773 self._CreateTest('testStat')
1774 self._VerifySuccess()
1776 def testMixinAgain(self):
1777 """Run same test as above but from the current test class.
1779 This ensures metaclass properly wrapped test methods from all base classes.
1780 If unsetting of stubs doesn't happen, this will fail.
1782 self._CreateTest('testStatOther')
1783 self._VerifySuccess()
1786 class VerifyTest(unittest.TestCase):
1787 """Verify Verify works properly."""
1789 def testVerify(self):
1790 """Verify should be called for all objects.
1792 This should throw an exception because the expected behavior did not occur.
1794 mock_obj = mox.MockObject(TestClass)
1795 mock_obj.ValidCall()
1796 mock_obj._Replay()
1797 self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
1800 class ResetTest(unittest.TestCase):
1801 """Verify Reset works properly."""
1803 def testReset(self):
1804 """Should empty all queues and put mocks in record mode."""
1805 mock_obj = mox.MockObject(TestClass)
1806 mock_obj.ValidCall()
1807 self.assertFalse(mock_obj._replay_mode)
1808 mock_obj._Replay()
1809 self.assertTrue(mock_obj._replay_mode)
1810 self.assertEquals(1, len(mock_obj._expected_calls_queue))
1812 mox.Reset(mock_obj)
1813 self.assertFalse(mock_obj._replay_mode)
1814 self.assertEquals(0, len(mock_obj._expected_calls_queue))
1817 class MyTestCase(unittest.TestCase):
1818 """Simulate the use of a fake wrapper around Python's unittest library."""
1820 def setUp(self):
1821 super(MyTestCase, self).setUp()
1822 self.critical_variable = 42
1823 self.another_critical_variable = 42
1825 def testMethodOverride(self):
1826 """Should be properly overriden in a derived class."""
1827 self.assertEquals(42, self.another_critical_variable)
1828 self.another_critical_variable += 1
1831 class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase):
1832 """Test that multiple inheritance can be used with MoxTestBase."""
1834 def setUp(self):
1835 super(MoxTestBaseMultipleInheritanceTest, self).setUp()
1836 self.another_critical_variable = 99
1838 def testMultipleInheritance(self):
1839 """Should be able to access members created by all parent setUp()."""
1840 self.assert_(isinstance(self.mox, mox.Mox))
1841 self.assertEquals(42, self.critical_variable)
1843 def testMethodOverride(self):
1844 """Should run before MyTestCase.testMethodOverride."""
1845 self.assertEquals(99, self.another_critical_variable)
1846 self.another_critical_variable = 42
1847 super(MoxTestBaseMultipleInheritanceTest, self).testMethodOverride()
1848 self.assertEquals(43, self.another_critical_variable)
1850 class MoxTestDontMockProperties(MoxTestBaseTest):
1851 def testPropertiesArentMocked(self):
1852 mock_class = self.mox.CreateMock(ClassWithProperties)
1853 self.assertRaises(mox.UnknownMethodCallError, lambda:
1854 mock_class.prop_attr)
1857 class TestClass:
1858 """This class is used only for testing the mock framework"""
1860 SOME_CLASS_VAR = "test_value"
1861 _PROTECTED_CLASS_VAR = "protected value"
1863 def __init__(self, ivar=None):
1864 self.__ivar = ivar
1866 def __eq__(self, rhs):
1867 return self.__ivar == rhs
1869 def __ne__(self, rhs):
1870 return not self.__eq__(rhs)
1872 def ValidCall(self):
1873 pass
1875 def MethodWithArgs(self, one, two, nine=None):
1876 pass
1878 def OtherValidCall(self):
1879 pass
1881 def ValidCallWithArgs(self, *args, **kwargs):
1882 pass
1884 @classmethod
1885 def MyClassMethod(cls):
1886 pass
1888 @staticmethod
1889 def MyStaticMethod():
1890 pass
1892 def _ProtectedCall(self):
1893 pass
1895 def __PrivateCall(self):
1896 pass
1898 def __getitem__(self, key):
1899 pass
1901 def __DoNotMock(self):
1902 pass
1904 def __getitem__(self, key):
1905 """Return the value for key."""
1906 return self.d[key]
1908 def __setitem__(self, key, value):
1909 """Set the value for key to value."""
1910 self.d[key] = value
1912 def __contains__(self, key):
1913 """Returns True if d contains the key."""
1914 return key in self.d
1916 def __iter__(self):
1917 pass
1920 class ChildClass(TestClass):
1921 """This inherits from TestClass."""
1922 def __init__(self):
1923 TestClass.__init__(self)
1925 def ChildValidCall(self):
1926 pass
1929 class CallableClass(object):
1930 """This class is callable, and that should be mockable!"""
1932 def __init__(self):
1933 pass
1935 def __call__(self, param):
1936 return param
1938 class ClassWithProperties(object):
1939 def setter_attr(self, value):
1940 pass
1942 def getter_attr(self):
1943 pass
1945 prop_attr = property(getter_attr, setter_attr)
1948 class SubscribtableNonIterableClass(object):
1949 def __getitem__(self, index):
1950 raise IndexError
1953 class InheritsFromCallable(CallableClass):
1954 """This class should also be mockable; it inherits from a callable class."""
1956 pass
1959 if __name__ == '__main__':
1960 unittest.main()