I\'m writing tests for a function like next one:
def foo():
print \'hello world!\'
So when I want to test this function the code will b
Both n611x007 and Noumenon already suggested using unittest.mock, but this answer adapts Acumenus's to show how you can easily wrap unittest.TestCase methods to interact with a mocked stdout.
import io
import unittest
import unittest.mock
msg = "Hello World!"
# function we will be testing
def foo():
print(msg, end="")
# create a decorator which wraps a TestCase method and pass it a mocked
# stdout object
mock_stdout = unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
class MyTests(unittest.TestCase):
@mock_stdout
def test_foo(self, stdout):
# run the function whose output we want to test
foo()
# get its output from the mocked stdout
actual = stdout.getvalue()
expected = msg
self.assertEqual(actual, expected)