I have a python program of about 500 lines that writes to stdout (using print statements). Now I'd like to make some changes and do refactoring of the program, but I want to make sure that in the process of doing so I keep getting the same output (given the same input, of course).
What would be a good strategy to do so, without rewriting the functions to return strings (allowing for easier testing) instead of the current print
-ing?
I though of redirecting the initial output (before I start changing it) to a text file. How can I then easily and automatically check the output of the modified program with the textfile (without redirecting that output again to a temporary text file and comparing the files)?
Edit: This is the solution I settled on:
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))
Edit 2: Actually, I think the doctest
solution which I provided as an answer below is much nicer.