首页 > 解决方案 > 你如何在 python 中模拟多个文件打开和读取?

问题描述

我在 Python 中有以下类:

# lib/filesum.py
class FileSum(object):

    def __init__(self, path1, path2, path3):
        self.path1 = path1
        self.path2 = path2
        self.path3 = path3

        self.a = int(open(self.path1).read().strip())
        self.b = int(open(self.path2).read().strip())
        

    def save_sum(self):
        s = self.a + self.b
        open(self.path3, mode='w').write(str(s))
        

我想编写一个单元测试来测试该save_sum()方法。如何模拟两个调用 open 和一个为不同文件编写的调用,而不必在运行测试时在那里有实际文件?我想忽略(而不是模拟)与除了这 3 个文件之外的任何其他文件的任何交互。

编辑:

我的尝试是:

def mock_file_open(filename, mode='r'):
    if filename == "a.txt":
        content = "3"
    elif filename == 'b.txt':
        content = "2"
    else:
        # I want to leave all other file interactions alone but
        #this causes infinite resursion
        return open(filename, mode=mode)

    file_object = mock.mock_open(read_data=content).return_value
    file_object.__iter__.return_value = content
    return file_object

...

with mock.patch('builtins.open', new=mock_file_open):
   ...

标签: python-3.xunit-testingmocking

解决方案


推荐阅读