5

I want to mock a function that calls an external function with parameters. I know how to mock a function, but I can't give parameters. I tried with @patch, side_effects, but no success.

def functionToTest(self, ip):
    var1 = self.config.get(self.section, 'externalValue1')
    var2 = self.config.get(self.section, 'externalValue2')
    var3 = self.config.get(self.section, 'externalValue3')

    if var1 == "xxx":
        return False
    if var2 == "yyy":
        return False

    [...]

In my test I can do this:

    def test_functionToTest(self):
    [...]
    c.config = Mock()
    c.config.get.return_value = 'xxx'

So both var1, var2 and var3 take "xxx" same value, but I don't know how to mock every single instruction and give var1, var2 and var3 values I want

(python version 2.7.3)

1 Answer 1

9

Use side_effect to queue up a series of return values.

c.config = Mock()
c.config.get.side_effect = ['xxx', 'yyy', 'zzz']

The first time c.config.get is called, it will return 'xxx'; the second time, 'yyy'; and the third time, 'zzz'. (If it is called a fourth time, it will raise a StopIteration error.)

Sign up to request clarification or add additional context in comments.

1 Comment

Hey chepner, it works! I was trying change parameters (self.section, 'externalValue') but your solution was better. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.