→ lycantrope: 有mock_open可以用 01/18 17:57
→ 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
→ 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
推 lycantrope: lambda 改成 *arg, **kwargs 但這樣寫只是邪門歪道 01/20 20:24
→ lycantrope: 拆成多個function來測才是正途吧.. 01/20 20:24
→ s860134: 問個蠢問題, 為何不用sample file? 02/01 01:46