From 530d26684b702547176e457af3be349a07c0f5bc Mon Sep 17 00:00:00 2001 From: David Evans Date: Thu, 25 Jul 2024 20:38:09 +0100 Subject: [PATCH] Avoid flakes in download test --- e2e/helpers/downloads.ts | 16 +++++++++++----- e2e/pages/RetroArchiveList.ts | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/e2e/helpers/downloads.ts b/e2e/helpers/downloads.ts index ce1f8e3..f7660e8 100644 --- a/e2e/helpers/downloads.ts +++ b/e2e/helpers/downloads.ts @@ -1,6 +1,6 @@ import { fileURLToPath } from 'node:url'; import { join, dirname } from 'node:path'; -import { readFile, mkdir, rm } from 'node:fs/promises'; +import { readFile, mkdir, rm, stat } from 'node:fs/promises'; export const downloadDir = join( dirname(fileURLToPath(import.meta.url)), @@ -11,8 +11,11 @@ export const downloadDir = join( await rm(downloadDir, { recursive: true, force: true }); await mkdir(downloadDir, { recursive: true }); +const sleep = (ms: number) => new Promise((res) => setTimeout(res, ms)); + export async function waitForFile( name: string, + minimumSize: number, timeout: number, ): Promise { const fileName = join(downloadDir, name); @@ -20,10 +23,13 @@ export async function waitForFile( do { try { - return await readFile(fileName, { encoding: 'utf-8' }); - } catch (e) { - await new Promise((res) => setTimeout(res, 100)); - } + const { size } = await stat(fileName); + if (size >= minimumSize) { // wait until file has some content + await sleep(10); // wait a little longer to avoid partial file reads if we get unlucky with the timing + return await readFile(fileName, { encoding: 'utf-8' }); + } + } catch {} + await sleep(100); } while (Date.now() < exp); throw new Error(`Failed to download file ${name} within ${timeout}ms`); diff --git a/e2e/pages/RetroArchiveList.ts b/e2e/pages/RetroArchiveList.ts index 47f0716..474d703 100644 --- a/e2e/pages/RetroArchiveList.ts +++ b/e2e/pages/RetroArchiveList.ts @@ -20,7 +20,7 @@ export class RetroArchiveList extends Page { public async clickExportJson(): Promise { await this.click(By.linkText('Export as JSON')); - return waitForFile(`${this.slug}-export.json`, this.explicitWaitTimeout); + return waitForFile(`${this.slug}-export.json`, 10, this.explicitWaitTimeout); } public async getArchiveLabels(): Promise {