New make_mock_fixture function
authorKarl O. Pinc <kop@karlpinc.com>
Wed, 24 Jun 2020 22:24:59 +0000 (17:24 -0500)
committerKarl O. Pinc <kop@karlpinc.com>
Wed, 24 Jun 2020 22:24:59 +0000 (17:24 -0500)
src/pgwui_testing/testing.py
tests/test_testing.py

index fb567fa36d48b5767a574c4ae9582894bd6c0bb2..a68f7a3e523a82f2aa1c9fc74a8fdbf035cf4c49 100644 (file)
@@ -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.
 #
 # <http://www.gnu.org/licenses/>.
 #
 
-# Karl O. Pinc <kop@meme.com>
+# Karl O. Pinc <kop@karlpinc.com>
 
 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
index 13063bbc9a8daf05498826442b162606744cdb88..9266b0ab37b79383e42f4446a6b6a63a6ccf71cd 100644 (file)
@@ -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.
 #
 # <http://www.gnu.org/licenses/>.
 #
 
-# Karl O. Pinc <kop@meme.com>
+# Karl O. Pinc <kop@karlpinc.com>
 
 # 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