0

I want to unittest my functions by comparing the actual printed output to some expected output in a textfile. That's OK, but there is one problem: I don't want the console to display any output from the prints made in function_to_be_tested, but I still want to catch the prints so that I can compare it to the textfile. Is there a way to achieve this?

class TestClass(unittest.TestCase):


    def test_output(self):

        with open("test.txt") as txt:
            expected_output = txt.read()

        sys.stdout = std_out = StringIO()
        function_to_be_tested()
        actual_output = std_out.getvalue()

        self.assertEqual(actual_output, expected_output)

The function that needs to be tested may just look something like this:

def function_to_be_tested():
    print("Hello")
  • 1
    You could create a class to grab the outputs like in https://stackoverflow.com/questions/24277488/in-python-how-to-capture-the-stdout-from-a-c-shared-library-to-a-variable/29834357#29834357. – Matt Pitkin Aug 06 '21 at 08:51

0 Answers0