Question

I have a question about argparse. Here is part of my code:

(...)
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-g', '--gfirst', dest="a", type=int, required=True)
    args = parser.parse_args()
    print args.a #Testing
    print args.a #Testing

if __name__ == '__main__':
    main()
    print "3"
    unittest.main(verbosity=2)
    print "4"

(...)

I am trying to set 'a' as a required value to execute the test cases, because I will need this value in the future. However...

$ python regular_test.py --gfirst 2
2
2
3
option --gfirst not recognized
Usage: regular-test.py [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output
  -f, --failfast   Stop on first failure
  -c, --catch      Catch control-C and display results
  -b, --buffer     Buffer stdout and stderr during test runs

...as you can see, the program accepts the argument and prints it, but the test case itself does not execute. I've inserted some prints to show whats executing and what isnt.

What am I doing wrong? Thanks in advance

ps.: I am using python 2.7.3
ps2.:The tests were running properly (before adding argparse to the program.)

Was it helpful?

Solution

unittest.main() itself parses command-line arguments and it cannot understand/recognize your custom defined arguments (see parseArgs() method of the TestProgram class).

Instead, run tests using TextTestRunner:

runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(unittest.makeSuite(MyTestCase))

Also see related threads:

OTHER TIPS

Your problem is that the unit-tester wants to own any command-line arguments. It might make it complicated to prescribe your own arguments.

Technically, unit-tests should contain everything they need in order to run, and shouldn't depend on arguments. You might consider moving any environment-related configuration (like a DB hostname, for example) to environment variables.

My two cents.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top