Add a fixture that magicmocks
authorKarl O. Pinc <kop@karlpinc.com>
Sun, 6 Dec 2020 23:08:50 +0000 (17:08 -0600)
committerKarl O. Pinc <kop@karlpinc.com>
Tue, 8 Dec 2020 04:08:34 +0000 (22:08 -0600)
src/pgwui_testing/testing.py
tests/test_testing.py

index 8b8c3e08e4852b15620bcbfb27554b7d6390c814..402626f61051387a3459c470325c8fc0b18b8d3c 100644 (file)
@@ -39,6 +39,24 @@ def make_mock_fixture(module, method, autouse=False, wraps=None):
     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.
index a9a8508b739f754f6ab8bade2b6968e1970894e3..236998312de1d537ba69dd5ebd1fc5341786b6e7 100644 (file)
@@ -56,6 +56,40 @@ def test_make_mock_fixture_fixture(mocked_func):
     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()
 #