0

how to mock a method who's been called 2 times and make it to return diferent values. To visualize in mind here's the code:

def method(self, param):
   # here I have the logic if param is equal to 1 -> return [1,2,3], if param is equal to 2 -> return [a,s,d]

def method_x(self, param_x):
   # here uses method returned values with 1 or 2

def main():
    one = self.method(1)
    two = self.method(2)

    three = self.method_x(one)
    four = self.method_x(two)

test:

def setUp(self):
    self.c = py_file.Class()

def test_main(self):
    self.c.method = MagicMock()
    self.c.main()

    self.c.method.assert_any_call(1)
    self.c.method.assert_any_call(2)
    self.assertEqual(2, self.c.method.call_count)

    # but the problem comes when I need to use for other methods method(1) in three and method(2) in four
    ...

I have tried to use side_effect like this:

self.c.method = MagicMock(side_effect=[[1,2,3],[a,s,d]])
# this way running test one has 1,2,3 values and two has a,s,d

but then when it comes to use the values for four and five I get (like c.method.side_effects= [[1,2,3],[a,s,d]] and then for four use c.method.side_effects[0] and for five with [1] :

TypeError: 'listiterator' object is unsubscriptable

How to pass the correct values to correct varaibles in test - how to mock and set return values correctly?

Using Python2.6.6, mock 1.0.0

Poli
  • 77
  • 1
  • 11
  • It's better if you use `patch()` as a decorator of the test for this: https://docs.python.org/3/library/unittest.mock.html#patch – Shinra tensei Jan 28 '20 at 13:43
  • @Shinratensei I'll give it a try – Poli Jan 28 '20 at 13:44
  • https://stackoverflow.com/questions/18191275/using-pythons-mock-patch-object-to-change-the-return-value-of-a-method-called-w this question will probably help you. Actually I would say that yours could be classified as a duplicate – Shinra tensei Jan 28 '20 at 13:45
  • @Shinratensei but in my case I'm using same method to pass the called values of ```call``` – Poli Jan 28 '20 at 13:47
  • I don't think I understood your last comment, I'm sorry – Shinra tensei Jan 28 '20 at 13:53
  • I think you don't understand my situation – Poli Jan 28 '20 at 13:54
  • Quite possible, that's why I was trying to understand your last comment, but you're talking about the called values of `call`, and I see no `call` in your example code – Shinra tensei Jan 28 '20 at 13:57
  • @Shinratensei I get method calls when I'm calling ```main``` in test when I'm asserting call_any – Poli Jan 28 '20 at 13:59

0 Answers0