2013-07-18 67 views
9

我正在使用Python的mock库。我知道如何通过遵循document嘲笑一个类的实例方法:Python模拟类实例变量

>>> def some_function(): 
...  instance = module.Foo() 
...  return instance.method() 
... 
>>> with patch('module.Foo') as mock: 
...  instance = mock.return_value 
...  instance.method.return_value = 'the result' 
...  result = some_function() 
...  assert result == 'the result' 

然而,试图嘲笑一个类的实例变量,但(在下面的例子中instance.labels)不工作:

>>> with patch('module.Foo') as mock: 
...  instance = mock.return_value 
...  instance.method.return_value = 'the result' 
...  instance.labels = [1, 1, 2, 2] 
...  result = some_function() 
...  assert result == 'the result' 

基本上我想instance.labels根据some_function得到我想要的值。任何提示?

回答

12

这的some_function()打印版本嘲笑labels属性:

def some_function(): 
    instance = module.Foo() 
    print instance.labels 
    return instance.method() 

module.py

class Foo(object): 

    labels = [5, 6, 7] 

    def method(self): 
     return 'some' 

补丁是一样的你:

with patch('module.Foo') as mock: 
    instance = mock.return_value 
    instance.method.return_value = 'the result' 
    instance.labels = [1,2,3,4,5] 
    result = some_function() 
    assert result == 'the result 

完全控制台会话:

>>> from mock import patch 
>>> import module 
>>> 
>>> def some_function(): 
...  instance = module.Foo() 
...  print instance.labels 
...  return instance.method() 
... 
>>> some_function() 
[5, 6, 7] 
'some' 
>>> 
>>> with patch('module.Foo') as mock: 
...  instance = mock.return_value 
...  instance.method.return_value = 'the result' 
...  instance.labels = [1,2,3,4,5] 
...  result = some_function() 
...  assert result == 'the result' 
...  
... 
[1, 2, 3, 4, 5] 
>>> 

对我来说你的代码的工作。

+0

它不起作用。我得到了与'instance.labels = [1,1,2,2]'相同的结果,这个模拟变量没有被'some_function'使用。在文档中,它嘲笑方法而不是变量。 – clwen

+0

更新了我的答案。现在我迷路了,因为你的代码正在工作。 – twil

+0

在我的代码中,只有在调用某个函数后才会出现'labels'。该函数在我想测试的函数中调用。也许这就是原因。我最终模拟了类的初始化,以便它返回具有我想要的行为的模拟对象。 – clwen