Files
crank/apps/ui/tests/e2e/openapi-import-plan.spec.js
T

279 lines
11 KiB
JavaScript

const { test, expect } = require('@playwright/test');
const { login, localized, uniqueName } = require('./helpers');
async function dismissOnboardingIfOpen(page) {
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
await page.evaluate(() => {
const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]');
if (dismiss) dismiss.click();
});
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
function importDocument(prefix) {
return [
'openapi: 3.0.3',
'info: { title: ImportPlan UI test, version: \'1\' }',
'paths:',
' /' + prefix + '-selected:',
' get:',
' operationId: ' + prefix + '_selected',
' responses:',
' \'200\': { description: OK }',
' /' + prefix + '-excluded:',
' get:',
' operationId: ' + prefix + '_excluded',
' responses:',
' \'200\': { description: OK }',
].join('\n');
}
function planResponse(prefix) {
return {
plan_reference: 'plan_e2e_importplan_213',
plan_digest: 'a'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: 'partial',
counts: { selected: 1, excluded: 1, actionable: 1, blocked: 0 },
candidates: [
{
key: 'GET /' + prefix + '-selected',
name: 'selected_operation',
state: 'actionable',
action: 'new_version',
target_operation_id: 'op_existing_target',
confirmed_name: null,
auth_profile_id: null,
reason: null,
},
{
key: 'GET /' + prefix + '-excluded',
name: 'excluded_operation',
state: 'excluded',
action: null,
target_operation_id: null,
confirmed_name: null,
auth_profile_id: null,
reason: 'not_selected',
},
],
};
}
async function preparePlanFlow(page, locale) {
const planCalls = [];
const applyCalls = [];
const prefix = uniqueName('plan_apply');
let releaseApplyResponse;
const applyResponseHeld = new Promise((resolve) => {
releaseApplyResponse = resolve;
});
// Keep this mock aligned with the public CreatePlan response shape.
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
planCalls.push({
url: route.request().url(),
payload: route.request().postDataJSON(),
});
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(planResponse(prefix)),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/apply$/, async (route) => {
applyCalls.push({
url: route.request().url(),
payload: route.request().postDataJSON(),
});
// Keep the request pending until the test has checked the duplicate guard.
await applyResponseHeld;
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
plan_digest: 'a'.repeat(64),
counts: { selected: 1, excluded: 1, created: 0, versioned: 1 },
outcomes: [{ status: 'versioned' }],
}),
});
});
// Contain the legacy path so this red-phase test cannot mutate the E2E DB.
await page.route(/\/imports\/openapi\/[^/]+\/create$/, async (route) => {
await route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ message: 'ImportPlan flow required' }),
});
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.evaluate((language) => window.setLang(language), locale);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await page.locator('#openapi-import-file').setInputFiles({
name: 'import-plan.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(importDocument(prefix)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'),
);
await page.locator('#openapi-import-preview').click();
await previewResponse;
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
// The existing preview action becomes Plan creation followed by confirmation.
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect.poll(() => planCalls.length).toBe(1);
return { planCalls, applyCalls, prefix, releaseApplyResponse };
}
async function assertConfirmation(page, prefix) {
const confirmation = page.locator('[data-testid="openapi-import-apply-confirmation"]');
const counts = page.locator('[data-testid="openapi-import-apply-counts"]');
const versioning = page.locator('[data-testid="openapi-import-versioning-consequences"]');
await expect(counts).toContainText(localized('Selected: 1', 'Выбрано: 1'));
await expect(counts).toContainText(localized('Excluded: 1', 'Исключено: 1'));
await expect(counts).toContainText(localized('Actionable: 1', 'Можно применить: 1'));
await expect(counts).toContainText(localized('Blocked: 0', 'Заблокировано: 0'));
await expect(versioning).toContainText(localized('new Draft Version', 'новая версия черновика'));
await expect(versioning).toContainText(
localized('Published Version and history remain unchanged', 'Опубликованная версия и история останутся без изменений'),
);
await expect(confirmation).toContainText('GET /' + prefix + '-selected');
await expect(confirmation).toContainText('GET /' + prefix + '-excluded');
await expect(confirmation).toContainText('op_existing_target');
}
test('[P1] AC-13 renders server-confirmed partial and new_version consequences in RU and EN', async ({ page }) => {
// This test covers rendering of a stored server plan only. It does not
// specify how UI controls compose selection/decision request fields.
const { planCalls, prefix } = await preparePlanFlow(page, 'ru');
for (const locale of ['ru', 'en']) {
await test.step('confirmation in ' + locale, async () => {
await page.evaluate((language) => window.setLang(language), locale);
await assertConfirmation(page, prefix);
});
}
expect(planCalls).toHaveLength(1);
expect(planCalls[0].url).toMatch(/\/imports\/openapi\/[^/]+\/plans$/);
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
})).toBeVisible();
});
test('[P1] AC-13 double-click sends one Apply with the stored reference, digest and idempotency key', async ({ page }) => {
const { applyCalls, releaseApplyResponse } = await preparePlanFlow(page, 'en');
const applyButton = page.getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
});
await applyButton.dblclick();
await expect.poll(() => applyCalls.length).toBe(1);
await expect(applyButton).toBeDisabled();
releaseApplyResponse();
await expect(page.locator('[data-testid="openapi-import-apply-result"]')).toBeVisible();
expect(applyCalls).toHaveLength(1);
expect(applyCalls[0].url).toMatch(/\/imports\/openapi\/plan_e2e_importplan_213\/apply$/);
expect(applyCalls[0].payload).toMatchObject({
plan_digest: 'a'.repeat(64),
});
expect(typeof applyCalls[0].payload.idempotency_key).toBe('string');
expect(applyCalls[0].payload.idempotency_key.length).toBeGreaterThan(0);
});
test('[P1] AC-13 submits the confirmed new_version decision for the exact existing operation', async ({ page }) => {
const prefix = uniqueName('plan_version');
const targetOperationId = 'op_exact_importplan_target';
const planCalls = [];
const expectedName = prefix + '_selected';
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
items: [{ id: targetOperationId, name: expectedName, protocol: 'rest', status: 'draft' }],
page: 1,
page_size: 1,
total: 1,
}),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
const payload = route.request().postDataJSON();
planCalls.push(payload);
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_reference: 'plan_e2e_importplan_decision',
plan_digest: 'b'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: payload.selection_mode,
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
candidates: [{
key: payload.decisions[0].operation_key,
name: expectedName,
state: 'actionable',
action: 'new_version',
target_operation_id: targetOperationId,
confirmed_name: null,
auth_profile_id: null,
reason: null,
}],
}),
});
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'import-plan-decision.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(importDocument(prefix)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview'),
);
await page.locator('#openapi-import-preview').click();
await previewResponse;
const operationRow = page.locator('.openapi-import-operation').filter({ hasText: expectedName });
const operationCheckbox = operationRow.locator('[data-openapi-operation]');
await expect(operationCheckbox).toBeVisible();
const operationKey = await operationCheckbox.inputValue();
for (const checkbox of await page.locator('[data-openapi-operation]').all()) {
if (await checkbox.inputValue() !== operationKey) await checkbox.uncheck();
}
await expect(operationRow.locator('.openapi-import-operation-meta')).toContainText(expectedName);
const action = operationRow.locator('[data-openapi-decision-action]');
await expect(action.locator('option[value="new_version"]')).toBeEnabled();
await action.selectOption('new_version');
await expect(operationRow.locator('[data-openapi-decision-target]')).toHaveValue(targetOperationId);
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(targetOperationId);
expect(planCalls).toHaveLength(1);
expect(planCalls[0].selection_mode).toBe('partial');
expect(planCalls[0].selected_operation_keys).toEqual([operationKey]);
expect(planCalls[0].decisions).toEqual([{
operation_key: operationKey,
action: 'new_version',
target_operation_id: targetOperationId,
}]);
});