2014-08-28 21 views
0

使用我知道這個問題已經被問過,但我有一個特別的問題,這意味着我要mock_open實際上返回一個特定的模擬對象時功能。模擬內置的「開放」在contextlib

我有一個函數我想測試:

def foo(src,dest): 
    with contextlib.nested(
     open(src,'r'), 
     open(dest,'w')) as (src,dest): 
     d = src.read(1) 
     .... 

我的問題是,使用mock_open(),我怎麼得到它返回一個特定的src和dest模擬,這樣我就可以對它們作出斷言,即使我用mock_open(模擬? = mock_src),它還是沒有通過我想要的對象,而是一個新的。

回答

1

你想那是什麼嘲弄open返回不同的模擬對象兩個呼叫:您可以使用side_effect獲得這種行爲,但你需要一個小竅門,以創建有效的嘲笑文件處理程序

m = msrc = mock_open() #That create a handle for the first file 
mdst = mock_open() #That create a handle for the second file 
m.side_effect=[msrc.return_value,mdst.return_value] # Mix the two handles in one of mock the we will use to patch open 
with patch("builtins.open", m): 
    with open("src",'r') as src , open("dest",'w') as dest: 
     print(src) #Two different mock file! 
     print(dest) 

我寫的代碼蟒蛇3,但應該是簡單的翻譯它爲較舊的蟒蛇(我指出,你使用嵌套)。

我已經給出答案了非常類似的問題,但這種解決辦法是好多了!只爲備案Python mock builtin 'open' in a class using two different files