return fix
+def make_magicmock_fixture(module, method, autouse=False, autospec=False):
+ '''Returns a pytest fixture that magic mocks a module's method or a
+ class's class method. "module" is a module or a class, but method
+ is a string.
+ '''
+ @fixture(autouse=autouse)
+ def fix(monkeypatch):
+ if autospec:
+ mocked = mock.create_autospec(
+ getattr(module, method), spec_set=True)
+ else:
+ mocked = mock.MagicMock(
+ spec=getattr(module, method), name=method)
+ 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.
assert result == test_value
+#
+# make_magicmock_fixture()
+#
+
+magic_mocked_func = testing.make_magicmock_fixture(
+ sys.modules[__name__], 'func_to_mock')
+
+
+@pytest.mark.integrationtest
+def test_make_magicmock_fixture_no_autospec(magic_mocked_func):
+ # The mock of the function works
+
+ test_value = 'test value'
+ magic_mocked_func.return_value = test_value
+ result = magic_mocked_func()
+
+ assert result == test_value
+
+
+magic_mocked_autospecced_func = testing.make_magicmock_fixture(
+ sys.modules[__name__], 'func_to_mock', autospec=True)
+
+
+@pytest.mark.integrationtest
+def test_make_magicmock_fixture_autospec(magic_mocked_autospecced_func):
+ # The mock of the function works
+
+ test_value = 'test value'
+ magic_mocked_autospecced_func.return_value = test_value
+ result = magic_mocked_autospecced_func()
+
+ assert result == test_value
+
+
#
# instance_method_mock_fixture()
#