Skip to main content
 首页 » 编程设计

python之py.test conftest之根据 sys.argv 修改 fixture 参数

2025年05月04日13lyhabc

我有一个用于 Selenium 测试的 pytest 工作环境。我在 conftest.py 中使用了一个参数化的 fixture ,它允许我测试所有不同的浏览器而无需重写测试。我想将命令行参数传递给我的脚本,这样我就可以让它只运行特定的浏览器,而不是所有浏览器。为此,我需要修改传递到我的 fixture 中的变量。到目前为止,我还没弄清楚该怎么做。我下面的示例不起作用,可能是因为 pytest 将 conftest.py 与我的启动脚本描述的变量分开解析。

#conftest.py 
browsers = { "ff" : webdriver.Firefox, "ie" : webdriver.Ie } 
@pytest.yield_fixture(params=browsers.keys()) 
def browser(request): 
    driver = browsers[request.param]() 
    yield driver 
    driver.quit() 
 
#test_simple.py 
def test_simple(browser): 
    browser.get("http://stackoverflow.com") 
 
#main.py 
browsers = {} 
if __name__ == "__main__": 
    if len(sys.argv) > 1: 
        for arg in sys.argv[1:]: 
            if arg == "-ff": 
                browsers = { "ff" : webdriver.Firefox } 
            elif arg == "-ie": 
                browsers = { "ie" : webdriver.Ie } 
            elif arg == "-all": 
                browsers = { "ff" : webdriver.Firefox, "ie" : webdriver.Ie } 
 
    pytest.main() 

如何将值传递给 conftest.py 中的参数化 fixture ?


请您参考如下方法:

参见:Pass different values to a test function, depending on command line options .

您实际上无法使用命令行选项更改参数化,因为参数化定义发生在导入期间,但如果用户在命令行中指定一个,您可以轻松跳过对其他浏览器的测试:

# conftest.py 
import pytest 
 
browsers = {"ff": 'FIREFOX', 'ie': 'INTERNETEXPLORER'} 
 
def pytest_addoption(parser): 
    parser.addoption("--browser", default='', 
        type='choice', choices=sorted(browsers), 
        help="runs tests only for given browser")     
 
@pytest.yield_fixture(params=browsers.keys()) 
def browser(request): 
    selected = request.config.getoption('browser') 
    if selected and selected != request.param: 
        pytest.skip('browser {} selected in the command line'.format(selected)) 
    driver = browsers[request.param] 
    yield driver 

有了这个,当用户运行 pytest 而不向 --browser 传递任何值时,所有测试都会照常运行:

============================= test session starts ============================= 
platform win32 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.7.0.dev1 -- X:\temp\sandbox\.env27\Scripts\python.exe 
plugins: xdist 
collecting ... collected 2 items 
 
test_simple.py::test_simple[ie] PASSED 
test_simple.py::test_simple[ff] PASSED 
 
========================== 2 passed in 0.01 seconds =========================== 

但是如果用户通过 --browser=ie,则跳过 firefox 测试:

============================= test session starts ============================= 
platform win32 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.7.0.dev1 -- X:\temp\sandbox\.env27\Scripts\python.exe 
plugins: xdist 
collecting ... collected 2 items 
 
test_simple.py::test_simple[ie] PASSED 
test_simple.py::test_simple[ff] SKIPPED 
 
===================== 1 passed, 1 skipped in 0.01 seconds =====================