Search code examples
pythonpython-2.7mockingpython-mock

Mock testing try/except with print statements


I am currently writing a unit test for my Python2 script. I am having trouble writing a test case that catches both the sys.exit and the print statement to validate the exception. Any help would be appreciated.

except ParseError, e:
        if len(self.args.password) == 0:
            print('Some Message')

        print 'Login response error'
        sys.exit(1)

Solution

  • You can mock sys calls and make assertions over them.

    For example you can patch the sys.exit method in your test and then assert that it was called as follows:

    @patch('sys.exit')
    def test_whatever(exit_mock):
        // force the exception
        assert exit_mock.call_count == 1
    

    For the print statement you can mock the sys.stdout call. A very concise example can be found in the Python cookbook book so I will not copy paste it here.