0
0
Selenium Pythontesting~5 mins

Conftest for shared fixtures in Selenium Python

Choose your learning style9 modes available
Introduction

We use conftest.py to share setup code called fixtures across many test files. This saves time and keeps tests clean.

When multiple test files need the same browser setup.
When you want to open and close a browser only once for many tests.
When you want to share login steps for different tests.
When you want to keep test code simple by moving setup outside tests.
When you want to reuse data or objects across tests.
Syntax
Selenium Python
import pytest

@pytest.fixture
def fixture_name():
    # setup code
    yield resource
    # teardown code

Fixtures are functions marked with @pytest.fixture.

Use yield to return the resource and then run cleanup after tests.

Examples
This fixture opens a Chrome browser before tests and closes it after.
Selenium Python
import pytest

@pytest.fixture
def browser():
    from selenium import webdriver
    driver = webdriver.Chrome()
    yield driver
    driver.quit()
This fixture opens Firefox once per test session, sharing it across tests.
Selenium Python
import pytest

@pytest.fixture(scope='session')
def browser():
    from selenium import webdriver
    driver = webdriver.Firefox()
    yield driver
    driver.quit()
Sample Program

This test file uses the shared browser fixture from conftest.py style setup. It opens Chrome for each test and closes it after.

Selenium Python
import pytest
from selenium import webdriver

@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_python_org_title(browser):
    browser.get('https://www.python.org')
    assert 'Python' in browser.title
OutputSuccess
Important Notes

Put conftest.py in the root test folder to share fixtures automatically.

Fixtures can have scopes: function (default), class, module, session.

Use fixtures to keep tests simple and avoid repeating setup code.

Summary

conftest.py holds shared fixtures for setup and cleanup.

Fixtures help reuse browser or data setup across tests.

Use @pytest.fixture and yield to manage resources.