【发布时间】:2019-05-21 10:31:05
【问题描述】:
我有一个 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
【问题讨论】:
-
scene_upload应该将文件名作为参数;将调用推送到askopenfilename尽可能靠近代码的“边缘”。 -
否则,你有什么问题?在对象上调用函数将更新该对象的状态,因此您只需创建一个对象,使用已知文件调用该方法,然后根据您提供的文件验证对象的状态。
-
我明白你的意思。我很困惑,因为我把对目录的请求放到了我的函数中。我将其从函数中取出,并将派生的 filename_scene 作为参数放入函数中,这很有效。非常感谢您的建议!
-
其实更好的是,取一个可以直接传给
csv.reader的参数作为参数,让调用者负责打开文件。然后你的测试用例使用简单的列表作为输入。
标签: python python-3.x unit-testing