测试断言失败

时间:2018-07-01 22:35:12

标签: python file-handling

我写了一个函数,可以将字典作为字符串导出到csv文件中。 在我的作业中,我被指示将这个字典导出为一个字符串(我从字典中取出键,并用逗号分隔它们-不能有空格)。我有一个测试此功能的文件-我在这里,所以它当然会失败。但是,当我打印该函数的输出时,它看起来像我的任务,例如sth1,sth2,sth3,sth4。我在这里想念的是什么? 这是我的代码:

def export_stock(stock, filename="export.csv"):

with open(filename, "w+") as exportation:
    a = list(stock.keys())
    a = ",".join(a)
    exportation.write(a)

这是测试功能:

def test_export(self):
    export_stock({'sth1': 3, 'sth2': 1, "sth3": 1},
                     "export.csv")

    with open("export.csv", newline='') as csvfile:
        expected = ["sth1", "sth2", "sth3", "sth1", "sth1"]
        expected.sort()
        reader = csv.reader(csvfile, delimiter=',', quotechar='|')
        for row in reader:
            row.sort()
            self.assertListEqual(expected, row)

1 个答案:

答案 0 :(得分:0)

调用函数时,您要传入文件名test_stock_export.csv,因此它将结果导出到该文件。在测试中,打开export.csv并检查其中的结果。我认为您打算在测试中打开test_stock_export.csv

相关问题