-1

I got a MagickMock and I want to return side effect values each times it is called. The amount of calls is not known. The return value should between 1 and 2. I was wondering how to do this, via Lambda function?

I was trying something like this:

patched.side_effect = lambda x: (1, 2)

Any ideas?

sg_sg94
  • 2,248
  • 4
  • 28
  • 56
  • _What_ value between those? A random one (see the `random` module)? Incrementing from one towards the other? How you implement it is going to depend on what you actually want. – jonrsharpe Aug 02 '21 at 09:50
  • yes random, increment is not needed, just random – sg_sg94 Aug 02 '21 at 09:51
  • Then have you read e.g. https://stackoverflow.com/q/6088077/3001761? – jonrsharpe Aug 02 '21 at 09:54
  • @jonrsharpe thanks. Any idea how to use the round(random.uniform(1,2), N) so it returns always a random when the mock is called? just side_effect = round(random.uniform(1,2), N)? – sg_sg94 Aug 02 '21 at 09:56
  • That would just be one random float, not a function or exception class/instance per https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock. – jonrsharpe Aug 02 '21 at 09:58

1 Answers1

0

Maybe you can try as below

>>>import random
>>>func = lambda x: random.randint(1, 2)
>>>val = func("")
>>>print(val)
>>>1
>>>print(val)
>>>2

patched.side_effect = func("")

only random module is enough to do same

>>>val = random.randint(1, 2)
>>>print(val)
>>>1
>>>print(val)
>>>2
patched.side_effect = random.randint(1, 2)