OK,
I know this is mentioned in the manual, and probably has to do with side_effect and/or return_value, but a simple, direct example will help me immensely.
I have:
class ClassToPatch():
def __init__(self, *args):
_do_some_init_stuff()
def some_func():
_do_stuff()
class UUT():
def __init__(self, *args)
resource_1 = ClassToPatch()
resource_2 = ClassToPatch()
Now, I want to unit test the UUT class, and mock the ClassToPatch. Knowing the UUT class will instantiate exactly two ClassToPatch objects, I want the Mock framework to return a new Mock object for each instantiation, so I can later assert calls on each separately.
How do I achieve this using the @patch decorator in a test case? Namely, how to fix the following code sample?
class TestCase1(unittest.TestCase):
@patch('classToPatch.ClassToPatch',autospec=True)
def test_1(self,mock1,mock2):
_assert_stuff()
Here’s a quick’n’dirty example to get you going:
I’ve added
test_propertyto UUT so that the unit test does something useful. Now, without the mocktest_propertyshould be a tuple containing the ids of the twoClassToPatchinstances. But with the mock it should be the tuple:("funky", "monkey").I’ve used the
side_effectproperty of the mock object so that a different instance ofClassToPatchis returned on each call in theUUTinitialiser.Hope this helps.
Edit: Oh, by the way, when I run the unit test I get: