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.loadTes开发者_如何学JAVAtsFromName(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.
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.
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__
.
I have similar wishes, in that i needed a way to set up fake command line arguments for a test.
I found that overriding sys.argv inside each test that i needed it for worked for me. The function argument of unittest.main()
that you describe is used for the unit test itself not the module you are wishing to test.
精彩评论