【发布时间】:2021-11-10 21:56:09
【问题描述】:
我有一个函数,它接受 3 个文件并返回一个包含文件数据的元组。 例如:
第一个文件:
SVF2018-05-24_12:02:58.917
NHR2018-05-24_12:02:49.914
第二个文件:
SVF2018-05-24_1:04:11.332
NHR2018-05-24_1:04:02.979
第三个文件:
SVF_塞巴斯蒂安维特尔_法拉利
NHR_Nico Hulkenberg_RENAULT
我得到这样的结果:
result = (
[('SVF', '2018-05-24_12:02:58.917'), ('NHR', '2018-05-24_12:02:49.914')],
[('SVF', '2018-05-24_1:04:11.332'), ('NHR', '2018-05-24_1:04:02.979')],
[['SVF', 'Sebastian Vettel', 'FERRARI'], ['NHR', 'Nico Hulkenberg', 'RENAULT']]
)
函数本身如下所示:
def read_files(start_log, end_log, abbr) -> tuple:
"""
Takes two .log files - start and end, and a file containing abbreviation explanations.
Processes the data from the files and returns a tuple of lists containing lines for each file.
"""
for argument in [start_log, end_log, abbr]:
if not os.path.isfile(argument):
raise FileNotFoundError('Attribute must be a file.')
with open(argument, 'r') as f:
if argument == abbr:
abbr_lines = [line.strip().split('_') for line in f]
elif argument == start_log:
start_lines = [(line[:3], line.strip()[3:]) for line in f]
start_lines.pop()
else:
end_lines = [(line[:3], line.strip()[3:]) for line in f]
return start_lines, end_lines, abbr_lines
我需要为它写一个测试。
我发现错误没有问题:
class ReadFilesTestCase(unittest.TestCase):
def test_file_not_found_error(self):
with self.assertRaises(FileNotFoundError):
read_files('a.txt', 'b.txt', 'c.txt')
但我真的很难将多个文件模拟为函数的参数。
我一直在尝试这样做:
class ReadFilesTestCase(unittest.TestCase):
def setUp(self):
self.file_1 = mock.patch("builtins.open", mock.mock_open(read_data=self.file_1_data))
self.file_2 = mock.patch("builtins.open", mock.mock_open(read_data=self.file_1_data))
self.file_3 = mock.patch("builtins.open", mock.mock_open(read_data=self.file_1_data))
def test_read_files:
self.assertEqual(read_files(self.file_1, self.file_2, self.file_3), self.result)
但我遇到了 FileNotFoundError。我也试过@mock.patch.multiple - 效果不佳。
我想知道是否可以模拟文件,所以我只是这样写:
self.assertEqual(read_files(fake_file_1, fake_file_2, fake_file_3), self.result)
我应该使用什么技术?我很感激任何建议。
【问题讨论】:
标签: python unit-testing mocking