When testing for exception codes, use self.assertRaises() as the context manager ; this gives you access to the .code exception, allowing you to test the .code attribute:
with self.assertRaises(SystemExit) as cm: arg_parse_obj.parse_known_args(['-h']) self.assertEqual(cm.exception.code, 0)
To "suppress" or test the output, you will need to capture either sys.stdout or sys.stderr , depending on the output of argparse (help text goes to stdout ). You can use the context manager for this:
from contextlib import contextmanager from StringIO import StringIO @contextmanager def capture_sys_output(): capture_out, capture_err = StringIO(), StringIO() current_out, current_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = capture_out, capture_err yield capture_out, capture_err finally: sys.stdout, sys.stderr = current_out, current_err
and use them like:
with self.assertRaises(SystemExit) as cm: with capture_sys_output() as (stdout, stderr): arg_parse_obj.parse_known_args(['-h']) self.assertEqual(cm.exception.code, 0) self.assertEqual(stderr.getvalue(), '') self.assertEqual(stdout.getvalue(), 'Some help value printed')
Context managers are nested here, but in Python 2.7 and later you can also combine them into one line; however, this may result in exceeding the recommended limit of 79 characters.
Martijn Pieters Sep 06 '13 at 7:14 2013-09-06 07:14
source share