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
137 changes: 136 additions & 1 deletion test/ui-e2e/src/fixtures/monitoring.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { execSync } from 'child_process';
import { mkdtempSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { test as base, expect } from '@playwright/test';
import { DashboardsPage } from '../pages/console/DashboardsPage';
import { MetricsPage } from '../pages/console/MetricsPage';
Expand All @@ -7,13 +11,144 @@ import {
resolveArgoCDInstance,
} from '../utils/argocd-instance';

const SETTINGS_NS = 'openshift-console-user-settings';

type Perspective = { id?: string; visibility?: { state?: string } };

//turn the dev perspective on when the console has it disabled
function enableDeveloperPerspective() {
const cluster = JSON.parse(
execSync('oc get console.operator.openshift.io cluster -o json', { encoding: 'utf8' })
);
const perspectives: Perspective[] = cluster.spec?.customization?.perspectives ?? [];
const dev = perspectives.find((item) => item.id === 'dev');
if (dev?.visibility?.state !== 'Disabled') {
console.log(' -> Developer perspective already available.');
return;
}

dev.visibility = { ...dev.visibility, state: 'Enabled' };
const dir = mkdtempSync(join(tmpdir(), 'console-perspective-'));
const patchFile = join(dir, 'patch.json');
writeFileSync(patchFile, JSON.stringify({ spec: { customization: { perspectives } } }));

console.log(' -> Enabling developer perspective...');
const before = execSync(
'oc get deployment console -n openshift-console -o jsonpath={.metadata.generation}',
{ encoding: 'utf8' }
).trim();
execSync(`oc patch console.operator.openshift.io cluster --type=merge --patch-file=${patchFile}`, {
stdio: 'inherit',
});

const deadline = Date.now() + 5 * 60 * 1000;
while (Date.now() < deadline) {
//replica counts lie until this generation is observed
//surge keeps an old pod available until it is gone
const status = execSync(
`oc get deployment console -n openshift-console -o jsonpath='{.metadata.generation}{" "}{.status.observedGeneration}{" "}{.status.replicas}{" "}{.status.updatedReplicas}{" "}{.status.availableReplicas}{" "}{.spec.replicas}'`,
{ encoding: 'utf8' }
).trim();
const [generation, observed, current, updated, available, desired] = status.split(' ');
if (
Number(generation) > Number(before) &&
observed === generation &&
desired !== '' &&
current === desired &&
updated === desired &&
available === desired
) {
console.log(' -> Developer perspective enabled.');
return;
}
execSync('sleep 5');
}

throw new Error('console did not finish restarting after enabling the developer perspective');
}

type MonitoringFixtures = {
dashboardsPage: DashboardsPage;
metricsPage: MetricsPage;
userDefinedArgoCD: ArgoCDInstance;
};

export const test = base.extend<MonitoringFixtures>({
type MonitoringWorker = {
//dev metrics sticks kubeadmin on the developer perspective
consoleSettings: void;
};

function settingsName() {
const user = process.env.CLUSTER_USER || 'kubeadmin';
const safe = user.toLowerCase().replace(/[^a-z0-9-]/g, '-');
if (!/^[a-z0-9-]+$/.test(safe)) {
throw new Error(`cannot resolve console user settings for ${user}`);
}
return `user-settings-${safe}`;
}

function readSettings(): Record<string, string> | null {
try {
const raw = execSync(`oc get configmap ${settingsName()} -n ${SETTINGS_NS} -o json`, {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
});
const data = JSON.parse(raw).data;
return data && typeof data === 'object' ? (data as Record<string, string>) : {};
} catch (error) {
const stderr =
error && typeof error === 'object' && 'stderr' in error ? String(error.stderr) : String(error);
if (stderr.includes('NotFound')) return null;
throw error;
}
}

function restoreSettings(before: Record<string, string> | null) {
const after = readSettings();
if (JSON.stringify(after) === JSON.stringify(before)) return;

const name = settingsName();
if (before === null) {
execSync(`oc delete configmap ${name} -n ${SETTINGS_NS} --ignore-not-found`, { stdio: 'inherit' });
return;
}

const dir = mkdtempSync(join(tmpdir(), 'console-user-settings-'));
const patchFile = join(dir, 'patch.json');
if (after === null) {
writeFileSync(
patchFile,
JSON.stringify({
apiVersion: 'v1',
kind: 'ConfigMap',
metadata: { name, namespace: SETTINGS_NS },
data: before,
})
);
execSync(`oc apply -f ${patchFile}`, { stdio: 'inherit' });
return;
}

writeFileSync(patchFile, JSON.stringify([{ op: 'replace', path: '/data', value: before }]));
execSync(`oc patch configmap ${name} -n ${SETTINGS_NS} --type=json --patch-file=${patchFile}`, {
stdio: 'inherit',
});
}

export const test = base.extend<MonitoringFixtures, MonitoringWorker>({
consoleSettings: [
async ({}, use) => {
enableDeveloperPerspective();
const before = readSettings();
try {
await use();
} finally {
restoreSettings(before);
}
},
{ scope: 'worker', auto: true },
],

dashboardsPage: async ({ page }, use) => {
await use(new DashboardsPage(page));
},
Expand Down
5 changes: 2 additions & 3 deletions test/ui-e2e/src/pages/SettingsRepositoriesPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ export class SettingsRepositoriesPage {

constructor(page: Page) {
this.page = page;
this.connectRepoButton = page
.getByRole('button', { name: /Connect Repo/i })
.or(page.getByText('Connect Repo', { exact: true }));
//3.6 nests connect repo in a span inside the button
this.connectRepoButton = page.getByRole('button', { name: /Connect Repo/i });
}

private passwordField() {
Expand Down
8 changes: 8 additions & 0 deletions test/ui-e2e/src/pages/console/DashboardsPage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, Locator, Page } from '@playwright/test';
import { usePerspective } from './perspective';
import { dismissConsoleTour } from './tour';
import { consoleUrl } from './url';

Expand Down Expand Up @@ -29,18 +30,25 @@ export class DashboardsPage {
'[role="listbox"]:visible [role="option"]',
'[role="menu"]:visible [role="menuitem"]',
'.pf-c-select__menu:visible .pf-c-select__menu-item',
//pf5 select menu has no listbox role
'.pf-v5-c-select__menu:visible .pf-v5-c-select__menu-item',
'.pf-v5-c-menu:visible .pf-v5-c-menu__item',
'.pf-v6-c-menu:visible .pf-v6-c-menu__item',
].join(', ')
);
}

async open() {
//a saved developer perspective redirects this url to the project picker
await this.page.goto(consoleUrl('/'), { waitUntil: 'domcontentloaded', timeout: 60000 });
await dismissConsoleTour(this.page);
await usePerspective(this.page, 'administrator');
await this.page.goto(consoleUrl('/monitoring/dashboards'), {
waitUntil: 'domcontentloaded',
timeout: 60000,
});
await dismissConsoleTour(this.page);
await expect(this.page).toHaveURL(/\/monitoring\/dashboards/, { timeout: TIMEOUTS.load });
await expect(this.page.getByRole('heading', { name: /dashboards/i })).toBeVisible({
timeout: TIMEOUTS.load,
});
Expand Down
16 changes: 13 additions & 3 deletions test/ui-e2e/src/pages/console/MetricsPage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, Page } from '@playwright/test';
import { usePerspective } from './perspective';
import { dismissConsoleTour } from './tour';
import { consoleUrl } from './url';

Expand All @@ -24,14 +25,23 @@ export class MetricsPage {
}

async openAdmin() {
await this.open('/monitoring/query-browser', /query-browser/);
await this.prepare('administrator');
await this.open('/monitoring/query-browser', /\/monitoring\/query-browser/);
}

async openDeveloper(namespace: string) {
const ns = encodeURIComponent(namespace);
//query browser only mounts in the developer perspective
await this.prepare('developer');
await this.open(`/dev-monitoring/ns/${ns}/metrics`, /\/metrics/);
}

private async prepare(which: 'administrator' | 'developer') {
await this.page.goto(consoleUrl('/'), { waitUntil: 'domcontentloaded', timeout: 60000 });
await dismissConsoleTour(this.page);
await usePerspective(this.page, which);
}

async runQuery(expression: string) {
await expect(this.queryInput).toBeVisible({ timeout: TIMEOUTS.load });
await this.queryInput.click();
Expand All @@ -51,9 +61,9 @@ export class MetricsPage {
await this.page.goto(consoleUrl(path), { waitUntil: 'domcontentloaded', timeout: 60000 });
await dismissConsoleTour(this.page);
await expect(this.page).toHaveURL(url, { timeout: TIMEOUTS.load });
//admin uses an h1, developer keeps Metrics as a tab under Observe
//refresh and actions are inside the h1 so the name is longer than metrics
const metricsTitle = this.page
.getByRole('heading', { name: /^metrics$/i })
.getByRole('heading', { name: /^metrics\b/i })
.or(this.page.getByRole('tab', { name: /^metrics$/i }));
await expect(metricsTitle).toBeVisible({ timeout: TIMEOUTS.load });
await expect(this.runQueriesButton.first()).toBeVisible({ timeout: TIMEOUTS.load });
Expand Down
41 changes: 41 additions & 0 deletions test/ui-e2e/src/pages/console/perspective.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Page } from '@playwright/test';
import { dismissConsoleTour } from './tour';

const TIMEOUT = 45000;

//core platform is the administrator label
function label(which: 'administrator' | 'developer') {
return which === 'administrator' ? /^(administrator|core platform)$/i : /^developer$/i;
}

//switcher label is a heading so the button name can be empty
function toggle(page: Page, which: 'administrator' | 'developer') {
const heading = page.getByRole('heading', { level: 2, name: label(which) });
return page
.locator('[data-test-id="perspective-switcher-toggle"]')
.filter({ has: heading })
.or(page.getByRole('button').filter({ has: heading }));
}

//console remembers the perspective across sessions
export async function usePerspective(page: Page, which: 'administrator' | 'developer') {
const admin = toggle(page, 'administrator');
const developer = toggle(page, 'developer');
const current = which === 'administrator' ? admin : developer;
const other = which === 'administrator' ? developer : admin;

await admin.or(developer).first().waitFor({ state: 'visible', timeout: TIMEOUT });
if (await current.isVisible().catch(() => false)) return;

await dismissConsoleTour(page);
await other.click({ timeout: TIMEOUT });
const choice = page
.getByRole('menuitem', { name: label(which) })
.or(page.getByRole('option', { name: label(which) }))
.or(page.getByRole('link', { name: label(which) }))
.or(page.getByRole('button', { name: label(which) }));
await choice.first().click({ timeout: TIMEOUT });
//the welcome dialog shows up after the switch
await dismissConsoleTour(page);
await current.waitFor({ state: 'visible', timeout: TIMEOUT });
}
34 changes: 21 additions & 13 deletions test/ui-e2e/src/pages/console/tour.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
import { expect, Page } from '@playwright/test';
import { Page } from '@playwright/test';

const handled = new WeakSet<Page>();

function skipTour(page: Page) {
return page
.getByRole('dialog')
.filter({
has: page.getByRole('heading', {
name: /welcome to the (new openshift experience|developer perspective)/i,
}),
})
.getByRole('button', { name: /^skip tour$/i });
}

//tour popup eats the first click
export async function dismissConsoleTour(page: Page) {
const dialog = page.getByRole('dialog').filter({
has: page.getByRole('heading', { name: /welcome to the new openshift experience/i }),
});

try {
await dialog.waitFor({ state: 'visible', timeout: 2000 });
} catch (error) {
if (error instanceof Error && error.name === 'TimeoutError') return;
throw error;
}
if (handled.has(page)) return;
handled.add(page);

await dialog.getByRole('button', { name: /skip tour|^close$/i }).first().click();
await expect(dialog).toBeHidden();
//dialog pops in after the route paints so a quick look misses it
//playwright runs this before the click the dialog would cover
await page.addLocatorHandler(skipTour(page), async (skip) => {
await skip.click({ timeout: 15000 });
});
}