0
0
Selenium Pythontesting~5 mins

Fixtures for browser setup/teardown in Selenium Python

Choose your learning style9 modes available
Introduction

Fixtures help open and close the browser automatically for each test. This keeps tests clean and avoids repeating code.

When you want to open a browser before each test and close it after.
When you want to reuse the same browser setup for many tests.
When you want to make sure the browser closes even if a test fails.
When you want to keep your test code simple and organized.
Syntax
Selenium Python
import pytest
from selenium import webdriver

@pytest.fixture
def browser():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

The @pytest.fixture decorator marks the setup function.

The yield keyword splits setup (before yield) and teardown (after yield).

Examples
This example uses Firefox instead of Chrome for the browser.
Selenium Python
import pytest
from selenium import webdriver

@pytest.fixture
def browser():
    driver = webdriver.Firefox()
    yield driver
    driver.quit()
This fixture runs once per test session, sharing the browser for all tests.
Selenium Python
import pytest
from selenium import webdriver

@pytest.fixture(scope="session")
def browser():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()
This fixture maximizes the browser window before tests run.
Selenium Python
import pytest
from selenium import webdriver

@pytest.fixture
def browser():
    driver = webdriver.Chrome()
    driver.maximize_window()
    yield driver
    driver.quit()
Sample Program

This test script uses a fixture to open and close Chrome for two tests. The first test checks the page title. The second test checks if the search box is visible.

Selenium Python
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By

@pytest.fixture
def browser():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()


def test_google_title(browser):
    browser.get("https://www.google.com")
    assert "Google" in browser.title


def test_google_search_box(browser):
    browser.get("https://www.google.com")
    search_box = browser.find_element(By.NAME, "q")
    assert search_box.is_displayed()
OutputSuccess
Important Notes

Always quit the browser in teardown to free resources.

Use fixtures to avoid repeating browser setup code in every test.

You can change the fixture scope to control how often the browser opens.

Summary

Fixtures automate browser setup and cleanup for tests.

Use yield to separate setup and teardown steps.

Fixtures keep tests simple and avoid code duplication.