我无法弄清楚当他们都使用上下文管理器时,如何模拟两个文件在类中打开。我知道如何使用模拟模块,这样做的一个上下文管理文件:Python模拟内建'打开'在一个类中使用两个不同的文件
@patch('__builtin__.open')
def test_interface_mapping(self, mock_config):
m = MagicMock(spec=file)
handle = m.return_value.__enter__.return_value
handle.__iter__.return_value = ('aa', 'bb')
我的问题是如何做到这一点,当一个类中打开同一呼叫两个不同的文件。在我的情况下,类__init__()
预加载文件到两个地图。这个类用于其他类。我想嘲笑这两个文件的加载,以提供我的测试数据,以便使用IfAddrConfig对象的其他类可以针对预先加载的测试文件内容进行测试。
下面是我正在努力加载两个文件在__init__()
,我都想模拟加载我的测试注入文件内容的类的示例。 getInterfaceMap()是经常调用的函数,所以我不希望每次调用都要加载和解析这些文件,因此一次预加载__init__()
中的地图的原因。
class IfAddrConfig(object):
def __init__(self):
# Initialize the static maps once since they require file operations
# that we do not want to be calling every time getInterfaceMap() is used
self.settings_map = self.loadSettings()
self.config_map = self.loadConfig()
def loadConfig(self):
config_map = defaultdict(dict)
with open(os.path.join('some_path.cfg'), 'r') as stream:
for line in stream:
# Parse line and build up config_map entries
return config_map
def loadSettings(self):
settings_map = {}
with open('another_path.cfg', 'r') as stream:
for line in stream:
# Parse line and build up settings_map entries
return settings_map
def getInterfaceMap(self, interface):
# Uses both the settings and config maps to finally create a composite map
# that is returned to called
interface_map = {}
for values in self.config_map.values():
# Accesss self.settings_map and combine/compare entries with
# self.config_map values to build new composite mappings that
# depend on supplied interface value
return interface_map
谢谢!这个答案是正确的,并有帮助。 – chromeeagle 2014-11-10 15:01:41
@Mark如果有用,请不要忘记+1 :) – 2014-11-10 15:23:47
谢谢!我的问题是不同的 - 我怎么嘲笑'打开(文件名)为f:为f中的行:...' - 你的答案帮助我这样做。不幸的是'mock_open'对迭代没有任何帮助。 – 2014-12-04 09:53:08