假设我想测试这个模块:
import osutils
def check_ip6(xml):
ib_output = osutils.call('iconfig ib0')
# process and validate ib_output (to be unit tested)
...这个方法依赖于环境,因为它进行一个系统调用(需要一个特定的网络接口),所以在测试机器上是不可调用的。
我想为该方法编写一个单元测试,用于检查ib_output的处理是否按预期工作。因此,我想模拟osutils.call,让它只返回测试数据。做这件事的首选方法是什么?我必须做模拟或(猴子)修补吗?
示例测试:
def test_ib6_check():
from migration import check_ib6
# how to mock os_utils.call used by the check_ib6-method?
assert check_ib6(test_xml) == True发布于 2012-02-02 20:26:31
一种解决方案是执行from osutils import call,然后在打补丁时,在调用test_ib6_check之前用其他东西替换yourmodule.call。
发布于 2012-02-02 20:44:28
好吧,我发现这与mock没有任何关系,我只需要一个猴子补丁:我需要导入并更改调用方法,然后导入测试下的方法(而不是整个模块,因为它会导入原始的osutils.call--method)。因此,此方法将使用我更改后的call- method:
def test_ib6_check():
def call_mock(cmd):
return "testdata"
osutils.call = call_mock
from migration import check_ib6
# the check_ib6 now uses the mocked method
assert check_ib6(test_xml) == Truehttps://stackoverflow.com/questions/9112156
复制相似问题