gpt4 book ai didi

python - 在单元测试中模拟 open(file_name)

转载 作者:IT老高 更新时间:2023-10-28 20:24:48 24 4
gpt4 key购买 nike

我有一个打开 csv 文件并设置标题的源代码值(value)关联。源码如下:

def ParseCsvFile(source): 
"""Parse the csv file.
Args:
source: file to be parsed

Returns: the list of dictionary entities; each dictionary contains
attribute to value mapping or its equivalent.
"""
global rack_file
rack_type_file = None
try:
rack_file = source
rack_type_file = open(rack_file) # Need to mock this line.
headers = rack_type_file.readline().split(',')
length = len(headers)
reader = csv.reader(rack_type_file, delimiter=',')
attributes_list=[] # list of dictionaries.
for line in reader:
# More process to happeng. Converting the rack name to sequence.
attributes_list.append(dict((headers[i],
line[i]) for i in range(length)))
return attributes_list
except IOError, (errno, strerror):
logging.error("I/O error(%s): %s" % (errno, strerror))
except IndexError, (errno, strerror):
logging.error('Index Error(%s), %s' %(errno, strerror))
finally:
rack_type_file.close()

我试图模拟以下语句

rack_type_file = open(rack_file) 

如何模拟 open(...) 函数?

最佳答案

这无疑是一个老问题,因此有些答案已经过时了。

在当前版本的 mock 库中专门为此目的设计了一个便利函数。以下是它的工作原理:

>>> from mock import mock_open
>>> m = mock_open()
>>> with patch('__main__.open', m, create=True):
... with open('foo', 'w') as h:
... h.write('some stuff')
...
>>> m.mock_calls
[call('foo', 'w'),
call().__enter__(),
call().write('some stuff'),
call().__exit__(None, None, None)]
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')

文档是 here .

关于python - 在单元测试中模拟 open(file_name),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5237693/

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