2015-01-14 29 views
0

我想測試一些執行日誌記錄的代碼。python mock_open斷言幾個寫入調用

logfile = open(file_name, 'w') 
logfile.write("blah1") 
logfile.write("blah2") 

我想斷言blah1和blah2都寫成了。我的測試函數如下:

def test_it(self): 
    logger.open = mock_open() 
    logger.time.time = Mock(return_value=12345) 

    logger.run_me() 

    logger.open.assert_called_once_with('test_12345.log', 'w'); 
    file_handle_mock = logger.open() 
    file_handle_mock.write.assert_called_with("blah1") 
    file_handle_mock.write.assert_called_with("blah2") 

但它給我一個錯誤:

AssertionError: Expected call: write('blah1') 
Actual call: write('blah2') 

我怎樣才能正確地測試,以寫功能的多個呼叫?

版本: 的Python 2.7.6 模擬== 1.0.1

回答

1

根據該文檔,assert_called_withassert_called_once_with如果呼叫最近的一次只有通過。竅門我們使用assert_any_callassert_has_calls

file_handle_mock.write.assert_has_calls([ 
    mock.call('blah1'), 
    mock.call('blah2'), 
]) 

它有點隱藏在文檔爲assert_any_call,所以我們真的不能責怪你失蹤了......

+0

非常感謝! – Selah

+0

沒問題。樂於幫助。 – mgilson