Bird
Raised Fist0
Selenium Pythontesting~8 mins

Fixtures for browser setup/teardown in Selenium Python - Framework Patterns

Choose your learning style10 modes available
Framework Mode - Fixtures for browser setup/teardown
Folder Structure
selenium-python-project/
├── tests/
│   ├── test_login.py
│   ├── test_search.py
│   └── conftest.py          # Fixtures for setup/teardown
├── pages/
│   ├── login_page.py
│   └── search_page.py
├── utils/
│   └── helpers.py
├── config/
│   └── config.yaml          # Environment and browser configs
├── reports/
│   └── test_report.html
├── requirements.txt
└── pytest.ini               # Pytest configuration
    
Test Framework Layers
  • Fixtures Layer:
    Located in tests/conftest.py. Contains browser setup and teardown using pytest fixtures. This layer manages browser lifecycle for tests.
  • Page Object Layer:
    Classes in pages/ folder represent web pages. They encapsulate element locators and actions.
  • Test Layer:
    Test scripts in tests/ folder use fixtures and page objects to perform test scenarios.
  • Utilities Layer:
    Helper functions and utilities in utils/ support common tasks like waits or data handling.
  • Configuration Layer:
    Configuration files in config/ hold environment variables, browser options, and credentials.
Configuration Patterns

Use a config.yaml file to store environment URLs, browser types, and credentials. Load this config in fixtures to decide which browser to launch and which environment to test.

Example snippet in conftest.py:

import pytest
import yaml
from selenium import webdriver

@pytest.fixture(scope="session")
def config():
    with open('config/config.yaml') as f:
        return yaml.safe_load(f)

@pytest.fixture(scope="function")
def browser(config):
    browser_name = config['browser']
    if browser_name == 'chrome':
        driver = webdriver.Chrome()
    elif browser_name == 'firefox':
        driver = webdriver.Firefox()
    else:
        raise ValueError(f"Unsupported browser: {browser_name}")
    driver.maximize_window()
    yield driver
    driver.quit()
Test Reporting and CI/CD Integration
  • Use pytest with plugins like pytest-html to generate readable HTML reports saved in reports/.
  • Integrate tests in CI/CD pipelines (e.g., GitHub Actions, Jenkins) to run tests automatically on code push.
  • Configure CI to install dependencies, run tests with fixtures, and archive reports as build artifacts.
  • Use environment variables in CI to switch browsers or environments dynamically.
Best Practices for Fixtures in Selenium Python
  • Scope wisely: Use session scope for config loading and function scope for browser to isolate tests.
  • Explicit teardown: Always quit the browser in fixture teardown to avoid resource leaks.
  • Parameterize fixtures: Allow browser type and environment to be passed via config or command line for flexibility.
  • Keep fixtures simple: Fixtures should only handle setup/teardown, not test logic.
  • Reuse fixtures: Share fixtures across tests by placing them in conftest.py.
Self Check

Where in this framework structure would you add a new fixture to handle user login before tests?

Key Result
Use pytest fixtures in conftest.py to manage browser setup and teardown cleanly and flexibly.

Practice

(1/5)
1. What is the main purpose of using a fixture for browser setup and teardown in Selenium tests?
easy
A. To avoid using assertions in tests
B. To write test cases faster without any setup
C. To automate opening and closing the browser before and after tests
D. To run tests only on one browser type

Solution

  1. Step 1: Understand fixture role

    Fixtures help prepare the environment before tests and clean up after tests.
  2. Step 2: Apply to browser context

    In Selenium, this means opening the browser before tests and closing it after.
  3. Final Answer:

    To automate opening and closing the browser before and after tests -> Option C
  4. Quick Check:

    Fixture = setup + teardown automation [OK]
Hint: Fixtures handle setup and cleanup automatically [OK]
Common Mistakes:
  • Thinking fixtures replace test cases
  • Believing fixtures remove need for assertions
  • Assuming fixtures limit browser types
2. Which of the following is the correct way to define a pytest fixture for browser setup and teardown using yield?
easy
A. def browser(): driver = webdriver.Chrome() yield driver driver.quit()
B. def browser(): driver = webdriver.Chrome() driver.quit() yield driver
C. def browser(): yield webdriver.Chrome() driver.quit()
D. def browser(): driver = webdriver.Chrome() driver.close() yield driver

Solution

  1. Step 1: Understand yield usage in fixtures

    Yield separates setup (before yield) and teardown (after yield).
  2. Step 2: Check correct order

    Setup: create driver; yield it; teardown: quit driver.
  3. Final Answer:

    def browser(): driver = webdriver.Chrome() yield driver driver.quit() -> Option A
  4. Quick Check:

    Setup before yield, teardown after yield [OK]
Hint: Setup before yield, teardown after yield in fixture [OK]
Common Mistakes:
  • Calling quit before yield
  • Using driver.close() instead of driver.quit() for teardown
  • Yielding before creating driver
3. Given this fixture and test code, what will be printed when the test runs?
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')
medium
A. Running test only
B. Running test\nSetup browser\nTeardown browser
C. Setup browser\nTeardown browser\nRunning test
D. Setup browser\nRunning test\nTeardown browser

Solution

  1. Step 1: Trace fixture execution order

    Fixture runs setup code before yield, then test runs, then fixture runs teardown after yield.
  2. Step 2: Match print statements order

    Prints 'Setup browser', then 'Running test', then 'Teardown browser'.
  3. Final Answer:

    Setup browser\nRunning test\nTeardown browser -> Option D
  4. Quick Check:

    Setup -> Test -> Teardown order [OK]
Hint: Fixture setup prints before test, teardown prints after [OK]
Common Mistakes:
  • Assuming teardown runs before test
  • Ignoring yield separates setup and teardown
  • Thinking prints run all before test
4. What is wrong with this fixture code for browser setup and teardown?
@pytest.fixture
def browser():
    driver = webdriver.Chrome()
    driver.quit()
    yield driver
medium
A. Missing import statement for webdriver
B. Calling driver.quit() before yield closes browser too early
C. Yield should be inside a try-except block
D. Fixture should return driver instead of yield

Solution

  1. Step 1: Analyze order of operations

    driver.quit() is called before yield, so browser closes before test uses it.
  2. Step 2: Understand yield role

    Yield should come before teardown to keep browser open during test.
  3. Final Answer:

    Calling driver.quit() before yield closes browser too early -> Option B
  4. Quick Check:

    Teardown must be after yield [OK]
Hint: Teardown code must be after yield in fixture [OK]
Common Mistakes:
  • Calling quit before yield
  • Confusing yield with return
  • Ignoring fixture import requirements
5. You want to run multiple tests using the same browser instance to save time. How should you modify the fixture to achieve this?
hard
A. Change fixture scope to 'module' so browser opens once per module
B. Add driver.quit() before yield to close browser early
C. Remove yield and return driver directly
D. Create a new fixture for each test to isolate browser

Solution

  1. Step 1: Understand fixture scopes

    Default scope is 'function' which runs fixture per test; 'module' runs once per file.
  2. Step 2: Apply scope to reuse browser

    Setting scope='module' opens browser once for all tests in module, saving time.
  3. Final Answer:

    Change fixture scope to 'module' so browser opens once per module -> Option A
  4. Quick Check:

    Fixture scope controls reuse [OK]
Hint: Use scope='module' to share browser across tests [OK]
Common Mistakes:
  • Closing browser before tests run
  • Removing yield breaks setup/teardown
  • Creating new fixture per test wastes time
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard