1
我有兩個文件:修補進口進口文件打開與模擬
#file1.py
def_writefile():
...
fp = open('file')
fp.write('blah')
...
#file2.py
file1.writefile()
我試着修補開放不同的方式:
#test_file.py
fn = mock.mock_open()
with mock.patch('__builtin__.open', fn):
file1.writefile()
with mock.patch('file1.open', fn):
file1.writefile()
with mock.patch('file2.open', fn):
file1.writefile()
with mock.patch('__main__.open', fn, create=True):
file1.writefile()
assert(mock_file().write.called_once_with('blah'))
但他們都不工作。使用模擬從內置模塊打開內置模塊的正確方法是什麼?