各位高人好,本人碰到一個很難解的問題
我在mainFunction.py的main()中用with.open分別讀取file1和file2兩個檔
亦即main()當中有以下code:
with open("path/to/file1", rb) as f1:
print(f1.read())
with open("path/to/file2", rb) as f2:
print(f2.read())
sys.exit(0)
我想用mock來給予file1和file2的內容,但沒有測試成功。
但stackoverflow爬了很多文依然無解,以下為我的unit test code:
==============================================================================
from mainFunction import main
from unittest import mock
class MyUnitTest(unittest.TestCase):
def test_main(self):
mocker = mock.Mock()
mocker.side_effect = ["read from f1", "read from f2"]
with self.assertRaises(SystemExit) as cm, mock.patch('builtins.open',
mock.mock_open(read_data=mocker())) as mock_files:
mainFunction.main()
assert mock_files.call_arg_list = [mock.call("path/to/file1","rb"), mock.call("path/to/file2", "rb")]
self.assertEqual(cm.exception, 0)
==============================================================================
然而我發現
with open("path/to/file2", rb) as f2:
print(f2.read())
所讀取到的值仍舊是"read from f1", 而非"read from f2"
我也嘗試過此頁面中 Chris Collett 的做法,但沒有成功
https://tinyurl.com/dwxbd4pu
不知怎麼進行下一步,先感謝各位願意看完。