【问题标题】:File upload testing using unit test python [closed]使用单元测试python进行文件上传测试[关闭]
【发布时间】: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


【解决方案1】:

首先重写方法以将可迭代对象作为参数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多