gpt4 book ai didi

Python测试: using a fake file with mock & io. StringIO

转载 作者:行者123 更新时间:2023-12-02 03:49:47 26 4
gpt4 key购买 nike

我正在尝试测试一些对文件进行操作的代码,但我似乎无法理解如何使用 mockio 替换真实文件。字符串IO我的代码大致如下:

class CheckConfig(object):
def __init__(self, config):
self.config = self._check_input_data(config)

def _check_input_data(self, data):
if isinstance(data, list):
return self._parse(data)
elif os.path.isfile(data):
with open(data) as f:
return self._parse(f.readlines())

def _parse(self, data):
return data

我有一个类可以接受列表或文件,如果它是文件,它会打开它并将内容提取到列表中,然后对结果列表执行需要执行的操作。

我有一个工作测试如下:

def test_CheckConfig_with_file():
config = 'config.txt'
expected = parsed_file_data
actual = CheckConfig(config).config
assert expected == actual

我想替换对文件系统的调用。我尝试用 io.StringIO 替换该文件,但从 os.path.isfile() 收到一个 TypeError,因为它需要一个字符串、字节或整数。我还尝试像这样模拟 isfile 方法:

@mock.patch('mymodule.os.path')
def test_CheckConfig_with_file(mock_path):
mock_path.isfile.return_value = True
config = io.StringIO('data')
expected = parsed_file_data
actual = CheckConfig(config).config
assert expected == actual

但我仍然得到相同的 TypeError ,因为 _io.StringIO 类型在 isfile 有机会返回某些内容之前导致异常。

当我传递一个假文件时,如何让 os.path.isfile 返回 True?或者这是我应该更改代码的建议?

最佳答案

只需模拟 os.path.isfile open()调用,并传入一个假文件名(毕竟,您不应该传入一个打开的文件)。

模拟库包含后者的实用程序: mock_open() :

@mock.patch('os.path.isfile')
def test_CheckConfig_with_file(mock_isfile):
mock_isfile.return_value = True
config_data = mock.mock_open(read_data='data')
with mock.patch('mymodule.open', config_data) as mock_open:
expected = parsed_file_data
actual = CheckConfig('mocked/filename').config
assert expected == actual

这会导致 if isinstance(data, list):测试为 false(因为 data 是一个字符串),后跟 elif os.path.isfile(data):返回True ,以及open(data)调用以使用 mock_open() 中的模拟数据结果。

您可以使用mock_open变量来断言 open()使用正确的数据调用(例如 mock_open. assert_called_once_with('mocked/filename'))。

演示:

>>> import os.path
>>> from unittest import mock
>>> class CheckConfig(object):
... def __init__(self, config):
... self.config = self._check_input_data(config)
... def _check_input_data(self, data):
... if isinstance(data, list):
... return self._parse(data)
... elif os.path.isfile(data):
... with open(data) as f:
... return self._parse(f.readlines())
... def _parse(self, data):
... return data
...
>>> with mock.patch('os.path.isfile') as mock_isfile:
... mock_isfile.return_value = True
... config_data = mock.mock_open(read_data='line1\nline2\n')
... with mock.patch('__main__.open', config_data) as mock_open:
... actual = CheckConfig('mocked/filename').config
...
>>> actual
['line1\n', 'line2\n']
>>> mock_open.mock_calls
[call('mocked/filename'),
call().__enter__(),
call().readlines(),
call().__exit__(None, None, None)]

关于Python测试: using a fake file with mock & io. StringIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com