各位高人好,本人碰到一个很难解的问题
我在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
不知怎么进行下一步,先感谢各位愿意看完。