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

如何在Python3中模拟部分文件系统,python,python-3.x,mocking,python-unittest,Python,Python 3.x,Mocking,Python Unittest,我想模拟正在创建文件的文件系统调用。但我遇到了一个问题,我使用flask来创建输出,flask还需要从文件系统读取teamplate。因此,我在使用flask渲染输出时出错。 有没有一种好方法可以只模拟一个文件而不是所有文件系统调用 def func_to_test(self, data_for_html): template_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates')) a

我想模拟正在创建文件的文件系统调用。但我遇到了一个问题,我使用flask来创建输出,flask还需要从文件系统读取teamplate。因此,我在使用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


这在windows上不起作用,如果您希望它在windows上起作用,则必须使用
delete=False
创建临时文件,关闭该文件,然后在测试后删除该文件,而不是模拟
open
,您可以创建一个临时文件,而不是使用


这在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\u to\u test
使用预期值调用它们的方法。

拆分要测试的函数,以便可以单独测试每个部分:

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\u to\u test
使用预期值调用它们