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

问题描述 投票:0回答:1

我在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(),以便一个返回异常,而另一个不返回?我尝试设置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()
python unit-testing mocking built-in
1个回答
0
投票

两件事:您必须模拟上下文管理器,例如__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()
© www.soinside.com 2019 - 2024. All rights reserved.