From 41aeca2d2f9bb0398ca147a3c9ec79ff4525fd05 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Sun, 6 Dec 2020 17:08:50 -0600 Subject: [PATCH] Add a fixture that magicmocks --- src/pgwui_testing/testing.py | 18 ++++++++++++++++++ tests/test_testing.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) 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() # -- 2.34.1