0

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)
  • Which print? How do you intend to catch an exit() call? – cs95 Jul 13 '17 at 14:27
  • I want to catch either print statement. It doesn't really matter which one. I am currently using the @raises(SystemExit) decorator included with the nose.tools package – user2769952 Jul 13 '17 at 14:28

1 Answers1

0

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.

Enrique Saez
  • 2,504
  • 16
  • 21