如何在 Python3 中模拟文件系统部分

How to mock filesystem partial in Python3

我想模拟一个正在创建文件的文件系统调用。但我遇到了问题,我正在使用 flask 来创建输出,而 flask 还需要从文件系统读取模板。所以我 运行 在用 flask 渲染输出时出错了。 有没有一种只模拟一个文件而不是所有文件系统调用的好方法?

def func_to_test(self, data_for_html):
    template_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates'))
    app = flask.Flask('my app', template_folder=template_dir)
    with app.app_context():
        rendered = render_template('index.html', data=data_for_html)
    with open(self.fileName, **self.options_file) as html_file:
        html_file.write(rendered)

def test_func(self, data):
     fake_file_path = "fake/file/path/filename"
     m = mock_open()
     with patch('builtins.open', mock_open()) as m:
        data_writer = FlaskObject(fileName=fake_file_path)
        data_writer.write(data)

而不是模拟 open 你可以创建一个你写入的临时文件而不是使用 tempfile.

def test_func(self, data):
    with tempfile.NamedTemporaryFile() as f:
       data_writer = FlaskObject(fileName=f.name)
       data_writer.write(data)

这在 windows 上不起作用,如果您希望它在 windows 上起作用,您必须使用 delete=False 创建临时文件,关闭文件然后删除测试后的文件

拆分要测试的功能,以便您可以单独测试每个部分:

def _generate_content(self, data):
    template_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates'))
    app = flask.Flask('my app', template_folder=template_dir)
    with app.app_context():
        return render_template('index.html', data=data_for_html)

def _write_content(self, content):
    with open(self.fileName, **self.options_file) as html_file:
        html_file.write(content)



def func_to_test(self, data_for_html):
    rendered = self._generate_content(data_for_html)
    self._write_content(rendered)

然后您可以模拟这两个方法并测试 func_to_test 是否使用预期值调用它们。