Mocking python function based on input arguments

后端 未结 8 496
无人及你
无人及你 2020-12-22 21:15

We have been using Mock for python for a while.

Now, we have a situation in which we want to mock a function

def foo(self, my_param):
    #do someth         


        
相关标签:
8条回答
  • 2020-12-22 22:10

    As indicated at Python Mock object with method called multiple times

    A solution is to write my own side_effect

    def my_side_effect(*args, **kwargs):
        if args[0] == 42:
            return "Called with 42"
        elif args[0] == 43:
            return "Called with 43"
        elif kwargs['foo'] == 7:
            return "Foo is seven"
    
    mockobj.mockmethod.side_effect = my_side_effect
    

    That does the trick

    0 讨论(0)
  • 2020-12-22 22:15

    Side effect takes a function (which can also be a lambda function), so for simple cases you may use:

    m = MagicMock(side_effect=(lambda x: x+1))
    
    0 讨论(0)
提交回复
热议问题