8000 Refactor admin-ui Playwright specs to action-oriented helpers by edewit · Pull Request #52267 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions js/apps/admin-ui/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pnpm lint
## Integration testing with Playwright

This repository contains integration tests developed with the [Playwright framework](https://playwright.dev/).
For conventions on how tests should be structured and written, see the [Playwright Test Style Guide](./test/README.md).

### Prerequisites

Expand Down
76 changes: 76 additions & 0 deletions js/apps/admin-ui/test/README.md
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Playwright Test Style Guide

This document describes how integration tests under `js/apps/admin-ui/test` should be written.

## Core principle

Tests should read like a user scenario. Prefer high-level action helpers over inline selector logic.

Use this style:

```ts
await login(page, { to: toAddUser({ realm: testBed.realm }) });

await fillUserForm(page, { username: "test-user" });
await joinGroup(page, ["test-group"]);
await clickSaveButton(page);
await assertNotificationMessage(page, "The user has been created");
```

The `*.spec.ts` file should communicate intent. Low-level Playwright details should live in helper files.

## File layout and naming

- Keep test files in `*.spec.ts`.
- Add companion helper files in the same folder (for example `main.ts`, `users.ts`, `flow.ts`).
- Keep helper names action-oriented and explicit:
- `login`, `goToUsers`, `fillUserForm`, `joinGroup`, `clickSaveButton`
- `assertNotificationMessage`, `assertRowExists`
- Use these prefixes consistently:
- `goTo*` for navigation
- `fill*` for form entry
- `select*` / `toggle*` / `click*` for user actions
- `assert*` for checks

## What goes in specs vs helpers

- `*.spec.ts` should contain:
- test setup
- scenario flow
- assertions that explain expected behavior
- Helper `*.ts` files should contain:
- selectors and locator details
- reusable UI actions
- reusable assertions
- Avoid embedding repeated selectors in specs. If a step appears in more than one test, extract it.

## Navigation and setup conventions

- Prefer route helpers and explicit destinations in login:
- `await login(page, { to: toUsers({ realm: testBed.realm }) });`
- For isolated realm data, prefer `createTestBed()` and `await using` so cleanup is automatic:
- `await using testBed = await createTestBed({ ...overrides });`
- Keep test data local to each test so scenarios are easy to understand.

## Selector conventions

- Prefer resilient selectors in helpers:
- first choice: `getByTestId`
- second choice: semantic queries (`getByRole`, `getByLabel`)
- Avoid brittle selectors (deep CSS chains, text-dependent selectors that are not stable).
- Keep selector changes localized to helper files to reduce churn.

## Assertions and stability

- Assert user-visible outcomes after meaningful actions (for example success notifications, row presence, URL change).
- Prefer explicit helper assertions such as `assertNotificationMessage(...)`.
- Rely on Playwright auto-waiting and expectations instead of manual sleeps.
- Do not use `waitForTimeout()` unless there is no better technical option and the reason is documented.

## Test design checklist

- Can the spec be read top-to-bottom as a scenario?
- Are action/assertion helper names describing intent clearly?
- Are selectors hidden in helpers?
- Is setup isolated and cleanup automatic?
- Are assertions validating behavior that matters to users?
107 changes: 44 additions & 63 deletions js/apps/admin-ui/test/clients/ssf-receiver.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import { expect, test, type Page } from "@playwright/test";
import { test } from "@playwright/test";
import { v4 as uuid } from "uuid";
import { toSsfClientTab } from "../../src/clients/routes/ClientSsfTab.tsx";
import adminClient from "../utils/AdminClient.ts";
import { login, navigateTo } from "../utils/login.ts";
import { assertNotificationMessage } from "../utils/masthead.ts";
import {
assertSsfAudienceValue,
assertSsfPollDeliveryMethodUnchecked,
assertSsfPushAndPollDeliveryMethodsChecked,
assertSsfPushDeliveryMethodChecked,
assertSsfReceiverSaveButtonVisible,
clickSsfReceiverRevert,
clickSsfReceiverSave,
disableSsfPollDeliveryMethod,
fillSsfAudience,
loginToSsfTab,
navigateToSsfTab,
} from "./ssf.ts";

// Exercises the Receiver sub-tab of a client's SSF view — the primary
// configuration form (Save / Revert). The integration server is always
Expand All @@ -16,14 +27,6 @@ test.describe.serial("Client SSF receiver", () => {
const clientId = `ssf-receiver-client-${uuid()}`;
const audience = "https://receiver.example.com/ssf";

// TextControl derives its data-testid from the form field name, which is the
// attribute path with dots after the first replaced by 🍺 (see
// convertAttributeNameToForm/beerify in src/util.ts). We reproduce that
// transform here rather than importing the helper — src/util.ts pulls the
// @keycloak/keycloak-ui-shared runtime into the Playwright transform, which
// fails to resolve — so the 🍺 path isn't embedded as a literal.
const audienceTestId = `attributes.${"ssf.streamAudience".replaceAll(".", "🍺")}`;

let clientUuid: string;

test.beforeAll(async () => {
Expand All @@ -45,78 +48,56 @@ test.describe.serial("Client SSF receiver", () => {
await adminClient.deleteRealm(realmName);
});

/**
* Navigate to the client's SSF Receiver sub-tab (the default SSF sub-tab).
* The integration server is always started with the `ssf` feature enabled
* (see js/apps/keycloak-server/scripts/start-server.js, #49977), so the SSF
* tab must render — assert it rather than skip, so a missing tab fails loudly.
*/
async function goToReceiverTab(page: Page) {
await login(page, {
to: toSsfClientTab({
realm: realmName,
clientId: clientUuid,
tab: "receiver",
}),
});

await expect(page.getByTestId("ssfTab")).toBeVisible({ timeout: 15_000 });
await expect(page.getByTestId("ssfReceiverSave")).toBeVisible();
}

// Runs first so the client is still pristine (audience empty), giving Revert
// a deterministic baseline to restore to.
test("reverts unsaved edits", async ({ page }) => {
await goToReceiverTab(page);

const audienceField = page.getByTestId(audienceTestId);
await expect(audienceField).toHaveValue("");

await audienceField.fill("temporary-unsaved-value");
await page.getByTestId("ssfReceiverRevert").click();
await loginToSsfTab(page, {
realm: realmName,
clientUuid,
tab: "receiver",
});
await assertSsfReceiverSaveButtonVisible(page);
await assertSsfAudienceValue(page, "");

await expect(audienceField).toHaveValue("");
await fillSsfAudience(page, "temporary-unsaved-value");
await clickSsfReceiverRevert(page);
await assertSsfAudienceValue(page, "");
});

test("saves receiver config and persists it across a reload", async ({
page,
}) => {
await goToReceiverTab(page);
await loginToSsfTab(page, {
realm: realmName,
clientUuid,
tab: "receiver",
});
await assertSsfReceiverSaveButtonVisible(page);

// A plain text field...
await page.getByTestId(audienceTestId).fill(audience);
await fillSsfAudience(page, audience);

// ...and the custom delivery-method checkboxes, which drive the
// ssf.allowedDeliveryMethods attribute. Both render checked on a fresh
// receiver (unset = both allowed); unchecking poll should persist "push".
const pushCheckbox = page.getByTestId("ssfAllowedDeliveryMethods.push");
const pollCheckbox = page.getByTestId("ssfAllowedDeliveryMethods.poll");
await expect(pushCheckbox).toBeChecked();
await expect(pollCheckbox).toBeChecked();
await pollCheckbox.click();
await expect(pollCheckbox).not.toBeChecked();
await assertSsfPushAndPollDeliveryMethodsChecked(page);
await disableSsfPollDeliveryMethod(page);
await assertSsfPollDeliveryMethodUnchecked(page);

await page.getByTestId("ssfReceiverSave").click();
await clickSsfReceiverSave(page);
await assertNotificationMessage(page, "Client successfully updated");

// Re-navigate from scratch (no re-login — the session persists, so
// login() would hang waiting for a sign-in form that never appears) and
// confirm the values round-tripped through storage and back into the form.
await navigateTo(
page,
toSsfClientTab({
realm: realmName,
clientId: clientUuid,
tab: "receiver",
}),
);
await expect(page.getByTestId("ssfReceiverSave")).toBeVisible();
await expect(page.getByTestId(audienceTestId)).toHaveValue(audience);
await expect(
page.getByTestId("ssfAllowedDeliveryMethods.push"),
).toBeChecked();
await expect(
page.getByTestId("ssfAllowedDeliveryMethods.poll"),
).not.toBeChecked();
await navigateToSsfTab(page, {
realm: realmName,
clientUuid,
tab: "receiver",
});
await assertSsfReceiverSaveButtonVisible(page);
await assertSsfAudienceValue(page, audience);
await assertSsfPushDeliveryMethodChecked(page);
await assertSsfPollDeliveryMethodUnchecked(page);
});
});
82 changes: 40 additions & 42 deletions js/apps/admin-ui/test/clients/ssf-stream.spec.ts
A989
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
import { expect, test, type Page } from "@playwright/test";
import { test } from "@playwright/test";
import { v4 as uuid } from "uuid";
import { toSsfClientTab } from "../../src/clients/routes/ClientSsfTab.tsx";
import adminClient from "../utils/AdminClient.ts";
import { login } from "../utils/login.ts";
import { assertNotificationMessage } from "../utils/masthead.ts";
import {
assertCreateSsfStreamEndpointErrorHidden,
assertCreateSsfStreamEndpointErrorVisible,
assertCreateSsfStreamEndpointVisible,
assertCreateSsfStreamSubmitDisabled,
assertCreateSsfStreamSubmitEnabled,
assertRegisteredSsfStreamView,
assertSsfStreamEmptyStateVisible,
fillCreateSsfStreamDescription,
fillCreateSsfStreamEndpoint,
loginToSsfTab,
openCreateSsfStreamForm,
submitCreateSsfStream,
} from "./ssf.ts";

// Exercises the admin-console "Create stream" flow on a client's SSF Stream
// sub-tab. The integration server is always started with the `ssf` feature
Expand Down Expand Up @@ -42,65 +54,51 @@ test.describe.serial("Client SSF stream creation", () => {
await adminClient.deleteRealm(realmName);
});

/**
* Navigate to the client's SSF Stream sub-tab. The integration server is
* always started with the `ssf` feature enabled (see
* js/apps/keycloak-server/scripts/start-server.js, #49977), so the SSF tab
* must render — assert it rather than skip, so a missing tab fails loudly.
*/
async function goToStreamTab(page: Page) {
await login(page, {
to: toSsfClientTab({
realm: realmName,
clientId: clientUuid,
tab: "stream",
}),
});

await expect(page.getByTestId("ssfTab")).toBeVisible({ timeout: 15_000 });
}

test("validates the push endpoint URL before allowing submit", async ({
page,
}) => {
await goToStreamTab(page);
await loginToSsfTab(page, {
realm: realmName,
clientUuid,
tab: "stream",
});

// Open the create-stream form from the empty state.
await expect(page.getByTestId("empty-state")).toBeVisible();
await page.getByRole("button", { name: "Create stream" }).click();
await assertSsfStreamEmptyStateVisible(page);
await openCreateSsfStreamForm(page);

// PUSH is the default delivery method, so the endpoint URL field is
// shown. With it empty, the submit button stays disabled.
const submit = page.getByTestId("ssfCreateStreamSubmit");
await expect(page.getByTestId("ssfCreateStreamEndpointUrl")).toBeVisible();
await expect(submit).toBeDisabled();
await assertCreateSsfStreamEndpointVisible(page);
await assertCreateSsfStreamSubmitDisabled(page);

// A non-http(s) URL is rejected inline and submit remains disabled.
await page.getByTestId("ssfCreateStreamEndpointUrl").fill("ftp://nope");
await expect(page.getByTestId("endpointUrl-helper")).toBeVisible();
await expect(submit).toBeDisabled();
await fillCreateSsfStreamEndpoint(page, "ftp://nope");
await assertCreateSsfStreamEndpointErrorVisible(page);
await assertCreateSsfStreamSubmitDisabled(page);

// A valid https URL clears the error and enables submit.
await page.getByTestId("ssfCreateStreamEndpointUrl").fill(pushEndpoint);
await expect(page.getByTestId("endpointUrl-helper")).toBeHidden();
await expect(submit).toBeEnabled();
await fillCreateSsfStreamEndpoint(page, pushEndpoint);
await assertCreateSsfStreamEndpointErrorHidden(page);
await assertCreateSsfStreamSubmitEnabled(page);
});

test("creates a push stream", async ({ page }) => {
await goToStreamTab(page);
await loginToSsfTab(page, {
realm: realmName,
clientUuid,
tab: "stream",
});

await page.getByRole("button", { name: "Create stream" }).click();
await page.getByTestId("ssfCreateStreamEndpointUrl").fill(pushEndpoint);
await page
.getByTestId("ssfCreateStreamDescription")
.fill("Created by test");
await page.getByTestId("ssfCreateStreamSubmit").click();
await openCreateSsfStreamForm(page);
await fillCreateSsfStreamEndpoint(page, pushEndpoint);
await fillCreateSsfStreamDescription(page, "Created by test");
await submitCreateSsfStream(page);

await assertNotificationMessage(page, "SSF stream created successfully.");

// The empty state is replaced by the registered-stream view, which
// surfaces the stream id and a refresh action.
await expect(page.getByTestId("ssfRefresh")).toBeVisible();
await expect(page.getByTestId("empty-state")).toBeHidden();
await assertRegisteredSsfStreamView(page);
});
});
Loading
Loading
0