导入到被测模块中的模拟方法

时间:2012-02-02 12:15:33

标签: python python-mock

说我想测试这个模块:

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并让它返回testdata。这样做的首选方法是什么?我是否必须进行模拟或(猴子)修补?

示例测试:

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

2 个答案:

答案 0 :(得分:1)

一个解决方案是执行from osutils import call,然后在调用yourmodule.call之前用其他内容替换test_ib6_check

答案 1 :(得分:0)

好吧,我发现这与模拟无关,afaik我只需要一个猴子补丁:我需要导入并更改osutils.call - 方法,然后导入测试中的方法(而不是然后,整个模块,因为它将导入原始的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) == True