Playwright Python Framework Folder Structure and Best Practices

A folder of fifty test files with copied helpers works until the second person joins the project. A clear structure tells everyone where pages, data, API clients, fixtures and tests belong, and it keeps the suite fast to change as it grows to hundreds of tests. In this lesson you will build a complete, runnable framework skeleton for the SQA Shop: a proven folder layout, all pytest settings in pyproject.toml, layered conftest.py files for UI and API tests, registered markers, one config module, pinned dependencies and the naming rules that keep it readable.

Advertisement

📖 What You’ll Learn: a proven folder layout and what goes where, pyproject.toml with [tool.pytest.ini_options], testpaths, pythonpath, addopts and strict markers, layered conftest.py files (root, ui, api), a config module, page objects and API clients as packages, test data folders, requirements with pinned versions, .gitignore for artifacts, naming conventions for files, tests and fixtures, checking the suite with –collect-only and markers, and the rules that keep tests independent.


🗺️ The Target Layout

This is the structure we will build. Each folder has one job:

shop-tests/
├── pyproject.toml          pytest settings, markers, project metadata
├── requirements.txt        pinned dependencies
├── .env.example            names of required environment variables (copy to .env)
├── .gitignore              .env, .auth/, reports/, test-results/
├── config/
│   ├── __init__.py
│   └── settings.py         one Settings object: URLs, credentials, timeouts
├── pages/                  page objects and components (Lesson 56)
│   ├── __init__.py
│   ├── base_page.py
│   ├── login_page.py
│   └── cart_page.py
├── api/                    API clients (Module 9)
│   ├── __init__.py
│   └── practice_api.py
├── data/
│   └── coupons.json        test data files (Lesson 46)
└── tests/
    ├── conftest.py         fixtures for ALL tests: settings, markers, report header
    ├── ui/
    │   ├── conftest.py     browser fixtures: page objects, logged-in state
    │   ├── test_login.py
    │   └── test_cart.py
    └── api/
        ├── conftest.py     API client fixture (no browser)
        └── test_products.py

Rules of thumb:

  • Tests only describe behaviour. Locators live in pages/, HTTP details in api/, values in config/ and data/.
  • Fixtures live in conftest.py files at the level where they are needed: shared ones at tests/, browser ones at tests/ui/, API ones at tests/api/.
  • Artifacts never go into Git: reports, traces, screenshots, .auth/ and .env.

⚙️ pyproject.toml: One Place for Settings

Modern Python projects keep tool settings in pyproject.toml. pytest reads the [tool.pytest.ini_options] table:

📄 pyproject.toml

[project]
name = "shop-tests"
version = "1.0.0"
requires-python = ">=3.10"

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]
addopts = [
    "--base-url=https://sqatools.in",
    "--strict-markers",
    "-ra",
]
markers = [
    "smoke: fast checks for every commit",
    "regression: full regression suite",
    "api: API tests (no browser)",
]
Setting Why
testpaths pytest with no arguments only looks in tests/ (faster collection, no accidental scripts)
pythonpath = ["."] import pages, import config work from any test without sys.path hacks
--strict-markers A typo like @pytest.mark.smokee becomes an error instead of a silently unused marker
-ra The summary lists every skipped, failed and xfailed test with its reason
markers Documents and registers the markers your team uses

📌 Note: Use either pytest.ini or pyproject.toml, not both: if a pytest.ini exists, pytest uses it and ignores the TOML settings.


🔧 config/: One Settings Object

📄 config/settings.py

import os
from dataclasses import dataclass, field
from pathlib import Path

from dotenv import load_dotenv

ROOT = Path(__file__).resolve().parent.parent
load_dotenv(ROOT / ".env")


@dataclass(frozen=True)
class Settings:
    shop_path: str = "/dummy-ecommerce-website/"
    api_url: str = "https://sqatools.in/wp-json/sqa-api/v1/"
    shop_user: str = "testuser"
    shop_password: str = field(default="", repr=False)
    expect_timeout_ms: int = 5_000


def load_settings() -> Settings:
    return Settings(
        shop_user=os.getenv("SHOP_USER", "testuser"),
        shop_password=os.getenv("SHOP_PASSWORD", "Test@123"),
        expect_timeout_ms=int(os.getenv("EXPECT_TIMEOUT", "5000")),
    )

📄 .env.example

SHOP_USER=testuser
SHOP_PASSWORD=
EXPECT_TIMEOUT=5000

The defaults make the public practice site work out of the box; in a real project the password would have no default (Lesson 47).


📄 pages/ and api/: Reusable Building Blocks

📄 pages/base_page.py

from playwright.sync_api import Page


class BasePage:
    path = ""

    def __init__(self, page: Page, shop_path: str):
        self.page = page
        self.shop_path = shop_path
        self.cart_count = page.get_by_test_id("cart-count")
        self.account_button = page.get_by_test_id("account-button")

    def open(self):
        self.page.goto(self.shop_path + self.path)
        return self

📄 pages/login_page.py

from pages.base_page import BasePage


class LoginPage(BasePage):
    path = "#/login"

    def __init__(self, page, shop_path):
        super().__init__(page, shop_path)
        self.username = page.get_by_test_id("login-username")
        self.password = page.get_by_test_id("login-password")
        self.button = page.get_by_test_id("login-button")
        self.error = page.get_by_test_id("login-error")

    def submit(self, username: str, password: str):
        self.username.fill(username)
        self.password.fill(password)
        self.button.click()
        return self

📄 pages/cart_page.py

from pages.base_page import BasePage


class CartPage(BasePage):
    path = "#/cart"

    def __init__(self, page, shop_path):
        super().__init__(page, shop_path)
        self.coupon_input = page.get_by_test_id("coupon-input")
        self.apply_button = page.get_by_test_id("apply-coupon")
        self.coupon_message = page.get_by_test_id("coupon-message")

    def apply_coupon(self, code: str):
        self.coupon_input.fill(code)
        self.apply_button.click()
        return self

📄 api/practice_api.py

from playwright.sync_api import APIRequestContext


class PracticeApi:
    """Thin client: one method per endpoint the tests use."""

    def __init__(self, request: APIRequestContext):
        self.request = request

    def products(self, **params) -> list[dict]:
        response = self.request.get("products", params=params)
        assert response.ok, response.text()
        return response.json()["data"]

Advertisement

🧩 Layered conftest.py Files

pytest loads every conftest.py from the root down to the test’s folder. Use that to scope fixtures:

📄 tests/conftest.py

"""Fixtures for every test (UI and API)."""
import pytest

from config.settings import Settings, load_settings


@pytest.fixture(scope="session")
def settings() -> Settings:
    return load_settings()


def pytest_report_header(config):
    return f"shop-tests framework | config: {load_settings()}"

📄 tests/ui/conftest.py

"""Browser-only fixtures."""
import pytest
from playwright.sync_api import Page, expect

from pages.cart_page import CartPage
from pages.login_page import LoginPage


@pytest.fixture(scope="session", autouse=True)
def _expect_timeout(settings):
    expect.set_options(timeout=settings.expect_timeout_ms)


@pytest.fixture
def login_page(page: Page, settings) -> LoginPage:
    return LoginPage(page, settings.shop_path).open()


@pytest.fixture
def cart_with_earbuds(page: Page, settings) -> CartPage:
    page.goto(settings.shop_path + "#/search/earbuds")
    page.get_by_test_id("product-card").filter(has_text="Wireless Earbuds").get_by_role("button", name="Add to cart").click()
    return CartPage(page, settings.shop_path).open()

📄 tests/api/conftest.py

"""API-only fixtures: no browser is started for these tests."""
from pathlib import Path

import pytest
from playwright.sync_api import Playwright

from api.practice_api import PracticeApi


@pytest.fixture(scope="session")
def practice_api(playwright: Playwright, settings) -> PracticeApi:
    request = playwright.request.new_context(base_url=settings.api_url)
    yield PracticeApi(request)
    request.dispose()


API_DIR = Path(__file__).parent


def pytest_collection_modifyitems(items):
    # This hook receives ALL collected items, even in a sub-folder conftest, so filter by path.
    for item in items:
        if item.path.is_relative_to(API_DIR):
            item.add_marker("api")           # every test in tests/api/ is an API test

📄 data/coupons.json

[
  {"code": "SAVE10", "message": "Coupon SAVE10 applied."},
  {"code": "FLAT200", "message": "Coupon FLAT200 applied."},
  {"code": "WINTER99", "message": "This coupon code is not valid."}
]

🧪 Tests That Only Describe Behaviour

📄 tests/ui/test_login.py

import pytest
from playwright.sync_api import expect


@pytest.mark.smoke
def test_valid_login(login_page, settings):
    login_page.submit(settings.shop_user, settings.shop_password)
    expect(login_page.account_button).to_contain_text("Hi, Test")


def test_locked_user(login_page):
    login_page.submit("lockeduser", "Test@123")
    expect(login_page.error).to_have_text("This account is locked. Please contact support.")

📄 tests/ui/test_cart.py

import json
from pathlib import Path

import pytest
from playwright.sync_api import expect

COUPONS = json.loads((Path(__file__).resolve().parents[2] / "data" / "coupons.json").read_text(encoding="utf-8"))


@pytest.mark.regression
@pytest.mark.parametrize("coupon", COUPONS, ids=lambda c: c["code"].lower())
def test_coupon_codes(cart_with_earbuds, coupon):
    cart_with_earbuds.apply_coupon(coupon["code"])
    expect(cart_with_earbuds.coupon_message).to_have_text(coupon["message"])

📄 tests/api/test_products.py

import pytest


@pytest.mark.smoke
def test_books_are_books(practice_api):
    books = practice_api.products(category="books")
    assert books and {b["category"] for b in books} == {"books"}


def test_prices_are_positive_integers(practice_api):
    for product in practice_api.products(per_page=50):
        assert isinstance(product["price"], int) and product["price"] > 0

Advertisement

✅ Check the Structure

--collect-only lists what pytest would run, without running it. It is the fastest way to check that the layout, imports and markers are right:

⌨️ Terminal

pytest --collect-only -q

🖥️ Output

tests/api/test_products.py::test_books_are_books
tests/api/test_products.py::test_prices_are_positive_integers
tests/ui/test_cart.py::test_coupon_codes[chromium-save10]
tests/ui/test_cart.py::test_coupon_codes[chromium-flat200]
tests/ui/test_cart.py::test_coupon_codes[chromium-winter99]
tests/ui/test_login.py::test_valid_login[chromium]
tests/ui/test_login.py::test_locked_user[chromium]

7 tests collected in 0.02s

Run only the smoke tests across UI and API, then only API tests:

⌨️ Terminal

pytest -m smoke -v

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0 -- C:\Users\you\playwright-python\.venv\Scripts\python.exe
cachedir: .pytest_cache
baseurl: https://sqatools.in
shop-tests framework | config: Settings(shop_path='/dummy-ecommerce-website/', api_url='https://sqatools.in/wp-json/sqa-api/v1/', shop_user='testuser', expect_timeout_ms=5000)
rootdir: C:\Users\you\playwright-python
configfile: pyproject.toml
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collecting ... collected 7 items / 5 deselected / 2 selected

tests/api/test_products.py::test_books_are_books PASSED                  [ 50%]
tests/ui/test_login.py::test_valid_login[chromium] PASSED                [100%]

======================= 2 passed, 5 deselected in 2.58s =======================

⌨️ Terminal

pytest -m api -q

🖥️ Output

..                                                                       [100%]
2 passed, 5 deselected in 1.35s

The API tests ran without starting a browser, because nothing in tests/api/ asks for page. And the whole suite:

⌨️ Terminal

pytest

🖥️ Output

============================= test session starts =============================
platform win32 -- Python 3.15.1, pytest-9.2.0, pluggy-1.7.0
baseurl: https://sqatools.in
shop-tests framework | config: Settings(shop_path='/dummy-ecommerce-website/', api_url='https://sqatools.in/wp-json/sqa-api/v1/', shop_user='testuser', expect_timeout_ms=5000)
rootdir: C:\Users\you\playwright-python
configfile: pyproject.toml
testpaths: tests
plugins: allure-pytest-2.16.2, base-url-2.1.0, bdd-9.0.1, html-4.2.0, metadata-3.1.1, playwright-0.10.0, rerunfailures-16.7, xdist-3.8.0
collected 7 items

tests\api\test_products.py ..                                            [ 28%]
tests\ui\test_cart.py ...                                                [ 71%]
tests\ui\test_login.py ..                                                [100%]

============================== 7 passed in 9.31s ==============================

--strict-markers at work: a typo in a marker fails collection immediately.

📄 typo_demo/test_typo.py

import pytest


@pytest.mark.smokee
def test_with_typo():
    pass

⌨️ Terminal

pytest typo_demo/test_typo.py -q

🖥️ Output

=================================== ERRORS ====================================
___________________ ERROR collecting typo_demo/test_typo.py ___________________
'smokee' not found in `markers` configuration option
=========================== short test summary info ===========================
ERROR typo_demo/test_typo.py - Failed: 'smokee' not found in `markers` config...
!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
1 error in 0.10s

📌 Pin Your Dependencies

A suite that passed yesterday and fails today without code changes is often a new library version. Pin exact versions and upgrade on purpose:

📄 requirements.txt

playwright==1.65.2
pytest==9.2.0
pytest-playwright==0.10.0
pytest-base-url==2.1.0
python-dotenv==1.2.4

📄 .gitignore

.venv/
.env
.auth/
reports/
test-results/
__pycache__/
.pytest_cache/

pip freeze > requirements.txt captures everything installed; a hand-written list of direct dependencies (as above) is easier to read and upgrade. Upgrade Playwright deliberately, then run playwright install to fetch the matching browsers.


🏷️ Naming Conventions

What Convention Example
Test files test_<feature>.py test_cart.py
Test functions test_<behaviour> that reads as a sentence test_locked_user_sees_error
Page classes <Name>Page, components without suffix CartPage, Header
Fixtures Named after what they give you cart_with_earbuds, practice_api
Markers Lower-case, registered smoke, regression, api
Data files <feature>_cases.<ext> with an id column coupons.json

🧭 Rules That Keep a Framework Healthy

  1. Every test runs alone (pytest path::test_name) and in any order. No test depends on another test’s data.
  2. No sleep(). Use auto-waiting actions and expect.
  3. No secrets in the repository. Use .env locally and CI secrets in pipelines.
  4. Fixtures over helpers with side effects. Setup and clean-up belong in yield fixtures.
  5. Small modules. If a page class passes 200 lines, split out components.
  6. Review tests like production code. Lint them (for example with ruff) and keep them in the same pull request as the feature when possible.

Advertisement

🏋️ Practice Exercises

Try each exercise on your own first, then open the answer to compare. The answers use the same practice sites and project layout as the lesson.

Exercise 1: Your team keeps pytest.ini and also adds [tool.pytest.ini_options] to pyproject.toml, but the new markers are “unknown”. Why?

Show answer

When a pytest.ini file exists, pytest uses it as the configuration file and ignores [tool.pytest.ini_options] in pyproject.toml. Move all settings into one file (and delete the other).

Exercise 2: Add a marker checkout to the framework so that pytest -m checkout works with --strict-markers. Show the change.

Show answer
[tool.pytest.ini_options]
markers = [
    "smoke: fast checks for every commit",
    "regression: full regression suite",
    "api: API tests (no browser)",
    "checkout: checkout flow tests",
]

Then decorate tests with @pytest.mark.checkout.

Exercise 3: Where should a fixture admin_api_token go in this layout, and why?

Show answer

In tests/api/conftest.py if only API tests use it; in tests/conftest.py if UI tests also need it (for example for hybrid setup). Put fixtures at the lowest level that covers every test that uses them, so other tests do not see or load them.

Exercise 4: A new tester puts time.sleep(3) in CartPage.apply_coupon() “because the message is slow”. What do you suggest?

Show answer

Remove the sleep. Let the action finish and assert the message in the test with expect(cart.coupon_message).to_have_text(...), which waits up to the expect timeout (configurable in Settings). Sleeps make every call slower and still fail when the app is slower than the guess.


🧠 MCQ Quiz: Framework Folder Structure and Best Practices

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does testpaths = ["tests"] do?
  2. What does --strict-markers change?
  3. Which file does pytest use if both pytest.ini and pyproject.toml exist?
  4. Why put the API client fixture in tests/api/conftest.py?
  5. What is the fastest way to check imports, layout and markers without running tests?
  6. What does -ra in addopts add?
  7. Why pin dependency versions in requirements.txt?
  8. Where do locators belong in this framework?
  9. Which item must be in .gitignore?
  10. Which rule keeps tests reliable as the suite grows?

Want a longer, timed test? Take the Module 10 mock interview (20 MCQs in 20 minutes).


Advertisement

❓ Frequently Asked Questions

🤔 Should tests be grouped by page or by feature?

By feature or user journey (test_cart.py, test_checkout.py). Page objects are already grouped by page; grouping tests the same way often splits one journey across several files.

🤔 Do I need __init__.py files in test folders?

With pythonpath = ["."] and pytest’s default import mode, no. Add them only if two test files in different folders share a name (for example two test_login.py), or use unique file names.

🤔 Where do helper functions go?

In a utils/ package if they are general (date formatting, random data), or next to what they support (pages/, api/). Avoid one huge helpers.py.

🤔 How do I share this framework between several projects?

Package the reusable parts (base page, API client, fixtures) as an installable Python package or a pytest plugin, and keep each product’s pages and tests in its own repository.

🤔 Is this layout too much for a small project?

Start with pages/, tests/ and one conftest.py, and add config/, api/ and data/ when you first need them. The point is to know where each kind of code will go.


🏁 Summary

  • Give every folder one job: config/, pages/, api/, data/, tests/ (split into ui/ and api/).
  • Put pytest settings in pyproject.toml: testpaths, pythonpath, addopts with --strict-markers and -ra, and registered markers.
  • Layer conftest.py files: shared fixtures at tests/, browser fixtures in tests/ui/, API fixtures in tests/api/.
  • Pin dependencies, ignore artifacts and secrets, and follow naming conventions.
  • Check the structure with --collect-only, and keep every test independent and sleep-free.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page