import unittest from unittest.mock import patch from io import StringIO # Import our program import hello_world as hw class TestHelloClass(unittest.TestCase): @patch('sys.stdout', new_callable = StringIO) def test_main(self, stdout): # Test main() hw.main() extected_out = 'main() is called\n' # Check stdout self.assertEqual(stdout.getvalue(), extected_out) # The order of decorator is important! @patch('sys.stdout', new_callable = StringIO) @patch('sys.stderr', new_callable = StringIO) def test_constructor(self, stderr, stdout): # Test empty string passed to HelloClass contructor hc = hw.HelloClass('') hc.hello() # Expect a warning message to stderr expected_err = 'Warning: empty string!\n' # Expect an empty string used as name expected_out = 'Hi, \n' # Check stdout and stderr self.assertEqual(stdout.getvalue(), expected_out) self.assertEqual(stderr.getvalue(), expected_err) # Note that no argument is passed to function after patching sys.stdin @patch('sys.stdin', StringIO('Bob\n')) @patch('sys.stdout', new_callable = StringIO) def test_change_name(self, stdout): # Initial class hc = hw.HelloClass('John') hc.hello() # Hi, John hc.update_name() hc.hello() # Hi, Bob expected_out = """Hi, John Your new name: You have changed your name! Hi, Bob """ self.assertEqual(stdout.getvalue(), expected_out) if __name__ == '__main__': unittest.main()