Home > Software design >  Is it possible to make `pytest.fixture` open different pages for Selenium tests using for loop?
Is it possible to make `pytest.fixture` open different pages for Selenium tests using for loop?

Time:12-20

I'm trying to run tests using pytest and selenium. I wrote @pytest.fixture, so a fresh web page would open for each test. 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".

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?

CodePudding user response:

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
  • Related