[Tutor] Testing print

boB Stepp robertvstepp at gmail.com
Thu Sep 29 22:24:51 EDT 2016


Testing output of print functions (Py 3).  First off, is it worth it to do so?

Second, it seems that prints are often intermingled with the main
logic of a function and only serve to pass on a message to the user.
For example, in an earlier thread (

Questions as to how to run the same unit test multiple times on
varying input data.:
https://mail.python.org/pipermail/tutor/2016-September/109686.html) I
finally wound up with this function:


def right_justify(a_string):
    '''This fucntion will take the string, "a_string", and right justify it by
    padding it with spaces until its last character falls in column 70 of the
    display.  The padded string will be returned.'''

    if len(a_string) <= 70:
        num_pad_spcs = 70 - len(a_string)
        return (' ' * num_pad_spcs) + a_string
    else:
        print("The string has too many characters (> 70)!")
        print("Only a partial, 70 character line will be returned.")
        return a_string[:70]


I had to consider the possibility that the string supplied to the
function was more than 70 characters long.  The exercise in "Think
Python2" did not give any input into how to handle such a case, so I
decided I would return 70 characters worth of the overly long string
and print a message to the user.  So (Even though this is a simple
exercise.) should I test the prints?  And if so, how to I separate
this out?  In my mind, if I am going to be testing calls to print,
then perhaps I should write a separate function, say "print_msg(msg)"
and put that in place of the prints in the else clause and then test
the print_msg function, where "print(msg)" would be isolated in its
own little function to be tested..

Anyway, it would seem that the only way to capture the output of a
print is to redirect the stdout to something I can capture and compare
against.  Googling brings up some people doing something with mock
objects, some redirecting to a string buffer, some to a file, some to
other things.  What, in your opinion(s), is the cleanest way to handle
this?

-- 
boB


More information about the Tutor mailing list