Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

python - Argparse unit tests: Suppress the help message

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 way to suppress that?

self.assertRaises(SystemExit, arg_parse_obj.parse_known_args, ['-h'])

Also, can we check for the exception number thrown? For example '-h' throws SystemExit: 0, while invalid or insufficient args throw SystemExit: 2. Is there a way to check the numeric code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When testing for exception codes, use self.assertRaises() as a context manager; this gives you access to the raised exception, letting you 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'll have to capture either sys.stdout or sys.stderr, depending on the argparse output (help text goes to stdout). You could use a context manager for that:

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 these as:

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')

I nested the context managers here, but in Python 2.7 and newer you can also combine them into one line; this tends to get beyond the recommended 79 character limit in a hurry though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...