Home > Net >  Argparse and unittest.main()
Argparse and unittest.main()

Time:09-07

I just added a graph utility to a unittest -- basically, the fully automatic version of the test just does a numerical compare, but I want a human to be able to ask for plots.

Just using argparse, unittest.main() was choking if I used my new argument. What I'm currently doing is checking for that argument, then deleting it from sys.argv which just seems wrong.

Is there a better way to skin this cat?

  • A way to tell argparse to consume arguments from sys.argv. Probably still wrong, but it's not me doing it, so it's OK.
  • A way to tell argparse to cough up version of sys.argv with all the "used arguments" taken out -- this would be cool, because it looks like unittest.main() will take an alternate argv.
  • A way to tell unittest.main() to ignore arguments.
if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Test correction'
    )
    parser.add_argument(
        '--plot-results',
        help='Plot results of cal test',
        action='store_true'
    )
    args = parser.parse_args()

    if args.plot_results:
        while '--plot-results' in sys.argv:
            sys.argv.remove('--plot-results')

    unittest.main()

CodePudding user response:

Argument.parse_known_args is basically your second option: parse the arguments you define, and get back the ones you don't recognize to pass on to unittest.main.

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Test correction'
    )
    parser.add_argument(
        '--plot-results',
        help='Plot results of cal test',
        action='store_true'
    )
    args, remaining = parser.parse_known_args()

    # Restore the script name which parse_known_args() also stripped.
    remaining.insert(0, sys.argv[0])
    unittest.main(argv=remaining)

Probably goes without saying, but don't add any arguments to parser that conflict with the parsers used by unittest itself. These are (mostly?) documented here.

  • Related