Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

front: simplify and make simulation PDF download test more robust #11027

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
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
15 changes: 4 additions & 11 deletions front/tests/013-stdcm-simulation-sheet.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import STDCMPage from './pages/stdcm/stdcm-page';
import ViaSection from './pages/stdcm/via-section';
import { waitForInfraStateToBeCached } from './utils';
import { getInfra } from './utils/api-utils';
import { findFirstPdf, parsePdfText, verifySimulationContent } from './utils/pdf-parser';
import { parsePdfText, verifySimulationContent } from './utils/pdf-parser';
import type { ConsistFields, PdfSimulationContent } from './utils/types';

test.describe('Verify stdcm simulation page', () => {
Expand Down Expand Up @@ -71,7 +71,7 @@ test.describe('Verify stdcm simulation page', () => {
await waitForInfraStateToBeCached(infra.id);
});

let downloadDir: string | undefined;
let downloadPath: string | undefined;

/** *************** Test 1 **************** */
test('Verify STDCM stops and simulation sheet', async ({ browserName, context }, testInfo) => {
Expand Down Expand Up @@ -102,8 +102,7 @@ test.describe('Verify stdcm simulation page', () => {
await simulationResultPage.displayAllOperationalPoints();
await simulationResultPage.verifyTableData('./tests/assets/stdcm/stdcm-with-all-via.json');
await simulationResultPage.retainSimulation();
downloadDir = testInfo.outputDir;
await simulationResultPage.downloadSimulation(downloadDir);
downloadPath = await simulationResultPage.downloadSimulation(testInfo.outputDir);
// Reset and verify empty fields
const [newPage] = await Promise.all([
context.waitForEvent('page'),
Expand All @@ -122,13 +121,7 @@ test.describe('Verify stdcm simulation page', () => {

/** *************** Test 2 *************** */
test('Verify simulation sheet content', async () => {
const pdfFilePath = findFirstPdf(downloadDir!);

if (!pdfFilePath) {
throw new Error(`No PDF files found in directory: ${downloadDir}`);
}
// Read and parse the PDF
const pdfBuffer = fs.readFileSync(pdfFilePath);
const pdfBuffer = fs.readFileSync(downloadPath!);
const actualPdfSimulationContent = await parsePdfText(pdfBuffer);
const expectedPdfSimulationContent: PdfSimulationContent = simulationSheetDetails();
verifySimulationContent(actualPdfSimulationContent, expectedPdfSimulationContent);
Expand Down
36 changes: 11 additions & 25 deletions front/tests/pages/stdcm/simulation-results-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ class SimulationResultPage extends STDCMPage {

private readonly downloadSimulationButton: Locator;

private readonly downloadLink: Locator;

private readonly startNewQueryButton: Locator;

private readonly startNewQueryWithDataButton: Locator;
Expand All @@ -50,8 +48,6 @@ class SimulationResultPage extends STDCMPage {
this.allViasButton = page.getByTestId('all-vias-button');
this.retainSimulationButton = page.getByTestId('retain-simulation-button');
this.downloadSimulationButton = page.locator('.download-simulation a[download]');
this.downloadSimulationButton = page.locator('.download-simulation a[download]');
this.downloadLink = page.locator('.download-simulation a');
this.startNewQueryButton = page.getByTestId('start-new-query-button');
this.startNewQueryWithDataButton = page.getByTestId('start-new-query-with-data-button');
this.simulationList = page.locator('.stdcm-results .simulation-list');
Expand Down Expand Up @@ -119,37 +115,27 @@ class SimulationResultPage extends STDCMPage {
await expect(this.startNewQueryWithDataButton).toBeVisible();
}

async downloadSimulation(downloadDir: string): Promise<void> {
async downloadSimulation(downloadDir: string): Promise<string> {
// Wait until there are no network requests for stability
await this.page.waitForLoadState('networkidle');

// Get the download link element and suggested filename
const suggestedFilename = await this.downloadLink.getAttribute('download');
expect(suggestedFilename).toMatch(/^Stdcm.*\.pdf$/);

const downloadPath = path.join(downloadDir, suggestedFilename!);

await fs.promises.mkdir(downloadDir, { recursive: true });

// Get the file content from the `blob:` URL
const fileContent = await this.downloadSimulationButton.evaluate(async (el) => {
if (!(el instanceof HTMLAnchorElement)) {
throw new Error('Element is not an anchor tag');
}
// react-pdf will create an <a> element without an href attribute while
// it's generating the PDF file
await expect(this.downloadSimulationButton).toHaveAttribute('href');

const response = await fetch(el.href);
if (!response.ok) {
throw new Error(`Failed to fetch the blob: ${response.status} ${response.statusText}`);
}
const downloadPromise = this.page.waitForEvent('download');
await this.downloadSimulationButton.click();
const download = await downloadPromise;

const buffer = await response.arrayBuffer();
return Array.from(new Uint8Array(buffer));
});
expect(download.suggestedFilename()).toMatch(/^Stdcm.*\.pdf$/);

// Write the file to the local file system
await fs.promises.writeFile(downloadPath, Buffer.from(fileContent));
const downloadPath = path.join(downloadDir, download.suggestedFilename());
await download.saveAs(downloadPath);

logger.info(`The PDF was successfully downloaded to: ${downloadPath}`);
return downloadPath;
}

async startNewQuery() {
Expand Down
23 changes: 0 additions & 23 deletions front/tests/utils/pdf-parser.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,7 @@
import fs from 'fs';
import path from 'path';

import { expect } from '@playwright/test';
import { getDocument } from 'pdfjs-dist/legacy/build/pdf.mjs';

import type { PdfSimulationContent } from './types';
import { logger } from '../logging-fixture';

/**
* Find the first PDF file in a directory.
* @param directory - The directory to search in.
* @returns The absolute path to the PDF file, or `null` if no PDF file is found.
*/
export function findFirstPdf(directory: string): string | null {
try {
const pdfFile = fs.readdirSync(directory).find((file) => file.endsWith('.pdf'));
if (!pdfFile) {
logger.error(`No PDF files found in directory: ${directory}`);
return null;
}
return path.resolve(directory, pdfFile);
} catch (error) {
logger.error(`Error reading directory: ${directory}`, error);
return null;
}
}

export async function parsePdfText(buffer: Buffer) {
const doc = await getDocument(new Uint8Array(buffer.buffer)).promise;
Expand Down
Loading