我有一个用于 Selenium 测试的工作 pytest 环境。我在 conftest.py 中使用参数化的固定装置,它允许我测试所有不同的浏览器,而无需重写测试。我想将命令行参数传递给我的脚本,以便我可以让它仅运行特定的浏览器,而不是所有浏览器。为此,我需要修改传递到我的装置中的变量。到目前为止,我还不知道如何做到这一点。我下面的示例不起作用,可能是因为 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 中的参数化装置?
最佳答案
参见: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 =====================
关于python - py.test conftest - 根据 sys.argv 修改 fixture 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707504/