[TIP] Patching the same object in multiple modules, resulting in a single Mock object to the patched function
m at funkyhat.org
Thu Nov 24 04:24:49 PST 2016
On Wed, 23 Nov 2016 at 21:58 Saravanan Shanmugham <sarvi at yahoo.com> wrote:
> I am testing some code that is distributed across multiple modules.
> Each module imports a single method that I want to mock,
> Say check_call from subprocess or open from builtins.
> I want to mock out these methods from the multiple modules with one mock
> Whats the best way to do it.
> # I don't want to see the following, where multiple mock open objects get
> def test_case1(mopen1, mopen2):
> m1_open.side_effect = [OSError]
> m2_open.side_effect = [OSError]
> # Test code
> I want to see something like the following
> @patch.special(['module1.open', 'module2.open', 'module3.open'], new=mopen)
> def test_case1(mopen):
> mopen.side_effect = [OSError, OSError]
> '# Test code
> Is there a way to do this?
You can patch it directly in builtins:
if sys.version_info.major == 2:
# if you need to support python2
import __builtin__ as builtins
@patch.object(builtins, 'open', mopen)
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the testing-in-python