Automate browser setup and teardown using fixtures
Preconditions (4)
✅ Expected Result: The browser opens, navigates to the page, verifies the title, and closes cleanly after the test
import pytest from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options @pytest.fixture def browser(): options = Options() options.add_argument('--headless=new') # Run headless for faster tests service = Service() # Assumes chromedriver is in PATH driver = webdriver.Chrome(service=service, options=options) yield driver driver.quit() def test_example_domain_title(browser): browser.get('https://example.com') title = browser.title assert 'Example Domain' in title, f"Expected 'Example Domain' in title but got '{title}'"
The browser fixture sets up the Chrome browser before the test and closes it after the test finishes using yield. This ensures clean setup and teardown.
The test test_example_domain_title uses the fixture to open the page and then asserts the page title contains the expected text.
Running Chrome in headless mode speeds up tests and avoids opening a visible window.
This structure keeps tests clean, reusable, and avoids resource leaks by closing the browser after each test.
Modify the fixture to accept a browser name parameter to run tests on Chrome and Firefox
yield?import pytest
from selenium import webdriver
@pytest.fixture
def browser():
driver = webdriver.Chrome()
print('Setup browser')
yield driver
print('Teardown browser')
driver.quit()
def test_example(browser):
print('Running test')@pytest.fixture
def browser():
driver = webdriver.Chrome()
driver.quit()
yield driverPass the test and this pattern moves unknown