我有一个python函数,它将输出文件写入磁盘。
我想使用python unit test模块为它编写一个单元测试。
我应该如何断言文件的相等性?如果文件内容与预期的一+差异列表不同,我希望得到一个错误。在unix diff命令的输出中。
是否有任何官方/推荐的方法?
我更喜欢让输出函数显式地接受文件句柄(或类似文件的对象),而不是接受文件名并自己打开文件。这样,我可以在单元测试中将一个StringIO对象传递给输出函数,然后将该StringIO对象(在.seek(0)调用之后)的内容返回到该StringIO对象,并与预期的输出进行比较。
例如,我们将像这样转换代码
##File:lamb.py
import sys
def write_lamb(outfile_path):
with open(outfile_path, 'w') as outfile:
outfile.write("Mary had a little lamb.
")
if __name__ == '__main__':
write_lamb(sys.argv[1])
##File test_lamb.py
import unittest
import tempfile
import lamb
class LambTests(unittest.TestCase):
def test_lamb_output(self):
outfile_path = tempfile.mkstemp()[1]
try:
lamb.write_lamb(outfile_path)
contents = open(tempfile_path).read()
finally:
# NOTE: To retain the tempfile if the test fails, remove
# the try-finally clauses
os.remove(outfile_path)
self.assertEqual(result,"Mary had a little lamb.
")
这样编码
##File:lamb.py
import sys
def write_lamb(outfile):
outfile.write("Mary had a little lamb.
")
if __name__ == '__main__':
with open(sys.argv[1], 'w') as outfile:
write_lamb(outfile)
##File test_lamb.py
import unittest
from