0
0
Selenium Pythontesting~15 mins

Fixtures for browser setup/teardown in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Automate browser setup and teardown using fixtures
Preconditions (4)
Step 1: Create a pytest fixture that opens a Chrome browser before each test
Step 2: Navigate to 'https://example.com' in the browser
Step 3: Verify the page title contains 'Example Domain'
Step 4: Close the browser after the test completes
✅ Expected Result: The browser opens, navigates to the page, verifies the title, and closes cleanly after the test
Automation Requirements - pytest with Selenium WebDriver
Assertions Needed:
Verify page title contains 'Example Domain'
Best Practices:
Use pytest fixtures for setup and teardown
Use explicit waits if needed
Keep test code clean and readable
Close browser in teardown to avoid resource leaks
Automated Solution
Selenium Python
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.

Common Mistakes - 3 Pitfalls
Not closing the browser after the test
Creating the browser inside the test instead of a fixture
Not using headless mode during automated tests
Bonus Challenge

Modify the fixture to accept a browser name parameter to run tests on Chrome and Firefox

Show Hint