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.
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])
40
"Verify: Expected methods never called:\n"
41
" 0. testMethod(1, 2) -> 'output'",
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])
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'",
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.
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.
156
"""Create an object to test with."""
159
class TestObject(object):
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 testEquailtyInListInvalid(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."""
328
self.expected_method = mox.MockMethod("testMethod", [], False)(['original'])
329
self.mock_method = mox.MockMethod("testMethod", [self.expected_method],
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(
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."""
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"""
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)
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."""
487
self.mock_object = mox.MockAnything()
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()
539
def testNotNone(self):
540
"""Mock should be comparable to None."""
541
self.mock_object._Replay()
542
if self.mock_object is not None:
545
if self.mock_object is None:
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)
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)
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)
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)
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)
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)
678
method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args)
679
self.assertRaises(AttributeError, method)
680
self.assertRaises(AttributeError, method, 1)
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)
695
self.assertRaises(AttributeError, method, 1, 2, 3)
696
self.assertRaises(AttributeError, method, 1, 2, a=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)
712
self.assertRaises(AttributeError, method, 1, a=2)
714
method(c=3, b=2, a=1)
718
class CheckCallTestClass(object):
719
def NoParameters(self):
722
def OneParameter(self, a):
725
def TwoParameters(self, a, b):
728
def OneDefaultValue(self, a=1):
731
def TwoDefaultValues(self, a, b, c=1, d=2):
734
def Args(self, a, b, *args):
737
def Kwargs(self, a, b=2, **kwargs):
740
def ArgsAndKwargs(self, a, *args, **kwargs):
744
class MockObjectTest(unittest.TestCase):
745
"""Verify that the MockObject class works as exepcted."""
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
761
self.mock_object.InvalidCall()
762
self.fail("No exception thrown, expected UnknownMethodCallError")
763
except mox.UnknownMethodCallError:
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
776
self.mock_object.InvalidCall()
777
self.fail("No exception thrown, expected UnknownMethodCallError")
778
except mox.UnknownMethodCallError:
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)
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)
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'
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'
880
# NOT doing dummy['X'] = 'Y'
884
def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self):
885
"""Test that __setitem__() fails if other parameters are expected."""
886
dummy = mox.MockObject(TestClass)
891
def call(): dummy['wrong'] = 'Y'
893
self.assertRaises(mox.UnexpectedMethodCallError, call)
897
def testMockSetItem_WithSubClassOfNewStyleClass(self):
898
class NewStyleTestClass(object):
902
def __setitem__(self, key, value):
903
self.my_dict[key], value
905
class TestSubClass(NewStyleTestClass):
908
dummy = mox.MockObject(TestSubClass)
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')
924
self.assertEqual(dummy['X'], 'value')
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')
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']
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')
959
def call(): return dummy['wrong']
961
self.assertRaises(mox.UnexpectedMethodCallError, call)
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):
973
dummy = mox.MockObject(TestSubClass)
974
dummy[1].AndReturn('3')
977
self.assertEquals('3', dummy.__getitem__(1))
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']))
990
self.assertEqual([x for x in dummy], ['X', 'Y'])
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)
1004
self.failUnless('X' in dummy)
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')
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)
1029
def call(): return 'Y' in dummy
1031
self.assertRaises(mox.UnexpectedMethodCallError, call)
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']))
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)
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)
1067
self.assertEquals(['a', 'b'], [x for x in dummy])
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]
1076
function = lambda: [x for x in dummy]
1077
self.assertRaises(mox.UnexpectedMethodCallError, function)
1079
def testMockGetIter_WithSubClassOfNewStyleClass(self):
1080
class NewStyleTestClass(object):
1082
return iter([1, 2, 3])
1084
class TestSubClass(NewStyleTestClass):
1087
dummy = mox.MockObject(TestSubClass)
1088
iter(dummy).AndReturn(iter(['a', 'b']))
1090
self.assertEquals(['a', 'b'], [x for x in dummy])
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."""
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 testUnorderedGroup(self):
1180
"""Test that using one unordered group works."""
1181
mock_obj = self.mox.CreateMockAnything()
1182
mock_obj.Method(1).InAnyOrder()
1183
mock_obj.Method(2).InAnyOrder()
1184
self.mox.ReplayAll()
1189
self.mox.VerifyAll()
1191
def testUnorderedGroupsInline(self):
1192
"""Unordered groups should work in the context of ordered calls."""
1193
mock_obj = self.mox.CreateMockAnything()
1195
mock_obj.Method(1).InAnyOrder()
1196
mock_obj.Method(2).InAnyOrder()
1198
self.mox.ReplayAll()
1205
self.mox.VerifyAll()
1207
def testMultipleUnorderdGroups(self):
1208
"""Multiple unoreded groups should work."""
1209
mock_obj = self.mox.CreateMockAnything()
1210
mock_obj.Method(1).InAnyOrder()
1211
mock_obj.Method(2).InAnyOrder()
1212
mock_obj.Foo().InAnyOrder('group2')
1213
mock_obj.Bar().InAnyOrder('group2')
1214
self.mox.ReplayAll()
1221
self.mox.VerifyAll()
1223
def testMultipleUnorderdGroupsOutOfOrder(self):
1224
"""Multiple unordered groups should maintain external order"""
1225
mock_obj = self.mox.CreateMockAnything()
1226
mock_obj.Method(1).InAnyOrder()
1227
mock_obj.Method(2).InAnyOrder()
1228
mock_obj.Foo().InAnyOrder('group2')
1229
mock_obj.Bar().InAnyOrder('group2')
1230
self.mox.ReplayAll()
1233
self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar)
1235
def testUnorderedGroupWithReturnValue(self):
1236
"""Unordered groups should work with return values."""
1237
mock_obj = self.mox.CreateMockAnything()
1239
mock_obj.Method(1).InAnyOrder().AndReturn(9)
1240
mock_obj.Method(2).InAnyOrder().AndReturn(10)
1242
self.mox.ReplayAll()
1245
actual_two = mock_obj.Method(2)
1246
actual_one = mock_obj.Method(1)
1249
self.assertEquals(9, actual_one)
1250
self.assertEquals(10, actual_two)
1252
self.mox.VerifyAll()
1254
def testUnorderedGroupWithComparator(self):
1255
"""Unordered groups should work with comparators"""
1258
if not isinstance(cmd, str):
1259
self.fail('Unexpected type passed to comparator: ' + str(cmd))
1260
return cmd == 'test'
1265
mock_obj = self.mox.CreateMockAnything()
1266
mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\
1267
AndReturn('yes test')
1268
mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\
1269
AndReturn('anything')
1271
self.mox.ReplayAll()
1273
mock_obj.Foo(['test'], 'anything', bar=1)
1274
mock_obj.Foo(['test'], 'test', bar=1)
1276
self.mox.VerifyAll()
1278
def testMultipleTimes(self):
1279
"""Test if MultipleTimesGroup works."""
1280
mock_obj = self.mox.CreateMockAnything()
1281
mock_obj.Method(1).MultipleTimes().AndReturn(9)
1282
mock_obj.Method(2).AndReturn(10)
1283
mock_obj.Method(3).MultipleTimes().AndReturn(42)
1284
self.mox.ReplayAll()
1286
actual_one = mock_obj.Method(1)
1287
second_one = mock_obj.Method(1) # This tests MultipleTimes.
1288
actual_two = mock_obj.Method(2)
1289
actual_three = mock_obj.Method(3)
1293
self.mox.VerifyAll()
1295
self.assertEquals(9, actual_one)
1296
self.assertEquals(9, second_one) # Repeated calls should return same number.
1297
self.assertEquals(10, actual_two)
1298
self.assertEquals(42, actual_three)
1300
def testMultipleTimesUsingIsAParameter(self):
1301
"""Test if MultipleTimesGroup works with a IsA parameter."""
1302
mock_obj = self.mox.CreateMockAnything()
1304
mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9)
1306
self.mox.ReplayAll()
1309
actual_one = mock_obj.Method("1")
1310
second_one = mock_obj.Method("2") # This tests MultipleTimes.
1313
self.mox.VerifyAll()
1315
self.assertEquals(9, actual_one)
1316
self.assertEquals(9, second_one) # Repeated calls should return same number.
1318
def testMutlipleTimesUsingFunc(self):
1319
"""Test that the Func is not evaluated more times than necessary.
1321
If a Func() has side effects, it can cause a passing test to fail.
1325
def MyFunc(actual_str):
1326
"""Increment the counter if actual_str == 'foo'."""
1327
if actual_str == 'foo':
1331
mock_obj = self.mox.CreateMockAnything()
1333
mock_obj.Method(mox.Func(MyFunc)).MultipleTimes()
1335
self.mox.ReplayAll()
1338
mock_obj.Method('foo')
1339
mock_obj.Method('foo')
1340
mock_obj.Method('not-foo')
1343
self.mox.VerifyAll()
1345
self.assertEquals(2, self.counter)
1347
def testMultipleTimesThreeMethods(self):
1348
"""Test if MultipleTimesGroup works with three or more methods."""
1349
mock_obj = self.mox.CreateMockAnything()
1351
mock_obj.Method(1).MultipleTimes().AndReturn(9)
1352
mock_obj.Method(2).MultipleTimes().AndReturn(8)
1353
mock_obj.Method(3).MultipleTimes().AndReturn(7)
1354
mock_obj.Method(4).AndReturn(10)
1356
self.mox.ReplayAll()
1359
actual_three = mock_obj.Method(3)
1361
actual_two = mock_obj.Method(2)
1363
actual_one = mock_obj.Method(1)
1364
actual_four = mock_obj.Method(4)
1367
self.assertEquals(9, actual_one)
1368
self.assertEquals(8, actual_two)
1369
self.assertEquals(7, actual_three)
1370
self.assertEquals(10, actual_four)
1372
self.mox.VerifyAll()
1374
def testMultipleTimesMissingOne(self):
1375
"""Test if MultipleTimesGroup fails if one method is missing."""
1376
mock_obj = self.mox.CreateMockAnything()
1378
mock_obj.Method(1).MultipleTimes().AndReturn(9)
1379
mock_obj.Method(2).MultipleTimes().AndReturn(8)
1380
mock_obj.Method(3).MultipleTimes().AndReturn(7)
1381
mock_obj.Method(4).AndReturn(10)
1383
self.mox.ReplayAll()
1392
self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4)
1394
def testMultipleTimesTwoGroups(self):
1395
"""Test if MultipleTimesGroup works with a group after a
1398
mock_obj = self.mox.CreateMockAnything()
1400
mock_obj.Method(1).MultipleTimes().AndReturn(9)
1401
mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1403
self.mox.ReplayAll()
1406
actual_one = mock_obj.Method(1)
1408
actual_three = mock_obj.Method(3)
1412
self.assertEquals(9, actual_one)
1413
self.assertEquals(42, actual_three)
1415
self.mox.VerifyAll()
1417
def testMultipleTimesTwoGroupsFailure(self):
1418
"""Test if MultipleTimesGroup fails with a group after a
1421
mock_obj = self.mox.CreateMockAnything()
1423
mock_obj.Method(1).MultipleTimes().AndReturn(9)
1424
mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1426
self.mox.ReplayAll()
1429
actual_one = mock_obj.Method(1)
1431
actual_three = mock_obj.Method(3)
1433
self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1)
1435
def testWithSideEffects(self):
1436
"""Test side effect operations actually modify their target objects."""
1437
def modifier(mutable_list):
1438
mutable_list[0] = 'mutated'
1439
mock_obj = self.mox.CreateMockAnything()
1440
mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier)
1441
mock_obj.WorkWithParameter(['mutated'])
1442
self.mox.ReplayAll()
1444
local_list = ['original']
1445
mock_obj.ConfigureInOutParameter(local_list)
1446
mock_obj.WorkWithParameter(local_list)
1448
self.mox.VerifyAll()
1450
def testWithSideEffectsException(self):
1451
"""Test side effect operations actually modify their target objects."""
1452
def modifier(mutable_list):
1453
mutable_list[0] = 'mutated'
1454
mock_obj = self.mox.CreateMockAnything()
1455
method = mock_obj.ConfigureInOutParameter(['original'])
1456
method.WithSideEffects(modifier).AndRaise(Exception('exception'))
1457
mock_obj.WorkWithParameter(['mutated'])
1458
self.mox.ReplayAll()
1460
local_list = ['original']
1461
self.failUnlessRaises(Exception,
1462
mock_obj.ConfigureInOutParameter,
1464
mock_obj.WorkWithParameter(local_list)
1466
self.mox.VerifyAll()
1468
def testStubOutMethod(self):
1469
"""Test that a method is replaced with a MockAnything."""
1470
test_obj = TestClass()
1471
# Replace OtherValidCall with a mock.
1472
self.mox.StubOutWithMock(test_obj, 'OtherValidCall')
1473
self.assert_(isinstance(test_obj.OtherValidCall, mox.MockAnything))
1474
test_obj.OtherValidCall().AndReturn('foo')
1475
self.mox.ReplayAll()
1477
actual = test_obj.OtherValidCall()
1479
self.mox.VerifyAll()
1480
self.mox.UnsetStubs()
1481
self.assertEquals('foo', actual)
1482
self.failIf(isinstance(test_obj.OtherValidCall, mox.MockAnything))
1484
def testStubOutClass(self):
1485
"""Test a mocked class whose __init__ returns a Mock."""
1486
self.mox.StubOutWithMock(mox_test_helper, 'TestClassFromAnotherModule')
1487
self.assert_(isinstance(mox_test_helper.TestClassFromAnotherModule,
1490
mock_instance = self.mox.CreateMock(
1491
mox_test_helper.TestClassFromAnotherModule)
1492
mox_test_helper.TestClassFromAnotherModule().AndReturn(mock_instance)
1493
mock_instance.Value().AndReturn('mock instance')
1495
self.mox.ReplayAll()
1497
a_mock = mox_test_helper.TestClassFromAnotherModule()
1498
actual = a_mock.Value()
1500
self.mox.VerifyAll()
1501
self.mox.UnsetStubs()
1502
self.assertEquals('mock instance', actual)
1504
def testWarnsUserIfMockingMock(self):
1505
"""Test that user is warned if they try to stub out a MockAnything."""
1506
self.mox.StubOutWithMock(TestClass, 'MyStaticMethod')
1507
self.assertRaises(TypeError, self.mox.StubOutWithMock, TestClass,
1510
def testStubOutObject(self):
1511
"""Test than object is replaced with a Mock."""
1515
self.obj = TestClass()
1518
self.mox.StubOutWithMock(foo, "obj")
1519
self.assert_(isinstance(foo.obj, mox.MockObject))
1521
self.mox.ReplayAll()
1525
self.mox.VerifyAll()
1526
self.mox.UnsetStubs()
1527
self.failIf(isinstance(foo.obj, mox.MockObject))
1529
def testForgotReplayHelpfulMessage(self):
1530
"""If there is an AttributeError on a MockMethod, give users a helpful msg.
1532
foo = self.mox.CreateMockAnything()
1533
bar = self.mox.CreateMockAnything()
1534
foo.GetBar().AndReturn(bar)
1535
bar.ShowMeTheMoney()
1538
foo.GetBar().ShowMeTheMoney()
1539
except AttributeError, e:
1540
self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". '
1541
'Did you remember to put your mocks in replay mode?', str(e))
1544
class ReplayTest(unittest.TestCase):
1545
"""Verify Replay works properly."""
1547
def testReplay(self):
1548
"""Replay should put objects into replay mode."""
1549
mock_obj = mox.MockObject(TestClass)
1550
self.assertFalse(mock_obj._replay_mode)
1551
mox.Replay(mock_obj)
1552
self.assertTrue(mock_obj._replay_mode)
1555
class MoxTestBaseTest(unittest.TestCase):
1556
"""Verify that all tests in a class derived from MoxTestBase are wrapped."""
1559
self.mox = mox.Mox()
1560
self.test_mox = mox.Mox()
1561
self.test_stubs = mox.stubout.StubOutForTesting()
1562
self.result = unittest.TestResult()
1565
self.mox.UnsetStubs()
1566
self.test_mox.UnsetStubs()
1567
self.test_stubs.UnsetAll()
1568
self.test_stubs.SmartUnsetAll()
1570
def _setUpTestClass(self):
1571
"""Replacement for setUp in the test class instance.
1573
Assigns a mox.Mox instance as the mox attribute of the test class instance.
1574
This replacement Mox instance is under our control before setUp is called
1575
in the test class instance.
1577
self.test.mox = self.test_mox
1578
self.test.stubs = self.test_stubs
1580
def _CreateTest(self, test_name):
1581
"""Create a test from our example mox class.
1583
The created test instance is assigned to this instances test attribute.
1585
self.test = mox_test_helper.ExampleMoxTest(test_name)
1586
self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass)
1588
def _VerifySuccess(self):
1589
"""Run the checks to confirm test method completed successfully."""
1590
self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1591
self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1592
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1593
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1594
self.test_mox.UnsetStubs()
1595
self.test_mox.VerifyAll()
1596
self.test_stubs.UnsetAll()
1597
self.test_stubs.SmartUnsetAll()
1598
self.mox.ReplayAll()
1599
self.test.run(result=self.result)
1600
self.assertTrue(self.result.wasSuccessful())
1601
self.mox.VerifyAll()
1602
self.mox.UnsetStubs() # Needed to call the real VerifyAll() below.
1603
self.test_mox.VerifyAll()
1605
def testSuccess(self):
1606
"""Successful test method execution test."""
1607
self._CreateTest('testSuccess')
1608
self._VerifySuccess()
1610
def testSuccessNoMocks(self):
1611
"""Let testSuccess() unset all the mocks, and verify they've been unset."""
1612
self._CreateTest('testSuccess')
1613
self.test.run(result=self.result)
1614
self.assertTrue(self.result.wasSuccessful())
1615
self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1617
def testStubs(self):
1618
"""Test that "self.stubs" is provided as is useful."""
1619
self._CreateTest('testHasStubs')
1620
self._VerifySuccess()
1622
def testStubsNoMocks(self):
1623
"""Let testHasStubs() unset the stubs by itself."""
1624
self._CreateTest('testHasStubs')
1625
self.test.run(result=self.result)
1626
self.assertTrue(self.result.wasSuccessful())
1627
self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1629
def testExpectedNotCalled(self):
1630
"""Stubbed out method is not called."""
1631
self._CreateTest('testExpectedNotCalled')
1632
self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1633
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1634
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1635
# Don't stub out VerifyAll - that's what causes the test to fail
1636
self.test_mox.UnsetStubs()
1637
self.test_stubs.UnsetAll()
1638
self.test_stubs.SmartUnsetAll()
1639
self.mox.ReplayAll()
1640
self.test.run(result=self.result)
1641
self.failIf(self.result.wasSuccessful())
1642
self.mox.VerifyAll()
1644
def testExpectedNotCalledNoMocks(self):
1645
"""Let testExpectedNotCalled() unset all the mocks by itself."""
1646
self._CreateTest('testExpectedNotCalled')
1647
self.test.run(result=self.result)
1648
self.failIf(self.result.wasSuccessful())
1649
self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1651
def testUnexpectedCall(self):
1652
"""Stubbed out method is called with unexpected arguments."""
1653
self._CreateTest('testUnexpectedCall')
1654
self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1655
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1656
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1657
# Ensure no calls are made to VerifyAll()
1658
self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1659
self.test_mox.UnsetStubs()
1660
self.test_stubs.UnsetAll()
1661
self.test_stubs.SmartUnsetAll()
1662
self.mox.ReplayAll()
1663
self.test.run(result=self.result)
1664
self.failIf(self.result.wasSuccessful())
1665
self.mox.VerifyAll()
1667
def testFailure(self):
1668
"""Failing assertion in test method."""
1669
self._CreateTest('testFailure')
1670
self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1671
self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1672
self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1673
# Ensure no calls are made to VerifyAll()
1674
self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1675
self.test_mox.UnsetStubs()
1676
self.test_stubs.UnsetAll()
1677
self.test_stubs.SmartUnsetAll()
1678
self.mox.ReplayAll()
1679
self.test.run(result=self.result)
1680
self.failIf(self.result.wasSuccessful())
1681
self.mox.VerifyAll()
1683
def testMixin(self):
1684
"""Run test from mix-in test class, ensure it passes."""
1685
self._CreateTest('testStat')
1686
self._VerifySuccess()
1688
def testMixinAgain(self):
1689
"""Run same test as above but from the current test class.
1691
This ensures metaclass properly wrapped test methods from all base classes.
1692
If unsetting of stubs doesn't happen, this will fail.
1694
self._CreateTest('testStatOther')
1695
self._VerifySuccess()
1698
class VerifyTest(unittest.TestCase):
1699
"""Verify Verify works properly."""
1701
def testVerify(self):
1702
"""Verify should be called for all objects.
1704
This should throw an exception because the expected behavior did not occur.
1706
mock_obj = mox.MockObject(TestClass)
1707
mock_obj.ValidCall()
1709
self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
1712
class ResetTest(unittest.TestCase):
1713
"""Verify Reset works properly."""
1715
def testReset(self):
1716
"""Should empty all queues and put mocks in record mode."""
1717
mock_obj = mox.MockObject(TestClass)
1718
mock_obj.ValidCall()
1719
self.assertFalse(mock_obj._replay_mode)
1721
self.assertTrue(mock_obj._replay_mode)
1722
self.assertEquals(1, len(mock_obj._expected_calls_queue))
1725
self.assertFalse(mock_obj._replay_mode)
1726
self.assertEquals(0, len(mock_obj._expected_calls_queue))
1729
class MyTestCase(unittest.TestCase):
1730
"""Simulate the use of a fake wrapper around Python's unittest library."""
1733
super(MyTestCase, self).setUp()
1734
self.critical_variable = 42
1735
self.another_critical_variable = 42
1737
def testMethodOverride(self):
1738
"""Should be properly overriden in a derived class."""
1739
self.assertEquals(42, self.another_critical_variable)
1740
self.another_critical_variable += 1
1743
class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase):
1744
"""Test that multiple inheritance can be used with MoxTestBase."""
1747
super(MoxTestBaseMultipleInheritanceTest, self).setUp()
1748
self.another_critical_variable = 99
1750
def testMultipleInheritance(self):
1751
"""Should be able to access members created by all parent setUp()."""
1752
self.assert_(isinstance(self.mox, mox.Mox))
1753
self.assertEquals(42, self.critical_variable)
1755
def testMethodOverride(self):
1756
"""Should run before MyTestCase.testMethodOverride."""
1757
self.assertEquals(99, self.another_critical_variable)
1758
self.another_critical_variable = 42
1759
super(MoxTestBaseMultipleInheritanceTest, self).testMethodOverride()
1760
self.assertEquals(43, self.another_critical_variable)
1764
"""This class is used only for testing the mock framework"""
1766
SOME_CLASS_VAR = "test_value"
1767
_PROTECTED_CLASS_VAR = "protected value"
1769
def __init__(self, ivar=None):
1772
def __eq__(self, rhs):
1773
return self.__ivar == rhs
1775
def __ne__(self, rhs):
1776
return not self.__eq__(rhs)
1778
def ValidCall(self):
1781
def OtherValidCall(self):
1784
def ValidCallWithArgs(self, *args, **kwargs):
1788
def MyClassMethod(cls):
1792
def MyStaticMethod():
1795
def _ProtectedCall(self):
1798
def __PrivateCall(self):
1801
def __getitem__(self, key):
1804
def __DoNotMock(self):
1807
def __getitem__(self, key):
1808
"""Return the value for key."""
1811
def __setitem__(self, key, value):
1812
"""Set the value for key to value."""
1815
def __contains__(self, key):
1816
"""Returns True if d contains the key."""
1817
return key in self.d
1822
class ChildClass(TestClass):
1823
"""This inherits from TestClass."""
1825
TestClass.__init__(self)
1827
def ChildValidCall(self):
1831
class CallableClass(object):
1832
"""This class is callable, and that should be mockable!"""
1837
def __call__(self, param):
1841
class SubscribtableNonIterableClass(object):
1842
def __getitem__(self, index):
1846
class InheritsFromCallable(CallableClass):
1847
"""This class should also be mockable; it inherits from a callable class."""
1852
if __name__ == '__main__':