Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unittest command line arguments?

I am trying to supply command line arguments to Python unittest and facing some issues. I have searched on internet and found a way to supply arguments as

unittest.main(argv=[myArg])

The issue is this works fine for single command line argument but fails for more than one arguments.

unittest.main(argv=[myArg1, myArg2, myArg3])

Above call fails with below error:

  File "/opt/python2.6.6/lib/python2.6/unittest.py", line 816, in __init__
    self.parseArgs(argv)
  File "/opt/python2.6.6/lib/python2.6/unittest.py", line 843, in parseArgs
    self.createTests()
  File "/opt/python2.6.6/lib/python2.6/unittest.py", line 849, in createTests
    self.module)
  File "/opt/python2.6.6/lib/python2.6/unittest.py", line 613, in 
    loadTestsFromNames suites = [self.loadTestsFromName(name, module) 
    for name in names]
  File "/opt/python2.6.6/lib/python2.6/unittest.py", line 584, in 
    loadTestsFromName parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'admin'

Digged more into this and found that Python unittest treats everything sent using argv as test case to be run.

Please let me know If there's still a way to supply more than one arguement to my unit test cases. I want to override some hard coded values like IP address, test case tag etc. and essentially run this test script from within main test script.

Thanks in advance.

like image 792
raj Avatar asked May 10 '11 11:05

raj


2 Answers

Why not just take out the command line arguments before running unittest.main, and then give it [sys.argv[0]] for its argv?

Something like:

if __name__ == '__main__':
   # do stuff with sys.argv
   unittest.main(argv=[sys.argv[0]])

Note that when given argv=None, unittest.main actually takes this as a signal to parse sys.argv. unittest.main requires at least one argv element to use as the program name. So avoiding None, [sys.argv[0]] is a good value to give since then it thinks it has no command-line arguments.


P.S. I just noticed your last sentence. If that's the case - don't use command-line arguments. Your "main" test script should just use unittest's APIs to load testcases for module, customizing them at its wish.

like image 167
Eli Bendersky Avatar answered Nov 16 '22 07:11

Eli Bendersky


Instead of actually sending a command in from the command line, assume that OptionParser will do its job, and seed the variables with input. If you've something like:

from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--tag", dest="tag", help="tag id")

Then try seeding tag with values as if they had come from the command line, and then pass these into your test classes __init__.

like image 4
sleepynate Avatar answered Nov 16 '22 05:11

sleepynate