2013-12-10 29 views
2
def file_handling(): 
    temp_file = open("/root/temp.tmp", 'w') 
    temp_file.write("a") 
    temp_file.write("b") 

如何在這裏模擬'open'方法和後續的寫入語句?當我在線查看解決方案時,建議使用mock庫來使用mock_open。我如何在這裏使用這個?如何在python中模擬像'open'這樣的內置方法?

self.stubs.Set(__builtins__, "open", lambda *args: <some obj>) does not seem to work. 
+1

歡迎(因此)。你是什​​麼意思的「模擬」,你會允許自己使用什麼方法? –

+2

我認爲「模擬」在編程時相當明確且毫不含糊 - http://en.wikipedia.org/wiki/Mock_object – Tim

+0

@Tim,dm03514,Qantas 94 Heavy謝謝大家。 – chinmay

回答

1

好,使用mock庫,我想這應該工作(未測試):

import mock 
from unittest2 import TestCase 

class MyTestCase(TestCase): 
    def test_file_handling_writes_file(self): 
     mocked_open_function = mock.mock_open(): 

     with mock.patch("__builtin__.open", mocked_open_function): 
      file_handling() 

     mocked_open_function.assert_called_once_with('/root/temp.tmp', 'w') 
     handle = mocked_open_function() 
     handle.write.assert_has_calls() 
+0

謝謝你的回覆。 assert_has_calls()至少需要2個參數(給出1個) 這裏應該是mock.call值? – chinmay

相關問題