I need to run Selenium tests with the pytest as a runner.
So, I need to create webdriver as a fixture, but also I need to create some test preconditions (setup and teardown).
Its easy to define webdriver in the setup method.
But I need to have more than 100+ different preconditions (setup) and I think, its a bad practice to copy-paste driver setup in each of them.
And I need to have same webdriver accessible from the setup and test_ methods.
What I have now is:
#conftest.py
def pytest_addoption(parser):
parser.addoption("--browser")
@pytest.fixture(scope='session')
def browser(request):
return request.config.getoption("--browser")
@pytest.fixture(scope='session')
def driver(browser):
if browser == 'firefox':
web_driver = webdriver.Firefox()
elif browser == 'edge':
web_driver = webdriver.Edge() # dk:needs to be added the path
else:
options = Options()
options.add_argument(arguments)
web_driver = webdriver.Chrome(chrome_options=options)
web_driver = browser
yield web_driver
web_driver.quit()
#test_case.py
@pytest.fixture
@pytest.mark.usefixtures("driver")
def resource_module_1(driver):
print('setup')
driver.get(some_link)
driver.click(some_button)
yield
print("teardown")
@pytest.mark.usefixtures("resource_module_1")
class TestOne:
def test_one(self):
# I need to have driver there for UI tests
print('test_1')
def test_two(self):
print('test_2')
But I do not have access to the driver in the test methods. Also this code looks bad.