在 python unittest 中模拟选择性文件写入

Mocking selective file writes in python unittest

我在 SO 上四处看了看,但没有找到我要找的东西,我很确定这已经在其他地方得到了回答。所以我的函数中有两个文件写入,如下所示:

def write_files():
    with open("a.txt", 'w') as f_h:
      f_h.write("data1")
    with open("b.txt", 'w') as f_h:
      f_h.write("data2")

我如何有选择地模拟 f_h.write() 以便一个 returns 是异常而另一个不是?我尝试设置 side_effect 但不清楚适合的位置。我试验过的测试代码是这样的:

from unittest.mock import patch, call, mock_open
import unittest

class Tester(unittest.TestCase):
    def test_analyze(self):
        with patch("builtins.open", mock_open(read_data="data")) as mf:
           # mf.side_effect = [None, Exception()] ?
           write_files()

if __name__ == '__main__':
    unittest.main()

两件事:你必须模拟上下文管理器,例如__enter__ 的结果,你必须将副作用放在模拟文件句柄的 write 方法上(例如 __enter__ 调用的结果):

class Tester(unittest.TestCase):
    def test_analyze(self):
        with patch("builtins.open", mock_open(read_data="data")) as mf:
            fh_mock = mf.return_value.__enter__.return_value
            fh_mock.write.side_effect = [None, Exception]

            with self.assertRaises(Exception):
                write_files()