Thursday 23 April 2020

patch multiple methods from different modules (using Python mock)

The short answer is no you cannot use patch.multiple() to do it. As described in patch.multiple all arguments will be applied to all created mocks and all arguments MUST be attribute of the same object. You MUST do it one of the time by single patch calls.
Unfortunately you are using python 2.6 so you can use just nested fron contextlib like pointed in python: create a "with" block on several context managers and Multiple context `with` statement in Python 2.6.
Maybe the more cleaner and simple way to do it is use @patch as decorator:
@patch("foo.load",side_effects=["a","b","c"])
@patch("bar.check",return_value=True)
def test_mytest(mock_check,mock_load):
    take_action()
    assert mock_load.called
    assert mock_check.called
If you need it in all tests of a test class you can decorate the class and use the mocks in all test methods:
@patch("foo.load",side_effects=["a","b","c"])
@patch("bar.check",return_value=True)
class TestMyTest(unittest.TestCase)
    def test_mytestA(self,mock_check,mock_load):
        take_action()
        self.assertTrue(mock_load.called)
        self.assertTrue(mock_check.called)

    def test_mytestA(self,mock_check,mock_load):
        mock_check.return_value = False
        take_action()
        self.assertTrue(mock_load.called)
        self.assertTrue(mock_check.called)
Finally you can do it by using with and contextlib and the first example become:
from contextlib import nested

with nested(patch("foo.load",side_effects=["a","b","c"]), patch("bar.check",return_value=True)) as (mock_load, mock_check):
    take_action()
    assert mock_load.called
    assert mock_check.called
... Or nest it by hand ....
with patch("foo.load",side_effects=["a","b","c"]) as mock_load:
    with patch("bar.check",return_value=True)) as mock_check:
        take_action()
        assert mock_load.called
        assert mock_check.called
My feel is that decorators are the most readable and simple to use.

from : https://stackoverflow.com/questions/27270958/patch-multiple-methods-from-different-modules-using-python-mock

No comments:

Post a Comment