QA Interview Hub · Knowledge base · Quizzes · Українська

System Design

Test framework architecture

Test framework layers

The layers of a test framework separate things that change for different reasons: the scenario, the markup, the API contract and the environment. An upper layer knows about a lower one, not the reverse: a test describes the business scenario, a Page Object hides locators and actions, and fixtures supply data created through the API. A new layer is added when duplication appears a third time.

System design · Framework

A button label changed and 200 tests needed edits. Where should the line between a test and the details run?

Login and the transfer form are copied into two hundred tests. Design renamed the «Sign in» button and the whole suite turned red. Playwright has nothing to do with it: the tests knew too much. This lesson covers how to split a framework into layers so a change in one place does not spread over the whole suite, and where that split stops paying off.

How it works and why. A layer exists to separate things that change for different reasons. A scenario changes when a business rule changes. Locators change when the markup changes. HTTP requests change with the API contract, and addresses and secrets with the environment. If everything sits in one file, any of these changes touches everything. The dependency rule is one: an upper layer knows about a lower one, never the other way round. A Page Object does not import a test, and a test does not know what a locator looks like.

Layers and the direction of dependencies

tests/what we verify: scenario and assertsfixtures/what a test gets ready, and cleanupflows/business steps: makeTransferpages/ + api/how to touch the UI and the APIconfig/environments, secrets, timeouts
Figure 1. Dependencies go only downwards. A reviewer reads the top layer, so it must be the shortest.

The top layer is read by a reviewer and by a new colleague, so it should be a short story about the business. Reporters and notifications stand to the side: they subscribe to run results and are not in the dependency chain.

Example: before and after. Here is a test that knows everything:

Which layer each part of this test belongs to

test('transfer of 30 leaves 70', async ({
  page,
}) => {
1  await page.goto('/login');
  await page
    .getByLabel('Email')
    .fill('qa1@example.test');
  await page
    .getByLabel('Password')
    .fill('secret');
  await page
    .getByRole('button', {
      name: 'Sign in',
    })
    .click();
2  await page
    .getByRole('link', {
      name: 'Transfer',
    })
    .click();
  await page
    .getByLabel('Amount')
    .fill('30');
  await page
    .getByRole('button', {
      name: 'Send',
    })
    .click();
3  await expect(
    page.getByTestId('balance'),
  ).toHaveText('70.00');
});
  1. Precondition: login on lines 4-15. It belongs to a fixture, not to the scenario.
  2. UI details: names of links, fields and buttons. A label changed: an edit in every test with this line.
  3. Scenario: the only check the test exists for.
Figure 2. The numbers mark three different reasons to change inside one short test.

Every line here belongs to a different layer: login is a precondition, the page path and labels are UI details, and the only thing the scenario really verifies is the last line. Now the same test split into layers.

test('transfer of 30 leaves 70', async ({ funded, transferPage }) => {
  await transferPage.open();
  await transferPage.send({ to: 'savings', amount: 30 });
  await expect(transferPage.balance).toHaveText('70.00');
});

// pages/transfer.page.ts
export class TransferPage {
  readonly balance: Locator;
  constructor(private page: Page) {
    this.balance = page.getByTestId('balance');
  }
  async open() { await this.page.goto('/transfer'); }
  async send(t: { to: string; amount: number }) {
    await this.page.getByLabel('To').fill(t.to);
    await this.page.getByLabel('Amount').fill(String(t.amount));
    await this.page.getByRole('button', { name: 'Send' }).click();
  }
}

The test gets the precondition «a signed-in user with a balance» from a fixture. With test.extend you describe what a test receives ready, and the fixture cleans up after the test itself:

type Fixtures = { api: BankApi; funded: User; transferPage: TransferPage };

export const test = base.extend<Fixtures>({
  api: async ({ request }, use) => {
    await use(new BankApi(request));
  },
  funded: async ({ api, page }, use) => {
    const user = await api.createUser();
    await api.deposit(user.accountId, 100);
    await api.signIn(page.context(), user); // this user's session
    await use(user); // the test runs here
    await api.deleteUser(user.id); // cleanup after the test
  },
  transferPage: async ({ page }, use) => {
    await use(new TransferPage(page));
  },
});

The same test before and after

Before

The test knows everything

Locators, URLs and data right in the test. A button label changed: edits in 200 files.

After

The test reads as a scenario

Locators in a Page Object, data in a fixture. The label changed: one line in one class.

Figure 3. The scenario did not change, only a detail did, and it now lives in one place.

Why preconditions are created through the API rather than by UI steps: a user, KYC and a top-up are one or two requests instead of dozens of clicks, and those requests do not depend on the markup. If a precondition fails, the test is marked as broken in setup, not as a failure of the scenario under test. The UI stays only where it is the subject of the check.

Limits and alternatives. Layers have a price: more files, more jumps through references, more places to hide bad code. For a suite of 30 tests three parts are enough: tests, Page Objects and fixtures. A flows layer (business steps like makeTransfer) appears when the same chain of steps repeats in many tests. A practical rule: extract when duplication shows up for the third time, not «for the future». A Page Object need not match a whole page: for repeated parts (a menu, modal windows) component objects are handier. Scenario asserts stay in the tests, while a page class returns locators and actions. An alternative to classes is helper functions and fixtures without a Page Object; Playwright allows both approaches.

Common mistakes.

  • A Page Object of five hundred lines with every action of the site: it cannot be read, and any edit touches everyone.
  • A test that imports a locator or calls page.locator itself: the scenario layer again knows details and the gain from the split is gone.
  • Fixtures with hidden shared state (one user for all tests): the layer does not isolate, it hides the cause of conflicts.
  • An API client with the checking business logic moved into it: the test stops being independent of the implementation.
  • Layers for the sake of layers in a small project: maintenance costs more than the duplication.

Check yourself

A test has the line page.getByRole('button', { name: 'Sign in' }).click(). Which principle is broken and what happens when the label changes?

Answer

The top layer (the scenario) knows a locator, which is a detail of a lower layer. The label changed, so every test with this line must be fixed. If the locator lives in a Page Object, there is one edit.

Why is it better to create the precondition «a user with balance 100» in a fixture through the API than with UI steps at the start of the test?

Answer

Through the API it is a few requests with no dependency on the markup, while UI steps duplicate other scenarios and are slow and brittle. A failure in setup is not confused with a failure of the scenario under test, and the fixture reliably cleans the data after the test. The UI is used only for what the test itself verifies.

In an interview. Junior: I build a framework in layers: tests describe the business scenario, Page Objects hide locators, fixtures hand out ready data. I create preconditions through the API and use the UI only for what is verified. Middle/Senior: A layer exists to separate the reasons for change: the scenario, the markup, the API contract, the environment. Dependencies go only downwards, and I add new layers when duplication appears for the third time, because each layer adds indirection. I keep scenario asserts in the tests, while a Page Object returns locators and actions. The quality criterion is simple: can the markup be changed by editing one place.

Task: 2000 e2e tests must finish in 15 minutes

The task of 2000 e2e tests in 15 minutes is solved with a calculation, not by adding machines. For 2000 tests of 20 seconds that is about 45 slots without overhead, about 56 with three minutes of overhead and 64 with a margin for uneven shards. Overhead does not divide across machines, so data isolation, sharding and a review of the pyramid are needed, and cost is named as the price.

System design · Framework

The nightly run takes 11 hours, but a PR should get an answer in 15 minutes. Where to start?

A suite of 2000 e2e tests runs at night, and the team wants the same on every merge to main, but within 15 minutes. The first reaction: «let us add machines». It may work, or it may give nothing. This lesson shows how to take the task apart with the scheme «requirements, layers, solution, trade-offs, metrics» and where the benefit of parallelism ends.

Requirements and calculation. We start with numbers, otherwise the answer hangs in the air. Assumptions: an average test takes 20 seconds, the target is 15 minutes for the whole suite, a run on every merge. Part of those 15 minutes goes to overhead: container start, browsers, merging reports. Take 3 minutes, the rest goes to tests.

Given: 2000 tests x 20 s, target 15 min, overhead 3 min
Work:     2000 x 20 s = 40,000 s  (~667 min)
For tests: 15 - 3 = 12 min
Slots:    667 / 12 = ~56
Margin:   8 machines x 8 workers = 64 slots

Without overhead it would be about 45 slots (40,000 / 900); that is a lower bound. With overhead about 56, and with a margin for uneven shards and retries we take 64. It is an estimate to be confirmed by a real run.

How it works and why. Run time is a fixed part (overhead) plus the work divided by the number of slots. The fixed part does not shrink when machines are added, and in money it multiplies: each machine pays for its start separately. So the gain from parallelism has a ceiling, while the cost grows almost linearly. Below is an ideal model (all shards equal, 8 workers per machine, 3 minutes of overhead):

MachinesSlotsTime, minMachine-minutes
432~24~95
864~13~107
16128~8~131

From 8 to 16 machines we win about 5 minutes but pay roughly a quarter more machine-minutes. The closer to the overhead, the less point in adding. Reality is worse than the model: shards are uneven and the workers of one machine compete for CPU.

Two ways to cut the time

Option 1

More slots

Shards and workers. Quick to turn on, but you pay in money and in load on the environment, and the gain has a ceiling.

Option 2

Less work

Move checks to the API level, remove duplicates, a faster setup. Slower to do, but cuts both time and cost.

Figure 1. It is not either-or: first the calculation, then both levers in order of price.

Solution. The config and the run look like this:

export default defineConfig({
  fullyParallel: true,
  workers: process.env.CI ? 8 : undefined,
  reporter: process.env.CI ? 'blob' : 'html',
});

// run one of 8 parts on a machine:
// npx playwright test --shard=3/8
  • Test isolation. Each test creates its own data. Without it parallelism gives failures from conflicts, not speed.
  • Sharding and reports. Each machine gets its part through --shard and writes a blob report; a separate job merges them with merge-reports.
  • Preconditions through the API and login through a saved storageState, so no test spends seconds on the UI.
  • A prepared image with browsers and dependencies, to avoid paying minutes for installation on every machine.
  • Reviewing the pyramid. Part of the 2000 e2e can move to the API level: that cuts both time and cost, unlike new machines.

Trade-offs. 64 parallel sessions may «knock over» a shared staging: the DB, request limits, data. Then there are more shards while the run does not get faster, only timeouts grow. The environment must be scaled too, or each shard given its own. There is an organisational price as well: eight machines (64 slots) on every merge is a CI budget someone has to approve.

Metrics. Pipeline time by p50 and p95, not the mean. The share of unstable tests, because retries eat the budget. Shard unevenness: the longest against the average. The cost of one run in machine-minutes. The 15-minute target must hold at p95, otherwise a queue for merging appears anyway.

Limits and alternatives. The calculation assumes equal test durations and balanced shards. By default Playwright splits the suite by the number of test groups, not by their time, so one shard with heavy tests can drag everything (see the lesson on workers and shards). If what matters is not the whole suite but a quick signal, the PR set can be narrowed (smoke and critical scenarios) and the full suite left for main. That is a different requirement: «15 minutes for everything» and «5 minutes for a signal» have different solutions.

Common mistakes.

  • Counting without overhead: 667 / 15 = 45 slots looks neat, but then 18 minutes appear instead of 15.
  • Adding shards without looking at the environment: the ceiling is there, not in the number of machines.
  • Going parallel without data isolation: the time gain is bought with flakiness.
  • Staying silent about cost: «just 64 slots» without a price is not an answer for a Senior.
  • Not measuring after the changes: the 15-minute target stays an assumption.

Check yourself

One of the 8 shards has 20% more work than the others. What happens to the 15-minute target in the model above?

Answer

A balanced shard carries 667 / 64 ≈ 10.4 min of tests. With 20% extra that is ≈ 12.5 min, plus 3 min of overhead, about 15.5 min in total: the target is missed even with 64 perfectly chosen slots. The longest shard sets the time, so unevenness is a metric.

Why might the answer «take 16 machines instead of 8» not shorten the run?

Answer

Overhead does not divide across machines, and the shared environment (DB, limits) may already be at its edge. Extra sessions give timeouts, not speed, and the cost grows. First find the bottleneck and cut the work, then add slots.

In an interview. Junior: First I calculate: 2000 tests of 20 seconds is about 11 hours sequentially, so 15 minutes needs dozens of parallel slots. Then I spread the tests over workers and machines with isolated data. Middle/Senior: I count with overhead: 3 minutes of start leaves 12 for tests, which is about 56 slots, and I take 64 with a margin. Data isolation, sharding with blob reports, a prepared image. In parallel I review the pyramid, because moving part of the e2e to the API is cheaper than machines. I name the price: more shards multiply the cost and load staging. I measure p95 time, shard unevenness and the share of unstable tests.

Configuration, environments and secrets

Configuration is kept as a separate layer so one framework runs on any environment without code changes. A single module reads the environment variables and validates them at startup, so a missing variable fails before the first test and is named. Environments are data rather than branches in code, secrets come from the CI secret store, and GitHub Actions does not pass them to pull request runs from forks.

System design · Framework

The test is green locally and fails in CI: BASE_URL is empty. Where should configuration live?

A CI run starts, passes three hundred tests and fails with Invalid URL because one environment variable is not set. On the local machine it was in the developer's shell. One framework must run locally, on a PR environment and on staging without code changes, so configuration is a separate layer. This lesson covers how to keep it, where secrets live and how to share a core between teams.

How it works and why. The environment changes more often than scenarios, and a mistake in it is expensive: it shows up late and looks like a test failure. Three principles follow. First: all environment variables are read in one place and validated at startup. Second: secrets never reach the repository. Third: execution settings (timeouts, retries, workers) live in the Playwright config, not scattered over tests.

Where the environment is read

Typical

process.env in tests

Dozens of files read the variable. BASE_URL forgotten: a failure at the 300th test with a confusing error.

Better

One point with validation

One module reads and checks everything at startup. A variable is missing: the run does not start and the error names it.

Figure 1. A failure at startup costs seconds, a failure mid-run costs hours.

In practice this is a schema (for example with the zod library): a module describes the required variables and fails on import if something is missing. Since the Playwright config imports this module, the error occurs before the first test.

import { z } from 'zod';

const schema = z.object({
  BASE_URL: z.url(),
  API_URL: z.url(),
  TEST_USER_PASSWORD: z.string().min(1),
});

// throws at startup, listing the missing variables
export const env = schema.parse(process.env);

The config uses the typed env rather than process.env:

import { defineConfig, devices } from '@playwright/test';
import { env } from './config/env';

export default defineConfig({
  fullyParallel: true,
  retries: process.env.CI ? 1 : 0,
  workers: process.env.CI ? 8 : undefined,
  reporter: process.env.CI ? 'blob' : 'html',
  use: { baseURL: env.BASE_URL, trace: 'on-first-retry' },
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
      dependencies: ['setup'],
    },
  ],
});

A setup project with a dependency is the standard way to log in once and save a storageState that all tests of the project then use. Projects separate suites (api, chromium, mobile), and they can be run separately with --project.

Environments as data. Addresses, flags and test account logins per environment are data, not code. They are set with environment variables or a separate file per environment (an .env.example template in the repository, the real .env files in .gitignore). The framework code has no branches like «if staging, then…», because each such branch is one more way to break a run.

Secrets. API keys and test user passwords come from the CI secret store or a vault and are not in the repository. Three nuances that set a thoughtful answer apart: GitHub Actions does not pass secrets to pull request runs from forks, so tests that need them get an empty value and must be skipped rather than left to fail (the env schema then makes such a secret optional, or the run stops at startup); values in the log are masked only when they match a known secret verbatim (a transformed or split secret ends up in the log), so they are not printed at all; where the provider supports it, short-lived credentials (OIDC) are better than a long key in a variable. Test accounts have minimal rights and are not the accounts of real people.

Several teams. When five teams write tests, the shared core (clients, fixtures, config, utilities) is worth separating, while tests stay next to the teams' services. Then the core develops centrally and the teams do not block each other.

A shared core for several teams

Option 1

A versioned package

Teams pull a version, the core develops centrally. The price: core and tests drift apart in versions, releases are needed.

Option 2

One repo with workspaces

A core change and the tests in one PR, no versions. The price: a shared CI and discipline of code owners.

Figure 2. Both are legitimate: the choice depends on the number of teams and who owns the core.

Limits and alternatives. Validation does not know whether a variable is right: BASE_URL may point to production and the schema will not catch it. For dangerous actions an explicit guard helps: the framework refuses to write data if the URL matches a list of forbidden ones. For a small project a separate module with zod is overkill: a function that throws on a missing variable is enough. Per-environment config files are handy while there are a few; when there are dozens, one template with overrides through variables is better.

Common mistakes.

  • Reading process.env in tests and helpers: a missing variable shows up mid-run and with the wrong error.
  • Defaults that point to staging or, worse, production: a forgotten BASE_URL does not fail but quietly runs the tests against someone else's environment.
  • Committing .env with real passwords: even after deletion they stay in the history.
  • Scattering timeouts over tests: the run cannot be sped up or slowed down with one change.
  • Sharing a core between teams with no owner and no versions: one team's change breaks everyone.

Check yourself

Why is it better to catch a missing BASE_URL by validation on config import than at the moment of first use?

Answer

Validation fails before the first test and names the variable, while an error at the moment of use appears mid-run (say, at the 300th test) and looks like a test failure. Diagnosis takes far longer.

A CI test from a fork did not get a secret and failed on login. Is it a framework bug?

Answer

No. GitHub Actions does not pass secrets to pull request runs from forks. Tests that need a secret must not start there, or must be marked as skipped, not fail. The solution: a separate suite without secrets for forks, the full suite after review in a trusted branch.

In an interview. Junior: Configuration is a separate layer for me: one point that reads environment variables, secrets only from CI, timeouts in the Playwright config. That lets me run on any environment with no code change. Middle/Senior: One module with startup validation reads the variables, so the error appears before the first test and names the variable. Environments are data, not branches in code. I take secrets from the CI store, never print them, remember they are not available from forks, and use short-lived credentials where possible. For several teams I move the core into a separate package or a workspace and choose by the number of teams, because a package gives independence at the price of versions.