Skip to content

Commit

Permalink
fixup! front: add towed rolling stock e2e test
Browse files Browse the repository at this point in the history
  • Loading branch information
Maymanaf committed Dec 20, 2024
1 parent 732200b commit 1db1fb2
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 88 deletions.
8 changes: 4 additions & 4 deletions front/tests/006-stdcm.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ test.describe('Verify train schedule elements and filters', () => {
maxSpeed: '288',
};
const towedRollingStockPrefilledValues = {
tonnage: '946',
length: '426',
maxSpeed: '288',
tonnage: '46',
length: '26',
maxSpeed: '180',
};

test.beforeAll('Fetch infrastructure', async () => {
Expand Down Expand Up @@ -164,7 +164,7 @@ test.describe('Verify train schedule elements and filters', () => {
await stdcmPage.verifySimulationDetails({
language: OSRDLanguage,
simulationNumber: 2,
simulationLengthAndDuration: '51 km — 20min',
simulationLengthAndDuration: '51 km — 24min',
});
await stdcmPage.verifyTableData(
'./tests/assets/stdcm/towedRollingStock/towedRollingStockTableResult.json'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
"C": 0.0225504
},
"const_gamma": 0.8,
"max_speed": 80
"max_speed": 50
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"index": 3,
"operationalPoint": "South_station",
"code": "BV",
"endStop": "20:41",
"endStop": "20:46",
"passageStop": "",
"startStop": "",
"weight": "561t",
Expand Down
185 changes: 107 additions & 78 deletions front/tests/pages/stdcm-page-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { expect, type Locator, type Page } from '@playwright/test';

import enTranslations from '../../public/locales/en/stdcm.json';
import frTranslations from '../../public/locales/fr/stdcm.json';
import { logger } from '../test-logger';
import {
CI_SUGGESTIONS,
DEFAULT_DETAILS,
Expand All @@ -13,6 +12,7 @@ import {
VIA_STOP_TIMES,
VIA_STOP_TYPES,
} from '../assets/stdcm-const';
import { logger } from '../test-logger';
import { handleAndVerifyInput, readJsonFile } from '../utils';

interface TableRow {
Expand Down Expand Up @@ -337,68 +337,89 @@ class STDCMPage {
await this.verifySuggestions(CI_SUGGESTIONS.south);
}

// Fills fields with test values in the consist section
// Fill fields with test values in the consist section
async fillAndVerifyConsistDetails(
fields: ConsistFields,
prefilledTractionEngineTonnage: string,
prefilledTractionEngineLength: string,
prefilledTractionEngineMaxSpeed: string,
prefilledTowedRollingStockTonnage?: string,
prefilledTowedRollingStockLength?: string,
prefilledTowedRollingStockMaxSpeed?: string
consistFields: ConsistFields,
tractionEngineTonnage: string,
tractionEngineLength: string,
tractionEngineMaxSpeed: string,
towedRollingStockTonnage?: string,
towedRollingStockLength?: string,
towedRollingStockMaxSpeed?: string
): Promise<void> {
// Generic function to handle dropdown selection and verify the first value
const { tractionEngine, towedRollingStock, tonnage, length, maxSpeed, speedLimitTag } =
consistFields;

// Generic utility for handling dropdown selection and value verification
const handleAndVerifyDropdown = async (
dropdownField: Locator,
prefilledValues: { tonnage: string; length: string; maxSpeed: string },
expectedValues: { expectedTonnage: string; expectedLength: string; expectedMaxSpeed: string },
selectedValue?: string
) => {
if (selectedValue) {
await dropdownField.fill(selectedValue);
await dropdownField.press('ArrowDown');
await dropdownField.press('Enter');
await dropdownField.dispatchEvent('blur');
await expect(dropdownField).toHaveValue(selectedValue);

// Verify the prefilled values
const { tonnage, length, maxSpeed } = prefilledValues;
await expect(this.tonnageField).toHaveValue(tonnage);
await expect(this.lengthField).toHaveValue(length);
await expect(this.maxSpeedField).toHaveValue(maxSpeed);
if (!selectedValue) return;

await dropdownField.fill(selectedValue);
await dropdownField.press('ArrowDown');
await dropdownField.press('Enter');
await dropdownField.dispatchEvent('blur');
await expect(dropdownField).toHaveValue(selectedValue);

const { expectedTonnage, expectedLength, expectedMaxSpeed } = expectedValues;
await expect(this.tonnageField).toHaveValue(expectedTonnage);
await expect(this.lengthField).toHaveValue(expectedLength);
await expect(this.maxSpeedField).toHaveValue(expectedMaxSpeed);
};

// Utility to calculate prefilled values for towed rolling stock
const calculateTowedPrefilledValues = () => {
if (!towedRollingStockTonnage || !towedRollingStockLength || !towedRollingStockMaxSpeed) {
return { expectedTonnage: '0', expectedLength: '0', expectedMaxSpeed: '0' };
}

return {
expectedTonnage: (
parseFloat(towedRollingStockTonnage) + parseFloat(tractionEngineTonnage)
).toString(),
expectedLength: (
parseFloat(towedRollingStockLength) + parseFloat(tractionEngineLength)
).toString(),
expectedMaxSpeed: Math.min(
parseFloat(towedRollingStockMaxSpeed),
parseFloat(tractionEngineMaxSpeed)
).toString(),
};
};

// Handle traction engine field
// Calculate prefilled values for the towed rolling stock
const towedPrefilledValues = calculateTowedPrefilledValues();

// Fill and verify traction engine dropdown
await handleAndVerifyDropdown(
this.tractionEngineField,
{
tonnage: prefilledTractionEngineTonnage,
length: prefilledTractionEngineLength,
maxSpeed: prefilledTractionEngineMaxSpeed,
expectedTonnage: tractionEngineTonnage,
expectedLength: tractionEngineLength,
expectedMaxSpeed: tractionEngineMaxSpeed,
},
fields.tractionEngine
tractionEngine
);

// Handle towed rolling stock field
// Fill and verify towed rolling stock dropdown
await handleAndVerifyDropdown(
this.towedRollingStockField,
{
tonnage: prefilledTowedRollingStockTonnage || '',
length: prefilledTowedRollingStockLength || '',
maxSpeed: prefilledTowedRollingStockMaxSpeed || '',
},
fields.towedRollingStock
towedPrefilledValues,
towedRollingStock
);

// Handle input fields for tonnage, length, and max speed
await handleAndVerifyInput(this.tonnageField, fields.tonnage);
await handleAndVerifyInput(this.lengthField, fields.length);
await handleAndVerifyInput(this.maxSpeedField, fields.maxSpeed);
// Fill and verify individual fields
await handleAndVerifyInput(this.tonnageField, tonnage);
await handleAndVerifyInput(this.lengthField, length);
await handleAndVerifyInput(this.maxSpeedField, maxSpeed);

// Handle speed limit tag if present
if (fields.speedLimitTag) {
await this.speedLimitTagField.selectOption(fields.speedLimitTag);
await expect(this.speedLimitTagField).toHaveValue(fields.speedLimitTag);
// Handle optional speed limit tag
if (speedLimitTag) {
await this.speedLimitTagField.selectOption(speedLimitTag);
await expect(this.speedLimitTagField).toHaveValue(speedLimitTag);
}
}

Expand Down Expand Up @@ -523,14 +544,18 @@ class STDCMPage {
await this.mapContainer.click();
}

async fillAndVerifyViaDetails(
viaNumber: number,
ciSearchText: string,
selectedLanguage?: string
) {
async fillAndVerifyViaDetails({
viaNumber,
ciSearchText,
language,
}: {
viaNumber: number;
ciSearchText: string;
language?: string;
}): Promise<void> {
const { PASSAGE_TIME, SERVICE_STOP, DRIVER_SWITCH } = VIA_STOP_TYPES;
const { serviceStop, driverSwitch } = VIA_STOP_TIMES;
const translations = selectedLanguage === 'English' ? enTranslations : frTranslations;
const translations = language === 'English' ? enTranslations : frTranslations;
const warning = this.getViaWarning(viaNumber);
// Helper function to fill common fields
const fillVia = async (selectedSuggestion: Locator) => {
Expand Down Expand Up @@ -576,20 +601,20 @@ class STDCMPage {

// Launch the simulation and check if simulation-related elements are visible
async launchSimulation() {
await this.launchSimulationButton.waitFor({ timeout: 30 * 1000 });
await expect(this.launchSimulationButton).toBeEnabled();
await this.launchSimulationButton.click({ force: true });
const simulationElements = await this.simulationList.all();
await Promise.all(
simulationElements.map((simulationElement) =>
simulationElement.waitFor({ timeout: 30 * 1000 })
)
);
expect(await this.simulationList.count()).toBeGreaterThanOrEqual(1);
// Check map result container visibility only for Chromium browser
if (this.page.context().browser()?.browserType().name() === 'chromium') {
await expect(this.mapResultContainer).toBeVisible();
}
await expect(async () => {
await this.launchSimulationButton.waitFor();
await expect(this.launchSimulationButton).toBeEnabled();
await this.launchSimulationButton.click({ force: true });
const simulationElements = await this.simulationList.all();
await Promise.all(simulationElements.map((simulationElement) => simulationElement.waitFor()));
expect(await this.simulationList.count()).toBeGreaterThanOrEqual(1);
// Check map result container visibility only for Chromium browser
if (this.page.context().browser()?.browserType().name() === 'chromium') {
await expect(this.mapResultContainer).toBeVisible();
}
}).toPass({
timeout: 90_000,
});
}

async verifyTableData(tableDataPath: string): Promise<void> {
Expand Down Expand Up @@ -643,20 +668,22 @@ class STDCMPage {
}

async downloadSimulation(browserName: string) {
// Wait for the download event
await this.page.waitForTimeout(1000);
const downloadPromise = this.page.waitForEvent('download', { timeout: 120000 });
await this.downloadSimulationButton.dispatchEvent('click');
const download = await downloadPromise.catch(() => {
throw new Error('Download event was not triggered.');
await expect(async () => {
const downloadPromise = this.page.waitForEvent('download');
await this.downloadSimulationButton.dispatchEvent('click');
const download = await downloadPromise.catch(() => {
throw new Error('Download event was not triggered.');
});

// Verify filename and save the download
const suggestedFilename = download.suggestedFilename();
expect(suggestedFilename).toMatch(/^STDCM.*\.pdf$/);
const downloadPath = `./tests/stdcm-results/${browserName}/${suggestedFilename}`;
await download.saveAs(downloadPath);
logger.info(`The PDF was successfully downloaded to: ${downloadPath}`);
}).toPass({
timeout: 90_000,
});

// Verify filename and save the download
const suggestedFilename = download.suggestedFilename();
expect(suggestedFilename).toMatch(/^STDCM.*\.pdf$/);
const downloadPath = `./tests/stdcm-results/${browserName}/${suggestedFilename}`;
await download.saveAs(downloadPath);
logger.info(`The PDF was successfully downloaded to: ${downloadPath}`);
}

async startNewQuery() {
Expand Down Expand Up @@ -685,7 +712,7 @@ class STDCMPage {
simulationLengthAndDuration?: string | null;
}): Promise<void> {
const translations = language === 'English' ? enTranslations : frTranslations;

const noCapacityLengthAndDuration = '— ';
// Determine expected simulation name
const isResultTableVisible = await this.simulationResultTable.isVisible();
const expectedSimulationName = isResultTableVisible
Expand All @@ -698,7 +725,9 @@ class STDCMPage {
expect(actualSimulationName).toEqual(expectedSimulationName);

// Determine expected length and duration
const expectedLengthAndDuration = isResultTableVisible ? simulationLengthAndDuration : '— ';
const expectedLengthAndDuration = isResultTableVisible
? simulationLengthAndDuration
: noCapacityLengthAndDuration;
const actualLengthAndDuration =
await this.getSimulationLengthAndDurationLocator(simulationNumber).textContent();

Expand Down
8 changes: 4 additions & 4 deletions front/tests/utils/api-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ export async function setStdcmEnvironment(stdcmEnvironment: StdcmSearchEnvironme
* @param towedRollingStockName - The name of the towed rolling stock to retrieve.
* @returns {Promise<TowedRollingStock >} - The matching towed rolling stock data .
*/
export const getTowedRollingStock = async (
export const getTowedRollingStockByName = async (
towedRollingStockName: string
): Promise<TowedRollingStock | undefined> => {
const towedRollingStocks: GetTowedRollingStockApiResponse = await getApiRequest(
Expand All @@ -281,17 +281,17 @@ export const getTowedRollingStock = async (
const towedRollingStock = towedRollingStocks.results.find(
(t: TowedRollingStock) => t.name === towedRollingStockName
);
return towedRollingStock as TowedRollingStock;
return towedRollingStock;
};

/**
* Creates a towed rolling stock using predefined data from the imported JSON file.
* Create a towed rolling stock using predefined data from the imported JSON file.
*
* @returns {Promise<TowedRollingStock>} - The created towed rolling stock.
*/
export async function setTowedRollingStock(): Promise<TowedRollingStock> {
// Check if the towed rolling stock already exists
const existingTowedRollingStock = await getTowedRollingStock(towedRollingStockData.name);
const existingTowedRollingStock = await getTowedRollingStockByName(towedRollingStockData.name);
if (existingTowedRollingStock) {
logger.info(`Towed rolling stock with name "${towedRollingStockData.name}" already exists.`);
return existingTowedRollingStock;
Expand Down

0 comments on commit 1db1fb2

Please sign in to comment.