I\'m writing test cases for argparse implementation. I intend to test \'-h\' feature. The following code does it. But it also outputs the usage for the script. Is there a wa
Mock could do this, allowing you the same functionality as Martijn Pieters' answer but without having to write your own function:
from unittest.mock import MagicMock, patch
argparse_mock = MagicMock()
with patch('argparse.ArgumentParser._print_message', argparse_mock):
with self.assertRaises(SystemExit) as cm:
arg_parse_obj.parse_known_args(['-h'])
patch also works as a decorator. If you have several instances where the argparse printing needs to be suppressed, you can do it as a decorator and avoid using a bunch of nested with statements.