如何测试写入文件的Python函数

时间:2013-12-09 13:54:44

标签: python unit-testing

我有一个Python函数,它将列表作为参数并将其写入文件:

def write_file(a):
    try:
        f = open('testfile', 'w')
        for i in a:
            f.write(str(i))

    finally:
        f.close()

如何测试此功能?

def test_write_file(self):
    a = [1,2,3]
    #what next ?

2 个答案:

答案 0 :(得分:5)

调用write_file函数并检查是否使用预期内容创建testfile

def test_write_file(self):
    a = [1,2,3]
    write_file(a)
    with open('testfile') as f:
        assert f.read() == '123' # Replace this line with the method
                                 #   provided by your testing framework.

如果您不希望将测试用例写入实际文件系统,请使用mock.mock_open

之类的内容

答案 1 :(得分:0)

第一个解决方案:重写您的函数以接受可写的类文件对象。然后,您可以改为传递StringIO并在调用后测试StringIO的值。

第二个解决方案:使用一些模拟库,可以修补内置函数。