Merge pull request #4 from quermit/fix_pep8_issues

Fixed pep8 issues
This commit is contained in:
Dawid Fatyga 2012-04-24 15:50:10 -07:00
commit 9e444c4ac7
7 changed files with 105 additions and 69 deletions

2
README
View File

@ -55,4 +55,4 @@ Mox is Copyright 2008 Google Inc, and licensed under the Apache
License, Version 2.0; see the file COPYING for details. If you would
like to help us improve Mox, join the group.
This is modified version from https://github.com/quermit/pymox
This is a modified version originated from https://github.com/quermit/pymox

69
mox.py
View File

@ -82,15 +82,18 @@ class Error(AssertionError):
class ExpectedMethodCallsError(Error):
"""Raised when Verify() is called before all expected methods have been called
"""Raised when an expected method wasn't called.
This can occur if Verify() is called before all expected methods have been
called.
"""
def __init__(self, expected_methods):
"""Init exception.
Args:
# expected_methods: A sequence of MockMethod objects that should have been
# called.
# expected_methods: A sequence of MockMethod objects that should have
# been called.
expected_methods: [MockMethod]
Raises:
@ -119,8 +122,8 @@ class UnexpectedMethodCallError(Error):
"""Init exception.
Args:
# unexpected_method: MockMethod that was called but was not at the head of
# the expected_method queue.
# unexpected_method: MockMethod that was called but was not at the head
# of the expected_method queue.
# expected: MockMethod or UnorderedGroup the method should have
# been in.
unexpected_method: MockMethod
@ -268,8 +271,8 @@ class Mox(object):
This does not enforce an interface.
Args:
description: str. Optionally, a descriptive name for the mock object being
created, for debugging output purposes.
description: str. Optionally, a descriptive name for the mock object
being created, for debugging output purposes.
"""
new_mock = MockAnything(description=description)
self._mock_objects.append(new_mock)
@ -281,7 +284,6 @@ class Mox(object):
for mock_obj in self._mock_objects:
mock_obj._Replay()
def VerifyAll(self):
"""Call verify on all mock objects created."""
@ -326,7 +328,8 @@ class Mox(object):
if type_check and not use_mock_anything:
stub = self.CreateMock(attr_to_replace, bounded_to=class_to_bind)
else:
stub = self.CreateMockAnything(description='Stub for %s' % attr_to_replace)
stub = self.CreateMockAnything(
description='Stub for %s' % attr_to_replace)
stub.__name__ = attr_name
self.stubs.Set(obj, attr_name, stub)
@ -432,8 +435,8 @@ class MockAnything(object):
"""Initialize a new MockAnything.
Args:
description: str. Optionally, a descriptive name for the mock object being
created, for debugging output purposes.
description: str. Optionally, a descriptive name for the mock object
being created, for debugging output purposes.
"""
self._description = description
self._Reset()
@ -685,7 +688,6 @@ class MockObject(MockAnything):
return MockMethod('__setitem__', self._expected_calls_queue,
self._replay_mode)(key, value)
# Otherwise, create a mock method __setitem__.
return self._CreateMockMethod('__setitem__')(key, value)
@ -714,7 +716,6 @@ class MockObject(MockAnything):
return MockMethod('__getitem__', self._expected_calls_queue,
self._replay_mode)(key)
# Otherwise, create a mock method __getitem__.
return self._CreateMockMethod('__getitem__')(key)
@ -754,11 +755,9 @@ class MockObject(MockAnything):
return MockMethod('__iter__', self._expected_calls_queue,
self._replay_mode)()
# Otherwise, create a mock method __iter__.
return self._CreateMockMethod('__iter__')()
def __contains__(self, key):
"""Provide custom logic for mocking classes that contain items.
@ -794,8 +793,8 @@ class MockObject(MockAnything):
if not is_callable:
raise TypeError('Not callable')
# Because the call is happening directly on this object instead of a method,
# the call on the mock method is made right here
# Because the call is happening directly on this object instead of
# a method, the call on the mock method is made right here
# If we are mocking a Function, then use the function, and not the
# __call__ method
@ -983,7 +982,6 @@ class MethodSignatureChecker(object):
except:
param_equality = False
if isinstance(params[0], expected) or param_equality:
params = params[1:]
# If the IsA() comparator is being used, we need to check the
@ -1022,10 +1020,10 @@ class MethodSignatureChecker(object):
class MockMethod(object):
"""Callable mock method.
A MockMethod should act exactly like the method it mocks, accepting parameters
and returning a value, or throwing an exception (as specified). When this
method is called, it can optionally verify whether the called method (name and
signature) matches the expected method.
A MockMethod should act exactly like the method it mocks, accepting
parameters and returning a value, or throwing an exception (as specified).
When this method is called, it can optionally verify whether the called
method (name and signature) matches the expected method.
"""
def __init__(self, method_name, call_queue, replay_mode,
@ -1202,7 +1200,8 @@ class MockMethod(object):
other methods are on the stack.
"""
# Remove this method from the tail of the queue so we can add it to a group.
# Remove this method from the tail of the queue so we can add it
# to a group.
this_method = self._call_queue.pop()
assert this_method == self
@ -1259,8 +1258,8 @@ class MockMethod(object):
def MultipleTimes(self, group_name="default"):
"""Move this method into group of calls which may be called multiple times.
A group of repeating calls must be defined together, and must be executed in
full before the next expected method can be called.
A group of repeating calls must be defined together, and must be executed
in full before the next expected method can be called.
Args:
group_name: the name of the unordered group.
@ -1303,6 +1302,7 @@ class MockMethod(object):
self._side_effects = side_effects
return self
class Comparator:
"""Base class for all Mox comparators.
@ -1341,6 +1341,7 @@ class Comparator:
def __ne__(self, rhs):
return not self.equals(rhs)
class Is(Comparator):
"""Comparison class used to check identity, instead of equality."""
@ -1353,6 +1354,7 @@ class Is(Comparator):
def __repr__(self):
return "<is %r (%s)>" % (self._obj, id(self._obj))
class IsA(Comparator):
"""This class wraps a basic Python type or class. It is used to verify
that a parameter is of the given type or class.
@ -1438,7 +1440,7 @@ class IsAlmost(Comparator):
"""
try:
return round(rhs-self._float_value, self._places) == 0
return round(rhs - self._float_value, self._places) == 0
except Exception:
# This is probably because either float_value or rhs is not a number.
return False
@ -1446,6 +1448,7 @@ class IsAlmost(Comparator):
def __repr__(self):
return str(self._float_value)
class StrContains(Comparator):
"""Comparison class used to check whether a substring exists in a
string parameter. This can be useful in mocking a database with SQL
@ -1649,7 +1652,7 @@ class ContainsAttributeValue(Comparator):
self._value = value
def equals(self, rhs):
"""Check whether the given attribute has a matching value in the rhs object.
"""Check if the given attribute has a matching value in the rhs object.
Returns:
bool
@ -1713,7 +1716,7 @@ class SameElementsAs(Comparator):
class And(Comparator):
"""Evaluates one or more Comparators on RHS and returns an AND of the results.
"""Evaluates one or more Comparators on RHS, returns an AND of the results.
"""
def __init__(self, *args):
@ -1924,6 +1927,7 @@ class MethodGroup(object):
def IsSatisfied(self):
raise NotImplementedError
class UnorderedGroup(MethodGroup):
"""UnorderedGroup holds a set of method calls that may occur in any order.
@ -2040,7 +2044,7 @@ class MultipleTimesGroup(MethodGroup):
return self, method
if self.IsSatisfied():
next_method = mock_method._PopNextMethod();
next_method = mock_method._PopNextMethod()
return next_method, None
else:
raise UnexpectedMethodCallError(mock_method, self)
@ -2083,7 +2087,7 @@ class MoxMetaTestBase(type):
otherwise pass.
Args:
cls: MoxTestBase or subclass; the class whose test method we are altering.
cls: MoxTestBase or subclass; the class whose method we are altering.
func: method; the method of the MoxTestBase test class we wish to alter.
Returns:
@ -2116,14 +2120,15 @@ class MoxMetaTestBase(type):
_MoxTestBase = MoxMetaTestBase('_MoxTestBase', (unittest.TestCase, ), {})
class MoxTestBase(_MoxTestBase):
"""Convenience test class to make stubbing easier.
Sets up a "mox" attribute which is an instance of Mox (any mox tests will
want this), and a "stubs" attribute that is an instance of StubOutForTesting
(needed at times). Also automatically unsets any stubs and verifies that all
mock methods have been called at the end of each test, eliminating boilerplate
code.
mock methods have been called at the end of each test, eliminating
boilerplate code.
"""
def setUp(self):

View File

@ -31,6 +31,7 @@ import mox_test_helper
OS_LISTDIR = mox_test_helper.os.listdir
class ExpectedMethodCallsErrorTest(unittest.TestCase):
"""Test creation and string conversion of ExpectedMethodCallsError."""
@ -96,16 +97,17 @@ class AndTest(unittest.TestCase):
Note: this test is reliant on In and ContainsKeyValue.
"""
test_dict = {"mock" : "obj", "testing" : "isCOOL"}
test_dict = {"mock": "obj", "testing": "isCOOL"}
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"}
test_dict = {"mock": "obj", "testing": "isCOOL"}
self.assertFalse(mox.And(mox.In("NOTFOUND"),
mox.ContainsKeyValue("mock", "obj")) == test_dict)
class FuncTest(unittest.TestCase):
"""Test Func correctly evaluates based upon true-false return."""
@ -133,7 +135,9 @@ class FuncTest(unittest.TestCase):
return True
self.assertTrue(mox.Func(raiseExceptionOnNotOne) == 1)
self.assertRaises(TestException, mox.Func(raiseExceptionOnNotOne).__eq__, 2)
self.assertRaises(
TestException, mox.Func(raiseExceptionOnNotOne).__eq__, 2)
class SameElementsAsTest(unittest.TestCase):
"""Test SameElementsAs correctly identifies sequences with same elements."""
@ -160,7 +164,7 @@ class SameElementsAsTest(unittest.TestCase):
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."""
"""Should return False if two lists with unhashable items are unequal."""
self.assertFalse(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])
def testActualIsNotASequence(self):
@ -171,8 +175,8 @@ class SameElementsAsTest(unittest.TestCase):
"""Store the entire iterator for a correct comparison.
In a previous version of SameElementsAs, iteration stopped when an
unhashable object was encountered and then was restarted, so the actual list
appeared smaller than it was.
unhashable object was encountered and then was restarted, so the actual
list appeared smaller than it was.
"""
self.assertFalse(mox.SameElementsAs([1, 2]) == iter([{}, 1, 2]))
@ -201,14 +205,13 @@ class ContainsAttributeValueTest(unittest.TestCase):
def setUp(self):
"""Create an object to test with."""
class TestObject(object):
key = 1
self.test_object = TestObject()
def testValidPair(self):
"""Should return True if the object has the key attribute and it matches."""
"""Should return True if the object has the key attribute that matches."""
self.assertTrue(mox.ContainsAttributeValue("key", 1) == self.test_object)
def testInvalidValue(self):
@ -229,7 +232,7 @@ class InTest(unittest.TestCase):
def testKeyInDict(self):
"""Should return True if the item is a key in a dict."""
self.assertTrue(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."""
@ -254,7 +257,7 @@ class NotTest(unittest.TestCase):
def testKeyInDict(self):
"""Should return True if the item is NOT a key in a dict."""
self.assertTrue(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."""
@ -310,7 +313,8 @@ class RegexTest(unittest.TestCase):
def testReprWithoutFlags(self):
"""repr should return the regular expression pattern."""
self.assertTrue(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."""
@ -324,8 +328,10 @@ class IsTest(unittest.TestCase):
class AlwaysComparesTrue(object):
def __eq__(self, other):
return True
def __cmp__(self, other):
return 0
def __ne__(self, other):
return False
@ -391,7 +397,7 @@ class IsATest(unittest.TestCase):
def testEquailtyInListInvalid(self):
"""Verify list contents are properly compared."""
isa_list = [mox.IsA(str),mox.IsA(str)]
isa_list = [mox.IsA(str), mox.IsA(str)]
mixed_list = ["abc", 123]
self.assertFalse(isa_list == mixed_list)
@ -461,7 +467,8 @@ class MockMethodTest(unittest.TestCase):
"""Test class to verify that the MockMethod class is working correctly."""
def setUp(self):
self.expected_method = mox.MockMethod("testMethod", [], False)(['original'])
self.expected_method = mox.MockMethod(
"testMethod", [], False)(['original'])
self.mock_method = mox.MockMethod("testMethod", [self.expected_method],
True)
@ -490,9 +497,11 @@ class MockMethodTest(unittest.TestCase):
def testWithSideEffects(self):
"""Should call state modifier."""
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.assertEqual('mutation', local_list[0])
@ -501,10 +510,12 @@ class MockMethodTest(unittest.TestCase):
"""Should call state modifier and propagate its return value."""
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 = self.mock_method(local_list)
self.assertEqual('mutation', local_list[0])
@ -515,10 +526,12 @@ class MockMethodTest(unittest.TestCase):
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.WithSideEffects(modifier_with_return).AndReturn(
expected_return)
actual_return = self.mock_method(local_list)
@ -575,8 +588,8 @@ class MockMethodTest(unittest.TestCase):
def testObjectEquality(self):
"""Equality of objects should work without a Comparator"""
instA = TestClass();
instB = TestClass();
instA = TestClass()
instB = TestClass()
params = [instA, ]
expected_method = mox.MockMethod("testMethod", [], False)
@ -592,7 +605,8 @@ class MockMethodTest(unittest.TestCase):
method = mox.MockMethod("testMethod", [], False)
method(1, 2, "only positional")
self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None")
self.assertEqual(str(method),
"testMethod(1, 2, 'only positional') -> None")
method = mox.MockMethod("testMethod", [], False)
method(a=1, b=2, c="only named")
@ -627,10 +641,10 @@ class MockAnythingTest(unittest.TestCase):
self.assertEqual('<MockAnything instance>', repr(self.mock_object))
def testCanMockStr(self):
self.mock_object.__str__().AndReturn("foo");
self.mock_object.__str__().AndReturn("foo")
self.mock_object._Replay()
actual = str(self.mock_object)
self.mock_object._Verify();
self.mock_object._Verify()
self.assertEqual("foo", actual)
def testSetupMode(self):
@ -919,7 +933,7 @@ class MockObjectTest(unittest.TestCase):
self.assertTrue(len(self.mock_object._expected_calls_queue) == 1)
def testSetupModeWithInvalidCall(self):
"""UnknownMethodCallError should be raised if a non-member method is called.
"""UnknownMethodCallError should be raised for a non-member method call.
"""
# Note: assertRaises does not catch exceptions thrown by MockObject's
# __getattr__
@ -932,7 +946,7 @@ class MockObjectTest(unittest.TestCase):
self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
def testReplayWithInvalidCall(self):
"""UnknownMethodCallError should be raised if a non-member method is called.
"""UnknownMethodCallError should be raised for a non-member method call.
"""
self.mock_object.ValidCall() # setup method call
self.mock_object._Replay() # start replay mode
@ -958,7 +972,8 @@ class MockObjectTest(unittest.TestCase):
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)
self.assertTrue(
'_TestClass__PrivateCall' in self.mock_object._known_methods)
def testFindsSuperclassMethods(self):
"""Mock should be able to mock superclasses methods."""
@ -1030,7 +1045,9 @@ class MockObjectTest(unittest.TestCase):
dummy._Replay()
def call(): dummy['X'] = 'Y'
def call():
dummy['X'] = 'Y'
self.assertRaises(mox.UnexpectedMethodCallError, call)
def testMockSetItem_ExpectedNoSetItem_NoSuccess(self):
@ -1054,7 +1071,8 @@ class MockObjectTest(unittest.TestCase):
dummy._Replay()
def call(): dummy['wrong'] = 'Y'
def call():
dummy['wrong'] = 'Y'
self.assertRaises(mox.UnexpectedMethodCallError, call)
@ -1112,7 +1130,9 @@ class MockObjectTest(unittest.TestCase):
dummy._Replay()
def call(): return dummy['X']
def call():
return dummy['X']
self.assertRaises(mox.UnexpectedMethodCallError, call)
def testMockGetItem_ExpectedGetItem_NonmatchingParameters(self):
@ -1122,7 +1142,8 @@ class MockObjectTest(unittest.TestCase):
dummy._Replay()
def call(): return dummy['wrong']
def call():
return dummy['wrong']
self.assertRaises(mox.UnexpectedMethodCallError, call)
@ -1192,7 +1213,8 @@ class MockObjectTest(unittest.TestCase):
dummy._Replay()
def call(): return 'Y' in dummy
def call():
return 'Y' in dummy
self.assertRaises(mox.UnexpectedMethodCallError, call)
@ -1219,7 +1241,8 @@ class MockObjectTest(unittest.TestCase):
dummy._Replay()
def call(): return [x for x in dummy]
def call():
return [x for x in dummy]
self.assertRaises(mox.UnexpectedMethodCallError, call)
def testMockIter_ExpectedGetItem_Success(self):
@ -1476,7 +1499,7 @@ class MoxTest(unittest.TestCase):
self.mox.ReplayAll()
actual_one = mock_obj.Method(1)
second_one = mock_obj.Method(1) # This tests MultipleTimes.
second_one = mock_obj.Method(1) # This tests MultipleTimes.
actual_two = mock_obj.Method(2)
actual_three = mock_obj.Method(3)
mock_obj.Method(3)
@ -1485,7 +1508,8 @@ class MoxTest(unittest.TestCase):
self.mox.VerifyAll()
self.assertEqual(9, actual_one)
self.assertEqual(9, second_one) # Repeated calls should return same number.
# Repeated calls should return same number.
self.assertEqual(9, second_one)
self.assertEqual(10, actual_two)
self.assertEqual(42, actual_three)
@ -1499,13 +1523,14 @@ class MoxTest(unittest.TestCase):
mock_obj.Open()
actual_one = mock_obj.Method("1")
second_one = mock_obj.Method("2") # This tests MultipleTimes.
second_one = mock_obj.Method("2") # This tests MultipleTimes.
mock_obj.Close()
self.mox.VerifyAll()
self.assertEqual(9, actual_one)
self.assertEqual(9, second_one) # Repeated calls should return same number.
# Repeated calls should return same number.
self.assertEqual(9, second_one)
def testMutlipleTimesUsingFunc(self):
"""Test that the Func is not evaluated more times than necessary.
@ -1514,6 +1539,7 @@ class MoxTest(unittest.TestCase):
"""
self.counter = 0
def MyFunc(actual_str):
"""Increment the counter if actual_str == 'foo'."""
if actual_str == 'foo':
@ -1690,7 +1716,8 @@ class MoxTest(unittest.TestCase):
self.assertEqual('foo', actual)
def testStubOutMethod_Unbound_Subclass_Comparator(self):
self.mox.StubOutWithMock(mox_test_helper.TestClassFromAnotherModule, 'Value')
self.mox.StubOutWithMock(
mox_test_helper.TestClassFromAnotherModule, 'Value')
mox_test_helper.TestClassFromAnotherModule.Value(
mox.IsA(mox_test_helper.ChildClassFromAnotherModule)).AndReturn('foo')
self.mox.ReplayAll()
@ -1782,7 +1809,7 @@ class MoxTest(unittest.TestCase):
t.MethodWithArgs(mox.IgnoreArg(), mox.IgnoreArg()).AndReturn('foo')
self.mox.ReplayAll()
actual = t.MethodWithArgs(None, None);
actual = t.MethodWithArgs(None, None)
self.mox.VerifyAll()
self.mox.UnsetStubs()
@ -1849,7 +1876,6 @@ class MoxTest(unittest.TestCase):
self.mox.VerifyAll()
self.mox.UnsetStubs()
def testStubOut_SignatureMatching_init_(self):
self.mox.StubOutWithMock(mox_test_helper.ExampleClass, '__init__')
mox_test_helper.ExampleClass.__init__(mox.IgnoreArg())
@ -2247,6 +2273,7 @@ class MoxTestBaseMultipleInheritanceTest(mox.MoxTestBase, MyTestCase):
super(MoxTestBaseMultipleInheritanceTest, self).testMethodOverride()
self.assertEqual(43, self.another_critical_variable)
class MoxTestDontMockProperties(MoxTestBaseTest):
def testPropertiesArentMocked(self):
mock_class = self.mox.CreateMock(ClassWithProperties)
@ -2335,6 +2362,7 @@ class CallableClass(object):
def __call__(self, param):
return param
class ClassWithProperties(object):
def setter_attr(self, value):
pass

View File

@ -31,6 +31,7 @@ import os
import mox
class ExampleMoxTestMixin(object):
"""Mix-in class for mox test case class.

View File

@ -26,6 +26,6 @@ setup(name='mox',
maintainer_email='quermit@gmail.com',
license='Apache License, Version 2.0',
description='Mock object framework',
long_description='''Mox is a mock object framework for Python based on the
Java mock object framework EasyMock.''',
long_description=('Mox is a mock object framework for Python based on'
'the Java mock object framework EasyMock.'),
)

View File

@ -18,6 +18,7 @@
import inspect
class StubOutForTesting(object):
"""Sample Usage:
You want os.path.exists() to always return true during testing.

View File

@ -14,5 +14,6 @@
#
# This file was mofified by quermit@gmail.com
def SampleFunction():
raise Exception('I should never be called!')