Argparse unit tests: Suppress the help message

前端 未结 3 1796
广开言路
广开言路 2020-12-19 17:17

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

3条回答
  •  失恋的感觉
    2020-12-19 17:42

    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.

提交回复
热议问题