From ee9a5d199f90991e6cc24e0b81f3ffa1ee36d45e Mon Sep 17 00:00:00 2001 From: Danilo Lakovic Date: Fri, 20 Nov 2026 00:32:59 +0100 Subject: [PATCH 1/4] Build the e2e API helpers on the generated client - Add e2e/support/sdk-request.ts: typed GET, POST, PATCH, DELETE and multipart calls on Playwright's request context, taking the address from a generated URL builder or a server href and collapsing the leading double slash a builder returns for an href - Move the set-up and clean-up helpers of api.ts onto them; endpoint tables, task reads and uploads use the generated builders and types - Let the delete spec name its endpoints through the builders --- e2e/remote/delete.spec.ts | 12 ++- e2e/support/api.ts | 185 ++++++++++++++++++++----------------- e2e/support/sdk-request.ts | 130 ++++++++++++++++++++++++++ 3 files changed, 236 insertions(+), 91 deletions(-) create mode 100644 e2e/support/sdk-request.ts diff --git a/e2e/remote/delete.spec.ts b/e2e/remote/delete.spec.ts index 183cd122..25dc26dc 100644 --- a/e2e/remote/delete.spec.ts +++ b/e2e/remote/delete.spec.ts @@ -1,4 +1,8 @@ import { expect, test } from '@playwright/test'; +import { getContentguardsCoreRbacListUrl } from '@pulp-ui/sdk/core/contentguards-rbac'; +import { getDistributionsFileFileListUrl } from '@pulp-ui/sdk/file/distributions-file'; +import { getPublicationsFileFileListUrl } from '@pulp-ui/sdk/file/publications-file'; +import { getRepositoriesFileFileListUrl } from '@pulp-ui/sdk/file/repositories-file'; import { type PulpObject, TestObjects } from '../support/api'; import { title } from '../support/sign-in'; @@ -7,8 +11,8 @@ import { title } from '../support/sign-in'; // protects. The dialog names all three, marks the guarded one and asks for the // repository name before it deletes anything. -const REPOSITORIES = 'repositories/file/file/'; -const DISTRIBUTIONS = 'distributions/file/file/'; +const REPOSITORIES = getRepositoriesFileFileListUrl(); +const DISTRIBUTIONS = getDistributionsFileFileListUrl(); let objects: TestObjects; let repository: PulpObject; @@ -24,10 +28,10 @@ test.beforeAll(async () => { repository = await objects.create(REPOSITORIES, { name: objects.name('doomed'), }); - const publication = await objects.create('publications/file/file/', { + const publication = await objects.create(getPublicationsFileFileListUrl(), { repository: repository.pulp_href, }); - const guard = await objects.create('contentguards/core/rbac/', { + const guard = await objects.create(getContentguardsCoreRbacListUrl(), { name: objects.name('guard'), }); diff --git a/e2e/support/api.ts b/e2e/support/api.ts index eea2fec4..8bb336b7 100644 --- a/e2e/support/api.ts +++ b/e2e/support/api.ts @@ -1,16 +1,45 @@ -import { - type APIRequestContext, - type APIResponse, - request, -} from '@playwright/test'; +import { type APIRequestContext, request } from '@playwright/test'; +import { getRepositoriesAnsibleAnsibleListUrl } from '@pulp-ui/sdk/ansible/repositories-ansible'; +import { getContentguardsCoreRbacListUrl } from '@pulp-ui/sdk/core/contentguards-rbac'; +import type { AsyncOperationResponse } from '@pulp-ui/sdk/core/models/async-operation-response.zod'; +import type { TaskResponse } from '@pulp-ui/sdk/core/models/tasks/task-response.zod'; +import { getRolesListUrl } from '@pulp-ui/sdk/core/roles'; +import { getTasksReadUrl } from '@pulp-ui/sdk/core/tasks'; +import { getDistributionsDebAptListUrl } from '@pulp-ui/sdk/deb/distributions-apt'; +import { getPublicationsDebAptListUrl } from '@pulp-ui/sdk/deb/publications-apt'; +import { getRemotesDebAptListUrl } from '@pulp-ui/sdk/deb/remotes-apt'; +import { getRepositoriesDebAptListUrl } from '@pulp-ui/sdk/deb/repositories-apt'; +import { getContentFileFilesCreateUrl } from '@pulp-ui/sdk/file/content-files'; +import { getDistributionsFileFileListUrl } from '@pulp-ui/sdk/file/distributions-file'; +import { getPublicationsFileFileListUrl } from '@pulp-ui/sdk/file/publications-file'; +import { getRemotesFileFileListUrl } from '@pulp-ui/sdk/file/remotes-file'; +import { getRepositoriesFileFileListUrl } from '@pulp-ui/sdk/file/repositories-file'; +import { getDistributionsPythonPypiListUrl } from '@pulp-ui/sdk/python/distributions-pypi'; +import { getPublicationsPythonPypiListUrl } from '@pulp-ui/sdk/python/publications-pypi'; +import { getRemotesPythonPythonListUrl } from '@pulp-ui/sdk/python/remotes-python'; +import { getRepositoriesPythonPythonListUrl } from '@pulp-ui/sdk/python/repositories-python'; +import { getDistributionsRpmRpmListUrl } from '@pulp-ui/sdk/rpm/distributions-rpm'; +import { getPublicationsRpmRpmListUrl } from '@pulp-ui/sdk/rpm/publications-rpm'; +import { getRemotesRpmRpmListUrl } from '@pulp-ui/sdk/rpm/remotes-rpm'; +import { getRepositoriesRpmRpmListUrl } from '@pulp-ui/sdk/rpm/repositories-rpm'; import { randomBytes } from 'node:crypto'; import { basicAuthorization } from '../../src/utilities/basic-authorization'; import { account } from './accounts'; import { origin } from './env'; +import { + apiCall, + apiDelete, + apiGet, + apiPatch, + apiPostForm, + resolveApiUrl, +} from './sdk-request'; // Set-up and clean-up of the objects a remote test needs, through the REST API // with the admin account of the run. Basic-authenticated calls carry no session -// and need no CSRF token. +// and need no CSRF token. Every address comes from a URL builder of the +// generated client (or from a href the server returned) and every answer is +// typed by its models; sdk-request.ts sends them. // // Every object a test writes is named zz-e2e---. The run // id is chosen once per run (and handed to the worker processes through the @@ -45,10 +74,16 @@ export interface PulpObject { [field: string]: unknown; } -interface Task { +// What a task reports of itself that the helpers read; the rest of the model +// is the generated one. +type Task = TaskResponse & { state: string; created_resources: string[]; - error?: { description?: string } | null; +}; + +interface Page { + results: PulpObject[]; + next: string | null; } // Endpoints that hold objects created by the tests, deepest dependants first: @@ -56,32 +91,32 @@ interface Task { // objects under these endpoints are ever deleted. Publications carry no name of // their own; every other kind must carry the scope's prefix. const DISTRIBUTIONS = [ - 'distributions/file/file/', - 'distributions/deb/apt/', - 'distributions/rpm/rpm/', - 'distributions/python/pypi/', + getDistributionsFileFileListUrl(), + getDistributionsDebAptListUrl(), + getDistributionsRpmRpmListUrl(), + getDistributionsPythonPypiListUrl(), ]; const PUBLICATIONS = [ - 'publications/file/file/', - 'publications/deb/apt/', - 'publications/rpm/rpm/', - 'publications/python/pypi/', + getPublicationsFileFileListUrl(), + getPublicationsDebAptListUrl(), + getPublicationsRpmRpmListUrl(), + getPublicationsPythonPypiListUrl(), ]; const REPOSITORIES = [ - 'repositories/file/file/', - 'repositories/deb/apt/', - 'repositories/rpm/rpm/', - 'repositories/python/python/', - 'repositories/ansible/ansible/', + getRepositoriesFileFileListUrl(), + getRepositoriesDebAptListUrl(), + getRepositoriesRpmRpmListUrl(), + getRepositoriesPythonPythonListUrl(), + getRepositoriesAnsibleAnsibleListUrl(), ]; const REMOTES = [ - 'remotes/file/file/', - 'remotes/deb/apt/', - 'remotes/rpm/rpm/', - 'remotes/python/python/', + getRemotesFileFileListUrl(), + getRemotesDebAptListUrl(), + getRemotesRpmRpmListUrl(), + getRemotesPythonPythonListUrl(), ]; -const CONTENT_GUARDS = ['contentguards/core/rbac/']; -const ROLES = ['roles/']; +const CONTENT_GUARDS = [getContentguardsCoreRbacListUrl()]; +const ROLES = [getRolesListUrl()]; // The endpoint groups in the order objects can be deleted. const DELETION_ORDER = [ @@ -101,20 +136,18 @@ const NAMED_DELETION_ORDER = DELETION_ORDER.filter( const NAMED_ENDPOINTS = NAMED_DELETION_ORDER.flat(); function groupOf(href: string): number { + const target = resolveApiUrl(href); return DELETION_ORDER.findIndex((endpoints) => - endpoints.some((path) => href.startsWith(`${API_BASE}${path}`)), + endpoints.some((endpoint) => target.startsWith(endpoint)), ); } +// An address as a spec gives it: a builder's address or a server href, or a +// path below the API root. function url(pathOrHref: string): string { return pathOrHref.startsWith('/') ? pathOrHref : `${API_BASE}${pathOrHref}`; } -async function fail(what: string, response: APIResponse): Promise { - const body = (await response.text()).slice(0, 300); - throw new Error(`${what}: ${response.status()} ${body}`); -} - // The objects of one spec file on one deployment. Create them through this // class, call cleanUp() in afterAll. export class TestObjects { @@ -142,16 +175,11 @@ export class TestObjects { async list(path: string, params: Record = {}) { const results: PulpObject[] = []; for (let offset = 0; ; offset += 100) { - const response = await this.api.get(url(path), { - params: { ...params, limit: '100', offset: String(offset) }, + const page = await apiGet(this.api, url(path), { + ...params, + limit: '100', + offset: String(offset), }); - if (!response.ok()) { - await fail(`GET ${path}`, response); - } - const page = (await response.json()) as { - results: PulpObject[]; - next: string | null; - }; results.push(...page.results); if (!page.next) { return results; @@ -160,25 +188,21 @@ export class TestObjects { } async get(href: string): Promise { - const response = await this.api.get(url(href)); - if (!response.ok()) { - await fail(`GET ${href}`, response); - } - return (await response.json()) as PulpObject; + return apiGet(this.api, url(href)); } // Waits for a task to finish and returns it; a failed or canceled task throws. async waitForTask(taskHref: string, timeoutMs = 120_000): Promise { const deadline = Date.now() + timeoutMs; for (;;) { - const task = (await this.get(taskHref)) as unknown as Task; + const task = await apiGet(this.api, getTasksReadUrl(taskHref)); if (task.state === 'completed') { return task; } if (task.state === 'failed' || task.state === 'canceled') { - throw new Error( - `task ${taskHref} ${task.state}: ${task.error?.description ?? ''}`, - ); + const description = (task.error as { description?: string } | undefined) + ?.description; + throw new Error(`task ${taskHref} ${task.state}: ${description ?? ''}`); } if (Date.now() > deadline) { throw new Error( @@ -202,17 +226,15 @@ export class TestObjects { ); } - const response = await this.api.post(url(path), { data: body }); - if (!response.ok()) { - await fail(`POST ${path}`, response); - } - const answer = (await response.json()) as PulpObject & { task?: string }; - if (response.status() === 201) { + const { status, body: answer } = await apiCall< + PulpObject & AsyncOperationResponse + >(this.api, 'POST', url(path), { data: body }); + if (status === 201) { this.registered.push(answer.pulp_href); return answer; } - const task = await this.waitForTask(answer.task as string); + const task = await this.waitForTask(answer.task); const href = task.created_resources[0] as string; this.registered.push(href); return this.get(href); @@ -220,11 +242,11 @@ export class TestObjects { // Changes an object and waits for the task the server starts. async patch(href: string, body: Record) { - const response = await this.api.patch(url(href), { data: body }); - if (!response.ok()) { - await fail(`PATCH ${href}`, response); - } - const answer = (await response.json()) as { task?: string }; + const answer = await apiPatch>( + this.api, + url(href), + body, + ); if (answer.task) { await this.waitForTask(answer.task); } @@ -240,14 +262,13 @@ export class TestObjects { throw new Error(`refusing to delete ${href}: not a known test endpoint`); } - const current = await this.api.get(url(href)); - if (current.status() === 404) { + const current = await apiCall(this.api, 'GET', url(href), { + accept: [404], + }); + if (current.status === 404) { return; } - if (!current.ok()) { - await fail(`GET ${href}`, current); - } - const { name } = (await current.json()) as PulpObject; + const { name } = current.body; // a publication belongs to a repository version and has no name const unnamedKind = DELETION_ORDER[group] === PUBLICATIONS; if ( @@ -259,17 +280,9 @@ export class TestObjects { ); } - const response = await this.api.delete(url(href)); - if (response.status() === 404) { - return; - } - if (!response.ok()) { - await fail(`DELETE ${href}`, response); - } - if (response.status() === 202) { - await this.waitForTask( - ((await response.json()) as { task: string }).task, - ); + const answer = await apiDelete(this.api, url(href), [404]); + if (answer.status === 202 && answer.body?.task) { + await this.waitForTask(answer.body.task); } } @@ -293,8 +306,10 @@ export class TestObjects { ); } - const response = await this.api.post(url('content/file/files/'), { - multipart: { + const answer = await apiPostForm( + this.api, + getContentFileFilesCreateUrl(), + { file: { name: relativePath.split('/').pop() as string, mimeType: 'text/plain', @@ -303,11 +318,7 @@ export class TestObjects { relative_path: relativePath, repository: repositoryHref, }, - }); - if (!response.ok()) { - await fail('POST content/file/files/', response); - } - const answer = (await response.json()) as { task: string }; + ); return this.waitForTask(answer.task); } diff --git a/e2e/support/sdk-request.ts b/e2e/support/sdk-request.ts new file mode 100644 index 00000000..4cd3d600 --- /dev/null +++ b/e2e/support/sdk-request.ts @@ -0,0 +1,130 @@ +import type { APIRequestContext, APIResponse } from '@playwright/test'; + +// Typed requests for the e2e support code. The address of a call comes from a +// URL builder of the generated client (or from a href the server returned) and +// the shapes of the answers from the generated types; the transport is +// Playwright's request context. The browser mutator of the client is never +// used: it belongs to the page, and a test must not depend on the code it is +// checking. +// +// A builder returns "/" and every href starts with "/", so a builder +// given an href yields an address that starts with two slashes. Left alone, +// that reads as a protocol-relative address and the request goes to a host +// named after the first path segment; resolveApiUrl collapses the run of +// slashes the same way the application does before it sends a request. + +// One request and its answer: the status and the body parsed as JSON (or +// undefined when the answer has no body). +export interface ApiAnswer { + status: number; + body: T; +} + +type Params = Record; + +// The address a request goes to: a single leading slash, and the query +// parameters appended to whatever query the address already carries. +export function resolveApiUrl(url: string, params: Params = {}): string { + const path = url.replace(/^\/+/, '/'); + const query = new URLSearchParams(params).toString(); + if (!query) { + return path; + } + return `${path}${path.includes('?') ? '&' : '?'}${query}`; +} + +async function parse(response: APIResponse): Promise { + const text = await response.text(); + return (text ? JSON.parse(text) : undefined) as T; +} + +// The error of a request the server refused, with the start of its answer. +export async function requestFailure( + method: string, + url: string, + response: APIResponse, +): Promise { + const body = (await response.text()).slice(0, 300); + return new Error(`${method} ${url}: ${response.status()} ${body}`); +} + +interface CallOptions { + params?: Params; + data?: unknown; + // a multipart body, for the endpoints that take a file + multipart?: Record< + string, + string | { name: string; mimeType: string; buffer: Buffer } + >; + // statuses that are not failures besides the 2xx ones, for example 404 for a + // read of an object that may already be gone + accept?: number[]; +} + +// The one place a request is sent. A status outside 2xx and `accept` throws. +export async function apiCall( + api: APIRequestContext, + method: 'GET' | 'POST' | 'PATCH' | 'DELETE', + url: string, + { params, data, multipart, accept = [] }: CallOptions = {}, +): Promise> { + const target = resolveApiUrl(url, params); + const response = await api.fetch(target, { + method, + ...(data === undefined ? {} : { data }), + ...(multipart === undefined ? {} : { multipart }), + }); + if (!response.ok() && !accept.includes(response.status())) { + throw await requestFailure(method, target, response); + } + return { + status: response.status(), + body: response.ok() ? await parse(response) : (undefined as T), + }; +} + +export async function apiGet( + api: APIRequestContext, + url: string, + params?: Params, +): Promise { + return (await apiCall(api, 'GET', url, params ? { params } : {})).body; +} + +export async function apiPost( + api: APIRequestContext, + url: string, + data?: unknown, +): Promise { + return (await apiCall(api, 'POST', url, { data })).body; +} + +// A multipart POST: text fields and file parts. +export async function apiPostForm( + api: APIRequestContext, + url: string, + multipart: NonNullable, +): Promise { + return (await apiCall(api, 'POST', url, { multipart })).body; +} + +export async function apiPatch( + api: APIRequestContext, + url: string, + data?: unknown, +): Promise { + return (await apiCall(api, 'PATCH', url, { data })).body; +} + +// Returns the status, so a caller can tell a deletion the server finished +// (204) from one it started as a task (202), or one that found nothing (404, +// when accepted). +export async function apiDelete( + api: APIRequestContext, + url: string, + accept: number[] = [], +): Promise> { + return apiCall<{ task?: string } | undefined>(api, 'DELETE', url, { + accept, + }); +} From 0b0da271eb02b4c4fcd60baf728f3da3ffbc9d4a Mon Sep 17 00:00:00 2001 From: Danilo Lakovic Date: Fri, 20 Nov 2026 00:39:19 +0100 Subject: [PATCH 2/4] Share the e2e session and API helpers instead of copying them - Add e2e/support/session.ts with the signed-out state, the login through the API for a given account and the matcher for the answer that tells the page what the account may do; the remote, shell and smoke specs use it instead of their own copies - Read through the typed helpers in the specs that built their own requests (paging, status, role and repository reads) and name the endpoints through the generated URL builders - Let clean-up find and delete users and groups of a run by their prefix, as it already does for repositories and roles - Take the storage state paths of the Playwright projects from storageStatePath --- e2e/remote/create.spec.ts | 8 +- e2e/remote/list-order.spec.ts | 15 +-- e2e/remote/list-pages.ts | 10 +- e2e/remote/permissions.editor.spec.ts | 82 +++++++--------- e2e/remote/role-actions.spec.ts | 10 +- e2e/remote/session-helpers.ts | 26 +---- e2e/shell/session-permission-states.spec.ts | 3 +- e2e/smoke/external-login.spec.ts | 22 +---- e2e/support/api.ts | 103 ++++++++++++++------ e2e/support/session.ts | 43 ++++++++ playwright.config.ts | 6 +- 11 files changed, 186 insertions(+), 142 deletions(-) create mode 100644 e2e/support/session.ts diff --git a/e2e/remote/create.spec.ts b/e2e/remote/create.spec.ts index 547132ed..e7d0ef2c 100644 --- a/e2e/remote/create.spec.ts +++ b/e2e/remote/create.spec.ts @@ -1,12 +1,14 @@ import { type Page, expect, test } from '@playwright/test'; +import { getDistributionsFileFileListUrl } from '@pulp-ui/sdk/file/distributions-file'; +import { getRepositoriesFileFileListUrl } from '@pulp-ui/sdk/file/repositories-file'; import { type PulpObject, TestObjects } from '../support/api'; import { title } from '../support/sign-in'; // The save rules of the repository form, run against a real server with // objects of this file's own prefix. Plugin: file, except where noted. -const REPOSITORIES = 'repositories/file/file/'; -const DISTRIBUTIONS = 'distributions/file/file/'; +const REPOSITORIES = getRepositoriesFileFileListUrl(); +const DISTRIBUTIONS = getDistributionsFileFileListUrl(); let objects: TestObjects; @@ -208,7 +210,7 @@ test('a double click on Save sends one repository POST', async ({ page }) => { await page.waitForURL(/repositories\/detail\//); expect( - posts.filter((path) => path.endsWith(`/${REPOSITORIES}`)), + posts.filter((path) => path === REPOSITORIES), 'POST requests to the repository endpoint', ).toHaveLength(1); expect(await objects.list(REPOSITORIES, { name })).toHaveLength(1); diff --git a/e2e/remote/list-order.spec.ts b/e2e/remote/list-order.spec.ts index bf7b74cf..f90a6022 100644 --- a/e2e/remote/list-order.spec.ts +++ b/e2e/remote/list-order.spec.ts @@ -1,5 +1,7 @@ import { expect, test } from '@playwright/test'; +import { getRepositoriesFileFileListUrl } from '@pulp-ui/sdk/file/repositories-file'; import { apiContext } from '../support/api'; +import { apiGet } from '../support/sdk-request'; import { title } from '../support/sign-in'; // A list opens ordered by name, the way the server orders it, so the first @@ -11,13 +13,12 @@ test('the file repository list opens with the repositories in the order the serv }) => { const api = await apiContext(); const names = async (params: Record) => { - const response = await api.get('/pulp/api/v3/repositories/file/file/', { - params: { ...params, ordering: 'name', fields: 'name' }, - }); - expect(response.ok(), 'the API list').toBe(true); - return ( - (await response.json()) as { results: { name: string }[] } - ).results.map(({ name }) => name); + const { results } = await apiGet<{ results: { name: string }[] }>( + api, + getRepositoriesFileFileListUrl(), + { ...params, ordering: 'name', fields: 'name' }, + ); + return results.map(({ name }) => name); }; try { diff --git a/e2e/remote/list-pages.ts b/e2e/remote/list-pages.ts index 5bd15692..b55069fd 100644 --- a/e2e/remote/list-pages.ts +++ b/e2e/remote/list-pages.ts @@ -1,5 +1,7 @@ import { type Page, expect } from '@playwright/test'; +import { getStatusReadUrl } from '@pulp-ui/sdk/core/status'; import { apiContext } from '../support/api'; +import { apiGet } from '../support/sdk-request'; import { title } from '../support/sign-in'; // Every list page of the application, with the plugin that has to be installed @@ -205,15 +207,11 @@ export function installedPlugins(): Promise> { installed ??= (async () => { const api = await apiContext(); try { - const response = await api.get('/pulp/api/v3/status/'); - if (!response.ok()) { - throw new Error(`GET status/ answered ${response.status()}`); - } // A request with credentials the server does not accept is answered // with the health fields only, so a missing list names the cause. - const { versions } = (await response.json()) as { + const { versions } = await apiGet<{ versions?: { component: string }[]; - }; + }>(api, getStatusReadUrl()); if (!Array.isArray(versions)) { throw new Error( 'the status answer has no versions: the admin account was not accepted', diff --git a/e2e/remote/permissions.editor.spec.ts b/e2e/remote/permissions.editor.spec.ts index 582a9ed5..ae3e60f3 100644 --- a/e2e/remote/permissions.editor.spec.ts +++ b/e2e/remote/permissions.editor.spec.ts @@ -5,9 +5,16 @@ import { expect, test, } from '@playwright/test'; +import { getRolesListUrl } from '@pulp-ui/sdk/core/roles'; +import { + getRepositoriesRpmRpmListRolesUrl, + getRepositoriesRpmRpmListUrl, +} from '@pulp-ui/sdk/rpm/repositories-rpm'; import { ACTION_PERMISSIONS } from '../../src/utilities/action-permissions'; import { account } from '../support/accounts'; -import { apiContext } from '../support/api'; +import { apiContext, listAll } from '../support/api'; +import { apiGet } from '../support/sdk-request'; +import { isPermissionsRead } from '../support/session'; import { title } from '../support/sign-in'; // What an account that is neither administrator nor read-only is shown. The @@ -36,15 +43,11 @@ let filePermissions: Set; let pythonPermissions: Set; let owned: { name: string; permissions: Set }; -async function getJson(path: string): Promise { - const response = await api.get(path); - expect(response.ok(), `GET ${path}`).toBe(true); - return (await response.json()) as T; -} - async function rolePermissions(role: string): Promise> { - const { results } = await getJson<{ results: { permissions: string[] }[] }>( - `/pulp/api/v3/roles/?name=${encodeURIComponent(role)}`, + const { results } = await apiGet<{ results: { permissions: string[] }[] }>( + api, + getRolesListUrl(), + { name: role }, ); expect(results, `the role ${role} exists on the server`).toHaveLength(1); return new Set(results[0]?.permissions); @@ -56,31 +59,22 @@ async function ownedRpmRepository( editor: string, permissions: Set, ): Promise<{ name: string; permissions: Set }> { - const found: string[] = []; - for (let offset = 0; ; offset += 100) { - const page = await getJson<{ - results: { name: string; pulp_href: string }[]; - next: string | null; - }>( - `/pulp/api/v3/repositories/rpm/rpm/?limit=100&offset=${offset}&fields=name,pulp_href`, - ); - const assignments = await Promise.all( - page.results.map(async ({ name, pulp_href }) => { - const { roles } = await getJson<{ - roles: { role: string; users: string[] }[]; - }>(`${pulp_href}list_roles/`); - return roles.some( - ({ role, users }) => role === RPM_ROLE && users.includes(editor), - ) - ? name - : null; - }), - ); - found.push(...assignments.filter((name): name is string => !!name)); - if (!page.next) { - break; - } - } + const repositories = await listAll(api, getRepositoriesRpmRpmListUrl(), { + fields: 'name,pulp_href', + }); + const assignments = await Promise.all( + repositories.map(async ({ name, pulp_href }) => { + const { roles } = await apiGet<{ + roles: { role: string; users: string[] }[]; + }>(api, getRepositoriesRpmRpmListRolesUrl(pulp_href)); + return roles.some( + ({ role, users }) => role === RPM_ROLE && users.includes(editor), + ) + ? name + : null; + }), + ); + const found = assignments.filter((name): name is string => !!name); expect( found, 'rpm repositories the editor holds the owner role on', @@ -118,13 +112,7 @@ async function openRepositoryList( plugin: Plugin, query = '', ): Promise { - const permissionsRead = page.waitForResponse( - (response) => - response.request().method() === 'GET' && - /\/pulp\/api\/v3\/users\/[^/]+\/roles\/$/.test( - new URL(response.url()).pathname, - ), - ); + const permissionsRead = page.waitForResponse(isPermissionsRead); await page.goto(`${plugin}/repositories${query}`); await permissionsRead; await expect(title(page, 'Repositories')).toBeVisible(); @@ -247,8 +235,10 @@ test('rpm repositories offer actions on the owned repository only', async ({ // server lists only what the account may read, and no row that is listed // draws a menu. const others = ( - await getJson<{ results: { name: string }[] }>( - '/pulp/api/v3/repositories/rpm/rpm/?limit=20&fields=name', + await apiGet<{ results: { name: string }[] }>( + api, + getRepositoriesRpmRpmListUrl(), + { limit: '20', fields: 'name' }, ) ).results .map(({ name }) => name) @@ -279,11 +269,7 @@ test('deb repositories offer no action', async ({ page }) => { }); test('the sidebar has no Users, Groups or Roles entry', async ({ page }) => { - const permissionsRead = page.waitForResponse((response) => - /\/pulp\/api\/v3\/users\/[^/]+\/roles\/$/.test( - new URL(response.url()).pathname, - ), - ); + const permissionsRead = page.waitForResponse(isPermissionsRead); await page.goto('status'); await permissionsRead; await expect(title(page, 'Status')).toBeVisible(); diff --git a/e2e/remote/role-actions.spec.ts b/e2e/remote/role-actions.spec.ts index 3daaad39..4773da65 100644 --- a/e2e/remote/role-actions.spec.ts +++ b/e2e/remote/role-actions.spec.ts @@ -1,12 +1,14 @@ import { expect, test } from '@playwright/test'; +import { getRolesListUrl } from '@pulp-ui/sdk/core/roles'; import { TestObjects } from '../support/api'; +import { apiCall } from '../support/sdk-request'; import { title } from '../support/sign-in'; // The row actions of the role list against a real server: a custom role is // edited and then deleted from its row, and each change is read back from the // server. Built-in roles are not touched. -const ROLES = 'roles/'; +const ROLES = getRolesListUrl(); let objects: TestObjects; @@ -63,6 +65,8 @@ test('a custom role is edited and deleted from the role list', async ({ await dialog.getByRole('button', { name: 'Delete' }).click(); await expect(page.getByText(/has been successfully deleted/)).toBeVisible(); - const gone = await objects.api.get(role.pulp_href); - expect(gone.status(), 'a read of the deleted role').toBe(404); + const gone = await apiCall(objects.api, 'GET', role.pulp_href, { + accept: [404], + }); + expect(gone.status, 'a read of the deleted role').toBe(404); }); diff --git a/e2e/remote/session-helpers.ts b/e2e/remote/session-helpers.ts index 3ceded80..d8c16ad2 100644 --- a/e2e/remote/session-helpers.ts +++ b/e2e/remote/session-helpers.ts @@ -4,37 +4,21 @@ import { type Response, expect, } from '@playwright/test'; -import { basicAuthorization } from '../../src/utilities/basic-authorization'; import { type Role, account } from '../support/accounts'; -import { origin } from '../support/env'; +import { apiLoginAs } from '../support/session'; import { submitLoginForm } from '../support/sign-in'; export const userMenu = '[data-cy=user-dropdown]'; export const loginMenuItem = '[data-cy=pulp-menu-item-login]'; -// A browser context that holds no session at all, for tests that sign in or -// out. They never touch the storage state shared by the other tests, so -// ending a session here cannot break a later test. -export const signedOut = { cookies: [], origins: [] }; +export { signedOut } from '../support/session'; -// Signs the role's account in inside the given context with the login API. The -// context's request client shares the cookie jar of its pages, so every page -// opened afterwards in that context is signed in. -export async function apiLogin( +// Signs the role's account in inside the given context with the login API. +export function apiLogin( context: BrowserContext, role: Role = 'admin', ): Promise { - const { username, password } = account(role); - const response = await context.request.post( - `${origin()}/pulp/api/v3/login/`, - { - headers: { - Authorization: basicAuthorization(username, password), - 'X-Requested-With': 'XMLHttpRequest', - }, - }, - ); - expect(response.status(), 'API sign in').toBe(201); + return apiLoginAs(context, account(role)); } // True for a call to the login endpoint made with the given method. diff --git a/e2e/shell/session-permission-states.spec.ts b/e2e/shell/session-permission-states.spec.ts index cb16c88c..db03ebff 100644 --- a/e2e/shell/session-permission-states.spec.ts +++ b/e2e/shell/session-permission-states.spec.ts @@ -4,6 +4,7 @@ import { mkdirSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { storageStatePath } from '../support/accounts'; import { type PulpObject, TestObjects } from '../support/api'; +import { signedOut } from '../support/session'; import { coveredAt } from '../support/session-cover'; import { title } from '../support/sign-in'; @@ -39,8 +40,6 @@ const NO_SUCH_PASSWORD = 'zz-e2e-no-such-password'; const LANGUAGES = ['en', 'es', 'fr', 'ko', 'nl', 'ja', 'zh']; -const signedOut = { cookies: [], origins: [] }; - // The server's own sentence for a refusal. const REFUSED = 'You do not have permission to perform this action.'; const LONG_DETAIL = 'x'.repeat(500); diff --git a/e2e/smoke/external-login.spec.ts b/e2e/smoke/external-login.spec.ts index 83aba9b3..517f5514 100644 --- a/e2e/smoke/external-login.spec.ts +++ b/e2e/smoke/external-login.spec.ts @@ -5,8 +5,8 @@ import { expect, test, } from '@playwright/test'; -import { basicAuthorization } from '../../src/utilities/basic-authorization'; -import { account, origin } from '../support/env'; +import { account } from '../support/env'; +import { apiLoginAs } from '../support/session'; import { title } from '../support/sign-in'; // An installation that signs in through an external login service sends the @@ -58,21 +58,9 @@ async function useStandInLogin( return { visits: () => visits }; } -// Signs the account of the run in with the login API inside the context. The -// context's request client shares the cookie jar of its pages, so every page of -// the context is signed in afterwards. -async function apiLogin(context: BrowserContext): Promise { - const { username, password } = account(); - const response = await context.request.post( - `${origin()}/pulp/api/v3/login/`, - { - headers: { - Authorization: basicAuthorization(username, password), - 'X-Requested-With': 'XMLHttpRequest', - }, - }, - ); - expect(response.status(), 'API sign in').toBe(201); +// Signs the account of the run in with the login API inside the context. +function apiLogin(context: BrowserContext): Promise { + return apiLoginAs(context, account()); } // Collects every request the page sends to the Pulp API from now on. diff --git a/e2e/support/api.ts b/e2e/support/api.ts index 8bb336b7..61d4302a 100644 --- a/e2e/support/api.ts +++ b/e2e/support/api.ts @@ -1,10 +1,12 @@ import { type APIRequestContext, request } from '@playwright/test'; import { getRepositoriesAnsibleAnsibleListUrl } from '@pulp-ui/sdk/ansible/repositories-ansible'; import { getContentguardsCoreRbacListUrl } from '@pulp-ui/sdk/core/contentguards-rbac'; +import { getGroupsListUrl } from '@pulp-ui/sdk/core/groups'; import type { AsyncOperationResponse } from '@pulp-ui/sdk/core/models/async-operation-response.zod'; import type { TaskResponse } from '@pulp-ui/sdk/core/models/tasks/task-response.zod'; import { getRolesListUrl } from '@pulp-ui/sdk/core/roles'; import { getTasksReadUrl } from '@pulp-ui/sdk/core/tasks'; +import { getUsersListUrl } from '@pulp-ui/sdk/core/users'; import { getDistributionsDebAptListUrl } from '@pulp-ui/sdk/deb/distributions-apt'; import { getPublicationsDebAptListUrl } from '@pulp-ui/sdk/deb/publications-apt'; import { getRemotesDebAptListUrl } from '@pulp-ui/sdk/deb/remotes-apt'; @@ -68,6 +70,27 @@ export function apiContext(): Promise { }); } +// Every object of a list endpoint matching the filters, all pages, read with +// any request context (the one of the account a spec signs in with). +export async function listAll( + api: APIRequestContext, + path: string, + params: Record = {}, +): Promise { + const results: PulpObject[] = []; + for (let offset = 0; ; offset += 100) { + const page = await apiGet(api, url(path), { + ...params, + limit: '100', + offset: String(offset), + }); + results.push(...page.results); + if (!page.next) { + return results; + } + } +} + export interface PulpObject { pulp_href: string; name?: string; @@ -87,9 +110,10 @@ interface Page { } // Endpoints that hold objects created by the tests, deepest dependants first: -// distributions, publications, repositories, remotes, content guards, roles. Only -// objects under these endpoints are ever deleted. Publications carry no name of -// their own; every other kind must carry the scope's prefix. +// groups, users, distributions, publications, repositories, remotes, content +// guards, roles. Only objects under these endpoints are ever deleted. +// Publications carry no name of their own; users are named by their user name; +// every other kind must carry the scope's prefix in its name. const DISTRIBUTIONS = [ getDistributionsFileFileListUrl(), getDistributionsDebAptListUrl(), @@ -117,9 +141,13 @@ const REMOTES = [ ]; const CONTENT_GUARDS = [getContentguardsCoreRbacListUrl()]; const ROLES = [getRolesListUrl()]; +const GROUPS = [getGroupsListUrl()]; +const USERS = [getUsersListUrl()]; // The endpoint groups in the order objects can be deleted. const DELETION_ORDER = [ + GROUPS, + USERS, DISTRIBUTIONS, PUBLICATIONS, REPOSITORIES, @@ -135,6 +163,25 @@ const NAMED_DELETION_ORDER = DELETION_ORDER.filter( ); const NAMED_ENDPOINTS = NAMED_DELETION_ORDER.flat(); +// The field that names an object of this endpoint, and the filter that finds +// the objects whose name starts with a prefix. Users and groups are matched on +// "contains" and checked again by the caller, because their filters offer no +// "startswith". +function nameField(path: string): 'username' | 'name' { + return USERS.some((endpoint) => path.startsWith(endpoint)) + ? 'username' + : 'name'; +} + +function prefixFilter(path: string, prefix: string): Record { + const field = nameField(path); + const matching = field === 'username' || GROUPS.includes(path); + return { + [`${field}__${matching ? 'contains' : 'startswith'}`]: prefix, + fields: `pulp_href,${field}`, + }; +} + function groupOf(href: string): number { const target = resolveApiUrl(href); return DELETION_ORDER.findIndex((endpoints) => @@ -172,19 +219,8 @@ export class TestObjects { } // Every object of a list endpoint matching the filters, all pages. - async list(path: string, params: Record = {}) { - const results: PulpObject[] = []; - for (let offset = 0; ; offset += 100) { - const page = await apiGet(this.api, url(path), { - ...params, - limit: '100', - offset: String(offset), - }); - results.push(...page.results); - if (!page.next) { - return results; - } - } + list(path: string, params: Record = {}) { + return listAll(this.api, path, params); } async get(href: string): Promise { @@ -217,12 +253,10 @@ export class TestObjects { // and registers the object for clean-up. A name that does not carry this // scope's prefix is refused, so a typo can never write a foreign object. async create(path: string, body: Record) { - if ( - typeof body['name'] === 'string' && - !body['name'].startsWith(this.prefix) - ) { + const label = body[nameField(url(path))]; + if (typeof label === 'string' && !label.startsWith(this.prefix)) { throw new Error( - `refusing to create "${body['name']}": not under ${this.prefix}`, + `refusing to create "${label}": not under ${this.prefix}`, ); } @@ -268,7 +302,7 @@ export class TestObjects { if (current.status === 404) { return; } - const { name } = current.body; + const name = current.body[nameField(href)]; // a publication belongs to a repository version and has no name const unnamedKind = DELETION_ORDER[group] === PUBLICATIONS; if ( @@ -327,21 +361,29 @@ export class TestObjects { this.registered.push(href); } + // The objects of one endpoint that carry this scope's prefix. + private async owned(path: string): Promise { + const field = nameField(path); + const objects = await this.list(path, prefixFilter(path, this.prefix)); + return objects.filter((object) => + String(object[field] ?? '').startsWith(this.prefix), + ); + } + // Objects of this scope that still exist, by endpoint. async leftovers(): Promise { const found: string[] = []; for (const path of NAMED_ENDPOINTS) { - const objects = await this.list(path, { - name__startswith: this.prefix, - fields: 'pulp_href,name', - }); - found.push(...objects.map((object) => `${path}${object.name}`)); + const field = nameField(path); + const objects = await this.owned(path); + found.push(...objects.map((object) => `${path}${String(object[field])}`)); } return found; } // Deletes everything this scope created: registered objects dependants first - // (distributions, publications, repositories, remotes, content guards, roles), then + // (groups, users, distributions, publications, repositories, remotes, content + // guards, roles), then // anything of the scope that is still listed, for objects created through // the UI. Throws when something is left; always closes the API context. async cleanUp(): Promise { @@ -363,10 +405,7 @@ export class TestObjects { for (const endpoints of NAMED_DELETION_ORDER) { for (const path of endpoints) { - const objects = await this.list(path, { - name__startswith: this.prefix, - fields: 'pulp_href,name', - }); + const objects = await this.owned(path); await Promise.all( objects.map(({ pulp_href }) => this.remove(pulp_href)), ); diff --git a/e2e/support/session.ts b/e2e/support/session.ts new file mode 100644 index 00000000..94fba867 --- /dev/null +++ b/e2e/support/session.ts @@ -0,0 +1,43 @@ +import { type BrowserContext, type Response, expect } from '@playwright/test'; +import { basicAuthorization } from '../../src/utilities/basic-authorization'; +import { origin } from './env'; + +// Helpers that the remote, shell and smoke specs share for starting a session +// without the login form and for waiting on the answer that tells the page +// what the account may do. + +// A browser context that holds no session at all, for tests that sign in or +// out. They never touch the storage state shared by the other tests, so +// ending a session here cannot break a later test. +export const signedOut = { cookies: [], origins: [] }; + +// Signs the given account in inside the context with the login API. The +// context's request client shares the cookie jar of its pages, so every page +// opened afterwards in that context is signed in. The credentials come from +// the caller, which reads them from the environment. +export async function apiLoginAs( + context: BrowserContext, + { username, password }: { username: string; password: string }, +): Promise { + const response = await context.request.post( + `${origin()}/pulp/api/v3/login/`, + { + headers: { + Authorization: basicAuthorization(username, password), + 'X-Requested-With': 'XMLHttpRequest', + }, + }, + ); + expect(response.status(), 'API sign in').toBe(201); +} + +// True for the answer to the read of the signed-in user's roles, which is how +// the application learns what the account may do. +export function isPermissionsRead(response: Response): boolean { + return ( + response.request().method() === 'GET' && + /\/pulp\/api\/v3\/users\/[^/]+\/roles\/$/.test( + new URL(response.url()).pathname, + ) + ); +} diff --git a/playwright.config.ts b/playwright.config.ts index a445d1ea..a6a77883 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -109,19 +109,19 @@ export default defineConfig({ name: 'remote-admin', testMatch: 'remote/**/*.spec.ts', testIgnore: ['**/*.viewer.spec.ts', '**/*.editor.spec.ts'], - use: { ...untraced, storageState: 'playwright/.auth/admin.json' }, + use: { ...untraced, storageState: storageStatePath('admin') }, dependencies: ['remote-setup'], }, { name: 'remote-viewer', testMatch: 'remote/**/*.viewer.spec.ts', - use: { ...untraced, storageState: 'playwright/.auth/viewer.json' }, + use: { ...untraced, storageState: storageStatePath('viewer') }, dependencies: ['remote-setup'], }, { name: 'remote-editor', testMatch: 'remote/**/*.editor.spec.ts', - use: { ...untraced, storageState: 'playwright/.auth/editor.json' }, + use: { ...untraced, storageState: storageStatePath('editor') }, dependencies: ['remote-setup'], }, crawlProject('light', 'desktop'), From 5d9ed9bc7add7059209432ca906a0528b015a83d Mon Sep 17 00:00:00 2001 From: Danilo Lakovic Date: Fri, 20 Nov 2026 00:39:19 +0100 Subject: [PATCH 3/4] Add end-to-end flows for status, tasks, users, groups and roles - Remote admin flows: a task from the list through the status filter to its own address and the old address ending on it; users created, edited and deleted; a group created with a member and a role, the role removed and the group deleted; a role created, edited and deleted - Status shows the administrator workers, storage and content settings, and shows the limited account versions only - The smoke project opens a task at its own address from the list and checks the old address, also for a task that does not exist --- e2e/remote/access.viewer.spec.ts | 37 ++-- e2e/remote/admin-screens.spec.ts | 329 +++++++++++++++++++++++++++++++ e2e/remote/tasks.spec.ts | 81 ++++++++ e2e/smoke/pages.spec.ts | 54 ++++- 4 files changed, 488 insertions(+), 13 deletions(-) create mode 100644 e2e/remote/admin-screens.spec.ts create mode 100644 e2e/remote/tasks.spec.ts diff --git a/e2e/remote/access.viewer.spec.ts b/e2e/remote/access.viewer.spec.ts index 1c4ac100..eea38ee1 100644 --- a/e2e/remote/access.viewer.spec.ts +++ b/e2e/remote/access.viewer.spec.ts @@ -1,6 +1,8 @@ import { type Page, expect, test } from '@playwright/test'; import { account } from '../support/accounts'; import { TestObjects } from '../support/api'; +import { apiGet } from '../support/sdk-request'; +import { isPermissionsRead } from '../support/session'; import { title } from '../support/sign-in'; import { type ListPage, missingPlugin } from './list-pages'; import { signedOut } from './session-helpers'; @@ -107,11 +109,7 @@ test.describe('the limited account', () => { } test('the task list offers none of the task actions', async ({ page }) => { - const permissionsRead = page.waitForResponse((response) => - /\/pulp\/api\/v3\/users\/[^/]+\/roles\/$/.test( - new URL(response.url()).pathname, - ), - ); + const permissionsRead = page.waitForResponse(isPermissionsRead); await page.goto('tasks'); await permissionsRead; await expect(title(page, 'Task management')).toBeVisible(); @@ -157,6 +155,23 @@ test.describe('the limited account', () => { await expect(page.getByText('Online workers')).toHaveCount(0); }); + test('sees the versions of the installed plugins on the Status screen and no workers, storage or content settings', async ({ + page, + }) => { + await page.goto('status'); + await expect(title(page, 'Status')).toBeVisible(); + await page.waitForLoadState('networkidle'); + + // each plugin shows with its version in the Versions card + const main = page.getByRole('main'); + await expect(main.getByText('Versions', { exact: true })).toBeVisible(); + await expect(main.getByText(/^core$/)).toBeVisible(); + + for (const card of ['Online workers', 'Storage', 'Content settings']) { + await expect(main.getByText(card, { exact: true }), card).toHaveCount(0); + } + }); + test('opens its own profile and sees it', async ({ page }) => { await page.goto('users/profile'); @@ -198,13 +213,11 @@ test.describe('the forms of repositories and remotes opened by address', () => { let found = names.get(key); if (!found) { found = (async () => { - const response = await objects.api.get(`/pulp/api/v3/${key}/`, { - params: { limit: '1', fields: 'name' }, - }); - expect(response.ok(), `GET ${key}`).toBe(true); - const { results } = (await response.json()) as { - results: { name: string }[]; - }; + const { results } = await apiGet<{ results: { name: string }[] }>( + objects.api, + `/pulp/api/v3/${key}/`, + { limit: '1', fields: 'name' }, + ); if (results[0]) { return results[0].name; } diff --git a/e2e/remote/admin-screens.spec.ts b/e2e/remote/admin-screens.spec.ts new file mode 100644 index 00000000..447d2a3f --- /dev/null +++ b/e2e/remote/admin-screens.spec.ts @@ -0,0 +1,329 @@ +import { type Page, expect, test } from '@playwright/test'; +import { getGroupsListUrl } from '@pulp-ui/sdk/core/groups'; +import { getGroupsRolesListUrl } from '@pulp-ui/sdk/core/groups-roles'; +import { getGroupsUsersListUrl } from '@pulp-ui/sdk/core/groups-users'; +import { getRolesListUrl } from '@pulp-ui/sdk/core/roles'; +import { getUsersListUrl } from '@pulp-ui/sdk/core/users'; +import { randomBytes } from 'node:crypto'; +import { TestObjects } from '../support/api'; +import { apiCall, apiGet } from '../support/sdk-request'; +import { title } from '../support/sign-in'; + +// The screens that administer accounts, used the way an administrator uses +// them against a real server: the status page, and users, groups (members and +// roles) and roles created, changed and deleted through their forms and +// dialogs. Every change is read back from the server, and every object carries +// the run's prefix so clean-up finds it. + +const USERS = getUsersListUrl(); +const GROUPS = getGroupsListUrl(); +const ROLES = getRolesListUrl(); + +let objects: TestObjects; + +test.beforeAll(async () => { + objects = await TestObjects.open('screens'); +}); + +test.afterAll(async () => { + test.setTimeout(180_000); + await objects.cleanUp(); +}); + +// A password for a test account, different on every run and never written +// anywhere. +function newPassword(): string { + return `Pw-${randomBytes(12).toString('hex')}`; +} + +// The row actions of a list row open from its menu. +async function openRowAction( + page: Page, + rowSelector: string, + action: 'Edit' | 'Delete', +): Promise { + const row = page.locator(rowSelector); + await expect(row).toBeVisible(); + await row.locator('[data-cy=kebab-toggle] button').click(); + await page.getByRole('menuitem', { name: action, exact: true }).click(); +} + +// The one object of an endpoint with this exact name or user name. +async function only(path: string, filter: Record) { + const found = await objects.list(path, filter); + expect(found, `${path} matching ${JSON.stringify(filter)}`).toHaveLength(1); + return found[0]!; +} + +test.describe('Status', () => { + test('shows the versions, the online workers, the storage and the content settings to an administrator', async ({ + page, + }) => { + await page.goto('status'); + await expect(title(page, 'Status')).toBeVisible(); + + const main = page.getByRole('main'); + for (const card of [ + 'Versions', + 'Online workers', + 'Storage', + 'Content settings', + ]) { + await expect(main.getByText(card, { exact: true }), card).toBeVisible(); + } + // an administrator's answer holds everything, so no note says it is cut + await expect( + page.getByText( + 'Workers, storage and content settings are shown to administrators.', + ), + ).toHaveCount(0); + }); +}); + +test.describe('users', () => { + test('a user is created from the form, edited from the list and deleted', async ({ + page, + }) => { + const name = objects.name('user'); + const password = newPassword(); + + // create + await page.goto('users/create'); + await expect(title(page, 'Create new user')).toBeVisible(); + await page.locator('#username').fill(name); + await page.locator('#first_name').fill('Before'); + await page.locator('#password').fill(password); + await page.locator('#password-confirm').fill(password); + await page.getByRole('button', { name: 'Save' }).click(); + await expect(page).toHaveURL(/\/users\/?$/); + + const created = await only(USERS, { username: name }); + objects.track(created.pulp_href); + expect(created['first_name'], 'the first name as created').toBe('Before'); + + // edit from the row + const row = `[data-cy="UserList-row-${name}"]`; + await page.goto(`users?username__contains=${encodeURIComponent(name)}`); + await expect(title(page, 'Users')).toBeVisible(); + await openRowAction(page, row, 'Edit'); + await expect(page).toHaveURL(/\/users\/edit\//); + await expect(page.locator('#first_name')).toHaveValue('Before'); + await page.locator('#first_name').fill('After'); + await page.getByRole('button', { name: 'Save' }).click(); + await expect(page).toHaveURL(/\/users\/?$/); + + const edited = await objects.get(created.pulp_href); + expect(edited['first_name'], 'the first name after the edit').toBe('After'); + expect(edited['username'], 'the user name is kept').toBe(name); + + // delete from the row + await page.goto(`users?username__contains=${encodeURIComponent(name)}`); + await openRowAction(page, row, 'Delete'); + const dialog = page.getByRole('dialog'); + await expect(dialog).toContainText('Delete user?'); + await expect(dialog).toContainText(name); + await dialog.getByRole('button', { name: 'Delete', exact: true }).click(); + await expect( + page.getByText(`User "${name}" has been successfully deleted.`), + ).toBeVisible(); + + const gone = await apiCall(objects.api, 'GET', created.pulp_href, { + accept: [404], + }); + expect(gone.status, 'a read of the deleted user').toBe(404); + }); +}); + +test.describe('groups', () => { + test('a group is created, gets a member and a role, loses the role and is deleted', async ({ + page, + }) => { + test.setTimeout(120_000); + const member = await objects.create(USERS, { + username: objects.name('member'), + password: newPassword(), + }); + const memberName = member['username'] as string; + const role = await objects.create(ROLES, { + name: objects.name('grouprole'), + permissions: ['file.view_filerepository'], + }); + const roleName = role.name as string; + const groupName = objects.name('group'); + + // create from the list: the new group opens on its roles tab + await page.goto('groups'); + await expect(title(page, 'Groups')).toBeVisible(); + await page.getByRole('button', { name: 'Create', exact: true }).click(); + const createDialog = page.getByRole('dialog'); + await createDialog.locator('#group_name').fill(groupName); + await createDialog + .getByRole('button', { name: 'Create', exact: true }) + .click(); + await expect(page).toHaveURL(/\/groups\/detail\//); + await expect(title(page, groupName)).toBeVisible(); + + const group = await only(GROUPS, { name: groupName }); + objects.track(group.pulp_href); + const tabs = page.locator('.pulp-tab-link-container'); + + // add the member; the dialog never offers a user who already is one + await tabs.getByRole('link', { name: 'Users', exact: true }).click(); + await page.getByRole('button', { name: 'Add', exact: true }).click(); + const addDialog = page.getByRole('dialog'); + const search = addDialog.getByRole('combobox', { name: 'Select users' }); + await search.fill(memberName); + await addDialog.getByRole('option', { name: memberName }).click(); + await addDialog.getByRole('button', { name: 'Add', exact: true }).click(); + await expect( + page.getByText( + `User "${memberName}" has been successfully added to group "${groupName}".`, + ), + ).toBeVisible(); + await expect( + page.locator(`[data-cy="GroupDetail-users-${memberName}"]`), + ).toBeVisible(); + + const members = await apiGet<{ results: { username: string }[] }>( + objects.api, + getGroupsUsersListUrl(group.pulp_href), + ); + expect(members.results.map(({ username }) => username)).toEqual([ + memberName, + ]); + + await page.getByRole('button', { name: 'Add', exact: true }).click(); + const again = page.getByRole('dialog'); + await again + .getByRole('combobox', { name: 'Select users' }) + .fill(memberName); + await expect( + again.getByRole('option', { name: memberName }), + 'the member in the add dialog', + ).toHaveCount(0); + await again.getByRole('button', { name: 'Cancel' }).click(); + await expect(page.getByRole('dialog')).toBeHidden(); + + // add the role through the wizard + await tabs.getByRole('link', { name: 'Access', exact: true }).click(); + await page.getByRole('button', { name: 'Add roles' }).click(); + const wizard = page.getByRole('dialog'); + await wizard + .getByRole('textbox', { name: 'name__icontains' }) + .fill(roleName); + await wizard + .getByRole('textbox', { name: 'name__icontains' }) + .press('Enter'); + const pick = wizard.locator( + `[data-cy="RoleListTable-CheckboxRow-row-${roleName}"]`, + ); + await expect(pick).toBeVisible(); + await pick.getByRole('checkbox').check(); + await wizard.getByRole('button', { name: 'Next' }).click(); + await wizard.getByRole('button', { name: 'Add', exact: true }).click(); + await expect( + page.getByText( + `Role ${roleName} has been successfully added to ${groupName}.`, + ), + ).toBeVisible(); + const roleRow = `[data-cy="RoleListTable-ExpandableRow-row-${roleName}"]`; + await expect(page.locator(roleRow)).toBeVisible(); + + const assigned = await apiGet<{ results: { role: string }[] }>( + objects.api, + getGroupsRolesListUrl(group.pulp_href), + ); + expect(assigned.results.map((entry) => entry.role)).toEqual([roleName]); + + // remove the role + await page + .locator(roleRow) + .locator('[data-cy=kebab-toggle] button') + .click(); + await page.getByRole('menuitem', { name: 'Remove role' }).click(); + const removeDialog = page.getByRole('dialog'); + await expect(removeDialog).toContainText(roleName); + await removeDialog + .getByRole('button', { name: 'Delete', exact: true }) + .click(); + await expect( + page.getByText(`Role "${roleName}" has been successfully removed.`), + ).toBeVisible(); + const left = await apiGet<{ results: { role: string }[] }>( + objects.api, + getGroupsRolesListUrl(group.pulp_href), + ); + expect(left.results, 'roles left on the group').toHaveLength(0); + + // delete the group from its page + await page.getByRole('button', { name: 'Delete', exact: true }).click(); + const deleteDialog = page.getByRole('dialog'); + await expect(deleteDialog).toContainText('Delete group?'); + await expect(deleteDialog).toContainText(memberName); + await deleteDialog + .getByRole('button', { name: 'Delete', exact: true }) + .click(); + await expect(page).toHaveURL(/\/groups\/?$/); + await expect( + page.getByText(`Group "${groupName}" has been successfully deleted.`), + ).toBeVisible(); + + const gone = await apiCall(objects.api, 'GET', group.pulp_href, { + accept: [404], + }); + expect(gone.status, 'a read of the deleted group').toBe(404); + }); +}); + +test.describe('roles', () => { + test('a role is created from the form, edited from the list and deleted', async ({ + page, + }) => { + const name = objects.name('role'); + + await page.goto('roles/create'); + await expect(title(page, 'Create a new role')).toBeVisible(); + await page.locator('#role_name').fill(name); + await page.locator('#role_description').fill('before the edit'); + await page.getByRole('button', { name: 'Save' }).click(); + await expect(page).toHaveURL(/\/roles\/?$/); + + const created = await only(ROLES, { name }); + objects.track(created.pulp_href); + expect(created['description'], 'the description as created').toBe( + 'before the edit', + ); + + const row = `[data-cy="RoleListTable-ExpandableRow-row-${name}"]`; + await page.goto(`roles?name__icontains=${encodeURIComponent(name)}`); + await expect(title(page, 'Roles')).toBeVisible(); + await openRowAction(page, row, 'Edit'); + await expect(page).toHaveURL(/\/roles\/edit\//); + await expect(page.locator('#role_description')).toHaveValue( + 'before the edit', + ); + await page.locator('#role_description').fill('after the edit'); + await page.getByRole('button', { name: 'Save' }).click(); + await expect(page).toHaveURL(/\/roles\/?$/); + + const edited = await objects.get(created.pulp_href); + expect(edited['description'], 'the description after the edit').toBe( + 'after the edit', + ); + expect(edited['name'], 'the name is kept').toBe(name); + + await page.goto(`roles?name__icontains=${encodeURIComponent(name)}`); + await openRowAction(page, row, 'Delete'); + const dialog = page.getByRole('dialog'); + await expect(dialog).toContainText('Delete role?'); + await dialog.getByRole('button', { name: 'Delete', exact: true }).click(); + await expect( + page.getByText(`Role "${name}" has been successfully deleted.`), + ).toBeVisible(); + + const gone = await apiCall(objects.api, 'GET', created.pulp_href, { + accept: [404], + }); + expect(gone.status, 'a read of the deleted role').toBe(404); + }); +}); diff --git a/e2e/remote/tasks.spec.ts b/e2e/remote/tasks.spec.ts new file mode 100644 index 00000000..1f7e6ccb --- /dev/null +++ b/e2e/remote/tasks.spec.ts @@ -0,0 +1,81 @@ +import { expect, test } from '@playwright/test'; +import { + getRepositoriesFileFileDeleteUrl, + getRepositoriesFileFileListUrl, +} from '@pulp-ui/sdk/file/repositories-file'; +import { TestObjects } from '../support/api'; +import { apiDelete } from '../support/sdk-request'; +import { title } from '../support/sign-in'; + +// A task a person follows from the task list to its page: the list shows it, +// the status filter narrows the list, opening it lands on its own address, and +// the address older links use ends on the new one. The task is made by the +// set-up: deleting a repository is a task of its own, and it finishes within +// moments. + +let objects: TestObjects; +let taskId = ''; + +test.beforeAll(async () => { + test.setTimeout(180_000); + objects = await TestObjects.open('tasks'); + const repository = await objects.create(getRepositoriesFileFileListUrl(), { + name: objects.name('doomed'), + }); + const answer = await apiDelete( + objects.api, + getRepositoriesFileFileDeleteUrl(repository.pulp_href), + ); + expect(answer.status, 'the answer to the delete').toBe(202); + const taskHref = answer.body?.task as string; + await objects.waitForTask(taskHref); + taskId = taskHref.split('/').filter(Boolean).pop() as string; +}); + +test.afterAll(async () => { + test.setTimeout(180_000); + await objects.cleanUp(); +}); + +test('a finished task is listed, found by its status, opened at its own address and reached from the old one', async ({ + page, +}) => { + const link = () => page.locator(`a[href$="/tasks/${taskId}"]`); + const completedOnPage = () => + page.getByText('Completed', { exact: true }).first(); + + // the list, newest first, wide enough that concurrent work cannot push the + // task off the first page + await page.goto('tasks?page_size=100'); + await expect(title(page, 'Task management')).toBeVisible(); + await expect(link()).toBeVisible(); + + // the status filter: a failed-only list does not hold a task that completed, + // a completed-only list does + const filter = page.locator('[data-cy=compound_filter]'); + const chooseStatus = async (status: 'Failed' | 'Completed') => { + await filter.getByRole('button', { name: 'Task name' }).click(); + await page.getByRole('menuitem', { name: 'Status', exact: true }).click(); + await filter.getByRole('button', { name: 'Status', exact: true }).click(); + await page.getByRole('option', { name: status, exact: true }).click(); + }; + await chooseStatus('Failed'); + await expect(page).toHaveURL(/state=failed/); + await expect(link()).toHaveCount(0); + + await page.goto('tasks?page_size=100'); + await chooseStatus('Completed'); + await expect(page).toHaveURL(/state=completed/); + await expect(link()).toBeVisible(); + + // opening the task lands on its address and shows how it ended + await link().click(); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await expect(completedOnPage()).toBeVisible(); + + // the address links used before tasks had their own address ends on the new + // one + await page.goto(`tasks/detail/${taskId}`); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await expect(completedOnPage()).toBeVisible(); +}); diff --git a/e2e/smoke/pages.spec.ts b/e2e/smoke/pages.spec.ts index 29d037fb..5f94b900 100644 --- a/e2e/smoke/pages.spec.ts +++ b/e2e/smoke/pages.spec.ts @@ -1,4 +1,8 @@ -import { expect, test } from '@playwright/test'; +import { expect, request, test } from '@playwright/test'; +import { getOrphansCleanupCleanupUrl } from '@pulp-ui/sdk/core/orphans-cleanup'; +import { basicAuthorization } from '../../src/utilities/basic-authorization'; +import { account, origin } from '../support/env'; +import { apiPost } from '../support/sdk-request'; import { signIn, title } from '../support/sign-in'; // Every list page opens with its title once signed in. A page that fails to @@ -35,6 +39,54 @@ test.describe('pages of a signed-in session', () => { }); } + // A task has its own address, /tasks/, and the address that links used + // before it ends on the new one. The task is an orphan cleanup the run starts + // itself with the throwaway Pulp's administrator; with the default + // protection time it removes nothing. + test('a task opens from the list at its own address and the old address ends on it', async ({ + page, + }) => { + const { username, password } = account(); + const api = await request.newContext({ + baseURL: origin(), + extraHTTPHeaders: { + Authorization: basicAuthorization(username, password), + }, + }); + let taskId: string; + try { + const started = await apiPost<{ task: string }>( + api, + getOrphansCleanupCleanupUrl(), + { orphan_protection_time: 1440 }, + ); + taskId = started.task.split('/').filter(Boolean).pop() as string; + } finally { + await api.dispose(); + } + + await page.goto('tasks?page_size=100'); + await expect(title(page, 'Task management')).toBeVisible(); + await page.locator(`a[href$="/tasks/${taskId}"]`).click(); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await expect(title(page, 'Task detail')).toBeVisible(); + + await page.goto(`tasks/detail/${taskId}`); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await expect(title(page, 'Task detail')).toBeVisible(); + }); + + // The old address of a task that does not exist ends on the new address, + // which says the page is not there. + test('the old address of an unknown task ends on the new address and shows the 404 page', async ({ + page, + }) => { + const unknown = '00000000-0000-4000-8000-000000000000'; + await page.goto(`tasks/detail/${unknown}`); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${unknown}$`)); + await expect(title(page, '404 - Page not found')).toBeVisible(); + }); + // A screen that needs an API this UI does not use yet says so instead of // failing. test('Search shows the placeholder', async ({ page }) => { From 687664b8a021818ff6f52b486f2395728e8dab8b Mon Sep 17 00:00:00 2001 From: Danilo Lakovic Date: Fri, 20 Nov 2026 00:45:49 +0100 Subject: [PATCH 4/4] Match the task address with its trailing slash in the e2e flows The application writes the task address as /tasks// (every route path ends with a slash), so a link or address pattern that ends at the id never matched. --- e2e/remote/tasks.spec.ts | 6 +++--- e2e/smoke/pages.spec.ts | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/e2e/remote/tasks.spec.ts b/e2e/remote/tasks.spec.ts index 1f7e6ccb..0903214f 100644 --- a/e2e/remote/tasks.spec.ts +++ b/e2e/remote/tasks.spec.ts @@ -40,7 +40,7 @@ test.afterAll(async () => { test('a finished task is listed, found by its status, opened at its own address and reached from the old one', async ({ page, }) => { - const link = () => page.locator(`a[href$="/tasks/${taskId}"]`); + const link = () => page.locator(`a[href*="/tasks/${taskId}"]`); const completedOnPage = () => page.getByText('Completed', { exact: true }).first(); @@ -70,12 +70,12 @@ test('a finished task is listed, found by its status, opened at its own address // opening the task lands on its address and shows how it ended await link().click(); - await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}/?$`)); await expect(completedOnPage()).toBeVisible(); // the address links used before tasks had their own address ends on the new // one await page.goto(`tasks/detail/${taskId}`); - await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}/?$`)); await expect(completedOnPage()).toBeVisible(); }); diff --git a/e2e/smoke/pages.spec.ts b/e2e/smoke/pages.spec.ts index 5f94b900..416a8354 100644 --- a/e2e/smoke/pages.spec.ts +++ b/e2e/smoke/pages.spec.ts @@ -67,12 +67,12 @@ test.describe('pages of a signed-in session', () => { await page.goto('tasks?page_size=100'); await expect(title(page, 'Task management')).toBeVisible(); - await page.locator(`a[href$="/tasks/${taskId}"]`).click(); - await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await page.locator(`a[href*="/tasks/${taskId}"]`).click(); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}/?$`)); await expect(title(page, 'Task detail')).toBeVisible(); await page.goto(`tasks/detail/${taskId}`); - await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}$`)); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${taskId}/?$`)); await expect(title(page, 'Task detail')).toBeVisible(); }); @@ -83,7 +83,7 @@ test.describe('pages of a signed-in session', () => { }) => { const unknown = '00000000-0000-4000-8000-000000000000'; await page.goto(`tasks/detail/${unknown}`); - await expect(page).toHaveURL(new RegExp(`/ui/tasks/${unknown}$`)); + await expect(page).toHaveURL(new RegExp(`/ui/tasks/${unknown}/?$`)); await expect(title(page, '404 - Page not found')).toBeVisible(); });