我有一个python函数,该函数基本上从用户输入的目录中上传文件。我想为此编写一个测试,但是找不到使用单元测试的方法。你能帮我这个忙吗?
我的功能是:
def scene_upload(self):
filename_scene = filedialog.askopenfilename(initialdir="/", title="Select file")
print(filename_scene)
with open(filename_scene, newline='') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',', quotechar='|')
line_count = 0
for row in csv_reader:
if line_count == 0:
line_count += 1
else:
self.time_stamp.append(int(row[0]))
self.active_func.append(int(row[1]))
self.active_func_output.append(row[2])
self.dstream_func.append(int(row[3]))
self.dstream_func_aspect.append(row[4])
self.time_tolerance.append(row[5])
line_count += 1
答案 0 :(得分:0)
从重写方法开始,以一个可迭代的作为参数:
def scene_upload(self, scene):
csv_reader = csv.reader(scene, delimiter=',', quotechar='|')
next(csv_reader) # Skip the header
for line_count, row in enumerate(csv_reader, 1):
self.time_stamp.append(int(row[0]))
self.active_func.append(int(row[1]))
self.active_func_output.append(row[2])
self.dstream_func.append(int(row[3]))
self.dstream_func_aspect.append(row[4])
self.time_tolerance.append(row[5])
在生产环境中,使调用者负责打开文件:
filename_scene = filedialog.askopenfilename(initialdir="/", title="Select file")
print(filename_scene)
with open(filename_scene, newline='') as csv_file:
x.scene_upload(csv_file)
不过,在测试中,您可以传递一个简单的字符串列表作为测试数据。
def test_upload(self):
test_data = ["header", "1,2,foo,4,bar,baz"]
x = MyClass()
x.scene_upload(test_data)
self.assertEqual(x.time_stamp, [1])
self.assertEqual(x.active_func, [2])
# etc