Files
crank/apps/ui/tests/e2e/openapi-import-plan.spec.js
bsodfather ad23cd9a46
CI / Rust Checks (pull_request) Successful in 24m43s
CI / UI Checks (pull_request) Successful in 6s
CI / Community Image Smoke (pull_request) Successful in 9m5s
CI / Frontend E2E (pull_request) Successful in 12m43s
CI / Deploy (pull_request) Skipped
fix(import): подтвердить обязательные гарантии второго эпика
2026-10-10 13:25:05 +03:00

337 lines
15 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, reportFixture) {
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(reportFixture || {
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);
});
for (const locale of ['en', 'ru']) {
test(`[P1] AC-2.13-13 renders every immutable Apply outcome in ${locale}`, async ({ page }) => {
const reportFixture = {
plan_digest: 'd'.repeat(64),
idempotency_key: 'apply-report-full-outcomes',
status: 'applied',
counts: { selected: 5, excluded: 0, created: 1, versioned: 1, renamed: 1, skipped: 1, rejected: 1 },
outcomes: [
{ key: 'GET /created', name: 'created_operation', status: 'created', version: 1 },
{ key: 'GET /versioned', name: 'versioned_operation', status: 'versioned', version: 2 },
{ key: 'GET /renamed', name: 'renamed_operation', status: 'renamed', version: 1 },
{ key: 'GET /skipped', name: 'skipped_operation', status: 'skipped', reason: 'not_selected' },
{
key: 'GET /rejected',
name: 'rejected_operation',
status: 'rejected',
reason: 'unsupported_schema',
message: 'raw-report-canary https://report-secret.example.test/internal',
},
],
};
const { releaseApplyResponse } = await preparePlanFlow(page, locale, reportFixture);
await page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
}).click();
releaseApplyResponse();
const report = page.locator('[data-testid="openapi-import-apply-result"]');
await expect(report).toBeVisible();
await expect(report.locator('.openapi-import-plan-summary')).toContainText(
localized('Applied: 3; skipped: 1; excluded: 0; rejected: 1.', 'Применено: 3; пропущено: 1; исключено: 0; отклонено: 1.'),
);
for (const outcome of reportFixture.outcomes) {
const row = report.locator(`[data-outcome="${outcome.status}"]`);
await expect(row).toHaveCount(1);
await expect(row).toContainText(outcome.name);
await expect(row).toContainText(outcome.key);
if (outcome.version) await expect(row).toContainText(`v${outcome.version}`);
if (outcome.reason) {
const reason = row.locator('.openapi-import-plan-reason');
await expect(reason).toBeVisible();
await expect(reason).toContainText(localized(
'This imported item needs review in the wizard.',
'Этот импортированный элемент нужно проверить в мастере.',
));
}
}
await expect(report.locator('[data-outcome="created"]')).toContainText(localized('Created', 'Создано'));
await expect(report.locator('[data-outcome="versioned"]')).toContainText(localized('New Draft Version', 'Новая версия черновика'));
await expect(report.locator('[data-outcome="renamed"]')).toContainText(localized('Created with confirmed name', 'Создано с подтверждённым именем'));
await expect(report.locator('[data-outcome="skipped"]')).toContainText(localized('Skipped', 'Пропущено'));
await expect(report.locator('[data-outcome="rejected"]')).toContainText(localized('Rejected', 'Отклонено'));
await expect(report).not.toContainText('raw-report-canary');
await expect(report).not.toContainText('https://report-secret.example.test/internal');
});
}
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();
await page.locator('#openapi-import-partial-mode').check();
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,
}]);
});