pythonseleniumautomationcommandargument

How do I insert a command argument into a string?


I'm trying to figure out how to send a command line argument into a string, and I keep getting an error.

Here is my python code with the command argument

import sys
class LoginTest(unittest.TestCase):
    def setUp(self):
        buildURL = sys.argv[1]
        self.driver = webdriver.Chrome()
        self.driver.get("https://" + buildURL + "test.com")

Here is the command line argument I send.

python test.py build190 

And lastly the error I keep getting.

AttributeError: 'module' object has no attribute 'build190'

The full error message I receive

Traceback (most recent call last):
  File "Test.py", line 60, in <module>
    unittest.main()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 94, in __init__
    self.parseArgs(argv)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 149, in parseArgs
    self.createTests()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/main.py", line 158, in createTests
    self.module)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: 'module' object has no attribute 'build190'

Solution

  • You are trying to run unittest and how it loads is interfering with your intention to pass argument to a script.

    Before we go further, unit tests should run as standalone and passing parameters to them is not a best practice. Here you can read reasons why not to do it.

    Anyway, try this snippet. It should work.

    import sys
    import unittest
    
    class LoginTest(unittest.TestCase):
        buildURL = ""
    
        def setUp(self):
            self.driver = webdriver.Chrome()
            self.driver.get("https://" + buildURL + "test.com")
    
    if __name__ == "__main__":
        LoginTest.buildURL = sys.argv[1]
        unittest.main()
    

    If you decide to go this path (passing parameter to a unit test), you should add some checking if there is any argument at all, and if you want to run with buildURL that is not set.