作者VivianAnn (薇薇安安)
看板Python
标题[问题] 如何用unittest.mock 测试多个 with open 的结果
时间Wed Jan 18 17:01:27 2023
各位高人好,本人碰到一个很难解的问题
我在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
不知怎麽进行下一步,先感谢各位愿意看完。
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 47.187.207.248 (美国)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1674032490.A.4B7.html
1F:→ lycantrope: 有mock_open可以用 01/18 17:57
2F:→ VivianAnn: 我的code就有用mock_open,但试不出想要的功能 01/19 16:03
Update一下,我改用side_effect,with open是没有问题了,但出现了其它问题:
with self.assertRaises(SystemExit) as cm, mock.patch("builtins.open",
side_effect = [
mock.mock_open(read_data="read from f1").return_value,
mock.mock_open(read_data="read from f2").return_value
]) as mock_files:
mainFunction.main()
mock_file.return_value.__enter__().read.assert_called_once_with("read from f1")
self.assertEqual(cm.exception, 0)
AssertionError: Expect 'read' to be called once. Called 0 times
我另外尝试将file1改成用写入而非读取:
with open("path/to/file1", "w+"):
print("message for file1")
并执行
mock_files.return_value.__enter__().write.assert_called_once_with("message for f2")
依然得到类似的错误
AssertionError: Expect 'write' to be called once. Called 0 times
求解,拜托了!
※ 编辑: VivianAnn (47.187.207.248 美国), 01/19/2023 16:39:33
4F:→ VivianAnn: 非常感谢,不过本人还有几个比较...难搞的问题 01/20 16:56
lycantrope大我问一下,如果with open中有encoding的话要如何mock?
比如:
with open("path/to/file1", "w+", encoding="utf-8") as f1:
f1.write("message for file1")
我用您提供的方法会出现
TypeError: <lambda>() got an unexpected keyword argument 'encoding'
另外请问要如何用mock_files确认文字是否有写入或读取
mock_files.return_value.__enter__().write.assert_called_once_with("message for file1") 依然行不通,实在不能理解
麻烦了,谢谢
另外其实我有点好奇l大你的方法参考哪里的资料得来的,本人觉得写unit test有时容易卡关
※ 编辑: VivianAnn (47.187.207.248 美国), 01/20/2023 17:23:46
5F:推 lycantrope: lambda 改成 *arg, **kwargs 但这样写只是邪门歪道 01/20 20:24
6F:→ lycantrope: 拆成多个function来测才是正途吧.. 01/20 20:24
7F:→ s860134: 问个蠢问题, 为何不用sample file? 02/01 01:46