[问题] 如何用unittest.mock 测试多个 with open 的结果

楼主: VivianAnn (薇薇安安)   2023-01-18 17:01:27
各位高人好,本人碰到一个很难解的问题
我在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
不知怎么进行下一步,先感谢各位愿意看完。
作者: lycantrope (阿宽)   2023-01-18 17:57:00
有mock_open可以用
楼主: VivianAnn (薇薇安安)   2023-01-19 16:03:00
我的code就有用mock_open,但试不出想要的功能
作者: lycantrope (阿宽)   2023-01-19 22:52:00
楼主: VivianAnn (薇薇安安)   2023-01-20 16:56:00
非常感谢,不过本人还有几个比较...难搞的问题
作者: lycantrope (阿宽)   2023-01-20 20:24:00
lambda 改成 *arg, **kwargs 但这样写只是邪门歪道拆成多个function来测才是正途吧..
作者: s860134 (s860134)   2023-02-01 01:46:00
问个蠢问题, 为何不用sample file?

Links booklink

Contact Us: admin [ a t ] ucptt.com