Merge pull request #3 from quermit/fix-callables-inconsistency
Full Python 3 compatibility
This commit is contained in:
commit
17bee3dab4
|
@ -3,6 +3,8 @@ python:
|
|||
- "2.6"
|
||||
- "2.7"
|
||||
- "3.2"
|
||||
install: pip install pep8
|
||||
script:
|
||||
- pep8 --ignore E111 *.py || echo "Done"
|
||||
- python mox_test.py
|
||||
- python stubout_test.py
|
||||
|
|
117
mox.py
117
mox.py
|
@ -14,7 +14,9 @@
|
|||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# This file was mofified by quermit@gmail.com
|
||||
# This file was mofified by:
|
||||
# quermit@gmail.com
|
||||
# dawid.fatyga@gmail.com
|
||||
|
||||
"""Mox, an object-mocking framework for Python.
|
||||
|
||||
|
@ -69,7 +71,6 @@ import inspect
|
|||
import re
|
||||
import types
|
||||
import unittest
|
||||
import collections
|
||||
|
||||
import stubout
|
||||
|
||||
|
@ -241,7 +242,7 @@ class Mox(object):
|
|||
self._mock_objects = []
|
||||
self.stubs = stubout.StubOutForTesting()
|
||||
|
||||
def CreateMock(self, class_to_mock, attrs=None):
|
||||
def CreateMock(self, class_to_mock, attrs=None, bounded_to=None):
|
||||
"""Create a new mock object.
|
||||
|
||||
Args:
|
||||
|
@ -249,13 +250,15 @@ class Mox(object):
|
|||
class_to_mock: class
|
||||
attrs: dict of attribute names to values that will be set on the mock
|
||||
object. Only public attributes may be set.
|
||||
bounded_to: optionally, when class_to_mock is not a class, it points
|
||||
to a real class object, to which attribute is bound
|
||||
|
||||
Returns:
|
||||
MockObject that can be used as the class_to_mock would be.
|
||||
"""
|
||||
if attrs is None:
|
||||
attrs = {}
|
||||
new_mock = MockObject(class_to_mock, attrs=attrs)
|
||||
new_mock = MockObject(class_to_mock, attrs=attrs, class_to_bind=bounded_to)
|
||||
self._mock_objects.append(new_mock)
|
||||
return new_mock
|
||||
|
||||
|
@ -305,18 +308,23 @@ class Mox(object):
|
|||
of the type of attribute.
|
||||
"""
|
||||
|
||||
if inspect.isclass(obj):
|
||||
class_to_bind = obj
|
||||
else:
|
||||
class_to_bind = None
|
||||
|
||||
attr_to_replace = getattr(obj, attr_name)
|
||||
attr_type = type(attr_to_replace)
|
||||
|
||||
if attr_type == MockAnything or attr_type == MockObject:
|
||||
raise TypeError('Cannot mock a MockAnything! Did you remember to '
|
||||
'call UnsetStubs in your previous test?')
|
||||
|
||||
|
||||
type_check = (
|
||||
attr_type in self._USE_MOCK_OBJECT or inspect.isclass(attr_to_replace)
|
||||
or isinstance(attr_to_replace, object))
|
||||
if type_check and not use_mock_anything:
|
||||
stub = self.CreateMock(attr_to_replace)
|
||||
stub = self.CreateMock(attr_to_replace, bounded_to=class_to_bind)
|
||||
else:
|
||||
stub = self.CreateMockAnything(description='Stub for %s' % attr_to_replace)
|
||||
stub.__name__ = attr_name
|
||||
|
@ -367,7 +375,7 @@ class Mox(object):
|
|||
if attr_type == MockAnything or attr_type == MockObject:
|
||||
raise TypeError('Cannot mock a MockAnything! Did you remember to '
|
||||
'call UnsetStubs in your previous test?')
|
||||
|
||||
|
||||
if not inspect.isclass(attr_to_replace):
|
||||
raise TypeError('Given attr is not a Class. Use StubOutWithMock.')
|
||||
|
||||
|
@ -380,6 +388,7 @@ class Mox(object):
|
|||
|
||||
self.stubs.UnsetAll()
|
||||
|
||||
|
||||
def Replay(*args):
|
||||
"""Put mocks into Replay mode.
|
||||
|
||||
|
@ -453,22 +462,24 @@ class MockAnything(object):
|
|||
return self.__class__.__dir__.__get__(self, self.__class__)
|
||||
|
||||
return self._CreateMockMethod(method_name)
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return self._CreateMockMethod('__str__')()
|
||||
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
return self._CreateMockMethod('__call__')(*args, **kwargs)
|
||||
|
||||
|
||||
def __getitem__(self, i):
|
||||
return self._CreateMockMethod('__getitem__')(i)
|
||||
|
||||
def _CreateMockMethod(self, method_name, method_to_mock=None):
|
||||
|
||||
def _CreateMockMethod(self, method_name, method_to_mock=None,
|
||||
class_to_bind=object):
|
||||
"""Create a new mock method call and return it.
|
||||
|
||||
Args:
|
||||
# method_name: the name of the method being called.
|
||||
# method_to_mock: The actual method being mocked, used for introspection.
|
||||
# class_to_bind: Class to which method is bounded (object by default)
|
||||
method_name: str
|
||||
method_to_mock: a method object
|
||||
|
||||
|
@ -478,13 +489,14 @@ class MockAnything(object):
|
|||
|
||||
return MockMethod(method_name, self._expected_calls_queue,
|
||||
self._replay_mode, method_to_mock=method_to_mock,
|
||||
description=self._description)
|
||||
description=self._description,
|
||||
class_to_bind=class_to_bind)
|
||||
|
||||
def __nonzero__(self):
|
||||
"""Return 1 for nonzero so the mock can be used as a conditional."""
|
||||
|
||||
return 1
|
||||
|
||||
|
||||
def __bool__(self):
|
||||
"""Return True for nonzero so the mock can be used as a conditional."""
|
||||
return True
|
||||
|
@ -537,7 +549,7 @@ class MockAnything(object):
|
|||
class MockObject(MockAnything):
|
||||
"""A mock object that simulates the public/protected interface of a class."""
|
||||
|
||||
def __init__(self, class_to_mock, attrs=None):
|
||||
def __init__(self, class_to_mock, attrs=None, class_to_bind=None):
|
||||
"""Initialize a mock object.
|
||||
|
||||
This determines the methods and properties of the class and stores them.
|
||||
|
@ -547,6 +559,8 @@ class MockObject(MockAnything):
|
|||
class_to_mock: class
|
||||
attrs: dict of attribute names to values that will be set on the mock
|
||||
object. Only public attributes may be set.
|
||||
class_to_bind: optionally, when class_to_mock is not a class at all, it
|
||||
points to a real class
|
||||
|
||||
Raises:
|
||||
PrivateAttributeError: if a supplied attribute is not public.
|
||||
|
@ -563,6 +577,12 @@ class MockObject(MockAnything):
|
|||
self._known_methods = set()
|
||||
self._known_vars = set()
|
||||
self._class_to_mock = class_to_mock
|
||||
|
||||
if inspect.isclass(class_to_mock):
|
||||
self._class_to_bind = self._class_to_mock
|
||||
else:
|
||||
self._class_to_bind = class_to_bind
|
||||
|
||||
try:
|
||||
if inspect.isclass(self._class_to_mock):
|
||||
self._description = class_to_mock.__name__
|
||||
|
@ -591,6 +611,11 @@ class MockObject(MockAnything):
|
|||
else:
|
||||
setattr(self, attr, value)
|
||||
|
||||
def _CreateMockMethod(self, *args, **kwargs):
|
||||
"""Overridden to provide self._class_to_mock to class_to_bind parameter."""
|
||||
kwargs.setdefault("class_to_bind", self._class_to_bind)
|
||||
return super(MockObject, self)._CreateMockMethod(*args, **kwargs)
|
||||
|
||||
def __getattr__(self, name):
|
||||
"""Intercept attribute request on this object.
|
||||
|
||||
|
@ -776,24 +801,36 @@ class MockObject(MockAnything):
|
|||
# __call__ method
|
||||
method = None
|
||||
if type(self._class_to_mock) in (types.FunctionType, types.MethodType):
|
||||
method = self._class_to_mock;
|
||||
method = self._class_to_mock
|
||||
else:
|
||||
method = getattr(self._class_to_mock, '__call__')
|
||||
mock_method = self._CreateMockMethod('__call__', method_to_mock=method)
|
||||
|
||||
return mock_method(*params, **named_params)
|
||||
|
||||
@property
|
||||
def __class__(self):
|
||||
"""Return the class that is being mocked."""
|
||||
|
||||
return self._class_to_mock
|
||||
|
||||
@property
|
||||
def __name__(self):
|
||||
"""Return the name that is being mocked."""
|
||||
return self._description
|
||||
|
||||
# TODO(dejw): this property stopped to work after I introduced changes with
|
||||
# binding classes. Fortunately I found a solution in the form of
|
||||
# __getattribute__ method below, but this issue should be investigated
|
||||
@property
|
||||
def __class__(self):
|
||||
return self._class_to_mock
|
||||
|
||||
def __dir__(self):
|
||||
"""Return only attributes of a class to mock """
|
||||
return dir(self._class_to_mock)
|
||||
|
||||
def __getattribute__(self, name):
|
||||
"""Return _class_to_mock on __class__ attribute. """
|
||||
if name == "__class__":
|
||||
return super(MockObject, self).__getattribute__("_class_to_mock")
|
||||
|
||||
return super(MockObject, self).__getattribute__(name)
|
||||
|
||||
|
||||
class _MockObjectFactory(MockObject):
|
||||
"""A MockObjectFactory creates mocks and verifies __init__ params.
|
||||
|
@ -848,12 +885,15 @@ class MethodSignatureChecker(object):
|
|||
|
||||
_NEEDED, _DEFAULT, _GIVEN = range(3)
|
||||
|
||||
def __init__(self, method):
|
||||
def __init__(self, method, class_to_bind=None):
|
||||
"""Creates a checker.
|
||||
|
||||
Args:
|
||||
# method: A method to check.
|
||||
# class_to_bind: optionally, a class used to type check first method
|
||||
# parameter, only used with unbound methods
|
||||
method: function
|
||||
class_to_bind: type or None
|
||||
|
||||
Raises:
|
||||
ValueError: method could not be inspected, so checks aren't possible.
|
||||
|
@ -864,10 +904,17 @@ class MethodSignatureChecker(object):
|
|||
except TypeError:
|
||||
raise ValueError('Could not get argument specification for %r'
|
||||
% (method,))
|
||||
if inspect.ismethod(method):
|
||||
if inspect.ismethod(method) or class_to_bind:
|
||||
self._args = self._args[1:] # Skip 'self'.
|
||||
self._method = method
|
||||
self._instance = None # May contain the instance this is bound to.
|
||||
self._instance = getattr(method, "__self__", None)
|
||||
|
||||
# _bounded_to determines whether the method is bound or not
|
||||
if self._instance:
|
||||
self._bounded_to = self._instance.__class__
|
||||
else:
|
||||
self._bounded_to = class_to_bind or getattr(method, "im_class", None)
|
||||
|
||||
self._has_varargs = varargs is not None
|
||||
self._has_varkw = varkw is not None
|
||||
|
@ -920,10 +967,10 @@ class MethodSignatureChecker(object):
|
|||
#
|
||||
# NOTE: If a Func() comparator is used, and the signature is not
|
||||
# correct, this will cause extra executions of the function.
|
||||
if inspect.ismethod(self._method):
|
||||
if inspect.ismethod(self._method) or self._bounded_to:
|
||||
# The extra param accounts for the bound instance.
|
||||
if len(params) > len(self._required_args):
|
||||
expected = getattr(self._method, 'im_class', None)
|
||||
expected = self._bounded_to
|
||||
|
||||
# Check if the param is an instance of the expected class,
|
||||
# or check equality (useful for checking Comparators).
|
||||
|
@ -934,7 +981,7 @@ class MethodSignatureChecker(object):
|
|||
try:
|
||||
param_equality = (params[0] == expected)
|
||||
except:
|
||||
param_equality = False;
|
||||
param_equality = False
|
||||
|
||||
|
||||
if isinstance(params[0], expected) or param_equality:
|
||||
|
@ -982,7 +1029,7 @@ class MockMethod(object):
|
|||
"""
|
||||
|
||||
def __init__(self, method_name, call_queue, replay_mode,
|
||||
method_to_mock=None, description=None):
|
||||
method_to_mock=None, description=None, class_to_bind=None):
|
||||
"""Construct a new mock method.
|
||||
|
||||
Args:
|
||||
|
@ -994,11 +1041,16 @@ class MockMethod(object):
|
|||
# method_to_mock: The actual method being mocked, used for introspection.
|
||||
# description: optionally, a descriptive name for this method. Typically
|
||||
# this is equal to the descriptive name of the method's class.
|
||||
# class_to_bind: optionally, a class that is used for unbound methods
|
||||
# (or functions in Python3) to which method is bound, in order not
|
||||
# to loose binding information. If given, it will be used for
|
||||
# checking the type of first method parameter
|
||||
method_name: str
|
||||
call_queue: list or deque
|
||||
replay_mode: bool
|
||||
method_to_mock: a method object
|
||||
description: str or None
|
||||
class_to_bind: type or None
|
||||
"""
|
||||
|
||||
self._name = method_name
|
||||
|
@ -1016,7 +1068,8 @@ class MockMethod(object):
|
|||
self._side_effects = None
|
||||
|
||||
try:
|
||||
self._checker = MethodSignatureChecker(method_to_mock)
|
||||
self._checker = MethodSignatureChecker(method_to_mock,
|
||||
class_to_bind=class_to_bind)
|
||||
except ValueError:
|
||||
self._checker = None
|
||||
|
||||
|
@ -1069,7 +1122,7 @@ class MockMethod(object):
|
|||
"""Raise a TypeError with a helpful message."""
|
||||
raise TypeError('MockMethod cannot be iterated. '
|
||||
'Did you remember to put your mocks in replay mode?')
|
||||
|
||||
|
||||
def __next__(self):
|
||||
"""Raise a TypeError with a helpful message."""
|
||||
raise TypeError('MockMethod cannot be iterated. '
|
||||
|
@ -1117,7 +1170,7 @@ class MockMethod(object):
|
|||
if self._description:
|
||||
full_desc = "%s.%s" % (self._description, full_desc)
|
||||
return full_desc
|
||||
|
||||
|
||||
def __hash__(self):
|
||||
return id(self)
|
||||
|
||||
|
@ -1643,7 +1696,7 @@ class SameElementsAs(Comparator):
|
|||
# This happens because Mox uses __eq__ both to check object equality (in
|
||||
# MethodSignatureChecker) and to invoke Comparators.
|
||||
return False
|
||||
|
||||
|
||||
try:
|
||||
return set(self._expected_list) == set(actual_list)
|
||||
except TypeError:
|
||||
|
|
369
mox_test.py
369
mox_test.py
|
@ -16,11 +16,14 @@
|
|||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# This file was mofified by quermit@gmail.com
|
||||
# This file was mofified by:
|
||||
# quermit@gmail.com
|
||||
# dawid.fatyga@gmail.com
|
||||
|
||||
import io
|
||||
import unittest
|
||||
import re
|
||||
import sys
|
||||
|
||||
import mox
|
||||
|
||||
|
@ -67,13 +70,13 @@ class OrTest(unittest.TestCase):
|
|||
|
||||
def testValidOr(self):
|
||||
"""Or should be True if either Comparator returns True."""
|
||||
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')
|
||||
self.assertTrue(mox.Or(mox.IsA(dict), mox.IsA(str)) == {})
|
||||
self.assertTrue(mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test')
|
||||
self.assertTrue(mox.Or(mox.IsA(str), mox.IsA(str)) == 'test')
|
||||
|
||||
def testInvalidOr(self):
|
||||
"""Or should be False if both Comparators return False."""
|
||||
self.failIf(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0)
|
||||
self.assertFalse(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0)
|
||||
|
||||
|
||||
class AndTest(unittest.TestCase):
|
||||
|
@ -81,12 +84,12 @@ class AndTest(unittest.TestCase):
|
|||
|
||||
def testValidAnd(self):
|
||||
"""And should be True if both Comparators return True."""
|
||||
self.assert_(mox.And(mox.IsA(str), mox.IsA(str)) == '1')
|
||||
self.assertTrue(mox.And(mox.IsA(str), mox.IsA(str)) == '1')
|
||||
|
||||
def testClauseOneFails(self):
|
||||
"""And should be False if the first Comparator returns False."""
|
||||
|
||||
self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1')
|
||||
self.assertFalse(mox.And(mox.IsA(dict), mox.IsA(str)) == '1')
|
||||
|
||||
def testAdvancedUsage(self):
|
||||
"""And should work with other Comparators.
|
||||
|
@ -94,13 +97,13 @@ class AndTest(unittest.TestCase):
|
|||
Note: this test is reliant on In and ContainsKeyValue.
|
||||
"""
|
||||
test_dict = {"mock" : "obj", "testing" : "isCOOL"}
|
||||
self.assert_(mox.And(mox.In("testing"),
|
||||
self.assertTrue(mox.And(mox.In("testing"),
|
||||
mox.ContainsKeyValue("mock", "obj")) == test_dict)
|
||||
|
||||
def testAdvancedUsageFails(self):
|
||||
"""Note: this test is reliant on In and ContainsKeyValue."""
|
||||
test_dict = {"mock" : "obj", "testing" : "isCOOL"}
|
||||
self.failIf(mox.And(mox.In("NOTFOUND"),
|
||||
self.assertFalse(mox.And(mox.In("NOTFOUND"),
|
||||
mox.ContainsKeyValue("mock", "obj")) == test_dict)
|
||||
|
||||
class FuncTest(unittest.TestCase):
|
||||
|
@ -111,13 +114,12 @@ class FuncTest(unittest.TestCase):
|
|||
equals_one = lambda x: x == 1
|
||||
always_none = lambda x: None
|
||||
|
||||
self.assert_(mox.Func(equals_one) == 1)
|
||||
self.failIf(mox.Func(equals_one) == 0)
|
||||
self.assertTrue(mox.Func(equals_one) == 1)
|
||||
self.assertFalse(mox.Func(equals_one) == 0)
|
||||
|
||||
|
||||
self.failIf(mox.Func(always_none) == 1)
|
||||
self.failIf(mox.Func(always_none) == 0)
|
||||
self.failIf(mox.Func(always_none) == None)
|
||||
self.assertFalse(mox.Func(always_none) == 1)
|
||||
self.assertFalse(mox.Func(always_none) == 0)
|
||||
self.assertFalse(mox.Func(always_none) == None)
|
||||
|
||||
def testFuncExceptionPropagation(self):
|
||||
"""Exceptions within the validating function should propagate."""
|
||||
|
@ -130,7 +132,7 @@ class FuncTest(unittest.TestCase):
|
|||
else:
|
||||
return True
|
||||
|
||||
self.assert_(mox.Func(raiseExceptionOnNotOne) == 1)
|
||||
self.assertTrue(mox.Func(raiseExceptionOnNotOne) == 1)
|
||||
self.assertRaises(TestException, mox.Func(raiseExceptionOnNotOne).__eq__, 2)
|
||||
|
||||
class SameElementsAsTest(unittest.TestCase):
|
||||
|
@ -138,32 +140,32 @@ class SameElementsAsTest(unittest.TestCase):
|
|||
|
||||
def testSortedLists(self):
|
||||
"""Should return True if two lists are exactly equal."""
|
||||
self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c'])
|
||||
self.assertTrue(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c'])
|
||||
|
||||
def testUnsortedLists(self):
|
||||
"""Should return True if two lists are unequal but have same elements."""
|
||||
self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1])
|
||||
self.assertTrue(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1])
|
||||
|
||||
def testUnhashableLists(self):
|
||||
"""Should return True if two lists have the same unhashable elements."""
|
||||
self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) ==
|
||||
self.assertTrue(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) ==
|
||||
[{2: 'b'}, {'a': 1}])
|
||||
|
||||
def testEmptyLists(self):
|
||||
"""Should return True for two empty lists."""
|
||||
self.assert_(mox.SameElementsAs([]) == [])
|
||||
self.assertTrue(mox.SameElementsAs([]) == [])
|
||||
|
||||
def testUnequalLists(self):
|
||||
"""Should return False if the lists are not equal."""
|
||||
self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c'])
|
||||
self.assertFalse(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c'])
|
||||
|
||||
def testUnequalUnhashableLists(self):
|
||||
"""Should return False if two lists with unhashable elements are unequal."""
|
||||
self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])
|
||||
self.assertFalse(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])
|
||||
|
||||
def testActualIsNotASequence(self):
|
||||
"""Should return False if the actual object is not a sequence."""
|
||||
self.failIf(mox.SameElementsAs([1]) == object())
|
||||
self.assertFalse(mox.SameElementsAs([1]) == object())
|
||||
|
||||
def testOneUnhashableObjectInActual(self):
|
||||
"""Store the entire iterator for a correct comparison.
|
||||
|
@ -172,7 +174,7 @@ class SameElementsAsTest(unittest.TestCase):
|
|||
unhashable object was encountered and then was restarted, so the actual list
|
||||
appeared smaller than it was.
|
||||
"""
|
||||
self.failIf(mox.SameElementsAs([1, 2]) == iter([{}, 1, 2]))
|
||||
self.assertFalse(mox.SameElementsAs([1, 2]) == iter([{}, 1, 2]))
|
||||
|
||||
|
||||
class ContainsKeyValueTest(unittest.TestCase):
|
||||
|
@ -181,15 +183,15 @@ class ContainsKeyValueTest(unittest.TestCase):
|
|||
|
||||
def testValidPair(self):
|
||||
"""Should return True if the key value is in the dict."""
|
||||
self.assert_(mox.ContainsKeyValue("key", 1) == {"key": 1})
|
||||
self.assertTrue(mox.ContainsKeyValue("key", 1) == {"key": 1})
|
||||
|
||||
def testInvalidValue(self):
|
||||
"""Should return False if the value is not correct."""
|
||||
self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2})
|
||||
self.assertFalse(mox.ContainsKeyValue("key", 1) == {"key": 2})
|
||||
|
||||
def testInvalidKey(self):
|
||||
"""Should return False if they key is not in the dict."""
|
||||
self.failIf(mox.ContainsKeyValue("qux", 1) == {"key": 2})
|
||||
self.assertFalse(mox.ContainsKeyValue("qux", 1) == {"key": 2})
|
||||
|
||||
|
||||
class ContainsAttributeValueTest(unittest.TestCase):
|
||||
|
@ -207,15 +209,15 @@ class ContainsAttributeValueTest(unittest.TestCase):
|
|||
|
||||
def testValidPair(self):
|
||||
"""Should return True if the object has the key attribute and it matches."""
|
||||
self.assert_(mox.ContainsAttributeValue("key", 1) == self.test_object)
|
||||
self.assertTrue(mox.ContainsAttributeValue("key", 1) == self.test_object)
|
||||
|
||||
def testInvalidValue(self):
|
||||
"""Should return False if the value is not correct."""
|
||||
self.failIf(mox.ContainsKeyValue("key", 2) == self.test_object)
|
||||
self.assertFalse(mox.ContainsKeyValue("key", 2) == self.test_object)
|
||||
|
||||
def testInvalidKey(self):
|
||||
"""Should return False if they the object doesn't have the property."""
|
||||
self.failIf(mox.ContainsKeyValue("qux", 1) == self.test_object)
|
||||
self.assertFalse(mox.ContainsKeyValue("qux", 1) == self.test_object)
|
||||
|
||||
|
||||
class InTest(unittest.TestCase):
|
||||
|
@ -223,24 +225,24 @@ class InTest(unittest.TestCase):
|
|||
|
||||
def testItemInList(self):
|
||||
"""Should return True if the item is in the list."""
|
||||
self.assert_(mox.In(1) == [1, 2, 3])
|
||||
self.assertTrue(mox.In(1) == [1, 2, 3])
|
||||
|
||||
def testKeyInDict(self):
|
||||
"""Should return True if the item is a key in a dict."""
|
||||
self.assert_(mox.In("test") == {"test" : "module"})
|
||||
self.assertTrue(mox.In("test") == {"test" : "module"})
|
||||
|
||||
def testItemInTuple(self):
|
||||
"""Should return True if the item is in the list."""
|
||||
self.assert_(mox.In(1) == (1, 2, 3))
|
||||
self.assertTrue(mox.In(1) == (1, 2, 3))
|
||||
|
||||
def testTupleInTupleOfTuples(self):
|
||||
self.assert_(mox.In((1, 2, 3)) == ((1, 2, 3), (1, 2)))
|
||||
self.assertTrue(mox.In((1, 2, 3)) == ((1, 2, 3), (1, 2)))
|
||||
|
||||
def testItemNotInList(self):
|
||||
self.failIf(mox.In(1) == [2, 3])
|
||||
self.assertFalse(mox.In(1) == [2, 3])
|
||||
|
||||
def testTupleNotInTupleOfTuples(self):
|
||||
self.failIf(mox.In((1, 2)) == ((1, 2, 3), (4, 5)))
|
||||
self.assertFalse(mox.In((1, 2)) == ((1, 2, 3), (4, 5)))
|
||||
|
||||
|
||||
class NotTest(unittest.TestCase):
|
||||
|
@ -248,15 +250,15 @@ class NotTest(unittest.TestCase):
|
|||
|
||||
def testItemInList(self):
|
||||
"""Should return True if the item is NOT in the list."""
|
||||
self.assert_(mox.Not(mox.In(42)) == [1, 2, 3])
|
||||
self.assertTrue(mox.Not(mox.In(42)) == [1, 2, 3])
|
||||
|
||||
def testKeyInDict(self):
|
||||
"""Should return True if the item is NOT a key in a dict."""
|
||||
self.assert_(mox.Not(mox.In("foo")) == {"key" : 42})
|
||||
self.assertTrue(mox.Not(mox.In("foo")) == {"key" : 42})
|
||||
|
||||
def testInvalidKeyWithNot(self):
|
||||
"""Should return False if they key is NOT in the dict."""
|
||||
self.assert_(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2})
|
||||
self.assertTrue(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2})
|
||||
|
||||
|
||||
class StrContainsTest(unittest.TestCase):
|
||||
|
@ -265,23 +267,23 @@ class StrContainsTest(unittest.TestCase):
|
|||
|
||||
def testValidSubstringAtStart(self):
|
||||
"""Should return True if the substring is at the start of the string."""
|
||||
self.assert_(mox.StrContains("hello") == "hello world")
|
||||
self.assertTrue(mox.StrContains("hello") == "hello world")
|
||||
|
||||
def testValidSubstringInMiddle(self):
|
||||
"""Should return True if the substring is in the middle of the string."""
|
||||
self.assert_(mox.StrContains("lo wo") == "hello world")
|
||||
self.assertTrue(mox.StrContains("lo wo") == "hello world")
|
||||
|
||||
def testValidSubstringAtEnd(self):
|
||||
"""Should return True if the substring is at the end of the string."""
|
||||
self.assert_(mox.StrContains("ld") == "hello world")
|
||||
self.assertTrue(mox.StrContains("ld") == "hello world")
|
||||
|
||||
def testInvaildSubstring(self):
|
||||
"""Should return False if the substring is not in the string."""
|
||||
self.failIf(mox.StrContains("AAA") == "hello world")
|
||||
self.assertFalse(mox.StrContains("AAA") == "hello world")
|
||||
|
||||
def testMultipleMatches(self):
|
||||
"""Should return True if there are multiple occurances of substring."""
|
||||
self.assert_(mox.StrContains("abc") == "ababcabcabcababc")
|
||||
self.assertTrue(mox.StrContains("abc") == "ababcabcabcababc")
|
||||
|
||||
|
||||
class RegexTest(unittest.TestCase):
|
||||
|
@ -296,23 +298,23 @@ class RegexTest(unittest.TestCase):
|
|||
|
||||
This ensures that re.search is used (instead of re.find).
|
||||
"""
|
||||
self.assert_(mox.Regex(r"a\s+b") == "x y z a b c")
|
||||
self.assertTrue(mox.Regex(r"a\s+b") == "x y z a b c")
|
||||
|
||||
def testNonMatchPattern(self):
|
||||
"""Should return False if the pattern does not match the string."""
|
||||
self.failIf(mox.Regex(r"a\s+b") == "x y z")
|
||||
self.assertFalse(mox.Regex(r"a\s+b") == "x y z")
|
||||
|
||||
def testFlagsPassedCorrectly(self):
|
||||
"""Should return True as we pass IGNORECASE flag."""
|
||||
self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a")
|
||||
self.assertTrue(mox.Regex(r"A", re.IGNORECASE) == "a")
|
||||
|
||||
def testReprWithoutFlags(self):
|
||||
"""repr should return the regular expression pattern."""
|
||||
self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>")
|
||||
self.assertTrue(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>")
|
||||
|
||||
def testReprWithFlags(self):
|
||||
"""repr should return the regular expression pattern and flags."""
|
||||
self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) ==
|
||||
self.assertTrue(repr(mox.Regex(r"a\s+b", flags=4)) ==
|
||||
"<regular expression 'a\s+b', flags=4>")
|
||||
|
||||
|
||||
|
@ -367,37 +369,37 @@ class IsATest(unittest.TestCase):
|
|||
|
||||
def testEqualityValid(self):
|
||||
"""Verify that == correctly identifies objects of the same type."""
|
||||
self.assert_(mox.IsA(str) == 'test')
|
||||
self.assertTrue(mox.IsA(str) == 'test')
|
||||
|
||||
def testEqualityInvalid(self):
|
||||
"""Verify that == correctly identifies objects of different types."""
|
||||
self.failIf(mox.IsA(str) == 10)
|
||||
self.assertFalse(mox.IsA(str) == 10)
|
||||
|
||||
def testInequalityValid(self):
|
||||
"""Verify that != identifies objects of different type."""
|
||||
self.assert_(mox.IsA(str) != 10)
|
||||
self.assertTrue(mox.IsA(str) != 10)
|
||||
|
||||
def testInequalityInvalid(self):
|
||||
"""Verify that != correctly identifies objects of the same type."""
|
||||
self.failIf(mox.IsA(str) != "test")
|
||||
self.assertFalse(mox.IsA(str) != "test")
|
||||
|
||||
def testEqualityInListValid(self):
|
||||
"""Verify list contents are properly compared."""
|
||||
isa_list = [mox.IsA(str), mox.IsA(str)]
|
||||
str_list = ["abc", "def"]
|
||||
self.assert_(isa_list == str_list)
|
||||
self.assertTrue(isa_list == str_list)
|
||||
|
||||
def testEquailtyInListInvalid(self):
|
||||
"""Verify list contents are properly compared."""
|
||||
isa_list = [mox.IsA(str),mox.IsA(str)]
|
||||
mixed_list = ["abc", 123]
|
||||
self.failIf(isa_list == mixed_list)
|
||||
self.assertFalse(isa_list == mixed_list)
|
||||
|
||||
def testSpecialTypes(self):
|
||||
"""Verify that IsA can handle objects like io.StringIO."""
|
||||
isA = mox.IsA(io.StringIO())
|
||||
stringIO = io.StringIO()
|
||||
self.assert_(isA == stringIO)
|
||||
self.assertTrue(isA == stringIO)
|
||||
|
||||
|
||||
class IsAlmostTest(unittest.TestCase):
|
||||
|
@ -405,23 +407,23 @@ class IsAlmostTest(unittest.TestCase):
|
|||
|
||||
def testEqualityValid(self):
|
||||
"""Verify that == correctly identifies nearly equivalent floats."""
|
||||
self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
|
||||
self.assertEqual(mox.IsAlmost(1.8999999999), 1.9)
|
||||
|
||||
def testEqualityInvalid(self):
|
||||
"""Verify that == correctly identifies non-equivalent floats."""
|
||||
self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
|
||||
self.assertNotEqual(mox.IsAlmost(1.899), 1.9)
|
||||
|
||||
def testEqualityWithPlaces(self):
|
||||
"""Verify that specifying places has the desired effect."""
|
||||
self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
|
||||
self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
|
||||
self.assertNotEqual(mox.IsAlmost(1.899), 1.9)
|
||||
self.assertEqual(mox.IsAlmost(1.899, places=2), 1.9)
|
||||
|
||||
def testNonNumericTypes(self):
|
||||
"""Verify that IsAlmost handles non-numeric types properly."""
|
||||
|
||||
self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9')
|
||||
self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9)
|
||||
self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
|
||||
self.assertNotEqual(mox.IsAlmost(1.8999999999), '1.9')
|
||||
self.assertNotEqual(mox.IsAlmost('1.8999999999'), 1.9)
|
||||
self.assertNotEqual(mox.IsAlmost('1.8999999999'), '1.9')
|
||||
|
||||
|
||||
class ValueRememberTest(unittest.TestCase):
|
||||
|
@ -431,28 +433,28 @@ class ValueRememberTest(unittest.TestCase):
|
|||
"""Verify that value will compare to stored value."""
|
||||
value = mox.Value()
|
||||
value.store_value('hello world')
|
||||
self.assertEquals(value, 'hello world')
|
||||
self.assertEqual(value, 'hello world')
|
||||
|
||||
def testNoValue(self):
|
||||
"""Verify that uninitialized value does not compare to "empty" values."""
|
||||
value = mox.Value()
|
||||
self.assertNotEquals(value, None)
|
||||
self.assertNotEquals(value, False)
|
||||
self.assertNotEquals(value, 0)
|
||||
self.assertNotEquals(value, '')
|
||||
self.assertNotEquals(value, ())
|
||||
self.assertNotEquals(value, [])
|
||||
self.assertNotEquals(value, {})
|
||||
self.assertNotEquals(value, object())
|
||||
self.assertNotEquals(value, set())
|
||||
self.assertNotEqual(value, None)
|
||||
self.assertNotEqual(value, False)
|
||||
self.assertNotEqual(value, 0)
|
||||
self.assertNotEqual(value, '')
|
||||
self.assertNotEqual(value, ())
|
||||
self.assertNotEqual(value, [])
|
||||
self.assertNotEqual(value, {})
|
||||
self.assertNotEqual(value, object())
|
||||
self.assertNotEqual(value, set())
|
||||
|
||||
def testRememberValue(self):
|
||||
"""Verify that comparing against remember will store argument."""
|
||||
value = mox.Value()
|
||||
remember = mox.Remember(value)
|
||||
self.assertNotEquals(value, 'hello world') # value not yet stored.
|
||||
self.assertEquals(remember, 'hello world') # store value here.
|
||||
self.assertEquals(value, 'hello world') # compare against stored value.
|
||||
self.assertNotEqual(value, 'hello world') # value not yet stored.
|
||||
self.assertEqual(remember, 'hello world') # store value here.
|
||||
self.assertEqual(value, 'hello world') # compare against stored value.
|
||||
|
||||
|
||||
class MockMethodTest(unittest.TestCase):
|
||||
|
@ -465,19 +467,19 @@ class MockMethodTest(unittest.TestCase):
|
|||
|
||||
def testNameAttribute(self):
|
||||
"""Should provide a __name__ attribute."""
|
||||
self.assertEquals('testMethod', self.mock_method.__name__)
|
||||
self.assertEqual('testMethod', self.mock_method.__name__)
|
||||
|
||||
def testAndReturnNoneByDefault(self):
|
||||
"""Should return None by default."""
|
||||
return_value = self.mock_method(['original'])
|
||||
self.assert_(return_value == None)
|
||||
self.assertTrue(return_value == None)
|
||||
|
||||
def testAndReturnValue(self):
|
||||
"""Should return a specificed return value."""
|
||||
expected_return_value = "test"
|
||||
self.expected_method.AndReturn(expected_return_value)
|
||||
return_value = self.mock_method(['original'])
|
||||
self.assert_(return_value == expected_return_value)
|
||||
self.assertTrue(return_value == expected_return_value)
|
||||
|
||||
def testAndRaiseException(self):
|
||||
"""Should raise a specified exception."""
|
||||
|
@ -493,7 +495,7 @@ class MockMethodTest(unittest.TestCase):
|
|||
mutable_list[0] = 'mutation'
|
||||
self.expected_method.WithSideEffects(modifier).AndReturn(1)
|
||||
self.mock_method(local_list)
|
||||
self.assertEquals('mutation', local_list[0])
|
||||
self.assertEqual('mutation', local_list[0])
|
||||
|
||||
def testWithReturningSideEffects(self):
|
||||
"""Should call state modifier and propagate its return value."""
|
||||
|
@ -505,8 +507,8 @@ class MockMethodTest(unittest.TestCase):
|
|||
return expected_return
|
||||
self.expected_method.WithSideEffects(modifier_with_return)
|
||||
actual_return = self.mock_method(local_list)
|
||||
self.assertEquals('mutation', local_list[0])
|
||||
self.assertEquals(expected_return, actual_return)
|
||||
self.assertEqual('mutation', local_list[0])
|
||||
self.assertEqual(expected_return, actual_return)
|
||||
|
||||
def testWithReturningSideEffectsWithAndReturn(self):
|
||||
"""Should call state modifier and ignore its return value."""
|
||||
|
@ -520,8 +522,8 @@ class MockMethodTest(unittest.TestCase):
|
|||
self.expected_method.WithSideEffects(modifier_with_return).AndReturn(
|
||||
expected_return)
|
||||
actual_return = self.mock_method(local_list)
|
||||
self.assertEquals('mutation', local_list[0])
|
||||
self.assertEquals(expected_return, actual_return)
|
||||
self.assertEqual('mutation', local_list[0])
|
||||
self.assertEqual(expected_return, actual_return)
|
||||
|
||||
def testEqualityNoParamsEqual(self):
|
||||
"""Methods with the same name and without params should be equal."""
|
||||
|
@ -531,7 +533,7 @@ class MockMethodTest(unittest.TestCase):
|
|||
def testEqualityNoParamsNotEqual(self):
|
||||
"""Methods with different names and without params should not be equal."""
|
||||
expected_method = mox.MockMethod("otherMethod", [], False)
|
||||
self.failIfEqual(self.mock_method, expected_method)
|
||||
self.assertNotEqual(self.mock_method, expected_method)
|
||||
|
||||
def testEqualityParamsEqual(self):
|
||||
"""Methods with the same name and parameters should be equal."""
|
||||
|
@ -548,7 +550,7 @@ class MockMethodTest(unittest.TestCase):
|
|||
expected_method._params = [1, 2, 3]
|
||||
|
||||
self.mock_method._params = ['a', 'b', 'c']
|
||||
self.failIfEqual(self.mock_method, expected_method)
|
||||
self.assertNotEqual(self.mock_method, expected_method)
|
||||
|
||||
def testEqualityNamedParamsEqual(self):
|
||||
"""Methods with the same name and same named params should be equal."""
|
||||
|
@ -565,11 +567,11 @@ class MockMethodTest(unittest.TestCase):
|
|||
expected_method._named_params = {"input1": "test", "input2": "params"}
|
||||
|
||||
self.mock_method._named_params = {"input1": "test2", "input2": "params2"}
|
||||
self.failIfEqual(self.mock_method, expected_method)
|
||||
self.assertNotEqual(self.mock_method, expected_method)
|
||||
|
||||
def testEqualityWrongType(self):
|
||||
"""Method should not be equal to an object of a different type."""
|
||||
self.failIfEqual(self.mock_method, "string?")
|
||||
self.assertNotEqual(self.mock_method, "string?")
|
||||
|
||||
def testObjectEquality(self):
|
||||
"""Equality of objects should work without a Comparator"""
|
||||
|
@ -629,12 +631,12 @@ class MockAnythingTest(unittest.TestCase):
|
|||
self.mock_object._Replay()
|
||||
actual = str(self.mock_object)
|
||||
self.mock_object._Verify();
|
||||
self.assertEquals("foo", actual)
|
||||
self.assertEqual("foo", actual)
|
||||
|
||||
def testSetupMode(self):
|
||||
"""Verify the mock will accept any call."""
|
||||
self.mock_object.NonsenseCall()
|
||||
self.assert_(len(self.mock_object._expected_calls_queue) == 1)
|
||||
self.assertTrue(len(self.mock_object._expected_calls_queue) == 1)
|
||||
|
||||
def testReplayWithExpectedCall(self):
|
||||
"""Verify the mock replays method calls as expected."""
|
||||
|
@ -668,7 +670,7 @@ class MockAnythingTest(unittest.TestCase):
|
|||
self.mock_object[1].AndReturn(True)
|
||||
self.mock_object._Replay()
|
||||
returned_val = self.mock_object[1]
|
||||
self.assert_(returned_val)
|
||||
self.assertTrue(returned_val)
|
||||
self.mock_object._Verify()
|
||||
|
||||
def testNonzero(self):
|
||||
|
@ -689,18 +691,18 @@ class MockAnythingTest(unittest.TestCase):
|
|||
def testEquals(self):
|
||||
"""A mock should be able to compare itself to another object."""
|
||||
self.mock_object._Replay()
|
||||
self.assertEquals(self.mock_object, self.mock_object)
|
||||
self.assertEqual(self.mock_object, self.mock_object)
|
||||
|
||||
def testEqualsMockFailure(self):
|
||||
"""Verify equals identifies unequal objects."""
|
||||
self.mock_object.SillyCall()
|
||||
self.mock_object._Replay()
|
||||
self.assertNotEquals(self.mock_object, mox.MockAnything())
|
||||
self.assertNotEqual(self.mock_object, mox.MockAnything())
|
||||
|
||||
def testEqualsInstanceFailure(self):
|
||||
"""Verify equals identifies that objects are different instances."""
|
||||
self.mock_object._Replay()
|
||||
self.assertNotEquals(self.mock_object, TestClass())
|
||||
self.assertNotEqual(self.mock_object, TestClass())
|
||||
|
||||
def testNotEquals(self):
|
||||
"""Verify not equals works."""
|
||||
|
@ -735,21 +737,37 @@ class MockAnythingTest(unittest.TestCase):
|
|||
self.mock_object().AndReturn('mox0rd')
|
||||
self.mock_object._Replay()
|
||||
|
||||
self.assertEquals('mox0rd', self.mock_object())
|
||||
self.assertEqual('mox0rd', self.mock_object())
|
||||
|
||||
self.mock_object._Verify()
|
||||
|
||||
def testIsReprable(self):
|
||||
"""Test that MockAnythings can be repr'd without causing a failure."""
|
||||
self.failUnless('MockAnything' in repr(self.mock_object))
|
||||
self.assertTrue('MockAnything' in repr(self.mock_object))
|
||||
|
||||
|
||||
class MethodCheckerTest(unittest.TestCase):
|
||||
"""Tests MockMethod's use of MethodChecker method."""
|
||||
|
||||
def testNoParameters(self):
|
||||
def testUnboundMethodsRequiresInstance(self):
|
||||
# SKIP TEST IN PYTHON 2.x (Ugly hack for python 2.6)
|
||||
# REASON: semantics for unbound methods has changed only in Python 3
|
||||
# so this test in earlier versions is invald
|
||||
if sys.version_info < (3, 0):
|
||||
return
|
||||
|
||||
instance = CheckCallTestClass()
|
||||
method = mox.MockMethod('NoParameters', [], False,
|
||||
CheckCallTestClass.NoParameters)
|
||||
|
||||
self.assertRaises(AttributeError, method)
|
||||
method(instance)
|
||||
self.assertRaises(AttributeError, method, instance, 1)
|
||||
|
||||
def testNoParameters(self):
|
||||
method = mox.MockMethod('NoParameters', [], False,
|
||||
CheckCallTestClass.NoParameters,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
method()
|
||||
self.assertRaises(AttributeError, method, 1)
|
||||
self.assertRaises(AttributeError, method, 1, 2)
|
||||
|
@ -758,7 +776,8 @@ class MethodCheckerTest(unittest.TestCase):
|
|||
|
||||
def testOneParameter(self):
|
||||
method = mox.MockMethod('OneParameter', [], False,
|
||||
CheckCallTestClass.OneParameter)
|
||||
CheckCallTestClass.OneParameter,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
self.assertRaises(AttributeError, method)
|
||||
method(1)
|
||||
method(a=1)
|
||||
|
@ -769,7 +788,8 @@ class MethodCheckerTest(unittest.TestCase):
|
|||
|
||||
def testTwoParameters(self):
|
||||
method = mox.MockMethod('TwoParameters', [], False,
|
||||
CheckCallTestClass.TwoParameters)
|
||||
CheckCallTestClass.TwoParameters,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
self.assertRaises(AttributeError, method)
|
||||
self.assertRaises(AttributeError, method, 1)
|
||||
self.assertRaises(AttributeError, method, a=1)
|
||||
|
@ -786,7 +806,8 @@ class MethodCheckerTest(unittest.TestCase):
|
|||
|
||||
def testOneDefaultValue(self):
|
||||
method = mox.MockMethod('OneDefaultValue', [], False,
|
||||
CheckCallTestClass.OneDefaultValue)
|
||||
CheckCallTestClass.OneDefaultValue,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
method()
|
||||
method(1)
|
||||
method(a=1)
|
||||
|
@ -797,7 +818,8 @@ class MethodCheckerTest(unittest.TestCase):
|
|||
|
||||
def testTwoDefaultValues(self):
|
||||
method = mox.MockMethod('TwoDefaultValues', [], False,
|
||||
CheckCallTestClass.TwoDefaultValues)
|
||||
CheckCallTestClass.TwoDefaultValues,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
self.assertRaises(AttributeError, method)
|
||||
self.assertRaises(AttributeError, method, c=3)
|
||||
self.assertRaises(AttributeError, method, 1)
|
||||
|
@ -816,7 +838,8 @@ class MethodCheckerTest(unittest.TestCase):
|
|||
self.assertRaises(AttributeError, method, a=1, b=2, e=9)
|
||||
|
||||
def testArgs(self):
|
||||
method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args)
|
||||
method = mox.MockMethod('Args', [], False, CheckCallTestClass.Args,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
self.assertRaises(AttributeError, method)
|
||||
self.assertRaises(AttributeError, method, 1)
|
||||
method(1, 2)
|
||||
|
@ -827,7 +850,8 @@ class MethodCheckerTest(unittest.TestCase):
|
|||
self.assertRaises(AttributeError, method, 1, 2, c=3)
|
||||
|
||||
def testKwargs(self):
|
||||
method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs)
|
||||
method = mox.MockMethod('Kwargs', [], False, CheckCallTestClass.Kwargs,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
self.assertRaises(AttributeError, method)
|
||||
method(1)
|
||||
method(1, 2)
|
||||
|
@ -843,7 +867,8 @@ class MethodCheckerTest(unittest.TestCase):
|
|||
|
||||
def testArgsAndKwargs(self):
|
||||
method = mox.MockMethod('ArgsAndKwargs', [], False,
|
||||
CheckCallTestClass.ArgsAndKwargs)
|
||||
CheckCallTestClass.ArgsAndKwargs,
|
||||
class_to_bind=CheckCallTestClass)
|
||||
self.assertRaises(AttributeError, method)
|
||||
method(1)
|
||||
method(1, 2)
|
||||
|
@ -891,7 +916,7 @@ class MockObjectTest(unittest.TestCase):
|
|||
def testSetupModeWithValidCall(self):
|
||||
"""Verify the mock object properly mocks a basic method call."""
|
||||
self.mock_object.ValidCall()
|
||||
self.assert_(len(self.mock_object._expected_calls_queue) == 1)
|
||||
self.assertTrue(len(self.mock_object._expected_calls_queue) == 1)
|
||||
|
||||
def testSetupModeWithInvalidCall(self):
|
||||
"""UnknownMethodCallError should be raised if a non-member method is called.
|
||||
|
@ -923,47 +948,47 @@ class MockObjectTest(unittest.TestCase):
|
|||
|
||||
def testIsInstance(self):
|
||||
"""Mock should be able to pass as an instance of the mocked class."""
|
||||
self.assert_(isinstance(self.mock_object, TestClass))
|
||||
self.assertTrue(isinstance(self.mock_object, TestClass))
|
||||
|
||||
def testFindValidMethods(self):
|
||||
"""Mock should be able to mock all public methods."""
|
||||
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 self.mock_object._known_methods)
|
||||
self.assert_('__PrivateCall' not in self.mock_object._known_methods)
|
||||
self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods)
|
||||
self.assertTrue('ValidCall' in self.mock_object._known_methods)
|
||||
self.assertTrue('OtherValidCall' in self.mock_object._known_methods)
|
||||
self.assertTrue('MyClassMethod' in self.mock_object._known_methods)
|
||||
self.assertTrue('MyStaticMethod' in self.mock_object._known_methods)
|
||||
self.assertTrue('_ProtectedCall' in self.mock_object._known_methods)
|
||||
self.assertTrue('__PrivateCall' not in self.mock_object._known_methods)
|
||||
self.assertTrue('_TestClass__PrivateCall' in self.mock_object._known_methods)
|
||||
|
||||
def testFindsSuperclassMethods(self):
|
||||
"""Mock should be able to mock superclasses methods."""
|
||||
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._known_methods)
|
||||
self.assertTrue('ValidCall' in self.mock_object._known_methods)
|
||||
self.assertTrue('OtherValidCall' in self.mock_object._known_methods)
|
||||
self.assertTrue('MyClassMethod' in self.mock_object._known_methods)
|
||||
self.assertTrue('ChildValidCall' in self.mock_object._known_methods)
|
||||
|
||||
def testAccessClassVariables(self):
|
||||
"""Class variables should be accessible through the mock."""
|
||||
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)
|
||||
self.assertTrue('SOME_CLASS_VAR' in self.mock_object._known_vars)
|
||||
self.assertTrue('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)
|
||||
self.assertEqual('test_value', self.mock_object.SOME_CLASS_VAR)
|
||||
|
||||
def testEquals(self):
|
||||
"""A mock should be able to compare itself to another object."""
|
||||
self.mock_object._Replay()
|
||||
self.assertEquals(self.mock_object, self.mock_object)
|
||||
self.assertEqual(self.mock_object, self.mock_object)
|
||||
|
||||
def testEqualsMockFailure(self):
|
||||
"""Verify equals identifies unequal objects."""
|
||||
self.mock_object.ValidCall()
|
||||
self.mock_object._Replay()
|
||||
self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
|
||||
self.assertNotEqual(self.mock_object, mox.MockObject(TestClass))
|
||||
|
||||
def testEqualsInstanceFailure(self):
|
||||
"""Verify equals identifies that objects are different instances."""
|
||||
self.mock_object._Replay()
|
||||
self.assertNotEquals(self.mock_object, TestClass())
|
||||
self.assertNotEqual(self.mock_object, TestClass())
|
||||
|
||||
def testNotEquals(self):
|
||||
"""Verify not equals works."""
|
||||
|
@ -1115,7 +1140,7 @@ class MockObjectTest(unittest.TestCase):
|
|||
dummy[1].AndReturn('3')
|
||||
|
||||
dummy._Replay()
|
||||
self.assertEquals('3', dummy.__getitem__(1))
|
||||
self.assertEqual('3', dummy.__getitem__(1))
|
||||
dummy._Verify()
|
||||
|
||||
def testMockIter_ExpectedIter_Success(self):
|
||||
|
@ -1142,7 +1167,7 @@ class MockObjectTest(unittest.TestCase):
|
|||
|
||||
dummy._Replay()
|
||||
|
||||
self.failUnless('X' in dummy)
|
||||
self.assertTrue('X' in dummy)
|
||||
|
||||
dummy._Verify()
|
||||
|
||||
|
@ -1205,7 +1230,7 @@ class MockObjectTest(unittest.TestCase):
|
|||
dummy[2].AndRaise(IndexError)
|
||||
|
||||
dummy._Replay()
|
||||
self.assertEquals(['a', 'b'], [x for x in dummy])
|
||||
self.assertEqual(['a', 'b'], [x for x in dummy])
|
||||
dummy._Verify()
|
||||
|
||||
def testMockIter_ExpectedNoGetItem_NoSuccess(self):
|
||||
|
@ -1228,12 +1253,12 @@ class MockObjectTest(unittest.TestCase):
|
|||
dummy = mox.MockObject(TestSubClass)
|
||||
iter(dummy).AndReturn(iter(['a', 'b']))
|
||||
dummy._Replay()
|
||||
self.assertEquals(['a', 'b'], [x for x in dummy])
|
||||
self.assertEqual(['a', 'b'], [x for x in dummy])
|
||||
dummy._Verify()
|
||||
|
||||
def testInstantiationWithAdditionalAttributes(self):
|
||||
mock_object = mox.MockObject(TestClass, attrs={"attr1": "value"})
|
||||
self.assertEquals(mock_object.attr1, "value")
|
||||
self.assertEqual(mock_object.attr1, "value")
|
||||
|
||||
def testCantOverrideMethodsWithAttributes(self):
|
||||
self.assertRaises(ValueError, mox.MockObject, TestClass,
|
||||
|
@ -1281,7 +1306,7 @@ class MoxTest(unittest.TestCase):
|
|||
self.mox.ReplayAll()
|
||||
|
||||
ret_val = mock_obj.ValidCall()
|
||||
self.assertEquals("yes", ret_val)
|
||||
self.assertEqual("yes", ret_val)
|
||||
self.mox.VerifyAll()
|
||||
|
||||
def testSignatureMatchingWithComparatorAsFirstArg(self):
|
||||
|
@ -1312,7 +1337,7 @@ class MoxTest(unittest.TestCase):
|
|||
self.mox.ReplayAll()
|
||||
|
||||
ret_val = mock_obj("foo")
|
||||
self.assertEquals("qux", ret_val)
|
||||
self.assertEqual("qux", ret_val)
|
||||
self.mox.VerifyAll()
|
||||
|
||||
def testInheritedCallableObject(self):
|
||||
|
@ -1322,7 +1347,7 @@ class MoxTest(unittest.TestCase):
|
|||
self.mox.ReplayAll()
|
||||
|
||||
ret_val = mock_obj("foo")
|
||||
self.assertEquals("qux", ret_val)
|
||||
self.assertEqual("qux", ret_val)
|
||||
self.mox.VerifyAll()
|
||||
|
||||
def testCallOnNonCallableObject(self):
|
||||
|
@ -1413,8 +1438,8 @@ class MoxTest(unittest.TestCase):
|
|||
actual_one = mock_obj.Method(1)
|
||||
mock_obj.Close()
|
||||
|
||||
self.assertEquals(9, actual_one)
|
||||
self.assertEquals(10, actual_two)
|
||||
self.assertEqual(9, actual_one)
|
||||
self.assertEqual(10, actual_two)
|
||||
|
||||
self.mox.VerifyAll()
|
||||
|
||||
|
@ -1459,10 +1484,10 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
|
||||
self.assertEquals(9, actual_one)
|
||||
self.assertEquals(9, second_one) # Repeated calls should return same number.
|
||||
self.assertEquals(10, actual_two)
|
||||
self.assertEquals(42, actual_three)
|
||||
self.assertEqual(9, actual_one)
|
||||
self.assertEqual(9, second_one) # Repeated calls should return same number.
|
||||
self.assertEqual(10, actual_two)
|
||||
self.assertEqual(42, actual_three)
|
||||
|
||||
def testMultipleTimesUsingIsAParameter(self):
|
||||
"""Test if MultipleTimesGroup works with a IsA parameter."""
|
||||
|
@ -1479,8 +1504,8 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
|
||||
self.assertEquals(9, actual_one)
|
||||
self.assertEquals(9, second_one) # Repeated calls should return same number.
|
||||
self.assertEqual(9, actual_one)
|
||||
self.assertEqual(9, second_one) # Repeated calls should return same number.
|
||||
|
||||
def testMutlipleTimesUsingFunc(self):
|
||||
"""Test that the Func is not evaluated more times than necessary.
|
||||
|
@ -1509,7 +1534,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
|
||||
self.assertEquals(2, self.counter)
|
||||
self.assertEqual(2, self.counter)
|
||||
|
||||
def testMultipleTimesThreeMethods(self):
|
||||
"""Test if MultipleTimesGroup works with three or more methods."""
|
||||
|
@ -1531,10 +1556,10 @@ class MoxTest(unittest.TestCase):
|
|||
actual_four = mock_obj.Method(4)
|
||||
mock_obj.Close()
|
||||
|
||||
self.assertEquals(9, actual_one)
|
||||
self.assertEquals(8, actual_two)
|
||||
self.assertEquals(7, actual_three)
|
||||
self.assertEquals(10, actual_four)
|
||||
self.assertEqual(9, actual_one)
|
||||
self.assertEqual(8, actual_two)
|
||||
self.assertEqual(7, actual_three)
|
||||
self.assertEqual(10, actual_four)
|
||||
|
||||
self.mox.VerifyAll()
|
||||
|
||||
|
@ -1576,8 +1601,8 @@ class MoxTest(unittest.TestCase):
|
|||
mock_obj.Method(3)
|
||||
mock_obj.Close()
|
||||
|
||||
self.assertEquals(9, actual_one)
|
||||
self.assertEquals(42, actual_three)
|
||||
self.assertEqual(9, actual_one)
|
||||
self.assertEqual(42, actual_three)
|
||||
|
||||
self.mox.VerifyAll()
|
||||
|
||||
|
@ -1625,7 +1650,7 @@ class MoxTest(unittest.TestCase):
|
|||
self.mox.ReplayAll()
|
||||
|
||||
local_list = ['original']
|
||||
self.failUnlessRaises(Exception,
|
||||
self.assertRaises(Exception,
|
||||
mock_obj.ConfigureInOutParameter,
|
||||
local_list)
|
||||
mock_obj.WorkWithParameter(local_list)
|
||||
|
@ -1648,7 +1673,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
self.mox.UnsetStubs()
|
||||
self.assertEquals('foo', actual)
|
||||
self.assertEqual('foo', actual)
|
||||
self.assertTrue(type(test_obj.OtherValidCall) is method_type)
|
||||
|
||||
def testStubOutMethod_Unbound_Comparator(self):
|
||||
|
@ -1662,7 +1687,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
self.mox.UnsetStubs()
|
||||
self.assertEquals('foo', actual)
|
||||
self.assertEqual('foo', actual)
|
||||
|
||||
def testStubOutMethod_Unbound_Subclass_Comparator(self):
|
||||
self.mox.StubOutWithMock(mox_test_helper.TestClassFromAnotherModule, 'Value')
|
||||
|
@ -1675,7 +1700,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
self.mox.UnsetStubs()
|
||||
self.assertEquals('foo', actual)
|
||||
self.assertEqual('foo', actual)
|
||||
|
||||
def testStubOuMethod_Unbound_WithOptionalParams(self):
|
||||
self.mox = mox.Mox()
|
||||
|
@ -1700,7 +1725,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
self.mox.UnsetStubs()
|
||||
self.assertEquals('foo', actual)
|
||||
self.assertEqual('foo', actual)
|
||||
|
||||
def testStubOutMethod_Unbound_DifferentInstance(self):
|
||||
instance = TestClass()
|
||||
|
@ -1761,7 +1786,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
self.mox.UnsetStubs()
|
||||
self.assertEquals('foo', actual)
|
||||
self.assertEqual('foo', actual)
|
||||
|
||||
def testStubOutMethod_Bound_NamedUsingPositional(self):
|
||||
"""Check positional parameters can be matched to keyword arguments."""
|
||||
|
@ -1840,7 +1865,7 @@ class MoxTest(unittest.TestCase):
|
|||
def testStubOutClass_OldStyle(self):
|
||||
"""Test a mocked class whose __init__ returns a Mock."""
|
||||
self.mox.StubOutWithMock(mox_test_helper, 'TestClassFromAnotherModule')
|
||||
self.assert_(isinstance(mox_test_helper.TestClassFromAnotherModule,
|
||||
self.assertTrue(isinstance(mox_test_helper.TestClassFromAnotherModule,
|
||||
mox.MockObject))
|
||||
|
||||
mock_instance = self.mox.CreateMock(
|
||||
|
@ -1855,7 +1880,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
self.mox.UnsetStubs()
|
||||
self.assertEquals('mock instance', actual)
|
||||
self.assertEqual('mock instance', actual)
|
||||
|
||||
def testStubOutClass(self):
|
||||
self.mox.StubOutClassWithMocks(mox_test_helper, 'CallableClass')
|
||||
|
@ -1880,12 +1905,12 @@ class MoxTest(unittest.TestCase):
|
|||
self.mox.UnsetStubs()
|
||||
|
||||
# Verify the correct mocks were returned
|
||||
self.assertEquals(mock_one, one)
|
||||
self.assertEquals(mock_two, two)
|
||||
self.assertEqual(mock_one, one)
|
||||
self.assertEqual(mock_two, two)
|
||||
|
||||
# Verify
|
||||
self.assertEquals('mock', actual_one)
|
||||
self.assertEquals('called mock', actual_two)
|
||||
self.assertEqual('mock', actual_one)
|
||||
self.assertEqual('called mock', actual_two)
|
||||
|
||||
def testStubOutClass_NotAClass(self):
|
||||
self.assertRaises(TypeError, self.mox.StubOutClassWithMocks,
|
||||
|
@ -1979,7 +2004,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
foo = Foo()
|
||||
self.mox.StubOutWithMock(foo, "obj")
|
||||
self.assert_(isinstance(foo.obj, mox.MockObject))
|
||||
self.assertTrue(isinstance(foo.obj, mox.MockObject))
|
||||
foo.obj.ValidCall()
|
||||
self.mox.ReplayAll()
|
||||
|
||||
|
@ -1987,7 +2012,7 @@ class MoxTest(unittest.TestCase):
|
|||
|
||||
self.mox.VerifyAll()
|
||||
self.mox.UnsetStubs()
|
||||
self.failIf(isinstance(foo.obj, mox.MockObject))
|
||||
self.assertFalse(isinstance(foo.obj, mox.MockObject))
|
||||
|
||||
def testForgotReplayHelpfulMessage(self):
|
||||
"""If there is an AttributeError on a MockMethod, give users a helpful msg.
|
||||
|
@ -2000,7 +2025,7 @@ class MoxTest(unittest.TestCase):
|
|||
try:
|
||||
foo.GetBar().ShowMeTheMoney()
|
||||
except AttributeError as e:
|
||||
self.assertEquals('MockMethod has no attribute "ShowMeTheMoney". '
|
||||
self.assertEqual('MockMethod has no attribute "ShowMeTheMoney". '
|
||||
'Did you remember to put your mocks in replay mode?', str(e))
|
||||
|
||||
|
||||
|
@ -2101,14 +2126,14 @@ class MoxTestBaseTest(unittest.TestCase):
|
|||
self.test_stubs.SmartUnsetAll()
|
||||
self.mox.ReplayAll()
|
||||
self.test.run(result=self.result)
|
||||
self.failIf(self.result.wasSuccessful())
|
||||
self.assertFalse(self.result.wasSuccessful())
|
||||
self.mox.VerifyAll()
|
||||
|
||||
def testExpectedNotCalledNoMocks(self):
|
||||
"""Let testExpectedNotCalled() unset all the mocks by itself."""
|
||||
self._CreateTest('testExpectedNotCalled')
|
||||
self.test.run(result=self.result)
|
||||
self.failIf(self.result.wasSuccessful())
|
||||
self.assertFalse(self.result.wasSuccessful())
|
||||
self.assertEqual(OS_LISTDIR, mox_test_helper.os.listdir)
|
||||
|
||||
def testUnexpectedCall(self):
|
||||
|
@ -2124,7 +2149,7 @@ class MoxTestBaseTest(unittest.TestCase):
|
|||
self.test_stubs.SmartUnsetAll()
|
||||
self.mox.ReplayAll()
|
||||
self.test.run(result=self.result)
|
||||
self.failIf(self.result.wasSuccessful())
|
||||
self.assertFalse(self.result.wasSuccessful())
|
||||
self.mox.VerifyAll()
|
||||
|
||||
def testFailure(self):
|
||||
|
@ -2140,7 +2165,7 @@ class MoxTestBaseTest(unittest.TestCase):
|
|||
self.test_stubs.SmartUnsetAll()
|
||||
self.mox.ReplayAll()
|
||||
self.test.run(result=self.result)
|
||||
self.failIf(self.result.wasSuccessful())
|
||||
self.assertFalse(self.result.wasSuccessful())
|
||||
self.mox.VerifyAll()
|
||||
|
||||
def testMixin(self):
|
||||
|
@ -2182,11 +2207,11 @@ class ResetTest(unittest.TestCase):
|
|||
self.assertFalse(mock_obj._replay_mode)
|
||||
mock_obj._Replay()
|
||||
self.assertTrue(mock_obj._replay_mode)
|
||||
self.assertEquals(1, len(mock_obj._expected_calls_queue))
|
||||
self.assertEqual(1, len(mock_obj._expected_calls_queue))
|
||||
|
||||
mox.Reset(mock_obj)
|
||||
self.assertFalse(mock_obj._replay_mode)
|
||||
self.assertEquals(0, len(mock_obj._expected_calls_queue))
|
||||
self.assertEqual(0, len(mock_obj._expected_calls_queue))
|
||||
|
||||
|
||||
class MyTestCase(unittest.TestCase):
|
||||
|
@ -2199,7 +2224,7 @@ class MyTestCase(unittest.TestCase):
|
|||
|
||||
def testMethodOverride(self):
|
||||
"""Should be properly overriden in a derived class."""
|
||||
self.assertEquals(42, self.another_critical_variable)
|
||||
self.assertEqual(42, self.another_critical_variable)
|
||||
self.another_critical_variable += 1
|
||||
|
||||
|
||||
|
@ -2212,15 +2237,15 @@ class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase):
|
|||
|
||||
def testMultipleInheritance(self):
|
||||
"""Should be able to access members created by all parent setUp()."""
|
||||
self.assert_(isinstance(self.mox, mox.Mox))
|
||||
self.assertEquals(42, self.critical_variable)
|
||||
self.assertTrue(isinstance(self.mox, mox.Mox))
|
||||
self.assertEqual(42, self.critical_variable)
|
||||
|
||||
def testMethodOverride(self):
|
||||
"""Should run before MyTestCase.testMethodOverride."""
|
||||
self.assertEquals(99, self.another_critical_variable)
|
||||
self.assertEqual(99, self.another_critical_variable)
|
||||
self.another_critical_variable = 42
|
||||
super(MoxTestBaseMultipleInheritanceTest, self).testMethodOverride()
|
||||
self.assertEquals(43, self.another_critical_variable)
|
||||
self.assertEqual(43, self.another_critical_variable)
|
||||
|
||||
class MoxTestDontMockProperties(MoxTestBaseTest):
|
||||
def testPropertiesArentMocked(self):
|
||||
|
|
Loading…
Reference in New Issue