我很难理解 python 的模拟测试方法。
我想对 this file 做一些模拟.
由于包 xbmc、xbmcaddon 和 xbmcgui 无法在正常的 python 环境中导入,我设法像这样模拟它们:
class XBMCTestCase(unittest.TestCase):
def setUp(self):
#Mock up any calls to modules that cannot be imported
self.xbmc = Mock()
self.xbmcgui = Mock()
self.xbmcaddon = Mock()
modules = {
'xbmc' : self.xbmc,
'xbmcgui': self.xbmcgui,
'xbmcaddon': self.xbmcaddon
}
self.module_patcher = patch.dict('sys.modules', modules) #@UndefinedVariable
self.module_patcher.start()
查看实际效果 here .
所以当我导入 setlocation.py 时,我得到这样的错误:
File "/home/paulo/workspace/weather.metoffice/src/metoffice/utils/utilities.py", line 21, in <module>
CACHE_FOLDER = os.path.join(ADDON_DATA_PATH, 'cache')
File "/usr/lib/python2.7/posixpath.py", line 78, in join
path += b
TypeError: unsupported operand type(s) for +=: 'Mock' and 'str'
即使我模拟“metoffice.utils”(通过将其添加到安装时创建的补丁中的模块列表中),我也会在 setlocation.py
File "/home/paulo/workspace/weather.metoffice/src/metoffice/setlocation.py", line 32, in <module>
GEOIP_PROVIDER = int(__addon__.getSetting('GeoIPProvider'))
TypeError: int() argument must be a string or a number, not 'Mock'
所以我需要 __addon__.getSetting() 来返回一个字符串。
有什么想法吗?
所有尝试都失败了,但我认为我没有完全掌握模拟包的功能。
请注意,我在 Python 2.7.3 上使用 mock 1.0.1
请您参考如下方法:
你需要告诉你的模拟返回什么。 __addon__ 值是 xbmcaddon.Addon() 调用的结果,因此您可以通过以下方式访问该模拟对象:
addon = self.xbmcaddon.Addon.return_value
因为 .return_value 为您提供调用 Addon() 将返回的实际 Mock 对象。
现在您可以告诉 Mock 对象在调用 getSetting() 方法时返回什么;此处提供两个值,因此您可以使用 side_effect设置要返回的值序列:
addon.getSetting.side_effect = ['some_api_key', '42']
第一次调用 __addon__.getSetting() 将产生第一个值 'some_api_key',第二次调用将产生 '42'.
