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



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

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)

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

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使用预期值调用它们。

与其嘲笑open,不如创建一个临时文件,而不是使用临时文件写入该文件。

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

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

最新更新