0

I'm trying to catching an output to be tested, I'm using unittest and unittest.mock libraries. I have taken a look in many others related questions (like this: How to assert output with nosetest/unittest in python? among others) and all they suggest something like which a have in my code, but I'm getting only an empty string, and can't find where I'm mistaking.

My function do something like that:

def my_func():
  a = int(input("put a 2 digit number"))
  b = [1,2,3,4,5,6,7,8,9,0]
  if a in b:
    print("wrong number")

And this is the related test:

import io
import sys
import unittest
from unittest.mock import patch
from io import StringIO
from somemodule import my_func

def test_entering_wrong_value(self):

        user_input = ['2']

        with patch('builtins.input', side_effect=user_input):
            self.my_func()
            capturedOutput = io.StringIO()
            sys.stdout = capturedOutput
            output = capturedOutput.getvalue().strip()
            self.assertEqual('wrong number', output)

As I undestood this should capture the outputed string and compared with the test value, but can't capturing the string, I'm just getting an empty string and this error:

AssertionError: 'wrong number' != ''

Where am I messing up?

Cristianjs19
  • 765
  • 1
  • 9
  • 15

1 Answers1

1

You have to redirect stdout BEFORE you do your prints. You can't redirect after and expect to get the prints that weren't being redirected:

import io
import sys
import unittest
from unittest.mock import patch
from somemodule import my_func

def test_entering_wrong_value(self):

        user_input = ['2']

        with patch('builtins.input', side_effect=user_input):
            capturedOutput = io.StringIO()
            sys.stdout = capturedOutput
            self.my_func()
            output = capturedOutput.getvalue().strip()
            sys.stdout = sys.__stdout__ # Restore stdout so prints work normally
            self.assertEqual('wrong number', output)
  • Restoring stdout (`sys.stdout = sys.__stdout__`) causes error `AttributeError: '_io.TextIOWrapper' object has no attribute 'getvalue'` when exiting the test. Added this code into the `tearDownClass` method. – Elephant Feb 02 '23 at 13:11