Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Fundamentals & Architecture · Chapter 02 / 06

Test automation learning path

Test architecture & framework design

Dependency boundaries, page and component objects, reusable test abstractions, naming and the Arrange-Act-Assert shape.

Layer boundaries and the one rule

Each layer may only use the layer directly below it; sideways imports mean a missing abstraction.

A suite has a predictable life. At fifty tests any structure works; at two hundred a redesign breaks forty tests at once and fixing them takes a week; past five hundred the suite is either well layered or abandoned. Architecture is what you do at test ten so that test four hundred costs the same to write as test four did. The structure that holds is four kinds of code: tests express what the system should do; page, screen and service objects express how to operate it; a driver or transport layer expresses how to talk to it; and configuration, data and reporting are cross-cutting utilities available to any of the other three. The rule that keeps them honest isn't "only the layer directly below" — it's an explicit, one-directional dependency graph. Tests may depend on the object-model layer, and deliberately may mix service objects with page objects in the same test: using the API to arrange state and the UI to verify it is a normal, encouraged pattern, not a boundary violation. Object-model code may depend on the transport/driver layer. Cross-cutting utilities are available everywhere. What never happens is a dependency running backward or sideways past that — a test importing an HTTP library directly, a page object reading environment variables itself instead of receiving already-resolved settings, a service object formatting a report attachment. When you catch yourself doing that, you have found a missing abstraction rather than an inconvenience.

Key points

  • Four kinds of code: tests, an object-model layer (pages, screens, services), a transport/driver layer, and cross-cutting utilities (config, data, reporting) available to all three
  • Dependencies run one direction only, down toward transport and cross-cutting utilities — never sideways or back up; that's the actual rule, not "only the layer directly below"
  • Mixing service objects and page objects in the same test — API to arrange, UI to verify — is a normal object-model-layer pattern, not a boundary violation

Code

# WRONG: the test knows about transport, endpoints and payload shape.
def test_cart_total(base_url, token):
    response = httpx.post(
        f"{base_url}/api/cart/items",
        json={"product_id": 1, "quantity": 2},
        headers={"Authorization": f"Bearer {token}"},
    )
    assert response.json()["total"] == 399.98


# RIGHT: the test expresses the rule; every detail lives one layer down.
def test_cart_total_reflects_quantity(shop_as_user):
    product = shop_as_user.products.first_in_stock()

    cart = shop_as_user.cart.add_item(product.id, quantity=2)

    approx_money(cart.total, product.price * 2)

The second version survives an endpoint rename, an auth change and a payload change without edits.

See it in the framework

  • Implementation · HTTP transport (bottom layer): framework/http/client.py — live · reviewed
  • Used by · Root fixtures wiring the layers together: conftest.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Letting a locator or a URL appear in a test file, which couples the test to a detail it should not know
  • Putting a business assertion inside a page object, so the test's intent lives in two files at once

Practice exercise

Grep a suite you work with for direct HTTP calls, raw selectors or environment reads inside test files. Pick the worst offender and push each detail down to the layer where it belongs.

Page objects that do not go stale

Keep locators lazy, name methods after intent, and return the destination page so flows read as flows.

Three decisions separate a page object that lasts from one that has to be rewritten after every redesign. First, don't confuse a Locator with a resolved element. A modern Locator (Playwright's, for instance) is a lazy query description — it re-resolves against the live DOM on every action and every assertion, so it never goes stale whether you store it in __init__ or rebuild it on each access (Playwright's own official Page Object example stores locators in the constructor). What genuinely does go stale on re-render is an older, lower-level handle to an already-resolved node (an ElementHandle) — don't reach for that instead. Exposing a locator as a property is still worth doing, but for readability and consistent access, not to dodge staleness. Second, methods express intent rather than mechanics: a single login method beats three methods that type, type and click, because the test should read like the acceptance criterion rather than like a recording. Third, a method that navigates returns the page object for its destination, which lets a test chain steps without knowing the navigation graph and lets a type checker catch wrong chaining. Add one more piece — a readiness locator per page, checked by every open call — and no test ever begins against a half-rendered screen.

Key points

  • A Locator is a lazy query, not a resolved element — it re-resolves on every action whether it's stored in __init__ or rebuilt as a property, so it never goes stale; the object to avoid is an ElementHandle
  • Name methods after intent, not mechanics: login(user, password), not three typing methods
  • Return the destination page object, and give every page a readiness locator checked on open

Code

class LoginPage(BasePage):
    path = "/login"
    ready_locator = "[data-testid=login-form]"

    @property
    def username(self) -> Locator:        # a query, not a resolved element -- re-resolves on every action
        return self.testid("username")

    def login(self, username: str, password: str) -> "ProductsPage":
        """Happy path returns the destination page, so flows chain naturally."""
        self.username.fill(username)
        self.password.fill(password)
        self.submit.click()
        return ProductsPage(self.page).wait_until_ready()

    def login_expecting_failure(self, username: str, password: str) -> "LoginPage":
        """Negative path stays here. Separate method, separate return type."""
        self.username.fill(username)
        self.password.fill(password)
        self.submit.click()
        expect(self.error).not_to_be_empty()
        return self

Two paths, two methods, two return types — never a union that the caller has to unpack.

See it in the framework

  • Implementation · Page object base: framework/web/base_page.py — live · reviewed
  • Used by · Concrete page objects: framework/web/pages.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Reaching for a lower-level, already-resolved element handle (e.g. Playwright's ElementHandle) instead of a Locator — that's the object that goes stale on re-render, not a Locator stored in the constructor
  • A single method that returns one page on success and another on failure — split it into two methods with two return types

Practice exercise

Find a page object in your codebase that resolves an already-found element handle once (Playwright's ElementHandle, Selenium's WebElement) instead of using a live Locator/query. Replace it with a proper Locator — as a property or stored directly, whichever reads better — and confirm the test survives a re-render that would have broken the old version. Then add a readiness locator and remove whatever wait the tests were using to compensate.

Component objects and responsive layouts

Model repeated UI blocks as components scoped to their root, and branch on layout rather than duplicating pages.

As soon as a repeated block of interface has behaviour of its own — a product card, a table row, a date picker — it deserves a class scoped to its own root locator, with every lookup made relative to that root. Without component objects a page object grows into a several-hundred-line class full of methods named after positions rather than meaning, and a test ends up asking for the add button in the third card. With them, a test asks for the card whose name matches and tells it to add itself to the cart, which is both readable and immune to reordering. The same discipline applies to responsive layouts, where the common mistake is to build a parallel hierarchy of mobile page objects. For a responsive site the markup is usually the same and only the affordances differ, so the right move is a single page object that branches on the one thing that actually changes — for example, opening a navigation menu only when the viewport is narrow enough to have collapsed it.

Key points

  • Scope a component to its root locator so every lookup inside it is relative and order-independent
  • Components keep page objects small and stop method names from encoding positions
  • For a responsive site use one page object that branches on layout, not a parallel mobile hierarchy

Code

class ProductCard:
    """Scoped to one card's root; every lookup is relative to it."""

    def __init__(self, root: Locator) -> None:
        self.root = root

    @property
    def name(self) -> str:
        return self.root.get_by_test_id("product-name").inner_text().strip()

    def add_to_cart(self) -> None:
        self.root.get_by_test_id("add-to-cart").click()


class BasePage:
    @property
    def is_mobile_layout(self) -> bool:
        viewport = self.page.viewport_size
        return bool(viewport and viewport["width"] <= 640)

    def open_nav(self):
        """Desktop shows the nav; mobile hides it behind a hamburger."""
        if self.is_mobile_layout:
            self.testid("menu-toggle").click()
            expect(self.testid("main-nav")).to_be_visible()
        return self


# In a test:  products.card_for("Aurora Headphones").add_to_cart()

One page object serves both layouts; the component makes cards addressable by meaning, not position.

See it in the framework

  • Implementation · Component + page objects: framework/web/pages.py — live · reviewed
  • Used by · Page object base: framework/web/base_page.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Index-based access such as the third card, which breaks as soon as sorting, filtering or data changes
  • Duplicating an entire page object for mobile when the only real difference is one collapsed menu

Practice exercise

Find a page object with a method name containing an ordinal such as first or third. Extract the repeated block into a component class and rewrite the tests to address it by its visible content instead.

Naming and the Arrange-Act-Assert shape

Test names are the report; one action per test, in three visually separated blocks.

Everyone who reads a pipeline summary sees only test names, which makes naming a design decision rather than a style preference. A name that states subject, action and expected outcome is a specification a stakeholder can read; a name like test_cart is a question. If you cannot write the sentence, you do not yet know what you are testing, and that is worth discovering before writing the body. The body itself should hold three visually separated blocks: arrangement, usually delegated to fixtures; exactly one action; and the assertions. The blank lines are not decoration, they are how a reader finds the action in two seconds. The one-action rule is the part people resist, and it is the part that pays: two actions in one test means either two tests, or that the first action is really preparation and belongs in a fixture. Long tests have more ways to fail and worse diagnostics when they do.

Key points

  • Name tests subject, action, expected outcome — the name is what a stakeholder reads in a report
  • Three visually separated blocks: arrange, act, assert, with blank lines between them
  • Exactly one action per test; a second action means a second test or a missing fixture

Code

# Progressively better names for the same test:
#   test_1                                        useless
#   test_cart                                     what about it?
#   test_add_item                                 what should happen?
#   test_adding_same_product_twice_increments_quantity   a specification

def test_adding_same_product_twice_increments_quantity(shop_as_user):
    product = shop_as_user.products.first_in_stock()      # Arrange
    shop_as_user.cart.add_item(product.id, 1)

    cart = shop_as_user.cart.add_item(product.id, 2)      # Act - exactly one

    assert len(cart.items) == 1, "Duplicate lines created instead of merging"
    assert cart.line_for(product.id).quantity == 3        # Assert

The name pins down a design decision — merge or append — that would otherwise flip silently in a refactor.

See it in the framework

  • Used by · AAA-shaped service test: tests/services/test_cart_flow.py — live · reviewed
  • Used by · AAA-shaped web test: tests/web/test_shopping_flow.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Names that describe mechanics rather than behaviour, so a report says what was clicked instead of what should happen
  • A long journey test with six actions, which fails somewhere in the middle and tells you almost nothing

Practice exercise

Take ten test names from a suite you work with and rewrite any that do not state an expected outcome. For each one you cannot rewrite, read the body and decide whether the test actually knows what it is checking.

Source registry

4 chapter references
qa-automation-python reference framework

The runnable framework and demo application every lesson in this path is drawn from

sergiiiavt · Reference implementation
Source ↗
The Practical Test Pyramid

Choosing the layer at which a given risk is cheapest to cover

martinfowler.com · Industry article
Source ↗
Playwright locators

Locator strategies, role-based queries and test ids

Microsoft · Official documentation
Source ↗
pytest documentation

Test discovery, assertions, configuration and the plugin model

pytest-dev · Official documentation
Source ↗