monkeypatch.setattr(module, method, mocked)
return mocked
return fix
+
+
+def instance_method_mock_fixture(method):
+ '''Returns a pytest fixture that mocks an instance method of a class.
+ "method" is a string.
+
+ The fixture is called by the test function with the class instance
+ that's to be monkeypatched and the mock is returned for the
+ test function to configure/etc.
+ '''
+ @fixture
+ def fix(monkeypatch):
+ def run(cls):
+ mocked = mock.Mock(spec=getattr(cls, method), name=method)
+ monkeypatch.setattr(cls, method, mocked)
+ return mocked
+ return run
+ return fix
# Test functions
+#
+# make_mock_fixture()
+#
# Function to test mocking
def func_to_mock():
sys.modules[__name__], 'func_to_mock')
-# make_mock_fixture
def test_make_mock_fixture_fixture(mocked_func):
'''The mock of the function works
'''
result = mocked_func()
assert result == test_value
+
+
+#
+# instance_method_mock_fixture()
+#
+
+normal_return_value = 'not mocked'
+
+
+# Class for mock testing
+class TestClass():
+
+ def method_to_mock(self):
+ return normal_return_value
+
+
+mocked_method = testing.instance_method_mock_fixture('method_to_mock')
+
+
+def test_instance_method_mock_fixture(mocked_method):
+ '''The mock of the instance method works
+ '''
+ test_value = 'mocked value'
+ cls = TestClass()
+ mocked_method(cls).return_value = test_value
+
+ result = cls.method_to_mock()
+
+ assert result == test_value
+
+
+def test_instance_method_mock_fixture_unmocked():
+ '''The test class works after the mocking
+ '''
+ cls = TestClass()
+ result = cls.method_to_mock()
+
+ assert result == normal_return_value