gpt4 book ai didi

python - 对打印到标准输出的程序执行单元测试的好策略?

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:55 25 4
gpt4 key购买 nike

我有一个大约 500 行的 python 程序,它写入标准输出(使用打印语句)。现在我想对程序进行一些更改和重构,但我想确保在这样做的过程中我始终获得相同的输出(当然,给定相同的输入)。

这样做的好策略是什么,而不是重写函数以返回字符串(允许更容易测试)而不是当前的 print-ing?

我虽然将初始输出(在我开始更改它之前)重定向到一个文本文件。我怎样才能轻松自动地使用文本文件检查修改后的程序的输出(无需将该输出再次重定向到临时文本文件并比较文件)?

编辑:这是我确定的解决方案:

def test_something():
# using lambda because we might test function with parameters
f = lambda: thing_to_test
test_generic('expect_output.txt', f)

def test_generic(filename_expected, function_to_test):

#Run and write to tmp file
tmpfile = 'test-tmp.txt'
sys.stdout = open(tmpfile, 'w')
function_to_test()
sys.stdout = sys.__stdout__

#compare with expected output
expected = open(filename_expected).read()
result = open(tmpfile).read()
d = difflib.Differ()
diff = d.compare(expected.splitlines(), result.splitlines())

#print result (different lines only)
diff_lines_only = [line for line in diff if line[0] in "+-?"]
if not diff_lines_only:
print "Test succeeded (%s)\n" % filename_expected
os.remove(tmpfile)
else:
print "Test FAILED (%s):\n" % filename_expected
print '\n'.join(list(diff_lines))

编辑 2: 实际上,我认为我在下面作为答案提供的 doctest 解决方案要好得多。

最佳答案

您可以通过重定向 sys.stdout 获得表示程序输出的字符串。要比较输出,您可以使用 difflib模块。特别是 Differ 类的作用或多或少与 diff 命令的作用相同:

>>> import difflib
>>> text = '''bar
... baz
... '''
>>> text2 = '''foo
... bar
... '''
>>> d = difflib.Differ()
>>> for line in d.compare(text.splitlines(), text2.splitlines()):
... print line
...
+ foo
bar
- baz

如果我没记错的话,unittest2 的 assertEqual 已经尝试显示字符串的差异,但我不知道在什么级别以及输出是否足够简单。

关于python - 对打印到标准输出的程序执行单元测试的好策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13296753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com