Add instance_method_mock_fixture() for mocking instance methods
authorKarl O. Pinc <kop@karlpinc.com>
Thu, 25 Jun 2020 02:40:30 +0000 (21:40 -0500)
committerKarl O. Pinc <kop@karlpinc.com>
Thu, 25 Jun 2020 02:40:30 +0000 (21:40 -0500)
src/pgwui_testing/testing.py
tests/test_testing.py

index a68f7a3e523a82f2aa1c9fc74a8fdbf035cf4c49..13010c771c74d8b66c1c0de87ab817eda12291b9 100644 (file)
@@ -73,3 +73,21 @@ def make_mock_fixture(module, method, autouse=False):
         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
index 9266b0ab37b79383e42f4446a6b6a63a6ccf71cd..a27e3978f33afad35defe61c7adc287818610fff 100644 (file)
@@ -110,6 +110,9 @@ def test_pgwui_component_entry_point(testdir):
 
 # Test functions
 
+#
+# make_mock_fixture()
+#
 
 # Function to test mocking
 def func_to_mock():
@@ -120,7 +123,6 @@ mocked_func = testing.make_mock_fixture(
     sys.modules[__name__], 'func_to_mock')
 
 
-# make_mock_fixture
 def test_make_mock_fixture_fixture(mocked_func):
     '''The mock of the function works
     '''
@@ -129,3 +131,41 @@ def test_make_mock_fixture_fixture(mocked_func):
     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