如何通过命令行将 url 作为参数传递给 运行 selenium python 测试用例

How to pass an url as argument through commandline to run selenium python test cases

有什么正确的方法可以在 cmd 中使用获取 url 作为 testcases.py 文件的参数吗?

我正在 运行 在 cmd 中向 python 文件的 运行 测试用例下命令: testcases.py"any url"

testcases.py有编码:

class JSAlertCheck(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome("E:\chromedriver.exe")
        self.url = sys.argv[1]

    def test_Case1(self):
        driver = self.driver

    def tearDown(self):
           self.driver.quit()

if __name__ == "__main__":
    unittest.main(sys.argv[1])

根据 Python unittest passing arguments 的讨论,Python 专家 似乎表达了:

Unit tests should be stand-alone which will have no dependencies outside of their setUp() and tearDown() methods. This is to make sure that each tests has minimal side-effects and reactions to the other test. Passing in a parameter defeats this property of unittest and thus makes them sort of invalid. Using a Test Configuration would have been the easiest way and more appropiate as a unittest should never rely on foreign data to perform the test.

如果您仍想这样做,这里是一种可行的解决方案:

  • 代码块:

    from selenium import webdriver
    import unittest
    import sys
    
    
    class MyTest(unittest.TestCase):
    
        URL = "foo"
    
        def setUp(self):
            self.driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
            driver = self.driver
            driver.get(self.URL)
    
        def test_Case1(self):
            driver = self.driver
            print(driver.title)
    
        def tearDown(self):
            self.driver.quit()
    
    if __name__ == "__main__":
        if len(sys.argv) > 1:
            MyTest.URL = sys.argv.pop()
        unittest.main()
    
  • CLI 命令:

    python unittest_cmdline_urlASarguments.py http://www.python.org
    
  • 输出:

    C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>python unittest_cmdline_urlASarguments.py http://www.python.org
    [4448:5632:0606/205445.017:ERROR:install_util.cc(589)] Unable to create registry key HKLM\SOFTWARE\Policies\Google\Chrome for reading result=2
    
    DevTools listening on ws://127.0.0.1:5634/devtools/browser/40cc6c16-1e52-4f49-a54f-08fac3ff7abc
    Welcome to Python.org
    .
    ----------------------------------------------------------------------
    Ran 1 test in 9.534s
    
    OK
    
    C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>
    
  • 命令行快照: