如何测试写入文件的Python函数
我有一个Python函数,它将列表作为参数并将其写入文件:如何测试写入文件的Python函数,python,unit-testing,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 ? 调用write_
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 ?
调用
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.
如果您不想将测试用例写入实际的文件系统,请使用类似的方法。第一种解决方案:重写您的函数以接受类似对象的可写文件。然后可以传递一个StringIO,并在调用后测试StringIO的值 第二种解决方案:使用一些模拟库,让您可以修补内置程序