From 81f0a5c083e8799c6a04bcc66ce605c6b3f58613 Mon Sep 17 00:00:00 2001 From: "Karl O. Pinc" Date: Wed, 24 Jun 2020 17:24:59 -0500 Subject: [PATCH] New make_mock_fixture function --- src/pgwui_testing/testing.py | 21 +++++++++++++++++++-- tests/test_testing.py | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/src/pgwui_testing/testing.py b/src/pgwui_testing/testing.py index fb567fa..a68f7a3 100644 --- a/src/pgwui_testing/testing.py +++ b/src/pgwui_testing/testing.py @@ -1,4 +1,5 @@ -# Copyright (C) 2015, 2018 The Meme Factory, Inc. http://www.meme.com/ +# Copyright (C) 2015, 2018, 2020 The Meme Factory, Inc. +# http://www.karlpinc.com/ # This file is part of PGWUI_Testing. # @@ -17,9 +18,10 @@ # . # -# Karl O. Pinc +# Karl O. Pinc import pkg_resources +from unittest import mock from pytest import ( fixture, @@ -56,3 +58,18 @@ def pgwui_component_entry_point(): pkg_resources.iter_entry_points('pgwui.components')]) return run + + +# Mock support + +def make_mock_fixture(module, method, autouse=False): + '''Returns a pytest fixture that 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): + mocked = mock.Mock( + spec=getattr(module, method), name=method) + monkeypatch.setattr(module, method, mocked) + return mocked + return fix diff --git a/tests/test_testing.py b/tests/test_testing.py index 13063bb..9266b0a 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -1,4 +1,5 @@ -# Copyright (C) 2018, 2019 The Meme Factory, Inc. http://www.meme.com/ +# Copyright (C) 2018, 2019, 2020 The Meme Factory, Inc. +# http://www.karlpinc.com/ # This file is part of PGWUI_Testing. # @@ -17,10 +18,14 @@ # . # -# Karl O. Pinc +# Karl O. Pinc # See: https://pytest-cov.readthedocs.io/en/latest/plugins.html +import sys + +from pgwui_testing import testing + from pyramid.config import ( Configurator ) @@ -101,3 +106,26 @@ def test_pgwui_component_entry_point(testdir): result = testdir.runpytest() result.assert_outcomes(passed=2) + + +# Test functions + + +# Function to test mocking +def func_to_mock(): + return 'mocked' + + +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 + ''' + test_value = 'test value' + mocked_func.return_value = test_value + result = mocked_func() + + assert result == test_value -- 2.34.1