简体   繁体   English

是否可以使用 for 循环使 `pytest.fixture` 打开不同的页面以进行 Selenium 测试?

[英]Is it possible to make `pytest.fixture` open different pages for Selenium tests using for loop?

I'm trying to run tests using pytest and selenium.我正在尝试使用 pytest 和 selenium 运行测试。 I wrote @pytest.fixture , so a fresh web page would open for each test.我写了@pytest.fixture ,所以每次测试都会打开一个新的网页。 I would like to use for loop to run these tests for various pages, but when I run the code, the test is run only for the last element of pages, "men".我想使用 for 循环为各种页面运行这些测试,但是当我运行代码时,测试只针对页面的最后一个元素“men”运行。

from selenium import webdriver
import pytest
import time

pages = ["what-is-new", "women", "men"]

for page in pages:
    @pytest.fixture()
    def driver():
        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.get(f"https://magento.softwaretestingboard.com/{page}.html")
        yield driver
        driver.quit()


    # Tests

    def test_number_one(driver):
        time.sleep(5)
        pass

I wanted the test to be run for all pages defined in the list.我希望对列表中定义的所有页面运行测试。

Is there any way to run these tests for all pages defined in the list?有没有办法对列表中定义的所有页面运行这些测试?

You can parametrize the fixture .您可以参数化夹具 Something like below should work for your example:类似下面的内容应该适用于您的示例:

from selenium import webdriver
import pytest
import time

pages = ["what-is-new", "women", "men"]


@pytest.fixture(params=pages)
def driver(request):
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get(f"https://magento.softwaretestingboard.com/{request.param}.html")
    yield driver
    driver.quit()


def test_number_one(driver):
    time.sleep(5)
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM