Setting command line arguments for main function tests

后端 未结 3 1739
我在风中等你
我在风中等你 2021-01-12 04:51

I have a main() function in python that gets command line arguments. Is there a way for me to write pytest tests for this function and define the arguments in the code?

3条回答
  •  暖寄归人
    2021-01-12 05:28

    parse_args takes a argv parameter. The docs uses this repeatedly in it's examples

    parser = argparse.ArgumentParser()
    parser.add_argument('--foo', action='store_true')
    parser.add_argument('bar')
    parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
    

    where the string list replicates sys.argv[1:] that it would get from the commandline. If the argument is None (or omitted) the parser uses sys.argv[1:].

    So if

    def main(argv=None):
        # argparse code
        args, other = arg_parser.parse_known_args(argv)
        return args.first_arg
    

    You could test with

    main(['foo', '-f','v'])
    

    The unittesting file for argparse.py uses both this approach, and your's of modifying sys.argv directly.

    https://docs.python.org/3/library/argparse.html#beyond-sys-argv

    https://docs.python.org/3/library/argparse.html#partial-parsing

提交回复
热议问题