1#!/usr/bin/python2.4
2#
3# Unit tests for Mox.
4#
5# Copyright 2008 Google Inc.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11#      http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18
19import cStringIO
20import unittest
21import re
22
23import mox
24
25import mox_test_helper
26
27OS_LISTDIR = mox_test_helper.os.listdir
28
29class ExpectedMethodCallsErrorTest(unittest.TestCase):
30  """Test creation and string conversion of ExpectedMethodCallsError."""
31
32  def testAtLeastOneMethod(self):
33    self.assertRaises(ValueError, mox.ExpectedMethodCallsError, [])
34
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))
43
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))
61
62
63class OrTest(unittest.TestCase):
64  """Test Or correctly chains Comparators."""
65
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')
71
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)
75
76
77class AndTest(unittest.TestCase):
78  """Test And correctly chains Comparators."""
79
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')
83
84  def testClauseOneFails(self):
85    """And should be False if the first Comparator returns False."""
86
87    self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1')
88
89  def testAdvancedUsage(self):
90    """And should work with other Comparators.
91
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)
97
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)
103
104
105class SameElementsAsTest(unittest.TestCase):
106  """Test SameElementsAs correctly identifies sequences with same elements."""
107
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'])
111
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])
115
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}])
120
121  def testEmptyLists(self):
122    """Should return True for two empty lists."""
123    self.assert_(mox.SameElementsAs([]) == [])
124
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'])
128
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'}])
132
133
134class ContainsKeyValueTest(unittest.TestCase):
135  """Test ContainsKeyValue correctly identifies key/value pairs in a dict.
136  """
137
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})
141
142  def testInvalidValue(self):
143    """Should return False if the value is not correct."""
144    self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2})
145
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})
149
150
151class ContainsAttributeValueTest(unittest.TestCase):
152  """Test ContainsAttributeValue correctly identifies properties in an object.
153  """
154
155  def setUp(self):
156    """Create an object to test with."""
157
158
159    class TestObject(object):
160      key = 1
161
162    self.test_object = TestObject()
163
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)
167
168  def testInvalidValue(self):
169    """Should return False if the value is not correct."""
170    self.failIf(mox.ContainsKeyValue("key", 2) == self.test_object)
171
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)
175
176
177class InTest(unittest.TestCase):
178  """Test In correctly identifies a key in a list/dict"""
179
180  def testItemInList(self):
181    """Should return True if the item is in the list."""
182    self.assert_(mox.In(1) == [1, 2, 3])
183
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"})
187
188  def testItemInTuple(self):
189    """Should return True if the item is in the list."""
190    self.assert_(mox.In(1) == (1, 2, 3))
191
192  def testTupleInTupleOfTuples(self):
193    self.assert_(mox.In((1, 2, 3)) == ((1, 2, 3), (1, 2)))
194
195  def testItemNotInList(self):
196    self.failIf(mox.In(1) == [2, 3])
197
198  def testTupleNotInTupleOfTuples(self):
199    self.failIf(mox.In((1, 2)) == ((1, 2, 3), (4, 5)))
200
201
202class NotTest(unittest.TestCase):
203  """Test Not correctly identifies False predicates."""
204
205  def testItemInList(self):
206    """Should return True if the item is NOT in the list."""
207    self.assert_(mox.Not(mox.In(42)) == [1, 2, 3])
208
209  def testKeyInDict(self):
210    """Should return True if the item is NOT a key in a dict."""
211    self.assert_(mox.Not(mox.In("foo")) == {"key" : 42})
212
213  def testInvalidKeyWithNot(self):
214    """Should return False if they key is NOT in the dict."""
215    self.assert_(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2})
216
217
218class StrContainsTest(unittest.TestCase):
219  """Test StrContains correctly checks for substring occurrence of a parameter.
220  """
221
222  def testValidSubstringAtStart(self):
223    """Should return True if the substring is at the start of the string."""
224    self.assert_(mox.StrContains("hello") == "hello world")
225
226  def testValidSubstringInMiddle(self):
227    """Should return True if the substring is in the middle of the string."""
228    self.assert_(mox.StrContains("lo wo") == "hello world")
229
230  def testValidSubstringAtEnd(self):
231    """Should return True if the substring is at the end of the string."""
232    self.assert_(mox.StrContains("ld") == "hello world")
233
234  def testInvaildSubstring(self):
235    """Should return False if the substring is not in the string."""
236    self.failIf(mox.StrContains("AAA") == "hello world")
237
238  def testMultipleMatches(self):
239    """Should return True if there are multiple occurances of substring."""
240    self.assert_(mox.StrContains("abc") == "ababcabcabcababc")
241
242
243class RegexTest(unittest.TestCase):
244  """Test Regex correctly matches regular expressions."""
245
246  def testIdentifyBadSyntaxDuringInit(self):
247    """The user should know immediately if a regex has bad syntax."""
248    self.assertRaises(re.error, mox.Regex, '(a|b')
249
250  def testPatternInMiddle(self):
251    """Should return True if the pattern matches at the middle of the string.
252
253    This ensures that re.search is used (instead of re.find).
254    """
255    self.assert_(mox.Regex(r"a\s+b") == "x y z a b c")
256
257  def testNonMatchPattern(self):
258    """Should return False if the pattern does not match the string."""
259    self.failIf(mox.Regex(r"a\s+b") == "x y z")
260
261  def testFlagsPassedCorrectly(self):
262    """Should return True as we pass IGNORECASE flag."""
263    self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a")
264
265  def testReprWithoutFlags(self):
266    """repr should return the regular expression pattern."""
267    self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>")
268
269  def testReprWithFlags(self):
270    """repr should return the regular expression pattern and flags."""
271    self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) ==
272                 "<regular expression 'a\s+b', flags=4>")
273
274
275class IsTest(unittest.TestCase):
276  """Verify Is correctly checks equality based upon identity, not value"""
277
278  class AlwaysComparesTrue(object):
279    def __eq__(self, other):
280      return True
281    def __cmp__(self, other):
282      return 0
283    def __ne__(self, other):
284      return False
285
286  def testEqualityValid(self):
287    o1 = self.AlwaysComparesTrue()
288    self.assertTrue(mox.Is(o1), o1)
289
290  def testEqualityInvalid(self):
291    o1 = self.AlwaysComparesTrue()
292    o2 = self.AlwaysComparesTrue()
293    self.assertTrue(o1 == o2)
294    # but...
295    self.assertFalse(mox.Is(o1) == o2)
296
297  def testInequalityValid(self):
298    o1 = self.AlwaysComparesTrue()
299    o2 = self.AlwaysComparesTrue()
300    self.assertTrue(mox.Is(o1) != o2)
301
302  def testInequalityInvalid(self):
303    o1 = self.AlwaysComparesTrue()
304    self.assertFalse(mox.Is(o1) != o1)
305
306  def testEqualityInListValid(self):
307    o1 = self.AlwaysComparesTrue()
308    o2 = self.AlwaysComparesTrue()
309    isa_list = [mox.Is(o1), mox.Is(o2)]
310    str_list = [o1, o2]
311    self.assertTrue(isa_list == str_list)
312
313  def testEquailtyInListInvalid(self):
314    o1 = self.AlwaysComparesTrue()
315    o2 = self.AlwaysComparesTrue()
316    isa_list = [mox.Is(o1), mox.Is(o2)]
317    mixed_list = [o2, o1]
318    self.assertFalse(isa_list == mixed_list)
319
320
321class IsATest(unittest.TestCase):
322  """Verify IsA correctly checks equality based upon class type, not value."""
323
324  def testEqualityValid(self):
325    """Verify that == correctly identifies objects of the same type."""
326    self.assert_(mox.IsA(str) == 'test')
327
328  def testEqualityInvalid(self):
329    """Verify that == correctly identifies objects of different types."""
330    self.failIf(mox.IsA(str) == 10)
331
332  def testInequalityValid(self):
333    """Verify that != identifies objects of different type."""
334    self.assert_(mox.IsA(str) != 10)
335
336  def testInequalityInvalid(self):
337    """Verify that != correctly identifies objects of the same type."""
338    self.failIf(mox.IsA(str) != "test")
339
340  def testEqualityInListValid(self):
341    """Verify list contents are properly compared."""
342    isa_list = [mox.IsA(str), mox.IsA(str)]
343    str_list = ["abc", "def"]
344    self.assert_(isa_list == str_list)
345
346  def testEquailtyInListInvalid(self):
347    """Verify list contents are properly compared."""
348    isa_list = [mox.IsA(str),mox.IsA(str)]
349    mixed_list = ["abc", 123]
350    self.failIf(isa_list == mixed_list)
351
352  def testSpecialTypes(self):
353    """Verify that IsA can handle objects like cStringIO.StringIO."""
354    isA = mox.IsA(cStringIO.StringIO())
355    stringIO = cStringIO.StringIO()
356    self.assert_(isA == stringIO)
357
358
359class IsAlmostTest(unittest.TestCase):
360  """Verify IsAlmost correctly checks equality of floating point numbers."""
361
362  def testEqualityValid(self):
363    """Verify that == correctly identifies nearly equivalent floats."""
364    self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
365
366  def testEqualityInvalid(self):
367    """Verify that == correctly identifies non-equivalent floats."""
368    self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
369
370  def testEqualityWithPlaces(self):
371    """Verify that specifying places has the desired effect."""
372    self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
373    self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
374
375  def testNonNumericTypes(self):
376    """Verify that IsAlmost handles non-numeric types properly."""
377
378    self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9')
379    self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9)
380    self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
381
382
383class MockMethodTest(unittest.TestCase):
384  """Test class to verify that the MockMethod class is working correctly."""
385
386  def setUp(self):
387    self.expected_method = mox.MockMethod("testMethod", [], False)(['original'])
388    self.mock_method = mox.MockMethod("testMethod", [self.expected_method],
389                                        True)
390
391  def testNameAttribute(self):
392    """Should provide a __name__ attribute."""
393    self.assertEquals('testMethod', self.mock_method.__name__)
394
395  def testAndReturnNoneByDefault(self):
396    """Should return None by default."""
397    return_value = self.mock_method(['original'])
398    self.assert_(return_value == None)
399
400  def testAndReturnValue(self):
401    """Should return a specificed return value."""
402    expected_return_value = "test"
403    self.expected_method.AndReturn(expected_return_value)
404    return_value = self.mock_method(['original'])
405    self.assert_(return_value == expected_return_value)
406
407  def testAndRaiseException(self):
408    """Should raise a specified exception."""
409    expected_exception = Exception('test exception')
410    self.expected_method.AndRaise(expected_exception)
411    self.assertRaises(Exception, self.mock_method)
412
413  def testWithSideEffects(self):
414    """Should call state modifier."""
415    local_list = ['original']
416    def modifier(mutable_list):
417      self.assertTrue(local_list is mutable_list)
418      mutable_list[0] = 'mutation'
419    self.expected_method.WithSideEffects(modifier).AndReturn(1)
420    self.mock_method(local_list)
421    self.assertEquals('mutation', local_list[0])
422
423  def testWithReturningSideEffects(self):
424    """Should call state modifier and propagate its return value."""
425    local_list = ['original']
426    expected_return = 'expected_return'
427    def modifier_with_return(mutable_list):
428      self.assertTrue(local_list is mutable_list)
429      mutable_list[0] = 'mutation'
430      return expected_return
431    self.expected_method.WithSideEffects(modifier_with_return)
432    actual_return = self.mock_method(local_list)
433    self.assertEquals('mutation', local_list[0])
434    self.assertEquals(expected_return, actual_return)
435
436  def testWithReturningSideEffectsWithAndReturn(self):
437    """Should call state modifier and ignore its return value."""
438    local_list = ['original']
439    expected_return = 'expected_return'
440    unexpected_return = 'unexpected_return'
441    def modifier_with_return(mutable_list):
442      self.assertTrue(local_list is mutable_list)
443      mutable_list[0] = 'mutation'
444      return unexpected_return
445    self.expected_method.WithSideEffects(modifier_with_return).AndReturn(
446        expected_return)
447    actual_return = self.mock_method(local_list)
448    self.assertEquals('mutation', local_list[0])
449    self.assertEquals(expected_return, actual_return)
450
451  def testEqualityNoParamsEqual(self):
452    """Methods with the same name and without params should be equal."""
453    expected_method = mox.MockMethod("testMethod", [], False)
454    self.assertEqual(self.mock_method, expected_method)
455
456  def testEqualityNoParamsNotEqual(self):
457    """Methods with different names and without params should not be equal."""
458    expected_method = mox.MockMethod("otherMethod", [], False)
459    self.failIfEqual(self.mock_method, expected_method)
460
461  def testEqualityParamsEqual(self):
462    """Methods with the same name and parameters should be equal."""
463    params = [1, 2, 3]
464    expected_method = mox.MockMethod("testMethod", [], False)
465    expected_method._params = params
466
467    self.mock_method._params = params
468    self.assertEqual(self.mock_method, expected_method)
469
470  def testEqualityParamsNotEqual(self):
471    """Methods with the same name and different params should not be equal."""
472    expected_method = mox.MockMethod("testMethod", [], False)
473    expected_method._params = [1, 2, 3]
474
475    self.mock_method._params = ['a', 'b', 'c']
476    self.failIfEqual(self.mock_method, expected_method)
477
478  def testEqualityNamedParamsEqual(self):
479    """Methods with the same name and same named params should be equal."""
480    named_params = {"input1": "test", "input2": "params"}
481    expected_method = mox.MockMethod("testMethod", [], False)
482    expected_method._named_params = named_params
483
484    self.mock_method._named_params = named_params
485    self.assertEqual(self.mock_method, expected_method)
486
487  def testEqualityNamedParamsNotEqual(self):
488    """Methods with the same name and diffnamed params should not be equal."""
489    expected_method = mox.MockMethod("testMethod", [], False)
490    expected_method._named_params = {"input1": "test", "input2": "params"}
491
492    self.mock_method._named_params = {"input1": "test2", "input2": "params2"}
493    self.failIfEqual(self.mock_method, expected_method)
494
495  def testEqualityWrongType(self):
496    """Method should not be equal to an object of a different type."""
497    self.failIfEqual(self.mock_method, "string?")
498
499  def testObjectEquality(self):
500    """Equality of objects should work without a Comparator"""
501    instA = TestClass();
502    instB = TestClass();
503
504    params = [instA, ]
505    expected_method = mox.MockMethod("testMethod", [], False)
506    expected_method._params = params
507
508    self.mock_method._params = [instB, ]
509    self.assertEqual(self.mock_method, expected_method)
510
511  def testStrConversion(self):
512    method = mox.MockMethod("f", [], False)
513    method(1, 2, "st", n1=8, n2="st2")
514    self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None"))
515
516    method = mox.MockMethod("testMethod", [], False)
517    method(1, 2, "only positional")
518    self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None")
519
520    method = mox.MockMethod("testMethod", [], False)
521    method(a=1, b=2, c="only named")
522    self.assertEqual(str(method),
523                     "testMethod(a=1, b=2, c='only named') -> None")
524
525    method = mox.MockMethod("testMethod", [], False)
526    method()
527    self.assertEqual(str(method), "testMethod() -> None")
528
529    method = mox.MockMethod("testMethod", [], False)
530    method(x="only 1 parameter")
531    self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None")
532
533    method = mox.MockMethod("testMethod", [], False)
534    method().AndReturn('return_value')
535    self.assertEqual(str(method), "testMethod() -> 'return_value'")
536
537    method = mox.MockMethod("testMethod", [], False)
538    method().AndReturn(('a', {1: 2}))
539    self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})")
540
541
542class MockAnythingTest(unittest.TestCase):
543  """Verify that the MockAnything class works as expected."""
544
545  def setUp(self):
546    self.mock_object = mox.MockAnything()
547
548  def testRepr(self):
549    """Calling repr on a MockAnything instance must work."""
550    self.assertEqual('<MockAnything instance>', repr(self.mock_object))
551
552  def testCanMockStr(self):
553    self.mock_object.__str__().AndReturn("foo");
554    self.mock_object._Replay()
555    actual = str(self.mock_object)
556    self.mock_object._Verify();
557    self.assertEquals("foo", actual)
558
559  def testSetupMode(self):
560    """Verify the mock will accept any call."""
561    self.mock_object.NonsenseCall()
562    self.assert_(len(self.mock_object._expected_calls_queue) == 1)
563
564  def testReplayWithExpectedCall(self):
565    """Verify the mock replays method calls as expected."""
566    self.mock_object.ValidCall()          # setup method call
567    self.mock_object._Replay()            # start replay mode
568    self.mock_object.ValidCall()          # make method call
569
570  def testReplayWithUnexpectedCall(self):
571    """Unexpected method calls should raise UnexpectedMethodCallError."""
572    self.mock_object.ValidCall()          # setup method call
573    self.mock_object._Replay()             # start replay mode
574    self.assertRaises(mox.UnexpectedMethodCallError,
575                      self.mock_object.OtherValidCall)
576
577#   def testReplayWithUnexpectedCell_BadSignatureWithTuple(self):
578#     self.mock_object.ValidCall(mox.In((1, 2, 3)))
579#     self.mock_object._Replay()
580#     self.assertRaises(mox.UnexpectedMethodCallError,
581#                       self.mock_object.ValidCall, 4)
582
583
584  def testVerifyWithCompleteReplay(self):
585    """Verify should not raise an exception for a valid replay."""
586    self.mock_object.ValidCall()          # setup method call
587    self.mock_object._Replay()             # start replay mode
588    self.mock_object.ValidCall()          # make method call
589    self.mock_object._Verify()
590
591  def testVerifyWithIncompleteReplay(self):
592    """Verify should raise an exception if the replay was not complete."""
593    self.mock_object.ValidCall()          # setup method call
594    self.mock_object._Replay()             # start replay mode
595    # ValidCall() is never made
596    self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify)
597
598  def testSpecialClassMethod(self):
599    """Verify should not raise an exception when special methods are used."""
600    self.mock_object[1].AndReturn(True)
601    self.mock_object._Replay()
602    returned_val = self.mock_object[1]
603    self.assert_(returned_val)
604    self.mock_object._Verify()
605
606  def testNonzero(self):
607    """You should be able to use the mock object in an if."""
608    self.mock_object._Replay()
609    if self.mock_object:
610      pass
611
612  def testNotNone(self):
613    """Mock should be comparable to None."""
614    self.mock_object._Replay()
615    if self.mock_object is not None:
616      pass
617
618    if self.mock_object is None:
619      pass
620
621  def testEquals(self):
622    """A mock should be able to compare itself to another object."""
623    self.mock_object._Replay()
624    self.assertEquals(self.mock_object, self.mock_object)
625
626  def testEqualsMockFailure(self):
627    """Verify equals identifies unequal objects."""
628    self.mock_object.SillyCall()
629    self.mock_object._Replay()
630    self.assertNotEquals(self.mock_object, mox.MockAnything())
631
632  def testEqualsInstanceFailure(self):
633    """Verify equals identifies that objects are different instances."""
634    self.mock_object._Replay()
635    self.assertNotEquals(self.mock_object, TestClass())
636
637  def testNotEquals(self):
638    """Verify not equals works."""
639    self.mock_object._Replay()
640    self.assertFalse(self.mock_object != self.mock_object)
641
642  def testNestedMockCallsRecordedSerially(self):
643    """Test that nested calls work when recorded serially."""
644    self.mock_object.CallInner().AndReturn(1)
645    self.mock_object.CallOuter(1)
646    self.mock_object._Replay()
647
648    self.mock_object.CallOuter(self.mock_object.CallInner())
649
650    self.mock_object._Verify()
651
652  def testNestedMockCallsRecordedNested(self):
653    """Test that nested cals work when recorded in a nested fashion."""
654    self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1))
655    self.mock_object._Replay()
656
657    self.mock_object.CallOuter(self.mock_object.CallInner())
658
659    self.mock_object._Verify()
660
661  def testIsCallable(self):
662    """Test that MockAnything can even mock a simple callable.
663
664    This is handy for "stubbing out" a method in a module with a mock, and
665    verifying that it was called.
666    """
667    self.mock_object().AndReturn('mox0rd')
668    self.mock_object._Replay()
669
670    self.assertEquals('mox0rd', self.mock_object())
671
672    self.mock_object._Verify()
673
674  def testIsReprable(self):
675    """Test that MockAnythings can be repr'd without causing a failure."""
676    self.failUnless('MockAnything' in repr(self.mock_object))
677
678
679class MethodCheckerTest(unittest.TestCase):
680  """Tests MockMethod's use of MethodChecker method."""
681
682  def testNoParameters(self):
683    method = mox.MockMethod('NoParameters', [], False,
684                            CheckCallTestClass.NoParameters)
685    method()
686    self.assertRaises(AttributeError, method, 1)
687    self.assertRaises(AttributeError, method, 1, 2)
688    self.assertRaises(AttributeError, method, a=1)
689    self.assertRaises(AttributeError, method, 1, b=2)
690
691  def testOneParameter(self):
692    method = mox.MockMethod('OneParameter', [], False,
693                            CheckCallTestClass.OneParameter)
694    self.assertRaises(AttributeError, method)
695    method(1)
696    method(a=1)
697    self.assertRaises(AttributeError, method, b=1)
698    self.assertRaises(AttributeError, method, 1, 2)
699    self.assertRaises(AttributeError, method, 1, a=2)
700    self.assertRaises(AttributeError, method, 1, b=2)
701
702  def testTwoParameters(self):
703    method = mox.MockMethod('TwoParameters', [], False,
704                            CheckCallTestClass.TwoParameters)
705    self.assertRaises(AttributeError, method)
706    self.assertRaises(AttributeError, method, 1)
707    self.assertRaises(AttributeError, method, a=1)
708    self.assertRaises(AttributeError, method, b=1)
709    method(1, 2)
710    method(1, b=2)
711    method(a=1, b=2)
712    method(b=2, a=1)
713    self.assertRaises(AttributeError, method, b=2, c=3)
714    self.assertRaises(AttributeError, method, a=1, b=2, c=3)
715    self.assertRaises(AttributeError, method, 1, 2, 3)
716    self.assertRaises(AttributeError, method, 1, 2, 3, 4)
717    self.assertRaises(AttributeError, method, 3, a=1, b=2)
718
719  def testOneDefaultValue(self):
720    method = mox.MockMethod('OneDefaultValue', [], False,
721                            CheckCallTestClass.OneDefaultValue)
722    method()
723    method(1)
724    method(a=1)
725    self.assertRaises(AttributeError, method, b=1)
726    self.assertRaises(AttributeError, method, 1, 2)
727    self.assertRaises(AttributeError, method, 1, a=2)
728    self.assertRaises(AttributeError, method, 1, b=2)
729
730  def testTwoDefaultValues(self):
731    method = mox.MockMethod('TwoDefaultValues', [], False,
732                            CheckCallTestClass.TwoDefaultValues)
733    self.assertRaises(AttributeError, method)
734    self.assertRaises(AttributeError, method, c=3)
735    self.assertRaises(AttributeError, method, 1)
736    self.assertRaises(AttributeError, method, 1, d=4)
737    self.assertRaises(AttributeError, method, 1, d=4, c=3)
738    method(1, 2)
739    method(a=1, b=2)
740    method(1, 2, 3)
741    method(1, 2, 3, 4)
742    method(1, 2, c=3)
743    method(1, 2, c=3, d=4)
744    method(1, 2, d=4, c=3)
745    method(d=4, c=3, a=1, b=2)
746    self.assertRaises(AttributeError, method, 1, 2, 3, 4, 5)
747    self.assertRaises(AttributeError, method, 1, 2, e=9)
748    self.assertRaises(AttributeError, method, a=1, b=2, e=9)
749
750  def testArgs(self):
751    method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args)
752    self.assertRaises(AttributeError, method)
753    self.assertRaises(AttributeError, method, 1)
754    method(1, 2)
755    method(a=1, b=2)
756    method(1, 2, 3)
757    method(1, 2, 3, 4)
758    self.assertRaises(AttributeError, method, 1, 2, a=3)
759    self.assertRaises(AttributeError, method, 1, 2, c=3)
760
761  def testKwargs(self):
762    method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs)
763    self.assertRaises(AttributeError, method)
764    method(1)
765    method(1, 2)
766    method(a=1, b=2)
767    method(b=2, a=1)
768    self.assertRaises(AttributeError, method, 1, 2, 3)
769    self.assertRaises(AttributeError, method, 1, 2, a=3)
770    method(1, 2, c=3)
771    method(a=1, b=2, c=3)
772    method(c=3, a=1, b=2)
773    method(a=1, b=2, c=3, d=4)
774    self.assertRaises(AttributeError, method, 1, 2, 3, 4)
775
776  def testArgsAndKwargs(self):
777    method = mox.MockMethod('ArgsAndKwargs', [], False,
778                            CheckCallTestClass.ArgsAndKwargs)
779    self.assertRaises(AttributeError, method)
780    method(1)
781    method(1, 2)
782    method(1, 2, 3)
783    method(a=1)
784    method(1, b=2)
785    self.assertRaises(AttributeError, method, 1, a=2)
786    method(b=2, a=1)
787    method(c=3, b=2, a=1)
788    method(1, 2, c=3)
789
790
791class CheckCallTestClass(object):
792  def NoParameters(self):
793    pass
794
795  def OneParameter(self, a):
796    pass
797
798  def TwoParameters(self, a, b):
799    pass
800
801  def OneDefaultValue(self, a=1):
802    pass
803
804  def TwoDefaultValues(self, a, b, c=1, d=2):
805    pass
806
807  def Args(self, a, b, *args):
808    pass
809
810  def Kwargs(self, a, b=2, **kwargs):
811    pass
812
813  def ArgsAndKwargs(self, a, *args, **kwargs):
814    pass
815
816
817class MockObjectTest(unittest.TestCase):
818  """Verify that the MockObject class works as exepcted."""
819
820  def setUp(self):
821    self.mock_object = mox.MockObject(TestClass)
822
823  def testSetupModeWithValidCall(self):
824    """Verify the mock object properly mocks a basic method call."""
825    self.mock_object.ValidCall()
826    self.assert_(len(self.mock_object._expected_calls_queue) == 1)
827
828  def testSetupModeWithInvalidCall(self):
829    """UnknownMethodCallError should be raised if a non-member method is called.
830    """
831    # Note: assertRaises does not catch exceptions thrown by MockObject's
832    # __getattr__
833    try:
834      self.mock_object.InvalidCall()
835      self.fail("No exception thrown, expected UnknownMethodCallError")
836    except mox.UnknownMethodCallError:
837      pass
838    except Exception:
839      self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
840
841  def testReplayWithInvalidCall(self):
842    """UnknownMethodCallError should be raised if a non-member method is called.
843    """
844    self.mock_object.ValidCall()          # setup method call
845    self.mock_object._Replay()             # start replay mode
846    # Note: assertRaises does not catch exceptions thrown by MockObject's
847    # __getattr__
848    try:
849      self.mock_object.InvalidCall()
850      self.fail("No exception thrown, expected UnknownMethodCallError")
851    except mox.UnknownMethodCallError:
852      pass
853    except Exception:
854      self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
855
856  def testIsInstance(self):
857    """Mock should be able to pass as an instance of the mocked class."""
858    self.assert_(isinstance(self.mock_object, TestClass))
859
860  def testFindValidMethods(self):
861    """Mock should be able to mock all public methods."""
862    self.assert_('ValidCall' in self.mock_object._known_methods)
863    self.assert_('OtherValidCall' in self.mock_object._known_methods)
864    self.assert_('MyClassMethod' in self.mock_object._known_methods)
865    self.assert_('MyStaticMethod' in self.mock_object._known_methods)
866    self.assert_('_ProtectedCall' in self.mock_object._known_methods)
867    self.assert_('__PrivateCall' not in self.mock_object._known_methods)
868    self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods)
869
870  def testFindsSuperclassMethods(self):
871    """Mock should be able to mock superclasses methods."""
872    self.mock_object = mox.MockObject(ChildClass)
873    self.assert_('ValidCall' in self.mock_object._known_methods)
874    self.assert_('OtherValidCall' in self.mock_object._known_methods)
875    self.assert_('MyClassMethod' in self.mock_object._known_methods)
876    self.assert_('ChildValidCall' in self.mock_object._known_methods)
877
878  def testAccessClassVariables(self):
879    """Class variables should be accessible through the mock."""
880    self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars)
881    self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)
882    self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR)
883
884  def testEquals(self):
885    """A mock should be able to compare itself to another object."""
886    self.mock_object._Replay()
887    self.assertEquals(self.mock_object, self.mock_object)
888
889  def testEqualsMockFailure(self):
890    """Verify equals identifies unequal objects."""
891    self.mock_object.ValidCall()
892    self.mock_object._Replay()
893    self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
894
895  def testEqualsInstanceFailure(self):
896    """Verify equals identifies that objects are different instances."""
897    self.mock_object._Replay()
898    self.assertNotEquals(self.mock_object, TestClass())
899
900  def testNotEquals(self):
901    """Verify not equals works."""
902    self.mock_object._Replay()
903    self.assertFalse(self.mock_object != self.mock_object)
904
905  def testMockSetItem_ExpectedSetItem_Success(self):
906    """Test that __setitem__() gets mocked in Dummy.
907
908    In this test, _Verify() succeeds.
909    """
910    dummy = mox.MockObject(TestClass)
911    dummy['X'] = 'Y'
912
913    dummy._Replay()
914
915    dummy['X'] = 'Y'
916
917    dummy._Verify()
918
919  def testMockSetItem_ExpectedSetItem_NoSuccess(self):
920    """Test that __setitem__() gets mocked in Dummy.
921
922    In this test, _Verify() fails.
923    """
924    dummy = mox.MockObject(TestClass)
925    dummy['X'] = 'Y'
926
927    dummy._Replay()
928
929    # NOT doing dummy['X'] = 'Y'
930
931    self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
932
933  def testMockSetItem_ExpectedNoSetItem_Success(self):
934    """Test that __setitem__() gets mocked in Dummy."""
935    dummy = mox.MockObject(TestClass)
936    # NOT doing dummy['X'] = 'Y'
937
938    dummy._Replay()
939
940    def call(): dummy['X'] = 'Y'
941    self.assertRaises(mox.UnexpectedMethodCallError, call)
942
943  def testMockSetItem_ExpectedNoSetItem_NoSuccess(self):
944    """Test that __setitem__() gets mocked in Dummy.
945
946    In this test, _Verify() fails.
947    """
948    dummy = mox.MockObject(TestClass)
949    # NOT doing dummy['X'] = 'Y'
950
951    dummy._Replay()
952
953    # NOT doing dummy['X'] = 'Y'
954
955    dummy._Verify()
956
957  def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self):
958    """Test that __setitem__() fails if other parameters are expected."""
959    dummy = mox.MockObject(TestClass)
960    dummy['X'] = 'Y'
961
962    dummy._Replay()
963
964    def call(): dummy['wrong'] = 'Y'
965
966    self.assertRaises(mox.UnexpectedMethodCallError, call)
967
968    dummy._Verify()
969
970  def testMockSetItem_WithSubClassOfNewStyleClass(self):
971    class NewStyleTestClass(object):
972      def __init__(self):
973        self.my_dict = {}
974
975      def __setitem__(self, key, value):
976        self.my_dict[key], value
977
978    class TestSubClass(NewStyleTestClass):
979      pass
980
981    dummy = mox.MockObject(TestSubClass)
982    dummy[1] = 2
983    dummy._Replay()
984    dummy[1] = 2
985    dummy._Verify()
986
987  def testMockGetItem_ExpectedGetItem_Success(self):
988    """Test that __getitem__() gets mocked in Dummy.
989
990    In this test, _Verify() succeeds.
991    """
992    dummy = mox.MockObject(TestClass)
993    dummy['X'].AndReturn('value')
994
995    dummy._Replay()
996
997    self.assertEqual(dummy['X'], 'value')
998
999    dummy._Verify()
1000
1001  def testMockGetItem_ExpectedGetItem_NoSuccess(self):
1002    """Test that __getitem__() gets mocked in Dummy.
1003
1004    In this test, _Verify() fails.
1005    """
1006    dummy = mox.MockObject(TestClass)
1007    dummy['X'].AndReturn('value')
1008
1009    dummy._Replay()
1010
1011    # NOT doing dummy['X']
1012
1013    self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
1014
1015  def testMockGetItem_ExpectedNoGetItem_NoSuccess(self):
1016    """Test that __getitem__() gets mocked in Dummy."""
1017    dummy = mox.MockObject(TestClass)
1018    # NOT doing dummy['X']
1019
1020    dummy._Replay()
1021
1022    def call(): return dummy['X']
1023    self.assertRaises(mox.UnexpectedMethodCallError, call)
1024
1025  def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self):
1026    """Test that __getitem__() fails if other parameters are expected."""
1027    dummy = mox.MockObject(TestClass)
1028    dummy['X'].AndReturn('value')
1029
1030    dummy._Replay()
1031
1032    def call(): return dummy['wrong']
1033
1034    self.assertRaises(mox.UnexpectedMethodCallError, call)
1035
1036    dummy._Verify()
1037
1038  def testMockGetItem_WithSubClassOfNewStyleClass(self):
1039    class NewStyleTestClass(object):
1040      def __getitem__(self, key):
1041        return {1: '1', 2: '2'}[key]
1042
1043    class TestSubClass(NewStyleTestClass):
1044      pass
1045
1046    dummy = mox.MockObject(TestSubClass)
1047    dummy[1].AndReturn('3')
1048
1049    dummy._Replay()
1050    self.assertEquals('3', dummy.__getitem__(1))
1051    dummy._Verify()
1052
1053  def testMockIter_ExpectedIter_Success(self):
1054    """Test that __iter__() gets mocked in Dummy.
1055
1056    In this test, _Verify() succeeds.
1057    """
1058    dummy = mox.MockObject(TestClass)
1059    iter(dummy).AndReturn(iter(['X', 'Y']))
1060
1061    dummy._Replay()
1062
1063    self.assertEqual([x for x in dummy], ['X', 'Y'])
1064
1065    dummy._Verify()
1066
1067  def testMockContains_ExpectedContains_Success(self):
1068    """Test that __contains__ gets mocked in Dummy.
1069
1070    In this test, _Verify() succeeds.
1071    """
1072    dummy = mox.MockObject(TestClass)
1073    dummy.__contains__('X').AndReturn(True)
1074
1075    dummy._Replay()
1076
1077    self.failUnless('X' in dummy)
1078
1079    dummy._Verify()
1080
1081  def testMockContains_ExpectedContains_NoSuccess(self):
1082    """Test that __contains__() gets mocked in Dummy.
1083
1084    In this test, _Verify() fails.
1085    """
1086    dummy = mox.MockObject(TestClass)
1087    dummy.__contains__('X').AndReturn('True')
1088
1089    dummy._Replay()
1090
1091    # NOT doing 'X' in dummy
1092
1093    self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
1094
1095  def testMockContains_ExpectedContains_NonmatchingParameter(self):
1096    """Test that __contains__ fails if other parameters are expected."""
1097    dummy = mox.MockObject(TestClass)
1098    dummy.__contains__('X').AndReturn(True)
1099
1100    dummy._Replay()
1101
1102    def call(): return 'Y' in dummy
1103
1104    self.assertRaises(mox.UnexpectedMethodCallError, call)
1105
1106    dummy._Verify()
1107
1108  def testMockIter_ExpectedIter_NoSuccess(self):
1109    """Test that __iter__() gets mocked in Dummy.
1110
1111    In this test, _Verify() fails.
1112    """
1113    dummy = mox.MockObject(TestClass)
1114    iter(dummy).AndReturn(iter(['X', 'Y']))
1115
1116    dummy._Replay()
1117
1118    # NOT doing self.assertEqual([x for x in dummy], ['X', 'Y'])
1119
1120    self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
1121
1122  def testMockIter_ExpectedNoIter_NoSuccess(self):
1123    """Test that __iter__() gets mocked in Dummy."""
1124    dummy = mox.MockObject(TestClass)
1125    # NOT doing iter(dummy)
1126
1127    dummy._Replay()
1128
1129    def call(): return [x for x in dummy]
1130    self.assertRaises(mox.UnexpectedMethodCallError, call)
1131
1132  def testMockIter_ExpectedGetItem_Success(self):
1133    """Test that __iter__() gets mocked in Dummy using getitem."""
1134    dummy = mox.MockObject(SubscribtableNonIterableClass)
1135    dummy[0].AndReturn('a')
1136    dummy[1].AndReturn('b')
1137    dummy[2].AndRaise(IndexError)
1138
1139    dummy._Replay()
1140    self.assertEquals(['a', 'b'], [x for x in dummy])
1141    dummy._Verify()
1142
1143  def testMockIter_ExpectedNoGetItem_NoSuccess(self):
1144    """Test that __iter__() gets mocked in Dummy using getitem."""
1145    dummy = mox.MockObject(SubscribtableNonIterableClass)
1146    # NOT doing dummy[index]
1147
1148    dummy._Replay()
1149    function = lambda: [x for x in dummy]
1150    self.assertRaises(mox.UnexpectedMethodCallError, function)
1151
1152  def testMockGetIter_WithSubClassOfNewStyleClass(self):
1153    class NewStyleTestClass(object):
1154      def __iter__(self):
1155        return iter([1, 2, 3])
1156
1157    class TestSubClass(NewStyleTestClass):
1158      pass
1159
1160    dummy = mox.MockObject(TestSubClass)
1161    iter(dummy).AndReturn(iter(['a', 'b']))
1162    dummy._Replay()
1163    self.assertEquals(['a', 'b'], [x for x in dummy])
1164    dummy._Verify()
1165
1166  def testInstantiationWithAdditionalAttributes(self):
1167    mock_object = mox.MockObject(TestClass, attrs={"attr1": "value"})
1168    self.assertEquals(mock_object.attr1, "value")
1169
1170  def testCantOverrideMethodsWithAttributes(self):
1171    self.assertRaises(ValueError, mox.MockObject, TestClass,
1172                      attrs={"ValidCall": "value"})
1173
1174  def testCantMockNonPublicAttributes(self):
1175    self.assertRaises(mox.PrivateAttributeError, mox.MockObject, TestClass,
1176                      attrs={"_protected": "value"})
1177    self.assertRaises(mox.PrivateAttributeError, mox.MockObject, TestClass,
1178                      attrs={"__private": "value"})
1179
1180
1181class MoxTest(unittest.TestCase):
1182  """Verify Mox works correctly."""
1183
1184  def setUp(self):
1185    self.mox = mox.Mox()
1186
1187  def testCreateObject(self):
1188    """Mox should create a mock object."""
1189    mock_obj = self.mox.CreateMock(TestClass)
1190
1191  def testVerifyObjectWithCompleteReplay(self):
1192    """Mox should replay and verify all objects it created."""
1193    mock_obj = self.mox.CreateMock(TestClass)
1194    mock_obj.ValidCall()
1195    mock_obj.ValidCallWithArgs(mox.IsA(TestClass))
1196    self.mox.ReplayAll()
1197    mock_obj.ValidCall()
1198    mock_obj.ValidCallWithArgs(TestClass("some_value"))
1199    self.mox.VerifyAll()
1200
1201  def testVerifyObjectWithIncompleteReplay(self):
1202    """Mox should raise an exception if a mock didn't replay completely."""
1203    mock_obj = self.mox.CreateMock(TestClass)
1204    mock_obj.ValidCall()
1205    self.mox.ReplayAll()
1206    # ValidCall() is never made
1207    self.assertRaises(mox.ExpectedMethodCallsError, self.mox.VerifyAll)
1208
1209  def testEntireWorkflow(self):
1210    """Test the whole work flow."""
1211    mock_obj = self.mox.CreateMock(TestClass)
1212    mock_obj.ValidCall().AndReturn("yes")
1213    self.mox.ReplayAll()
1214
1215    ret_val = mock_obj.ValidCall()
1216    self.assertEquals("yes", ret_val)
1217    self.mox.VerifyAll()
1218
1219  def testCallableObject(self):
1220    """Test recording calls to a callable object works."""
1221    mock_obj = self.mox.CreateMock(CallableClass)
1222    mock_obj("foo").AndReturn("qux")
1223    self.mox.ReplayAll()
1224
1225    ret_val = mock_obj("foo")
1226    self.assertEquals("qux", ret_val)
1227    self.mox.VerifyAll()
1228
1229  def testInheritedCallableObject(self):
1230    """Test recording calls to an object inheriting from a callable object."""
1231    mock_obj = self.mox.CreateMock(InheritsFromCallable)
1232    mock_obj("foo").AndReturn("qux")
1233    self.mox.ReplayAll()
1234
1235    ret_val = mock_obj("foo")
1236    self.assertEquals("qux", ret_val)
1237    self.mox.VerifyAll()
1238
1239  def testCallOnNonCallableObject(self):
1240    """Test that you cannot call a non-callable object."""
1241    mock_obj = self.mox.CreateMock(TestClass)
1242    self.assertRaises(TypeError, mock_obj)
1243
1244  def testCallableObjectWithBadCall(self):
1245    """Test verifying calls to a callable object works."""
1246    mock_obj = self.mox.CreateMock(CallableClass)
1247    mock_obj("foo").AndReturn("qux")
1248    self.mox.ReplayAll()
1249
1250    self.assertRaises(mox.UnexpectedMethodCallError, mock_obj, "ZOOBAZ")
1251
1252  def testCallableObjectVerifiesSignature(self):
1253    mock_obj = self.mox.CreateMock(CallableClass)
1254    # Too many arguments
1255    self.assertRaises(AttributeError, mock_obj, "foo", "bar")
1256
1257  def testUnorderedGroup(self):
1258    """Test that using one unordered group works."""
1259    mock_obj = self.mox.CreateMockAnything()
1260    mock_obj.Method(1).InAnyOrder()
1261    mock_obj.Method(2).InAnyOrder()
1262    self.mox.ReplayAll()
1263
1264    mock_obj.Method(2)
1265    mock_obj.Method(1)
1266
1267    self.mox.VerifyAll()
1268
1269  def testUnorderedGroupsInline(self):
1270    """Unordered groups should work in the context of ordered calls."""
1271    mock_obj = self.mox.CreateMockAnything()
1272    mock_obj.Open()
1273    mock_obj.Method(1).InAnyOrder()
1274    mock_obj.Method(2).InAnyOrder()
1275    mock_obj.Close()
1276    self.mox.ReplayAll()
1277
1278    mock_obj.Open()
1279    mock_obj.Method(2)
1280    mock_obj.Method(1)
1281    mock_obj.Close()
1282
1283    self.mox.VerifyAll()
1284
1285  def testMultipleUnorderdGroups(self):
1286    """Multiple unoreded groups should work."""
1287    mock_obj = self.mox.CreateMockAnything()
1288    mock_obj.Method(1).InAnyOrder()
1289    mock_obj.Method(2).InAnyOrder()
1290    mock_obj.Foo().InAnyOrder('group2')
1291    mock_obj.Bar().InAnyOrder('group2')
1292    self.mox.ReplayAll()
1293
1294    mock_obj.Method(2)
1295    mock_obj.Method(1)
1296    mock_obj.Bar()
1297    mock_obj.Foo()
1298
1299    self.mox.VerifyAll()
1300
1301  def testMultipleUnorderdGroupsOutOfOrder(self):
1302    """Multiple unordered groups should maintain external order"""
1303    mock_obj = self.mox.CreateMockAnything()
1304    mock_obj.Method(1).InAnyOrder()
1305    mock_obj.Method(2).InAnyOrder()
1306    mock_obj.Foo().InAnyOrder('group2')
1307    mock_obj.Bar().InAnyOrder('group2')
1308    self.mox.ReplayAll()
1309
1310    mock_obj.Method(2)
1311    self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Bar)
1312
1313  def testUnorderedGroupWithReturnValue(self):
1314    """Unordered groups should work with return values."""
1315    mock_obj = self.mox.CreateMockAnything()
1316    mock_obj.Open()
1317    mock_obj.Method(1).InAnyOrder().AndReturn(9)
1318    mock_obj.Method(2).InAnyOrder().AndReturn(10)
1319    mock_obj.Close()
1320    self.mox.ReplayAll()
1321
1322    mock_obj.Open()
1323    actual_two = mock_obj.Method(2)
1324    actual_one = mock_obj.Method(1)
1325    mock_obj.Close()
1326
1327    self.assertEquals(9, actual_one)
1328    self.assertEquals(10, actual_two)
1329
1330    self.mox.VerifyAll()
1331
1332  def testUnorderedGroupWithComparator(self):
1333    """Unordered groups should work with comparators"""
1334
1335    def VerifyOne(cmd):
1336      if not isinstance(cmd, str):
1337        self.fail('Unexpected type passed to comparator: ' + str(cmd))
1338      return cmd == 'test'
1339
1340    def VerifyTwo(cmd):
1341      return True
1342
1343    mock_obj = self.mox.CreateMockAnything()
1344    mock_obj.Foo(['test'], mox.Func(VerifyOne), bar=1).InAnyOrder().\
1345        AndReturn('yes test')
1346    mock_obj.Foo(['test'], mox.Func(VerifyTwo), bar=1).InAnyOrder().\
1347        AndReturn('anything')
1348
1349    self.mox.ReplayAll()
1350
1351    mock_obj.Foo(['test'], 'anything', bar=1)
1352    mock_obj.Foo(['test'], 'test', bar=1)
1353
1354    self.mox.VerifyAll()
1355
1356  def testMultipleTimes(self):
1357    """Test if MultipleTimesGroup works."""
1358    mock_obj = self.mox.CreateMockAnything()
1359    mock_obj.Method(1).MultipleTimes().AndReturn(9)
1360    mock_obj.Method(2).AndReturn(10)
1361    mock_obj.Method(3).MultipleTimes().AndReturn(42)
1362    self.mox.ReplayAll()
1363
1364    actual_one = mock_obj.Method(1)
1365    second_one = mock_obj.Method(1) # This tests MultipleTimes.
1366    actual_two = mock_obj.Method(2)
1367    actual_three = mock_obj.Method(3)
1368    mock_obj.Method(3)
1369    mock_obj.Method(3)
1370
1371    self.mox.VerifyAll()
1372
1373    self.assertEquals(9, actual_one)
1374    self.assertEquals(9, second_one) # Repeated calls should return same number.
1375    self.assertEquals(10, actual_two)
1376    self.assertEquals(42, actual_three)
1377
1378  def testMultipleTimesUsingIsAParameter(self):
1379    """Test if MultipleTimesGroup works with a IsA parameter."""
1380    mock_obj = self.mox.CreateMockAnything()
1381    mock_obj.Open()
1382    mock_obj.Method(mox.IsA(str)).MultipleTimes("IsA").AndReturn(9)
1383    mock_obj.Close()
1384    self.mox.ReplayAll()
1385
1386    mock_obj.Open()
1387    actual_one = mock_obj.Method("1")
1388    second_one = mock_obj.Method("2") # This tests MultipleTimes.
1389    mock_obj.Close()
1390
1391    self.mox.VerifyAll()
1392
1393    self.assertEquals(9, actual_one)
1394    self.assertEquals(9, second_one) # Repeated calls should return same number.
1395
1396  def testMutlipleTimesUsingFunc(self):
1397    """Test that the Func is not evaluated more times than necessary.
1398
1399    If a Func() has side effects, it can cause a passing test to fail.
1400    """
1401
1402    self.counter = 0
1403    def MyFunc(actual_str):
1404      """Increment the counter if actual_str == 'foo'."""
1405      if actual_str == 'foo':
1406        self.counter += 1
1407      return True
1408
1409    mock_obj = self.mox.CreateMockAnything()
1410    mock_obj.Open()
1411    mock_obj.Method(mox.Func(MyFunc)).MultipleTimes()
1412    mock_obj.Close()
1413    self.mox.ReplayAll()
1414
1415    mock_obj.Open()
1416    mock_obj.Method('foo')
1417    mock_obj.Method('foo')
1418    mock_obj.Method('not-foo')
1419    mock_obj.Close()
1420
1421    self.mox.VerifyAll()
1422
1423    self.assertEquals(2, self.counter)
1424
1425  def testMultipleTimesThreeMethods(self):
1426    """Test if MultipleTimesGroup works with three or more methods."""
1427    mock_obj = self.mox.CreateMockAnything()
1428    mock_obj.Open()
1429    mock_obj.Method(1).MultipleTimes().AndReturn(9)
1430    mock_obj.Method(2).MultipleTimes().AndReturn(8)
1431    mock_obj.Method(3).MultipleTimes().AndReturn(7)
1432    mock_obj.Method(4).AndReturn(10)
1433    mock_obj.Close()
1434    self.mox.ReplayAll()
1435
1436    mock_obj.Open()
1437    actual_three = mock_obj.Method(3)
1438    mock_obj.Method(1)
1439    actual_two = mock_obj.Method(2)
1440    mock_obj.Method(3)
1441    actual_one = mock_obj.Method(1)
1442    actual_four = mock_obj.Method(4)
1443    mock_obj.Close()
1444
1445    self.assertEquals(9, actual_one)
1446    self.assertEquals(8, actual_two)
1447    self.assertEquals(7, actual_three)
1448    self.assertEquals(10, actual_four)
1449
1450    self.mox.VerifyAll()
1451
1452  def testMultipleTimesMissingOne(self):
1453    """Test if MultipleTimesGroup fails if one method is missing."""
1454    mock_obj = self.mox.CreateMockAnything()
1455    mock_obj.Open()
1456    mock_obj.Method(1).MultipleTimes().AndReturn(9)
1457    mock_obj.Method(2).MultipleTimes().AndReturn(8)
1458    mock_obj.Method(3).MultipleTimes().AndReturn(7)
1459    mock_obj.Method(4).AndReturn(10)
1460    mock_obj.Close()
1461    self.mox.ReplayAll()
1462
1463    mock_obj.Open()
1464    mock_obj.Method(3)
1465    mock_obj.Method(2)
1466    mock_obj.Method(3)
1467    mock_obj.Method(3)
1468    mock_obj.Method(2)
1469
1470    self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 4)
1471
1472  def testMultipleTimesTwoGroups(self):
1473    """Test if MultipleTimesGroup works with a group after a
1474    MultipleTimesGroup.
1475    """
1476    mock_obj = self.mox.CreateMockAnything()
1477    mock_obj.Open()
1478    mock_obj.Method(1).MultipleTimes().AndReturn(9)
1479    mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1480    mock_obj.Close()
1481    self.mox.ReplayAll()
1482
1483    mock_obj.Open()
1484    actual_one = mock_obj.Method(1)
1485    mock_obj.Method(1)
1486    actual_three = mock_obj.Method(3)
1487    mock_obj.Method(3)
1488    mock_obj.Close()
1489
1490    self.assertEquals(9, actual_one)
1491    self.assertEquals(42, actual_three)
1492
1493    self.mox.VerifyAll()
1494
1495  def testMultipleTimesTwoGroupsFailure(self):
1496    """Test if MultipleTimesGroup fails with a group after a
1497    MultipleTimesGroup.
1498    """
1499    mock_obj = self.mox.CreateMockAnything()
1500    mock_obj.Open()
1501    mock_obj.Method(1).MultipleTimes().AndReturn(9)
1502    mock_obj.Method(3).MultipleTimes("nr2").AndReturn(42)
1503    mock_obj.Close()
1504    self.mox.ReplayAll()
1505
1506    mock_obj.Open()
1507    actual_one = mock_obj.Method(1)
1508    mock_obj.Method(1)
1509    actual_three = mock_obj.Method(3)
1510
1511    self.assertRaises(mox.UnexpectedMethodCallError, mock_obj.Method, 1)
1512
1513  def testWithSideEffects(self):
1514    """Test side effect operations actually modify their target objects."""
1515    def modifier(mutable_list):
1516      mutable_list[0] = 'mutated'
1517    mock_obj = self.mox.CreateMockAnything()
1518    mock_obj.ConfigureInOutParameter(['original']).WithSideEffects(modifier)
1519    mock_obj.WorkWithParameter(['mutated'])
1520    self.mox.ReplayAll()
1521
1522    local_list = ['original']
1523    mock_obj.ConfigureInOutParameter(local_list)
1524    mock_obj.WorkWithParameter(local_list)
1525
1526    self.mox.VerifyAll()
1527
1528  def testWithSideEffectsException(self):
1529    """Test side effect operations actually modify their target objects."""
1530    def modifier(mutable_list):
1531      mutable_list[0] = 'mutated'
1532    mock_obj = self.mox.CreateMockAnything()
1533    method = mock_obj.ConfigureInOutParameter(['original'])
1534    method.WithSideEffects(modifier).AndRaise(Exception('exception'))
1535    mock_obj.WorkWithParameter(['mutated'])
1536    self.mox.ReplayAll()
1537
1538    local_list = ['original']
1539    self.failUnlessRaises(Exception,
1540                          mock_obj.ConfigureInOutParameter,
1541                          local_list)
1542    mock_obj.WorkWithParameter(local_list)
1543
1544    self.mox.VerifyAll()
1545
1546  def testStubOutMethod(self):
1547    """Test that a method is replaced with a MockObject."""
1548    test_obj = TestClass()
1549    method_type = type(test_obj.OtherValidCall)
1550    # Replace OtherValidCall with a mock.
1551    self.mox.StubOutWithMock(test_obj, 'OtherValidCall')
1552    self.assertTrue(isinstance(test_obj.OtherValidCall, mox.MockObject))
1553    self.assertFalse(type(test_obj.OtherValidCall) is method_type)
1554
1555    test_obj.OtherValidCall().AndReturn('foo')
1556    self.mox.ReplayAll()
1557
1558    actual = test_obj.OtherValidCall()
1559
1560    self.mox.VerifyAll()
1561    self.mox.UnsetStubs()
1562    self.assertEquals('foo', actual)
1563    self.assertTrue(type(test_obj.OtherValidCall) is method_type)
1564
1565  def testStubOutMethod_CalledAsUnboundMethod_Comparator(self):
1566    instance = TestClass()
1567    self.mox.StubOutWithMock(TestClass, 'OtherValidCall')
1568
1569    TestClass.OtherValidCall(mox.IgnoreArg()).AndReturn('foo')
1570    self.mox.ReplayAll()
1571
1572    actual = TestClass.OtherValidCall(instance)
1573
1574    self.mox.VerifyAll()
1575    self.mox.UnsetStubs()
1576    self.assertEquals('foo', actual)
1577
1578  def testStubOutMethod_CalledAsUnboundMethod_ActualInstance(self):
1579    instance = TestClass()
1580    self.mox.StubOutWithMock(TestClass, 'OtherValidCall')
1581
1582    TestClass.OtherValidCall(instance).AndReturn('foo')
1583    self.mox.ReplayAll()
1584
1585    actual = TestClass.OtherValidCall(instance)
1586
1587    self.mox.VerifyAll()
1588    self.mox.UnsetStubs()
1589    self.assertEquals('foo', actual)
1590
1591  def testStubOutMethod_CalledAsUnboundMethod_DifferentInstance(self):
1592    instance = TestClass()
1593    self.mox.StubOutWithMock(TestClass, 'OtherValidCall')
1594
1595    TestClass.OtherValidCall(instance).AndReturn('foo')
1596    self.mox.ReplayAll()
1597
1598    # This should fail, since the instances are different
1599    self.assertRaises(mox.UnexpectedMethodCallError,
1600                      TestClass.OtherValidCall, "wrong self")
1601
1602
1603    self.mox.VerifyAll()
1604    self.mox.UnsetStubs()
1605
1606  def testStubOutMethod_CalledAsBoundMethod(self):
1607    t = self.mox.CreateMock(TestClass)
1608
1609    t.MethodWithArgs(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn('foo')
1610    self.mox.ReplayAll()
1611
1612    actual = t.MethodWithArgs(None, None);
1613
1614    self.mox.VerifyAll()
1615    self.mox.UnsetStubs()
1616    self.assertEquals('foo', actual)
1617
1618  def testStubOutClass_OldStyle(self):
1619    """Test a mocked class whose __init__ returns a Mock."""
1620    self.mox.StubOutWithMock(mox_test_helper, 'TestClassFromAnotherModule')
1621    self.assert_(isinstance(mox_test_helper.TestClassFromAnotherModule,
1622                            mox.MockObject))
1623
1624    mock_instance = self.mox.CreateMock(
1625        mox_test_helper.TestClassFromAnotherModule)
1626    mox_test_helper.TestClassFromAnotherModule().AndReturn(mock_instance)
1627    mock_instance.Value().AndReturn('mock instance')
1628
1629    self.mox.ReplayAll()
1630
1631    a_mock = mox_test_helper.TestClassFromAnotherModule()
1632    actual = a_mock.Value()
1633
1634    self.mox.VerifyAll()
1635    self.mox.UnsetStubs()
1636    self.assertEquals('mock instance', actual)
1637
1638  def testStubOutClass(self):
1639    self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1640
1641    # Instance one
1642    mock_one = mox_test_helper.CallableClass(1, 2)
1643    mock_one.Value().AndReturn('mock')
1644
1645    # Instance two
1646    mock_two = mox_test_helper.CallableClass(8, 9)
1647    mock_two('one').AndReturn('called mock')
1648
1649    self.mox.ReplayAll()
1650
1651    one = mox_test_helper.CallableClass(1, 2)
1652    actual_one = one.Value()
1653
1654    two = mox_test_helper.CallableClass(8, 9)
1655    actual_two = two('one')
1656
1657    self.mox.VerifyAll()
1658    self.mox.UnsetStubs()
1659
1660    # Verify the correct mocks were returned
1661    self.assertEquals(mock_one, one)
1662    self.assertEquals(mock_two, two)
1663
1664    # Verify
1665    self.assertEquals('mock', actual_one)
1666    self.assertEquals('called mock', actual_two)
1667
1668  def testStubOutClass_NotAClass(self):
1669    self.assertRaises(TypeError, self.mox.StubOutClassWithMocks,
1670                      mox_test_helper, 'MyTestFunction')
1671
1672  def testStubOutClassNotEnoughCreated(self):
1673    self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1674
1675    mox_test_helper.CallableClass(1, 2)
1676    mox_test_helper.CallableClass(8, 9)
1677
1678    self.mox.ReplayAll()
1679    mox_test_helper.CallableClass(1, 2)
1680
1681    self.assertRaises(mox.ExpectedMockCreationError, self.mox.VerifyAll)
1682    self.mox.UnsetStubs()
1683
1684  def testStubOutClassWrongSignature(self):
1685    self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1686
1687    self.assertRaises(AttributeError, mox_test_helper.CallableClass)
1688
1689    self.mox.UnsetStubs()
1690
1691  def testStubOutClassWrongParameters(self):
1692    self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1693
1694    mox_test_helper.CallableClass(1, 2)
1695
1696    self.mox.ReplayAll()
1697
1698    self.assertRaises(mox.UnexpectedMethodCallError,
1699                      mox_test_helper.CallableClass, 8, 9)
1700    self.mox.UnsetStubs()
1701
1702  def testStubOutClassTooManyCreated(self):
1703    self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
1704
1705    mox_test_helper.CallableClass(1, 2)
1706
1707    self.mox.ReplayAll()
1708    mox_test_helper.CallableClass(1, 2)
1709    self.assertRaises(mox.UnexpectedMockCreationError,
1710                      mox_test_helper.CallableClass, 8, 9)
1711
1712    self.mox.UnsetStubs()
1713
1714  def testWarnsUserIfMockingMock(self):
1715    """Test that user is warned if they try to stub out a MockAnything."""
1716    self.mox.StubOutWithMock(TestClass, 'MyStaticMethod')
1717    self.assertRaises(TypeError, self.mox.StubOutWithMock, TestClass,
1718                      'MyStaticMethod')
1719
1720  def testStubOutFirstClassMethodVerifiesSignature(self):
1721    self.mox.StubOutWithMock(mox_test_helper, 'MyTestFunction')
1722
1723    # Wrong number of arguments
1724    self.assertRaises(AttributeError, mox_test_helper.MyTestFunction, 1)
1725    self.mox.UnsetStubs()
1726
1727  def _testMethodSignatureVerification(self, stubClass):
1728    # If stubClass is true, the test is run against an a stubbed out class,
1729    # else the test is run against a stubbed out instance.
1730    if stubClass:
1731      self.mox.StubOutWithMock(mox_test_helper.ExampleClass, "TestMethod")
1732      obj = mox_test_helper.ExampleClass()
1733    else:
1734      obj = mox_test_helper.ExampleClass()
1735      self.mox.StubOutWithMock(mox_test_helper.ExampleClass, "TestMethod")
1736    self.assertRaises(AttributeError, obj.TestMethod)
1737    self.assertRaises(AttributeError, obj.TestMethod, 1)
1738    self.assertRaises(AttributeError, obj.TestMethod, nine=2)
1739    obj.TestMethod(1, 2)
1740    obj.TestMethod(1, 2, 3)
1741    obj.TestMethod(1, 2, nine=3)
1742    self.assertRaises(AttributeError, obj.TestMethod, 1, 2, 3, 4)
1743    self.mox.UnsetStubs()
1744
1745  def testStubOutClassMethodVerifiesSignature(self):
1746    self._testMethodSignatureVerification(stubClass=True)
1747
1748  def testStubOutObjectMethodVerifiesSignature(self):
1749    self._testMethodSignatureVerification(stubClass=False)
1750
1751  def testStubOutObject(self):
1752    """Test than object is replaced with a Mock."""
1753
1754    class Foo(object):
1755      def __init__(self):
1756        self.obj = TestClass()
1757
1758    foo = Foo()
1759    self.mox.StubOutWithMock(foo, "obj")
1760    self.assert_(isinstance(foo.obj, mox.MockObject))
1761    foo.obj.ValidCall()
1762    self.mox.ReplayAll()
1763
1764    foo.obj.ValidCall()
1765
1766    self.mox.VerifyAll()
1767    self.mox.UnsetStubs()
1768    self.failIf(isinstance(foo.obj, mox.MockObject))
1769
1770  def testForgotReplayHelpfulMessage(self):
1771    """If there is an AttributeError on a MockMethod, give users a helpful msg.
1772    """
1773    foo = self.mox.CreateMockAnything()
1774    bar = self.mox.CreateMockAnything()
1775    foo.GetBar().AndReturn(bar)
1776    bar.ShowMeTheMoney()
1777    # Forgot to replay!
1778    try:
1779      foo.GetBar().ShowMeTheMoney()
1780    except AttributeError, e:
1781      self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". '
1782          'Did you remember to put your mocks in replay mode?', str(e))
1783
1784
1785class ReplayTest(unittest.TestCase):
1786  """Verify Replay works properly."""
1787
1788  def testReplay(self):
1789    """Replay should put objects into replay mode."""
1790    mock_obj = mox.MockObject(TestClass)
1791    self.assertFalse(mock_obj._replay_mode)
1792    mox.Replay(mock_obj)
1793    self.assertTrue(mock_obj._replay_mode)
1794
1795
1796class MoxTestBaseTest(unittest.TestCase):
1797  """Verify that all tests in a class derived from MoxTestBase are wrapped."""
1798
1799  def setUp(self):
1800    self.mox = mox.Mox()
1801    self.test_mox = mox.Mox()
1802    self.test_stubs = mox.stubout.StubOutForTesting()
1803    self.result = unittest.TestResult()
1804
1805  def tearDown(self):
1806    self.mox.UnsetStubs()
1807    self.test_mox.UnsetStubs()
1808    self.test_stubs.UnsetAll()
1809    self.test_stubs.SmartUnsetAll()
1810
1811  def _setUpTestClass(self):
1812    """Replacement for setUp in the test class instance.
1813
1814    Assigns a mox.Mox instance as the mox attribute of the test class instance.
1815    This replacement Mox instance is under our control before setUp is called
1816    in the test class instance.
1817    """
1818    self.test.mox = self.test_mox
1819    self.test.stubs = self.test_stubs
1820
1821  def _CreateTest(self, test_name):
1822    """Create a test from our example mox class.
1823
1824    The created test instance is assigned to this instances test attribute.
1825    """
1826    self.test = mox_test_helper.ExampleMoxTest(test_name)
1827    self.mox.stubs.Set(self.test, 'setUp', self._setUpTestClass)
1828
1829  def _VerifySuccess(self):
1830    """Run the checks to confirm test method completed successfully."""
1831    self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1832    self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1833    self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1834    self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1835    self.test_mox.UnsetStubs()
1836    self.test_mox.VerifyAll()
1837    self.test_stubs.UnsetAll()
1838    self.test_stubs.SmartUnsetAll()
1839    self.mox.ReplayAll()
1840    self.test.run(result=self.result)
1841    self.assertTrue(self.result.wasSuccessful())
1842    self.mox.VerifyAll()
1843    self.mox.UnsetStubs()  # Needed to call the real VerifyAll() below.
1844    self.test_mox.VerifyAll()
1845
1846  def testSuccess(self):
1847    """Successful test method execution test."""
1848    self._CreateTest('testSuccess')
1849    self._VerifySuccess()
1850
1851  def testSuccessNoMocks(self):
1852    """Let testSuccess() unset all the mocks, and verify they've been unset."""
1853    self._CreateTest('testSuccess')
1854    self.test.run(result=self.result)
1855    self.assertTrue(self.result.wasSuccessful())
1856    self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1857
1858  def testStubs(self):
1859    """Test that "self.stubs" is provided as is useful."""
1860    self._CreateTest('testHasStubs')
1861    self._VerifySuccess()
1862
1863  def testStubsNoMocks(self):
1864    """Let testHasStubs() unset the stubs by itself."""
1865    self._CreateTest('testHasStubs')
1866    self.test.run(result=self.result)
1867    self.assertTrue(self.result.wasSuccessful())
1868    self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1869
1870  def testExpectedNotCalled(self):
1871    """Stubbed out method is not called."""
1872    self._CreateTest('testExpectedNotCalled')
1873    self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1874    self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1875    self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1876    # Don't stub out VerifyAll - that's what causes the test to fail
1877    self.test_mox.UnsetStubs()
1878    self.test_stubs.UnsetAll()
1879    self.test_stubs.SmartUnsetAll()
1880    self.mox.ReplayAll()
1881    self.test.run(result=self.result)
1882    self.failIf(self.result.wasSuccessful())
1883    self.mox.VerifyAll()
1884
1885  def testExpectedNotCalledNoMocks(self):
1886    """Let testExpectedNotCalled() unset all the mocks by itself."""
1887    self._CreateTest('testExpectedNotCalled')
1888    self.test.run(result=self.result)
1889    self.failIf(self.result.wasSuccessful())
1890    self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
1891
1892  def testUnexpectedCall(self):
1893    """Stubbed out method is called with unexpected arguments."""
1894    self._CreateTest('testUnexpectedCall')
1895    self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1896    self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1897    self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1898    # Ensure no calls are made to VerifyAll()
1899    self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1900    self.test_mox.UnsetStubs()
1901    self.test_stubs.UnsetAll()
1902    self.test_stubs.SmartUnsetAll()
1903    self.mox.ReplayAll()
1904    self.test.run(result=self.result)
1905    self.failIf(self.result.wasSuccessful())
1906    self.mox.VerifyAll()
1907
1908  def testFailure(self):
1909    """Failing assertion in test method."""
1910    self._CreateTest('testFailure')
1911    self.mox.StubOutWithMock(self.test_mox, 'UnsetStubs')
1912    self.mox.StubOutWithMock(self.test_stubs, 'UnsetAll')
1913    self.mox.StubOutWithMock(self.test_stubs, 'SmartUnsetAll')
1914    # Ensure no calls are made to VerifyAll()
1915    self.mox.StubOutWithMock(self.test_mox, 'VerifyAll')
1916    self.test_mox.UnsetStubs()
1917    self.test_stubs.UnsetAll()
1918    self.test_stubs.SmartUnsetAll()
1919    self.mox.ReplayAll()
1920    self.test.run(result=self.result)
1921    self.failIf(self.result.wasSuccessful())
1922    self.mox.VerifyAll()
1923
1924  def testMixin(self):
1925    """Run test from mix-in test class, ensure it passes."""
1926    self._CreateTest('testStat')
1927    self._VerifySuccess()
1928
1929  def testMixinAgain(self):
1930    """Run same test as above but from the current test class.
1931
1932    This ensures metaclass properly wrapped test methods from all base classes.
1933    If unsetting of stubs doesn't happen, this will fail.
1934    """
1935    self._CreateTest('testStatOther')
1936    self._VerifySuccess()
1937
1938
1939class VerifyTest(unittest.TestCase):
1940  """Verify Verify works properly."""
1941
1942  def testVerify(self):
1943    """Verify should be called for all objects.
1944
1945    This should throw an exception because the expected behavior did not occur.
1946    """
1947    mock_obj = mox.MockObject(TestClass)
1948    mock_obj.ValidCall()
1949    mock_obj._Replay()
1950    self.assertRaises(mox.ExpectedMethodCallsError, mox.Verify, mock_obj)
1951
1952
1953class ResetTest(unittest.TestCase):
1954  """Verify Reset works properly."""
1955
1956  def testReset(self):
1957    """Should empty all queues and put mocks in record mode."""
1958    mock_obj = mox.MockObject(TestClass)
1959    mock_obj.ValidCall()
1960    self.assertFalse(mock_obj._replay_mode)
1961    mock_obj._Replay()
1962    self.assertTrue(mock_obj._replay_mode)
1963    self.assertEquals(1, len(mock_obj._expected_calls_queue))
1964
1965    mox.Reset(mock_obj)
1966    self.assertFalse(mock_obj._replay_mode)
1967    self.assertEquals(0, len(mock_obj._expected_calls_queue))
1968
1969
1970class MyTestCase(unittest.TestCase):
1971  """Simulate the use of a fake wrapper around Python's unittest library."""
1972
1973  def setUp(self):
1974    super(MyTestCase, self).setUp()
1975    self.critical_variable = 42
1976    self.another_critical_variable = 42
1977
1978  def testMethodOverride(self):
1979    """Should be properly overriden in a derived class."""
1980    self.assertEquals(42, self.another_critical_variable)
1981    self.another_critical_variable += 1
1982
1983
1984class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase):
1985  """Test that multiple inheritance can be used with MoxTestBase."""
1986
1987  def setUp(self):
1988    super(MoxTestBaseMultipleInheritanceTest, self).setUp()
1989    self.another_critical_variable = 99
1990
1991  def testMultipleInheritance(self):
1992    """Should be able to access members created by all parent setUp()."""
1993    self.assert_(isinstance(self.mox, mox.Mox))
1994    self.assertEquals(42, self.critical_variable)
1995
1996  def testMethodOverride(self):
1997    """Should run before MyTestCase.testMethodOverride."""
1998    self.assertEquals(99, self.another_critical_variable)
1999    self.another_critical_variable = 42
2000    super(MoxTestBaseMultipleInheritanceTest, self).testMethodOverride()
2001    self.assertEquals(43, self.another_critical_variable)
2002
2003class MoxTestDontMockProperties(MoxTestBaseTest):
2004    def testPropertiesArentMocked(self):
2005        mock_class = self.mox.CreateMock(ClassWithProperties)
2006        self.assertRaises(mox.UnknownMethodCallError, lambda:
2007                mock_class.prop_attr)
2008
2009
2010class TestClass:
2011  """This class is used only for testing the mock framework"""
2012
2013  SOME_CLASS_VAR = "test_value"
2014  _PROTECTED_CLASS_VAR = "protected value"
2015
2016  def __init__(self, ivar=None):
2017    self.__ivar = ivar
2018
2019  def __eq__(self, rhs):
2020    return self.__ivar == rhs
2021
2022  def __ne__(self, rhs):
2023    return not self.__eq__(rhs)
2024
2025  def ValidCall(self):
2026    pass
2027
2028  def MethodWithArgs(self, one, two, nine=None):
2029    pass
2030
2031  def OtherValidCall(self):
2032    pass
2033
2034  def ValidCallWithArgs(self, *args, **kwargs):
2035    pass
2036
2037  @classmethod
2038  def MyClassMethod(cls):
2039    pass
2040
2041  @staticmethod
2042  def MyStaticMethod():
2043    pass
2044
2045  def _ProtectedCall(self):
2046    pass
2047
2048  def __PrivateCall(self):
2049    pass
2050
2051  def __getitem__(self, key):
2052    pass
2053
2054  def __DoNotMock(self):
2055    pass
2056
2057  def __getitem__(self, key):
2058    """Return the value for key."""
2059    return self.d[key]
2060
2061  def __setitem__(self, key, value):
2062    """Set the value for key to value."""
2063    self.d[key] = value
2064
2065  def __contains__(self, key):
2066     """Returns True if d contains the key."""
2067     return key in self.d
2068
2069  def __iter__(self):
2070    pass
2071
2072
2073class ChildClass(TestClass):
2074  """This inherits from TestClass."""
2075  def __init__(self):
2076    TestClass.__init__(self)
2077
2078  def ChildValidCall(self):
2079    pass
2080
2081
2082class CallableClass(object):
2083  """This class is callable, and that should be mockable!"""
2084
2085  def __init__(self):
2086    pass
2087
2088  def __call__(self, param):
2089    return param
2090
2091class ClassWithProperties(object):
2092    def setter_attr(self, value):
2093        pass
2094
2095    def getter_attr(self):
2096        pass
2097
2098    prop_attr = property(getter_attr, setter_attr)
2099
2100
2101class SubscribtableNonIterableClass(object):
2102  def __getitem__(self, index):
2103    raise IndexError
2104
2105
2106class InheritsFromCallable(CallableClass):
2107  """This class should also be mockable; it inherits from a callable class."""
2108
2109  pass
2110
2111
2112if __name__ == '__main__':
2113  unittest.main()
2114