desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raises: UnexpectedMethodCallError if the mock_method was not in the group.'
def MethodCalled(self, mock_method):
for method in self._methods: if (method == mock_method): self._methods.remove(mock_method) if (not self.IsSatisfied()): mock_method._call_queue.appendleft(self) return (self, method) raise UnexpectedMethodCallError(mock_method, self)
'Return True if there are not any methods in this group.'
def IsSatisfied(self):
return (len(self._methods) == 0)
'Add a method to this group. Args: mock_method: A mock method to be added to this group.'
def AddMethod(self, mock_method):
self._methods.add(mock_method) self._methods_left.add(mock_method)
'Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raises: UnexpectedMethodCallError if the mock_method was not in the group.'
def MethodCalled(self, mock_method):
for method in self._methods: if (method == mock_method): self._methods_left.discard(method) mock_method._call_queue.appendleft(self) return (self, method) if self.IsSatisfied(): next_method = mock_method._PopNextMethod() return (next_method, None) ...
'Return True if all methods in this group are called at least once.'
def IsSatisfied(self):
return (len(self._methods_left) == 0)
'Adds Mox cleanup code to any MoxTestBase method. Always unsets stubs after a test. Will verify all mocks for tests that otherwise pass. Args: cls: MoxTestBase or subclass; the class whose test method we are altering. func: method; the method of the MoxTestBase test class we wish to alter. Returns: The modified method....
@staticmethod def CleanUpTest(cls, func):
def new_method(self, *args, **kwargs): mox_obj = getattr(self, 'mox', None) stubout_obj = getattr(self, 'stubs', None) cleanup_mox = False cleanup_stubout = False if (mox_obj and isinstance(mox_obj, Mox)): cleanup_mox = True if (stubout_obj and isinstance(...
'Or should be True if either Comparator returns True.'
def testValidOr(self):
self.assert_((mox.Or(mox.IsA(dict), mox.IsA(str)) == {})) self.assert_((mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test')) self.assert_((mox.Or(mox.IsA(str), mox.IsA(str)) == 'test'))
'Or should be False if both Comparators return False.'
def testInvalidOr(self):
self.failIf((mox.Or(mox.IsA(dict), mox.IsA(str)) == 0))
'And should be True if both Comparators return True.'
def testValidAnd(self):
self.assert_((mox.And(mox.IsA(str), mox.IsA(str)) == '1'))
'And should be False if the first Comparator returns False.'
def testClauseOneFails(self):
self.failIf((mox.And(mox.IsA(dict), mox.IsA(str)) == '1'))
'And should work with other Comparators. Note: this test is reliant on In and ContainsKeyValue.'
def testAdvancedUsage(self):
test_dict = {'mock': 'obj', 'testing': 'isCOOL'} self.assert_((mox.And(mox.In('testing'), mox.ContainsKeyValue('mock', 'obj')) == test_dict))
'Note: this test is reliant on In and ContainsKeyValue.'
def testAdvancedUsageFails(self):
test_dict = {'mock': 'obj', 'testing': 'isCOOL'} self.failIf((mox.And(mox.In('NOTFOUND'), mox.ContainsKeyValue('mock', 'obj')) == test_dict))
'Should return True if two lists are exactly equal.'
def testSortedLists(self):
self.assert_((mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c']))
'Should return True if two lists are unequal but have same elements.'
def testUnsortedLists(self):
self.assert_((mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1]))
'Should return True if two lists have the same unhashable elements.'
def testUnhashableLists(self):
self.assert_((mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}, {'a': 1}]))
'Should return True for two empty lists.'
def testEmptyLists(self):
self.assert_((mox.SameElementsAs([]) == []))
'Should return False if the lists are not equal.'
def testUnequalLists(self):
self.failIf((mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c']))
'Should return False if two lists with unhashable elements are unequal.'
def testUnequalUnhashableLists(self):
self.failIf((mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}]))
'Should return True if the key value is in the dict.'
def testValidPair(self):
self.assert_((mox.ContainsKeyValue('key', 1) == {'key': 1}))
'Should return False if the value is not correct.'
def testInvalidValue(self):
self.failIf((mox.ContainsKeyValue('key', 1) == {'key': 2}))
'Should return False if they key is not in the dict.'
def testInvalidKey(self):
self.failIf((mox.ContainsKeyValue('qux', 1) == {'key': 2}))
'Create an object to test with.'
def setUp(self):
class TestObject(object, ): key = 1 self.test_object = TestObject()
'Should return True if the object has the key attribute and it matches.'
def testValidPair(self):
self.assert_((mox.ContainsAttributeValue('key', 1) == self.test_object))
'Should return False if the value is not correct.'
def testInvalidValue(self):
self.failIf((mox.ContainsKeyValue('key', 2) == self.test_object))
'Should return False if they the object doesn\'t have the property.'
def testInvalidKey(self):
self.failIf((mox.ContainsKeyValue('qux', 1) == self.test_object))
'Should return True if the item is in the list.'
def testItemInList(self):
self.assert_((mox.In(1) == [1, 2, 3]))
'Should return True if the item is a key in a dict.'
def testKeyInDict(self):
self.assert_((mox.In('test') == {'test': 'module'}))
'Should return True if the item is NOT in the list.'
def testItemInList(self):
self.assert_((mox.Not(mox.In(42)) == [1, 2, 3]))
'Should return True if the item is NOT a key in a dict.'
def testKeyInDict(self):
self.assert_((mox.Not(mox.In('foo')) == {'key': 42}))
'Should return False if they key is NOT in the dict.'
def testInvalidKeyWithNot(self):
self.assert_((mox.Not(mox.ContainsKeyValue('qux', 1)) == {'key': 2}))
'Should return True if the substring is at the start of the string.'
def testValidSubstringAtStart(self):
self.assert_((mox.StrContains('hello') == 'hello world'))
'Should return True if the substring is in the middle of the string.'
def testValidSubstringInMiddle(self):
self.assert_((mox.StrContains('lo wo') == 'hello world'))
'Should return True if the substring is at the end of the string.'
def testValidSubstringAtEnd(self):
self.assert_((mox.StrContains('ld') == 'hello world'))
'Should return False if the substring is not in the string.'
def testInvaildSubstring(self):
self.failIf((mox.StrContains('AAA') == 'hello world'))
'Should return True if there are multiple occurances of substring.'
def testMultipleMatches(self):
self.assert_((mox.StrContains('abc') == 'ababcabcabcababc'))
'The user should know immediately if a regex has bad syntax.'
def testIdentifyBadSyntaxDuringInit(self):
self.assertRaises(re.error, mox.Regex, '(a|b')
'Should return True if the pattern matches at the middle of the string. This ensures that re.search is used (instead of re.find).'
def testPatternInMiddle(self):
self.assert_((mox.Regex('a\\s+b') == 'x y z a b c'))
'Should return False if the pattern does not match the string.'
def testNonMatchPattern(self):
self.failIf((mox.Regex('a\\s+b') == 'x y z'))
'Should return True as we pass IGNORECASE flag.'
def testFlagsPassedCorrectly(self):
self.assert_((mox.Regex('A', re.IGNORECASE) == 'a'))
'repr should return the regular expression pattern.'
def testReprWithoutFlags(self):
self.assert_((repr(mox.Regex('a\\s+b')) == "<regular expression 'a\\s+b'>"))
'repr should return the regular expression pattern and flags.'
def testReprWithFlags(self):
self.assert_((repr(mox.Regex('a\\s+b', flags=4)) == "<regular expression 'a\\s+b', flags=4>"))
'Verify that == correctly identifies objects of the same type.'
def testEqualityValid(self):
self.assert_((mox.IsA(str) == 'test'))
'Verify that == correctly identifies objects of different types.'
def testEqualityInvalid(self):
self.failIf((mox.IsA(str) == 10))
'Verify that != identifies objects of different type.'
def testInequalityValid(self):
self.assert_((mox.IsA(str) != 10))
'Verify that != correctly identifies objects of the same type.'
def testInequalityInvalid(self):
self.failIf((mox.IsA(str) != 'test'))
'Verify list contents are properly compared.'
def testEqualityInListValid(self):
isa_list = [mox.IsA(str), mox.IsA(str)] str_list = ['abc', 'def'] self.assert_((isa_list == str_list))
'Verify list contents are properly compared.'
def testEquailtyInListInvalid(self):
isa_list = [mox.IsA(str), mox.IsA(str)] mixed_list = ['abc', 123] self.failIf((isa_list == mixed_list))
'Verify that IsA can handle objects like cStringIO.StringIO.'
def testSpecialTypes(self):
isA = mox.IsA(cStringIO.StringIO()) stringIO = cStringIO.StringIO() self.assert_((isA == stringIO))
'Verify that == correctly identifies nearly equivalent floats.'
def testEqualityValid(self):
self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
'Verify that == correctly identifies non-equivalent floats.'
def testEqualityInvalid(self):
self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
'Verify that specifying places has the desired effect.'
def testEqualityWithPlaces(self):
self.assertNotEquals(mox.IsAlmost(1.899), 1.9) self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
'Verify that IsAlmost handles non-numeric types properly.'
def testNonNumericTypes(self):
self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9') self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9) self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
'Should provide a __name__ attribute.'
def testNameAttribute(self):
self.assertEquals('testMethod', self.mock_method.__name__)
'Should return None by default.'
def testAndReturnNoneByDefault(self):
return_value = self.mock_method(['original']) self.assert_((return_value == None))
'Should return a specificed return value.'
def testAndReturnValue(self):
expected_return_value = 'test' self.expected_method.AndReturn(expected_return_value) return_value = self.mock_method(['original']) self.assert_((return_value == expected_return_value))
'Should raise a specified exception.'
def testAndRaiseException(self):
expected_exception = Exception('test exception') self.expected_method.AndRaise(expected_exception) self.assertRaises(Exception, self.mock_method)
'Should call state modifier.'
def testWithSideEffects(self):
local_list = ['original'] def modifier(mutable_list): self.assertTrue((local_list is mutable_list)) mutable_list[0] = 'mutation' self.expected_method.WithSideEffects(modifier).AndReturn(1) self.mock_method(local_list) self.assertEquals('mutation', local_list[0])
'Should call state modifier and propagate its return value.'
def testWithReturningSideEffects(self):
local_list = ['original'] expected_return = 'expected_return' def modifier_with_return(mutable_list): self.assertTrue((local_list is mutable_list)) mutable_list[0] = 'mutation' return expected_return self.expected_method.WithSideEffects(modifier_with_return) actual_return = s...
'Should call state modifier and ignore its return value.'
def testWithReturningSideEffectsWithAndReturn(self):
local_list = ['original'] expected_return = 'expected_return' unexpected_return = 'unexpected_return' def modifier_with_return(mutable_list): self.assertTrue((local_list is mutable_list)) mutable_list[0] = 'mutation' return unexpected_return self.expected_method.WithSideEffec...
'Methods with the same name and without params should be equal.'
def testEqualityNoParamsEqual(self):
expected_method = mox.MockMethod('testMethod', [], False) self.assertEqual(self.mock_method, expected_method)
'Methods with different names and without params should not be equal.'
def testEqualityNoParamsNotEqual(self):
expected_method = mox.MockMethod('otherMethod', [], False) self.failIfEqual(self.mock_method, expected_method)
'Methods with the same name and parameters should be equal.'
def testEqualityParamsEqual(self):
params = [1, 2, 3] expected_method = mox.MockMethod('testMethod', [], False) expected_method._params = params self.mock_method._params = params self.assertEqual(self.mock_method, expected_method)
'Methods with the same name and different params should not be equal.'
def testEqualityParamsNotEqual(self):
expected_method = mox.MockMethod('testMethod', [], False) expected_method._params = [1, 2, 3] self.mock_method._params = ['a', 'b', 'c'] self.failIfEqual(self.mock_method, expected_method)
'Methods with the same name and same named params should be equal.'
def testEqualityNamedParamsEqual(self):
named_params = {'input1': 'test', 'input2': 'params'} expected_method = mox.MockMethod('testMethod', [], False) expected_method._named_params = named_params self.mock_method._named_params = named_params self.assertEqual(self.mock_method, expected_method)
'Methods with the same name and diffnamed params should not be equal.'
def testEqualityNamedParamsNotEqual(self):
expected_method = mox.MockMethod('testMethod', [], False) expected_method._named_params = {'input1': 'test', 'input2': 'params'} self.mock_method._named_params = {'input1': 'test2', 'input2': 'params2'} self.failIfEqual(self.mock_method, expected_method)
'Method should not be equal to an object of a different type.'
def testEqualityWrongType(self):
self.failIfEqual(self.mock_method, 'string?')
'Equality of objects should work without a Comparator'
def testObjectEquality(self):
instA = TestClass() instB = TestClass() params = [instA] expected_method = mox.MockMethod('testMethod', [], False) expected_method._params = params self.mock_method._params = [instB] self.assertEqual(self.mock_method, expected_method)
'Calling repr on a MockAnything instance must work.'
def testRepr(self):
self.assertEqual('<MockAnything instance>', repr(self.mock_object))
'Verify the mock will accept any call.'
def testSetupMode(self):
self.mock_object.NonsenseCall() self.assert_((len(self.mock_object._expected_calls_queue) == 1))
'Verify the mock replays method calls as expected.'
def testReplayWithExpectedCall(self):
self.mock_object.ValidCall() self.mock_object._Replay() self.mock_object.ValidCall()
'Unexpected method calls should raise UnexpectedMethodCallError.'
def testReplayWithUnexpectedCall(self):
self.mock_object.ValidCall() self.mock_object._Replay() self.assertRaises(mox.UnexpectedMethodCallError, self.mock_object.OtherValidCall)
'Verify should not raise an exception for a valid replay.'
def testVerifyWithCompleteReplay(self):
self.mock_object.ValidCall() self.mock_object._Replay() self.mock_object.ValidCall() self.mock_object._Verify()
'Verify should raise an exception if the replay was not complete.'
def testVerifyWithIncompleteReplay(self):
self.mock_object.ValidCall() self.mock_object._Replay() self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify)
'Verify should not raise an exception when special methods are used.'
def testSpecialClassMethod(self):
self.mock_object[1].AndReturn(True) self.mock_object._Replay() returned_val = self.mock_object[1] self.assert_(returned_val) self.mock_object._Verify()
'You should be able to use the mock object in an if.'
def testNonzero(self):
self.mock_object._Replay() if self.mock_object: pass
'Mock should be comparable to None.'
def testNotNone(self):
self.mock_object._Replay() if (self.mock_object is not None): pass if (self.mock_object is None): pass
'A mock should be able to compare itself to another object.'
def testEquals(self):
self.mock_object._Replay() self.assertEquals(self.mock_object, self.mock_object)
'Verify equals identifies unequal objects.'
def testEqualsMockFailure(self):
self.mock_object.SillyCall() self.mock_object._Replay() self.assertNotEquals(self.mock_object, mox.MockAnything())
'Verify equals identifies that objects are different instances.'
def testEqualsInstanceFailure(self):
self.mock_object._Replay() self.assertNotEquals(self.mock_object, TestClass())
'Verify not equals works.'
def testNotEquals(self):
self.mock_object._Replay() self.assertFalse((self.mock_object != self.mock_object))
'Test that nested calls work when recorded serially.'
def testNestedMockCallsRecordedSerially(self):
self.mock_object.CallInner().AndReturn(1) self.mock_object.CallOuter(1) self.mock_object._Replay() self.mock_object.CallOuter(self.mock_object.CallInner()) self.mock_object._Verify()
'Test that nested cals work when recorded in a nested fashion.'
def testNestedMockCallsRecordedNested(self):
self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1)) self.mock_object._Replay() self.mock_object.CallOuter(self.mock_object.CallInner()) self.mock_object._Verify()
'Test that MockAnything can even mock a simple callable. This is handy for "stubbing out" a method in a module with a mock, and verifying that it was called.'
def testIsCallable(self):
self.mock_object().AndReturn('mox0rd') self.mock_object._Replay() self.assertEquals('mox0rd', self.mock_object()) self.mock_object._Verify()
'Test that MockAnythings can be repr\'d without causing a failure.'
def testIsReprable(self):
self.failUnless(('MockAnything' in repr(self.mock_object)))
'Verify the mock object properly mocks a basic method call.'
def testSetupModeWithValidCall(self):
self.mock_object.ValidCall() self.assert_((len(self.mock_object._expected_calls_queue) == 1))
'UnknownMethodCallError should be raised if a non-member method is called.'
def testSetupModeWithInvalidCall(self):
try: self.mock_object.InvalidCall() self.fail('No exception thrown, expected UnknownMethodCallError') except mox.UnknownMethodCallError: pass except Exception: self.fail('Wrong exception type thrown, expected UnknownMethodCallError')
'UnknownMethodCallError should be raised if a non-member method is called.'
def testReplayWithInvalidCall(self):
self.mock_object.ValidCall() self.mock_object._Replay() try: self.mock_object.InvalidCall() self.fail('No exception thrown, expected UnknownMethodCallError') except mox.UnknownMethodCallError: pass except Exception: self.fail('Wrong exception type ...
'Mock should be able to pass as an instance of the mocked class.'
def testIsInstance(self):
self.assert_(isinstance(self.mock_object, TestClass))
'Mock should be able to mock all public methods.'
def testFindValidMethods(self):
self.assert_(('ValidCall' in self.mock_object._known_methods)) self.assert_(('OtherValidCall' in self.mock_object._known_methods)) self.assert_(('MyClassMethod' in self.mock_object._known_methods)) self.assert_(('MyStaticMethod' in self.mock_object._known_methods)) self.assert_(('_ProtectedCall' in ...
'Mock should be able to mock superclasses methods.'
def testFindsSuperclassMethods(self):
self.mock_object = mox.MockObject(ChildClass) self.assert_(('ValidCall' in self.mock_object._known_methods)) self.assert_(('OtherValidCall' in self.mock_object._known_methods)) self.assert_(('MyClassMethod' in self.mock_object._known_methods)) self.assert_(('ChildValidCall' in self.mock_object._know...
'Class variables should be accessible through the mock.'
def testAccessClassVariables(self):
self.assert_(('SOME_CLASS_VAR' in self.mock_object._known_vars)) self.assert_(('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)) self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR)
'A mock should be able to compare itself to another object.'
def testEquals(self):
self.mock_object._Replay() self.assertEquals(self.mock_object, self.mock_object)
'Verify equals identifies unequal objects.'
def testEqualsMockFailure(self):
self.mock_object.ValidCall() self.mock_object._Replay() self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
'Verify equals identifies that objects are different instances.'
def testEqualsInstanceFailure(self):
self.mock_object._Replay() self.assertNotEquals(self.mock_object, TestClass())
'Verify not equals works.'
def testNotEquals(self):
self.mock_object._Replay() self.assertFalse((self.mock_object != self.mock_object))
'Test that __setitem__() gets mocked in Dummy. In this test, _Verify() succeeds.'
def testMockSetItem_ExpectedSetItem_Success(self):
dummy = mox.MockObject(TestClass) dummy['X'] = 'Y' dummy._Replay() dummy['X'] = 'Y' dummy._Verify()
'Test that __setitem__() gets mocked in Dummy. In this test, _Verify() fails.'
def testMockSetItem_ExpectedSetItem_NoSuccess(self):
dummy = mox.MockObject(TestClass) dummy['X'] = 'Y' dummy._Replay() self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)
'Test that __setitem__() gets mocked in Dummy.'
def testMockSetItem_ExpectedNoSetItem_Success(self):
dummy = mox.MockObject(TestClass) dummy._Replay() def call(): dummy['X'] = 'Y' self.assertRaises(mox.UnexpectedMethodCallError, call)
'Test that __setitem__() gets mocked in Dummy. In this test, _Verify() fails.'
def testMockSetItem_ExpectedNoSetItem_NoSuccess(self):
dummy = mox.MockObject(TestClass) dummy._Replay() dummy._Verify()
'Test that __setitem__() fails if other parameters are expected.'
def testMockSetItem_ExpectedSetItem_NonmatchingParameters(self):
dummy = mox.MockObject(TestClass) dummy['X'] = 'Y' dummy._Replay() def call(): dummy['wrong'] = 'Y' self.assertRaises(mox.UnexpectedMethodCallError, call) dummy._Verify()