Python模拟补丁函数缺少参数

时间:2014-11-23 23:53:27

标签: python mocking

我在模块a中有以下代码:

class MyManager(models.Manager):

    def dowork(self, value1, value2):
        print value1, value2

在模块b中:

class MyModel(models.Model):
    objects = MyManager()
    value1 = ...        
    value2 = ...

    def call_manager(self):
        self.objects.dowork(self.value1, self.value2)

在unittest中,我使用不同的主体修补dowork,例如:

def new_dowork(self, value1, value2):
    print 123

with patch('a.MyManager.dowork', new_callable=new_dowork):
    record = MyModel(value=111)
    record.call_manager()
    ...

但我得到了TypeError: new_dowork() takes exactly 3 arguments (0 given)

1 个答案:

答案 0 :(得分:2)

我对Mock了解不多,但我认为主要问题是您应该在new参数中传递模拟函数,而不是new_callable中的模拟函数,使用patch.object实际覆盖对象中的方法。

这似乎有效:

from mock import patch

class MyManager(object):

    def dowork(self, value1, value2):
        print value1, value2

class MyModel(object):
    objects = MyManager()
    value1 = 'foo'        
    value2 = 'bar'

    def __init__(self, value=0):
        # You don't need this __init__... Is just so I don't have to 
        # use models.MyModel thingy
        pass

    def call_manager(self):
        self.objects.dowork(self.value1, self.value2)

def new_dowork(self, value1, value2):
    print "Mock called"
    print 123

with patch.object(MyManager, 'dowork', new=new_dowork):
    record = MyModel(value=111)
    record.call_manager()

输出:

Mock called
123