Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python mock functions with parameters

Tags:

python

mocking

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)

like image 930
myg Avatar asked Mar 14 '23 07:03

myg


1 Answers

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.)

like image 119
chepner Avatar answered Mar 25 '23 16:03

chepner