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.
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.Why not just take out the command line arguments before running
unittest.main
, and then give it[sys.argv[0]]
for itsargv
?Something like:
Note that when given
argv=None
,unittest.main
actually takes this as a signal to parsesys.argv
.unittest.main
requires at least oneargv
element to use as the program name. So avoidingNone
,[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:Then try seeding
tag
with values as if they had come from the command line, and then pass these into your test classes__init__
.