Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 35 ยท Test Structure

Selenium with pytest

Use pytest with Selenium: a driver fixture with setup and teardown, conftest.py, headless option, parametrized tests and markers, plus a runnable fixture stand-in.

Selenium by itself only drives a browser. It has no idea what a "test" is, which tests failed, or how to start and stop a browser for each one. For that you need a test framework. In Python, the most popular choice is pytest. It finds your test functions, runs them, reports the failures, and gives you fixtures: reusable setup and teardown code that you request simply by naming it as a function argument.

In this lesson you will build the standard pytest layout for Selenium: a conftest.py with a driver fixture, a headless switch, parametrized tests and markers. If pytest is new to you, read Testing in Python and pytest in Depth first. The fixture mechanism is the heart of it, so the runnable examples rebuild it in plain Python.

The Selenium and pytest commands below are read-only, because a real browser cannot run on this site. The TryIts are stand-ins: a small hand-written runner that imitates how pytest calls a fixture, runs the test, and then resumes the fixture for teardown. Real pytest does much more, but this core idea is the same.

Project layout

A small Selenium suite usually looks like this.

TEXT
shop-tests/
  conftest.py          # fixtures shared by all tests
  pytest.ini           # markers and default options
  pages/
    login_page.py      # page objects
  tests/
    test_login.py
    test_cart.py

pytest loads conftest.py automatically and makes its fixtures available to every test below it, so you never import them. Install the tools once with pip install selenium pytest. Since Selenium 4.6, a built-in tool called Selenium Manager finds or downloads the right browser driver for you, so you do not install ChromeDriver by hand.

A driver fixture

A fixture is a function marked with @pytest.fixture. A test that lists the fixture's name as a parameter receives its return value. A fixture that uses yield splits into two halves: code before the yield is setup, the yielded value goes to the test, and code after the yield is teardown, which runs even if the test failed.

Python
# Read-only: conftest.py
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


@pytest.fixture
def driver():
    options = Options()
    options.add_argument("--window-size=1280,900")
    browser = webdriver.Chrome(options=options)   # setup: start a browser
    yield browser                                  # the test runs here
    browser.quit()                                 # teardown: always close it
Python
# Read-only: tests/test_login.py
from pages.login_page import LoginPage


def test_valid_login(driver):                      # pytest passes the fixture's value
    dashboard = LoginPage(driver).open().log_in("[email protected]", "s3cret!")
    assert dashboard.heading_text() == "Dashboard"

Without yield and quit(), a failing test would leave a browser process open, and a long run would pile up dozens of orphan browsers. The fixture guarantees cleanup in one place.

Scope: how often to start a browser

By default a fixture runs once per test (scope="function"). Starting a browser is slow, so you may share one across a file or the whole run with scope="module" or scope="session". The trade-off is isolation: tests sharing one browser also share cookies, local storage and the current page, so one test can break the next.

Fixture scope trade-off

function Fresh browser per test. Slow but isolated.
module One browser per file. Faster, some sharing.
session One for the whole run. Fastest, most fragile.

Start with function scope and optimize only when it hurts.

1 / 2

A common compromise is a function-scoped driver fixture, and a faster way to reset state (clear cookies, open a fresh page) when speed becomes a problem.

Seeing setup and teardown happen

Here is the mechanism in plain Python. A tiny runner takes a test function, looks at its parameter names, calls the matching fixture to get the value, runs the test, and then resumes the fixture so its teardown code runs. The third test fails on purpose to show that teardown still happens.

Python How a yield fixture works

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the "quit browser" line appears after both tests, including the failing one. That is exactly what you want from a yield fixture: no leaked browsers. Real pytest also catches errors thrown in setup, handles fixtures that depend on other fixtures, and reports teardown errors separately, but the shape is the one in the example.

A headless switch

On a CI server there is no screen, so you run the browser headless. Instead of editing the fixture, add a command-line option in conftest.py.

Python
# Read-only: conftest.py (extended)
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


def pytest_addoption(parser):
    parser.addoption("--headless", action="store_true", help="run the browser without a window")


@pytest.fixture
def driver(request):
    options = Options()
    if request.config.getoption("--headless"):
        options.add_argument("--headless=new")
    browser = webdriver.Chrome(options=options)
    yield browser
    browser.quit()

Now pytest opens a visible window on your laptop, while pytest --headless runs without one on CI. The request object is a built-in fixture that gives a fixture access to the command line and to the test that asked for it. Headless Mode and Browser Options covers the option objects in detail.

Parametrized tests

The same steps often need to run with different data: several bad passwords, several browsers, several sizes. @pytest.mark.parametrize turns one test function into many test cases.

Python
# Read-only
import pytest
from pages.login_page import LoginPage


@pytest.mark.parametrize("email, password, message", [
    ("[email protected]", "wrong",    "Wrong email or password"),
    ("",                "s3cret!",  "Email is required"),
    ("[email protected]", "",         "Password is required"),
])
def test_login_errors(driver, email, password, message):
    page = LoginPage(driver).open().log_in_expecting_error(email, password)
    assert page.error_message() == message

pytest reports three separate tests, each with its own pass or fail. A failure in the second row does not stop the third. The runner below shows what that expansion looks like: each row becomes a case with an id built from its values, and a failing case is reported with that id.

Python Parametrize expands one test into many

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last case fails because the expectation is wrong, and the report names the exact row. In real pytest you would see the same idea: an id like test_login_errors[[email protected] email or password] and a normal failure report for that case only. You can parametrize the fixture too (@pytest.fixture(params=["chrome", "firefox"])) to run the whole suite on several browsers.

Markers: choose which tests to run

A marker is a label you attach to tests. Typical labels are smoke (a quick set that runs on every commit), slow and checkout. You then select tests on the command line.

Python
# Read-only
import pytest


@pytest.mark.smoke
def test_home_page_loads(driver):
    driver.get("https://app.example/")
    assert "Shop" in driver.title


@pytest.mark.slow
def test_full_checkout(driver):
    ...
INI
# Read-only: pytest.ini
[pytest]
markers =
    smoke: fast checks run on every commit
    slow: long end-to-end flows
addopts = -ra
Terminal
# Read-only
pytest -m smoke                 # only smoke tests
pytest -m "not slow"            # everything except slow tests
pytest tests/test_login.py -k wrong   # tests whose name contains "wrong"

Registering markers in pytest.ini avoids typo problems: with --strict-markers, an unregistered marker is an error rather than a silent new label.

Good habits

  • Use the fixture for the driver only. Put page objects in their own modules (see The Page Object Model) and create them inside the test or in a small fixture that depends on driver.
  • Keep tests independent. A test should not rely on another test having run before it. With the pytest-xdist plugin (see Running in CI) they may run in parallel and in any order.
  • Fail with a useful message. assert dashboard.heading_text() == "Dashboard" prints both values on failure; a bare assert ok does not.
  • Do not catch AssertionError or Selenium exceptions in the test just to keep going. Let them fail loudly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a fixture that contains yield browser, when does the code after the yield run?

    Code after yield is the teardown. pytest resumes the fixture after the test, whether the test passed or failed, so the browser is always closed.
  2. 2. Where should a fixture shared by many test files normally live?

    pytest loads conftest.py automatically, and its fixtures become available to all tests in that directory and below without any import.
  3. 3. What does @pytest.mark.parametrize do?

    Each row becomes its own test case with its own result, so one failing row does not hide the others.
  4. 4. Which command runs only the tests marked smoke?

    -m selects tests by marker expression. -k matches names instead, so it would miss tests that are marked but not named smoke.
  5. 5. What is the downside of a scope="session" driver fixture?

    A session-scoped browser is faster to start once, but cookies, storage and the current page are shared, so tests are no longer isolated.

Summary

  • pytest finds and runs tests; fixtures supply the driver and clean it up.
  • A yield fixture does setup before the yield and teardown after it, even when a test fails.
  • Put shared fixtures and command-line options in conftest.py; add a --headless option for CI.
  • parametrize runs one test with many data rows; markers and -m select groups of tests.
  • Default to a fresh browser per test, and relax the scope only when you must.

Next: Selenium with JUnit and TestNG.