我無法弄清楚當他們都使用上下文管理器時,如何模擬兩個文件在類中打開。我知道如何使用模擬模塊,這樣做的一個上下文管理文件: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