test(e2e): add Playwright E2E tests for Chart List page (#37866)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Joe Li
2026-02-12 14:16:11 -08:00
committed by GitHub
parent 6328e51620
commit 142b2cc425
8 changed files with 801 additions and 48 deletions

View File

@@ -0,0 +1,52 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Page } from '@playwright/test';
import { Modal } from '../core';
/**
* Chart properties edit modal.
* Opened by clicking the edit icon on a chart row in the chart list.
* General section is expanded by default (defaultActiveKey="general").
*/
export class ChartPropertiesModal extends Modal {
private static readonly SELECTORS = {
NAME_INPUT: '[data-test="properties-modal-name-input"]',
};
constructor(page: Page) {
super(page, '[data-test="properties-edit-modal"]');
}
/**
* Fills the chart name input field
* @param name - The new chart name
*/
async fillName(name: string): Promise<void> {
const input = this.body.locator(ChartPropertiesModal.SELECTORS.NAME_INPUT);
await input.fill(name);
}
/**
* Clicks the Save button in the modal footer
*/
async clickSave(): Promise<void> {
await this.clickFooterButton('Save');
}
}

View File

@@ -19,6 +19,7 @@
import type { Response, APIResponse } from '@playwright/test';
import { expect } from '@playwright/test';
import * as unzipper from 'unzipper';
/**
* Common interface for response types with status() method.
@@ -59,3 +60,60 @@ export function expectStatusOneOf<T extends ResponseLike>(
).toContain(response.status());
return response;
}
interface ExportZipOptions {
/** Directory name containing resource yaml files (e.g. 'charts', 'datasets') */
resourceDir: string;
/** Minimum number of resource yaml files expected (default: 1) */
minCount?: number;
/** Regex to validate Content-Disposition header (skipped if omitted) */
contentDispositionPattern?: RegExp;
/** Resource names that must each appear in at least one YAML filepath */
expectedNames?: string[];
}
/**
* Validate an export zip response: content-type, zip structure, and resource yaml files.
* Shared across chart and dataset export tests.
*/
export async function expectValidExportZip(
response: ResponseLike,
options: ExportZipOptions,
): Promise<void> {
const {
resourceDir,
minCount = 1,
contentDispositionPattern,
expectedNames,
} = options;
expect(response.headers()['content-type']).toContain('application/zip');
if (contentDispositionPattern) {
expect(response.headers()['content-disposition']).toMatch(
contentDispositionPattern,
);
}
const body = await response.body();
expect(body.length).toBeGreaterThan(0);
const entries: string[] = [];
const directory = await unzipper.Open.buffer(body);
directory.files.forEach(file => entries.push(file.path));
const resourceYamlFiles = entries.filter(
entry => entry.includes(`${resourceDir}/`) && entry.endsWith('.yaml'),
);
expect(resourceYamlFiles.length).toBeGreaterThanOrEqual(minCount);
expect(entries.some(entry => entry.endsWith('metadata.yaml'))).toBe(true);
if (expectedNames) {
for (const name of expectedNames) {
expect(
resourceYamlFiles.some(f => f.includes(name)),
`Expected export zip to contain a YAML file matching "${name}"`,
).toBe(true);
}
}
}

View File

@@ -0,0 +1,104 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Page, APIResponse } from '@playwright/test';
import {
apiGet,
apiPost,
apiDelete,
apiPut,
ApiRequestOptions,
} from './requests';
export const ENDPOINTS = {
CHART: 'api/v1/chart/',
CHART_EXPORT: 'api/v1/chart/export/',
} as const;
/**
* TypeScript interface for chart creation API payload.
* Only slice_name, datasource_id, datasource_type are required (ChartPostSchema).
*/
export interface ChartCreatePayload {
slice_name: string;
datasource_id: number;
datasource_type: string;
viz_type?: string;
params?: string;
}
/**
* POST request to create a chart
* @param page - Playwright page instance (provides authentication context)
* @param requestBody - Chart configuration object
* @returns API response from chart creation
*/
export async function apiPostChart(
page: Page,
requestBody: ChartCreatePayload,
): Promise<APIResponse> {
return apiPost(page, ENDPOINTS.CHART, requestBody);
}
/**
* GET request to fetch a chart's details
* @param page - Playwright page instance (provides authentication context)
* @param chartId - ID of the chart to fetch
* @param options - Optional request options
* @returns API response with chart details
*/
export async function apiGetChart(
page: Page,
chartId: number,
options?: ApiRequestOptions,
): Promise<APIResponse> {
return apiGet(page, `${ENDPOINTS.CHART}${chartId}`, options);
}
/**
* DELETE request to remove a chart
* @param page - Playwright page instance (provides authentication context)
* @param chartId - ID of the chart to delete
* @param options - Optional request options
* @returns API response from chart deletion
*/
export async function apiDeleteChart(
page: Page,
chartId: number,
options?: ApiRequestOptions,
): Promise<APIResponse> {
return apiDelete(page, `${ENDPOINTS.CHART}${chartId}`, options);
}
/**
* PUT request to update a chart
* @param page - Playwright page instance (provides authentication context)
* @param chartId - ID of the chart to update
* @param data - Partial chart payload (Marshmallow allows optional fields)
* @param options - Optional request options
* @returns API response from chart update
*/
export async function apiPutChart(
page: Page,
chartId: number,
data: Record<string, unknown>,
options?: ApiRequestOptions,
): Promise<APIResponse> {
return apiPut(page, `${ENDPOINTS.CHART}${chartId}`, data, options);
}

View File

@@ -18,6 +18,7 @@
*/
import { test as base } from '@playwright/test';
import { apiDeleteChart } from '../api/chart';
import { apiDeleteDataset } from '../api/dataset';
import { apiDeleteDatabase } from '../api/database';
@@ -26,40 +27,78 @@ import { apiDeleteDatabase } from '../api/database';
* Inspired by Cypress's cleanDashboards/cleanCharts pattern.
*/
export interface TestAssets {
trackChart(id: number): void;
trackDataset(id: number): void;
trackDatabase(id: number): void;
}
const EXPECTED_CLEANUP_STATUSES = new Set([200, 202, 204, 404]);
export const test = base.extend<{ testAssets: TestAssets }>({
testAssets: async ({ page }, use) => {
// Use Set to de-dupe IDs (same resource may be tracked multiple times)
const chartIds = new Set<number>();
const datasetIds = new Set<number>();
const databaseIds = new Set<number>();
await use({
trackChart: id => chartIds.add(id),
trackDataset: id => datasetIds.add(id),
trackDatabase: id => databaseIds.add(id),
});
// Cleanup: Delete datasets FIRST (they reference databases)
// Then delete databases. Use failOnStatusCode: false for tolerance.
// Cleanup order: charts → datasets → databases (respects FK dependencies)
// Use failOnStatusCode: false to avoid throwing on 404 (resource already deleted by test)
// Warn on unexpected status codes (401/403/500) that may indicate leaked state
await Promise.all(
[...chartIds].map(id =>
apiDeleteChart(page, id, { failOnStatusCode: false })
.then(response => {
if (!EXPECTED_CLEANUP_STATUSES.has(response.status())) {
console.warn(
`[testAssets] Unexpected status ${response.status()} cleaning up chart ${id}`,
);
}
})
.catch(error => {
console.warn(`[testAssets] Failed to cleanup chart ${id}:`, error);
}),
),
);
await Promise.all(
[...datasetIds].map(id =>
apiDeleteDataset(page, id, { failOnStatusCode: false }).catch(error => {
console.warn(`[testAssets] Failed to cleanup dataset ${id}:`, error);
}),
apiDeleteDataset(page, id, { failOnStatusCode: false })
.then(response => {
if (!EXPECTED_CLEANUP_STATUSES.has(response.status())) {
console.warn(
`[testAssets] Unexpected status ${response.status()} cleaning up dataset ${id}`,
);
}
})
.catch(error => {
console.warn(
`[testAssets] Failed to cleanup dataset ${id}:`,
error,
);
}),
),
);
await Promise.all(
[...databaseIds].map(id =>
apiDeleteDatabase(page, id, { failOnStatusCode: false }).catch(
error => {
apiDeleteDatabase(page, id, { failOnStatusCode: false })
.then(response => {
if (!EXPECTED_CLEANUP_STATUSES.has(response.status())) {
console.warn(
`[testAssets] Unexpected status ${response.status()} cleaning up database ${id}`,
);
}
})
.catch(error => {
console.warn(
`[testAssets] Failed to cleanup database ${id}:`,
error,
);
},
),
}),
),
);
},

View File

@@ -0,0 +1,132 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { Page, Locator } from '@playwright/test';
import { Table } from '../components/core';
import { BulkSelect } from '../components/ListView';
import { URL } from '../utils/urls';
/**
* Chart List Page object.
*/
export class ChartListPage {
private readonly page: Page;
private readonly table: Table;
readonly bulkSelect: BulkSelect;
/**
* Action button names for getByRole('button', { name })
* Verified: ChartList uses Icons.DeleteOutlined, Icons.UploadOutlined, Icons.EditOutlined
*/
private static readonly ACTION_BUTTONS = {
DELETE: 'delete',
EDIT: 'edit',
EXPORT: 'upload',
} as const;
constructor(page: Page) {
this.page = page;
this.table = new Table(page);
this.bulkSelect = new BulkSelect(page, this.table);
}
/**
* Navigate to the chart list page.
* Forces table view via URL parameter to avoid card view default
* (ListviewsDefaultCardView feature flag may enable card view).
*/
async goto(): Promise<void> {
await this.page.goto(`${URL.CHART_LIST}?viewMode=table`);
}
/**
* Wait for the table to load
* @param options - Optional wait options
*/
async waitForTableLoad(options?: { timeout?: number }): Promise<void> {
await this.table.waitForVisible(options);
}
/**
* Gets a chart row locator by name.
* Returns a Locator that tests can use with expect().toBeVisible(), etc.
*
* @param chartName - The name of the chart
* @returns Locator for the chart row
*/
getChartRow(chartName: string): Locator {
return this.table.getRow(chartName);
}
/**
* Clicks the delete action button for a chart
* @param chartName - The name of the chart to delete
*/
async clickDeleteAction(chartName: string): Promise<void> {
const row = this.table.getRow(chartName);
await row
.getByRole('button', { name: ChartListPage.ACTION_BUTTONS.DELETE })
.click();
}
/**
* Clicks the edit action button for a chart
* @param chartName - The name of the chart to edit
*/
async clickEditAction(chartName: string): Promise<void> {
const row = this.table.getRow(chartName);
await row
.getByRole('button', { name: ChartListPage.ACTION_BUTTONS.EDIT })
.click();
}
/**
* Clicks the export action button for a chart
* @param chartName - The name of the chart to export
*/
async clickExportAction(chartName: string): Promise<void> {
const row = this.table.getRow(chartName);
await row
.getByRole('button', { name: ChartListPage.ACTION_BUTTONS.EXPORT })
.click();
}
/**
* Clicks the "Bulk select" button to enable bulk selection mode
*/
async clickBulkSelectButton(): Promise<void> {
await this.bulkSelect.enable();
}
/**
* Selects a chart's checkbox in bulk select mode
* @param chartName - The name of the chart to select
*/
async selectChartCheckbox(chartName: string): Promise<void> {
await this.bulkSelect.selectRow(chartName);
}
/**
* Clicks a bulk action button by name (e.g., "Export", "Delete")
* @param actionName - The name of the bulk action to click
*/
async clickBulkAction(actionName: string): Promise<void> {
await this.bulkSelect.clickAction(actionName);
}
}

View File

@@ -0,0 +1,307 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
test as testWithAssets,
expect,
} from '../../../helpers/fixtures/testAssets';
import { ChartListPage } from '../../../pages/ChartListPage';
import { ChartPropertiesModal } from '../../../components/modals/ChartPropertiesModal';
import { DeleteConfirmationModal } from '../../../components/modals/DeleteConfirmationModal';
import { Toast } from '../../../components/core/Toast';
import { apiGetChart, ENDPOINTS } from '../../../helpers/api/chart';
import { createTestChart } from './chart-test-helpers';
import { waitForGet, waitForPut } from '../../../helpers/api/intercepts';
import {
expectStatusOneOf,
expectValidExportZip,
} from '../../../helpers/api/assertions';
/**
* Extend testWithAssets with chartListPage navigation (beforeEach equivalent).
*/
const test = testWithAssets.extend<{ chartListPage: ChartListPage }>({
chartListPage: async ({ page }, use) => {
const chartListPage = new ChartListPage(page);
await chartListPage.goto();
await chartListPage.waitForTableLoad();
await use(chartListPage);
},
});
test('should delete a chart with confirmation', async ({
page,
chartListPage,
testAssets,
}) => {
// Create throwaway chart for deletion
const { id: chartId, name: chartName } = await createTestChart(
page,
testAssets,
test.info(),
{ prefix: 'test_delete' },
);
// Refresh to see the new chart (created via API)
await chartListPage.goto();
await chartListPage.waitForTableLoad();
// Verify chart is visible in list
await expect(chartListPage.getChartRow(chartName)).toBeVisible();
// Click delete action button
await chartListPage.clickDeleteAction(chartName);
// Delete confirmation modal should appear
const deleteModal = new DeleteConfirmationModal(page);
await deleteModal.waitForVisible();
// Type "DELETE" to confirm
await deleteModal.fillConfirmationInput('DELETE');
// Click the Delete button
await deleteModal.clickDelete();
// Modal should close
await deleteModal.waitForHidden();
// Verify success toast appears
const toast = new Toast(page);
await expect(toast.getSuccess()).toBeVisible();
// Verify chart is removed from list
await expect(chartListPage.getChartRow(chartName)).not.toBeVisible();
// Backend verification: API returns 404
await expect
.poll(
async () => {
const response = await apiGetChart(page, chartId, {
failOnStatusCode: false,
});
return response.status();
},
{ timeout: 10000, message: `Chart ${chartId} should return 404` },
)
.toBe(404);
});
test('should edit chart name via properties modal', async ({
page,
chartListPage,
testAssets,
}) => {
// Create throwaway chart for editing
const { id: chartId, name: chartName } = await createTestChart(
page,
testAssets,
test.info(),
{ prefix: 'test_edit' },
);
// Refresh to see the new chart
await chartListPage.goto();
await chartListPage.waitForTableLoad();
// Verify chart is visible in list
await expect(chartListPage.getChartRow(chartName)).toBeVisible();
// Click edit action to open properties modal
await chartListPage.clickEditAction(chartName);
// Wait for properties modal to be ready
const propertiesModal = new ChartPropertiesModal(page);
await propertiesModal.waitForReady();
// Edit the chart name
const newName = `renamed_${Date.now()}_${test.info().parallelIndex}`;
await propertiesModal.fillName(newName);
// Set up response intercept for save
const saveResponsePromise = waitForPut(page, `${ENDPOINTS.CHART}${chartId}`);
// Click Save button
await propertiesModal.clickSave();
// Wait for save to complete and verify success
expectStatusOneOf(await saveResponsePromise, [200, 201]);
// Modal should close
await propertiesModal.waitForHidden();
// Verify success toast appears
const toast = new Toast(page);
await expect(toast.getSuccess()).toBeVisible();
// Backend verification: API returns updated name
const response = await apiGetChart(page, chartId);
const chart = (await response.json()).result;
expect(chart.slice_name).toBe(newName);
});
test('should export a chart as a zip file', async ({
page,
chartListPage,
testAssets,
}) => {
// Create throwaway chart for export
const { name: chartName } = await createTestChart(
page,
testAssets,
test.info(),
{ prefix: 'test_export' },
);
// Refresh to see the new chart
await chartListPage.goto();
await chartListPage.waitForTableLoad();
// Verify chart is visible in list
await expect(chartListPage.getChartRow(chartName)).toBeVisible();
// Set up API response intercept for export endpoint
const exportResponsePromise = waitForGet(page, ENDPOINTS.CHART_EXPORT);
// Click export action button
await chartListPage.clickExportAction(chartName);
// Wait for export API response and validate zip contents
const exportResponse = expectStatusOneOf(await exportResponsePromise, [200]);
await expectValidExportZip(exportResponse, {
resourceDir: 'charts',
expectedNames: [chartName],
});
});
test('should bulk delete multiple charts', async ({
page,
chartListPage,
testAssets,
}) => {
test.setTimeout(60_000);
// Create 2 throwaway charts for bulk delete
const [chart1, chart2] = await Promise.all([
createTestChart(page, testAssets, test.info(), {
prefix: 'bulk_delete_1',
}),
createTestChart(page, testAssets, test.info(), {
prefix: 'bulk_delete_2',
}),
]);
// Refresh to see new charts
await chartListPage.goto();
await chartListPage.waitForTableLoad();
// Verify both charts are visible in list
await expect(chartListPage.getChartRow(chart1.name)).toBeVisible();
await expect(chartListPage.getChartRow(chart2.name)).toBeVisible();
// Enable bulk select mode
await chartListPage.clickBulkSelectButton();
// Select both charts
await chartListPage.selectChartCheckbox(chart1.name);
await chartListPage.selectChartCheckbox(chart2.name);
// Click bulk delete action
await chartListPage.clickBulkAction('Delete');
// Delete confirmation modal should appear
const deleteModal = new DeleteConfirmationModal(page);
await deleteModal.waitForVisible();
// Type "DELETE" to confirm
await deleteModal.fillConfirmationInput('DELETE');
// Click the Delete button
await deleteModal.clickDelete();
// Modal should close
await deleteModal.waitForHidden();
// Verify success toast appears
const toast = new Toast(page);
await expect(toast.getSuccess()).toBeVisible();
// Verify both charts are removed from list
await expect(chartListPage.getChartRow(chart1.name)).not.toBeVisible();
await expect(chartListPage.getChartRow(chart2.name)).not.toBeVisible();
// Backend verification: Both return 404
for (const chart of [chart1, chart2]) {
await expect
.poll(
async () => {
const response = await apiGetChart(page, chart.id, {
failOnStatusCode: false,
});
return response.status();
},
{ timeout: 10000, message: `Chart ${chart.id} should return 404` },
)
.toBe(404);
}
});
test('should bulk export multiple charts', async ({
page,
chartListPage,
testAssets,
}) => {
// Create 2 throwaway charts for bulk export
const [chart1, chart2] = await Promise.all([
createTestChart(page, testAssets, test.info(), {
prefix: 'bulk_export_1',
}),
createTestChart(page, testAssets, test.info(), {
prefix: 'bulk_export_2',
}),
]);
// Refresh to see new charts
await chartListPage.goto();
await chartListPage.waitForTableLoad();
// Verify both charts are visible in list
await expect(chartListPage.getChartRow(chart1.name)).toBeVisible();
await expect(chartListPage.getChartRow(chart2.name)).toBeVisible();
// Enable bulk select mode
await chartListPage.clickBulkSelectButton();
// Select both charts
await chartListPage.selectChartCheckbox(chart1.name);
await chartListPage.selectChartCheckbox(chart2.name);
// Set up API response intercept for export endpoint
const exportResponsePromise = waitForGet(page, ENDPOINTS.CHART_EXPORT);
// Click bulk export action
await chartListPage.clickBulkAction('Export');
// Wait for export API response and validate zip contains both charts
const exportResponse = expectStatusOneOf(await exportResponsePromise, [200]);
await expectValidExportZip(exportResponse, {
resourceDir: 'charts',
minCount: 2,
expectedNames: [chart1.name, chart2.name],
});
});

View File

@@ -0,0 +1,88 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import type { Page, TestInfo } from '@playwright/test';
import type { TestAssets } from '../../../helpers/fixtures/testAssets';
import { apiPostChart } from '../../../helpers/api/chart';
import { getDatasetByName } from '../../../helpers/api/dataset';
interface TestChartResult {
id: number;
name: string;
}
interface CreateTestChartOptions {
/** Prefix for generated name (default: 'test_chart') */
prefix?: string;
}
/**
* Creates a test chart via the API for E2E testing.
* Uses the members_channels_2 dataset (loaded via --load-examples).
*
* @example
* const { id, name } = await createTestChart(page, testAssets, test.info());
*
* @example
* const { id, name } = await createTestChart(page, testAssets, test.info(), {
* prefix: 'test_delete',
* });
*/
export async function createTestChart(
page: Page,
testAssets: TestAssets,
testInfo: TestInfo,
options?: CreateTestChartOptions,
): Promise<TestChartResult> {
const prefix = options?.prefix ?? 'test_chart';
const name = `${prefix}_${Date.now()}_${testInfo.parallelIndex}`;
// Look up the members_channels_2 dataset for chart creation
const dataset = await getDatasetByName(page, 'members_channels_2');
if (!dataset) {
throw new Error(
'members_channels_2 dataset not found — run Superset with --load-examples',
);
}
const response = await apiPostChart(page, {
slice_name: name,
datasource_id: dataset.id,
datasource_type: 'table',
viz_type: 'table',
params: '{}',
});
if (!response.ok()) {
throw new Error(`Failed to create test chart: ${response.status()}`);
}
const body = await response.json();
// Handle both response shapes: { id } or { result: { id } }
const id = body.result?.id ?? body.id;
if (!id) {
throw new Error(
`Chart creation returned no id. Response: ${JSON.stringify(body)}`,
);
}
testAssets.trackChart(id);
return { id, name };
}

View File

@@ -21,9 +21,7 @@ import {
test as testWithAssets,
expect,
} from '../../../helpers/fixtures/testAssets';
import type { Response } from '@playwright/test';
import path from 'path';
import * as unzipper from 'unzipper';
import { DatasetListPage } from '../../../pages/DatasetListPage';
import { ExplorePage } from '../../../pages/ExplorePage';
import { ConfirmDialog } from '../../../components/modals/ConfirmDialog';
@@ -45,7 +43,10 @@ import {
waitForPost,
waitForPut,
} from '../../../helpers/api/intercepts';
import { expectStatusOneOf } from '../../../helpers/api/assertions';
import {
expectStatusOneOf,
expectValidExportZip,
} from '../../../helpers/api/assertions';
import { TIMEOUT } from '../../../utils/constants';
/**
@@ -60,40 +61,6 @@ const test = testWithAssets.extend<{ datasetListPage: DatasetListPage }>({
},
});
/**
* Helper to validate an export zip response.
* Verifies headers, parses zip contents, and validates expected structure.
*/
async function expectValidExportZip(
response: Response,
options: { minDatasetCount?: number; checkContentDisposition?: boolean } = {},
): Promise<void> {
const { minDatasetCount = 1, checkContentDisposition = false } = options;
// Verify headers
expect(response.headers()['content-type']).toContain('application/zip');
if (checkContentDisposition) {
expect(response.headers()['content-disposition']).toMatch(
/filename=.*dataset_export.*\.zip/,
);
}
// Parse and validate zip contents
const body = await response.body();
expect(body.length).toBeGreaterThan(0);
const entries: string[] = [];
const directory = await unzipper.Open.buffer(body);
directory.files.forEach(file => entries.push(file.path));
// Validate structure
const datasetYamlFiles = entries.filter(
entry => entry.includes('datasets/') && entry.endsWith('.yaml'),
);
expect(datasetYamlFiles.length).toBeGreaterThanOrEqual(minDatasetCount);
expect(entries.some(entry => entry.endsWith('metadata.yaml'))).toBe(true);
}
test('should navigate to Explore when dataset name is clicked', async ({
page,
datasetListPage,
@@ -286,7 +253,10 @@ test('should export a dataset as a zip file', async ({
// Wait for export API response and validate zip contents
const exportResponse = expectStatusOneOf(await exportResponsePromise, [200]);
await expectValidExportZip(exportResponse, { checkContentDisposition: true });
await expectValidExportZip(exportResponse, {
resourceDir: 'datasets',
contentDispositionPattern: /filename=.*dataset_export.*\.zip/,
});
});
test('should export multiple datasets via bulk select action', async ({
@@ -327,7 +297,10 @@ test('should export multiple datasets via bulk select action', async ({
// Wait for export API response and validate zip contains multiple datasets
const exportResponse = expectStatusOneOf(await exportResponsePromise, [200]);
await expectValidExportZip(exportResponse, { minDatasetCount: 2 });
await expectValidExportZip(exportResponse, {
resourceDir: 'datasets',
minCount: 2,
});
});
test('should edit dataset name via modal', async ({