Search code examples
pythontestingwebdriverpytestfixtures

pytest, initialize webdriver for each test file with teardown quit


Current part of code in the test module:

def test_01():
    driver.get('https://www.google.com')

Conftest code:

import pytest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait


@pytest.fixture(autouse=True)
def browser():
    driver = webdriver.Chrome(executable_path=r"C:\webdrivers\1\chromedriver.exe")
    driver.implicitly_wait(5)
    wait = WebDriverWait(driver, 10)
    driver.maximize_window()
    yield
    driver.quit()

Result: "E NameError: name 'driver' is not defined"

Target result: initialize webdriver without class, setup webdriver as driver into each test function, run function with it and quit with fixtures postcondition from conftest. I have a lot of test files and thats why I should to do it once.

I've also tried return variable from fixture, but as I understood the test function still need to have variable for fixture and it looks wrong as for me. For example: fixture - return x, testfunction(fixture): x = fixture. And it still not works with webdriver\driver (or rather I didn’t figure it out).


Solution

  • Your test function needs to take the fixture as an argument, that's the first part of the problem.

    For instance:

    def test_01(driver):
        driver.get('https://www.google.com')
    

    But you don't have a driver fixture yet, just one called browser, so you'll need to change the name of the fixture:

    @pytest.fixture(autouse=True)
    def driver(request):
       ...
    

    Finally, the fixture needs to return the driver, so that you can use it.

    @pytest.fixture(autouse=True)
    def driver(request):
        ...
        yield driver
        ...