0

我想编写一个测试用例来测试功能列表。这是我想做的一个例子:

from mock import Mock
def method1 ():
    pass

def method2 ():
    pass

## The testcase will then contain:
for func in method_list:
    func = Mock()
    # continue to setup the mock and do some testing

我想要实现的目标如下:
步骤 1)将我的本地方法变量分配给 method_list 中的每个项目
步骤 2)Monkeypatch 方法。在这个例子中,我使用了一个 mock.Mock 对象

实际发生的是:
步骤 1) 方法已成功分配给来自 method_list 的项目 - OK
步骤 2) 然后将方法分配给对象 Mock() - NOK

我在第 2 步中想要的是从 method_list 中获取项目,例如将 method1 分配给 Mock() 对象。最终结果是 method 和 method1 都指向同一个 Mock() 对象

我意识到我实际上在做的是 a = b
a = c
然后期待 c==b !

我想如果没有以某种方式获得指向 b 的指针,这实际上是不可能的?

4

3 回答 3

1

嗯,简单地修改method_list怎么样?

for i in range(len(method_list)): # xrange in Python 2
    method_list[i] = Mock()

您所描述的更接近 C++ 引用而不是指针。很少有语言具有这样的语义(少数语言为传递引用提供了特殊的关键字),包括 Python。

于 2010-08-26T13:48:20.377 回答
1

如果我理解正确,您想更改变量 method1指向的内容吗?那正确吗?

您可以通过修改其在局部变量字典中的条目来做到这一点:

for method_name in [ 'method1', 'method2' ]:
    locals()[ method_name ] = Mock( )

您之前的代码没有执行您想要的操作的原因func是对 function 的引用method1。通过分配给 is,您只需更改它所指向的内容。

你确定要这么做吗?

Monkeypatching 很讨厌,会导致很多问题。

于 2010-08-26T14:24:40.097 回答
1

像这样的东西?

from mock import Mock
def method1 ():
    pass

def method2 ():
    pass

method_list=list(f for f in globals() if hasattr(globals()[f],'__call__') and f.startswith('method'))
print method_list
## The testcase will then contain:
for func in method_list:
    globals()[func] = Mock(func)
    # continue to setup the mock and do some testing

不过,我不太确定这样做是否明智。看起来与装饰器有关。

于 2010-08-26T14:51:13.887 回答