From: Karl O. Pinc Date: Sun, 6 Dec 2020 23:08:50 +0000 (-0600) Subject: Add a fixture that magicmocks X-Git-Url: https://papio.biology.duke.edu/gitweb/?a=commitdiff_plain;h=41aeca2d2f9bb0398ca147a3c9ec79ff4525fd05;p=pgwui_develop Add a fixture that magicmocks --- diff --git a/src/pgwui_testing/testing.py b/src/pgwui_testing/testing.py index 8b8c3e0..402626f 100644 --- a/src/pgwui_testing/testing.py +++ b/src/pgwui_testing/testing.py @@ -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. diff --git a/tests/test_testing.py b/tests/test_testing.py index a9a8508..2369983 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -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() #