[問題] 如何用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