-
Notifications
You must be signed in to change notification settings - Fork 972
E2E: Downloads coverage #3859
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
Merged
Merged
E2E: Downloads coverage #3859
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,252 @@ | ||
| // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. | ||
| // See LICENSE.txt for license information. | ||
|
|
||
| import * as fs from 'fs'; | ||
| import * as http from 'http'; | ||
| import * as path from 'path'; | ||
|
|
||
| import {expect} from '@playwright/test'; | ||
| import type {ElectronApplication} from 'playwright'; | ||
|
|
||
| import {waitForAppReady} from './appReadiness'; | ||
| import {electronBinaryPath, appDir, emptyConfig} from './config'; | ||
| import {closeElectronAppFast} from './electronApp'; | ||
|
|
||
| export type DownloadServer = { | ||
| server: http.Server; | ||
| url: string; | ||
| close: () => Promise<void>; | ||
| }; | ||
|
|
||
| export async function startDownloadServer( | ||
| filename: string, | ||
| options?: {contents?: string; slow?: boolean}, | ||
| ): Promise<DownloadServer> { | ||
| const contents = options?.contents ?? 'download test contents'; | ||
| const slow = options?.slow ?? false; | ||
|
|
||
| const server = http.createServer((request, response) => { | ||
| if (request.url === '/download.txt') { | ||
| if (slow) { | ||
| // Keep the response open long enough for CI to observe a progressing | ||
| // download even when popup setup and the will-download round-trip are slow. | ||
| const chunkCount = 120; | ||
| const chunkIntervalMs = 500; | ||
| const chunkPayload = `chunk-${'x'.repeat(4096)}`; | ||
|
|
||
| response.writeHead(200, { | ||
| 'Content-Type': 'text/plain', | ||
| 'Content-Disposition': `attachment; filename="${filename}"`, | ||
| }); | ||
|
|
||
| let sentChunks = 0; | ||
| let closed = false; | ||
| let timer: ReturnType<typeof setInterval> | undefined; | ||
| const clearTimer = () => { | ||
| if (timer) { | ||
| clearInterval(timer); | ||
| timer = undefined; | ||
| } | ||
| }; | ||
| response.on('close', () => { | ||
| closed = true; | ||
| clearTimer(); | ||
| }); | ||
| const writeChunk = () => { | ||
| if (closed || response.destroyed || response.writableEnded) { | ||
| clearTimer(); | ||
| return; | ||
| } | ||
| sentChunks += 1; | ||
| response.write(`${chunkPayload}-${sentChunks}\n`); | ||
| if (sentChunks >= chunkCount) { | ||
| clearTimer(); | ||
| response.end(); | ||
| } | ||
| }; | ||
|
|
||
| writeChunk(); | ||
| if (closed) { | ||
| return; | ||
| } | ||
| timer = setInterval(writeChunk, chunkIntervalMs); | ||
| return; | ||
| } | ||
|
|
||
| response.writeHead(200, { | ||
| 'Content-Type': 'text/plain', | ||
| 'Content-Disposition': `attachment; filename="${filename}"`, | ||
| 'Content-Length': Buffer.byteLength(contents), | ||
| }); | ||
| response.end(contents); | ||
| return; | ||
| } | ||
|
|
||
| response.writeHead(200, {'Content-Type': 'text/html'}); | ||
| response.end(` | ||
| <!doctype html> | ||
| <html> | ||
| <body> | ||
| <a id="download-link" href="/download.txt">Download file</a> | ||
| </body> | ||
| </html> | ||
| `); | ||
| }); | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| server.once('error', reject); | ||
| server.listen(0, '127.0.0.1', () => resolve()); | ||
| }); | ||
| const address = server.address(); | ||
| if (!address || typeof address === 'string') { | ||
| throw new Error('Failed to start local download server'); | ||
| } | ||
|
|
||
| return { | ||
| server, | ||
| url: `http://127.0.0.1:${address.port}`, | ||
| close: () => new Promise<void>((resolve, reject) => { | ||
| server.close((error) => (error ? reject(error) : resolve())); | ||
| }), | ||
| }; | ||
| } | ||
|
|
||
| export async function launchAppWithDownloadsDir(userDataDir: string, downloadLocation: string) { | ||
| const config = { | ||
| ...emptyConfig, | ||
| downloadLocation, | ||
| }; | ||
|
|
||
| fs.mkdirSync(userDataDir, {recursive: true}); | ||
| fs.mkdirSync(downloadLocation, {recursive: true}); | ||
| fs.writeFileSync(path.join(userDataDir, 'config.json'), JSON.stringify(config)); | ||
|
|
||
| const {_electron: electron} = await import('playwright'); | ||
| const app = await electron.launch({ | ||
| executablePath: electronBinaryPath, | ||
| args: [appDir, `--user-data-dir=${userDataDir}`, '--no-sandbox', '--disable-gpu'], | ||
| env: {...process.env, NODE_ENV: 'test'}, | ||
| timeout: 60_000, | ||
| }); | ||
| await waitForAppReady(app); | ||
| return app; | ||
| } | ||
|
|
||
| export async function openDownloadsDropdown(app: ElectronApplication) { | ||
| const mainWindow = app.windows().find((window) => window.url().includes('index')) ?? | ||
| await app.waitForEvent('window', { | ||
| predicate: (window) => window.url().includes('index'), | ||
| timeout: 15_000, | ||
| }); | ||
| await mainWindow.waitForLoadState(); | ||
| await mainWindow.bringToFront(); | ||
|
|
||
| const button = await mainWindow.waitForSelector('.DownloadsDropdownButton'); | ||
| await button.click(); | ||
|
|
||
| let downloadsWindow = app.windows().find((window) => window.url().includes('downloadsDropdown.html')); | ||
| if (!downloadsWindow) { | ||
| downloadsWindow = await app.waitForEvent('window', { | ||
| predicate: (window) => window.url().includes('downloadsDropdown.html'), | ||
| timeout: 10_000, | ||
| }); | ||
| } | ||
| await downloadsWindow.waitForLoadState(); | ||
| await downloadsWindow.bringToFront(); | ||
| await downloadsWindow.waitForSelector('.DownloadsDropdown', {state: 'visible', timeout: 15_000}); | ||
| return {mainWindow, downloadsWindow}; | ||
| } | ||
|
|
||
| export async function triggerDownloadFromPopup(app: ElectronApplication, popupUrl: string) { | ||
| const popupPromise = app.waitForEvent('window', { | ||
| predicate: (window) => window.url().startsWith(popupUrl), | ||
| timeout: 15_000, | ||
| }); | ||
|
|
||
| await app.evaluate(async ({BrowserWindow}, url) => { | ||
| const popup = new BrowserWindow({ | ||
| show: true, | ||
| width: 900, | ||
| height: 700, | ||
| }); | ||
| await popup.loadURL(url); | ||
| (global as any).__e2eDownloadPopup = popup; | ||
| }, popupUrl); | ||
|
|
||
| const popupWindow = await popupPromise; | ||
| await popupWindow.waitForLoadState(); | ||
| await popupWindow.click('#download-link'); | ||
| return popupWindow; | ||
| } | ||
|
|
||
| export function readDownloadsState(userDataDir: string): Record<string, {state?: string; location?: string}> { | ||
| try { | ||
| return JSON.parse(fs.readFileSync(path.join(userDataDir, 'downloads.json'), 'utf-8')); | ||
| } catch { | ||
| return {}; | ||
| } | ||
| } | ||
|
|
||
| export async function waitForDownloadState( | ||
| userDataDir: string, | ||
| filename: string, | ||
| state: string, | ||
| timeout = 90_000, | ||
| ) { | ||
| await expect.poll( | ||
| () => readDownloadsState(userDataDir)[filename]?.state, | ||
| {timeout, intervals: [25, 50, 100, 200, 500]}, | ||
| ).toBe(state); | ||
| } | ||
|
|
||
| export async function waitForDownloadFile( | ||
| userDataDir: string, | ||
| downloadLocation: string, | ||
| filename: string, | ||
| timeout = 30_000, | ||
| ): Promise<string> { | ||
| let resolvedPath = path.join(downloadLocation, filename); | ||
| await expect.poll(() => { | ||
| const entry = readDownloadsState(userDataDir)[filename]; | ||
| if (entry?.location && fs.existsSync(entry.location)) { | ||
| resolvedPath = entry.location; | ||
| return true; | ||
| } | ||
| return fs.existsSync(path.join(downloadLocation, filename)); | ||
| }, {timeout, message: `Downloaded file "${filename}" should exist on disk`}).toBe(true); | ||
| return resolvedPath; | ||
| } | ||
|
|
||
| export async function closeDownloadTestApp(app: ElectronApplication, userDataDir: string, downloadLocation: string) { | ||
| await app.evaluate(() => { | ||
| const popup = (global as any).__e2eDownloadPopup; | ||
| if (popup && !popup.isDestroyed?.()) { | ||
| popup.close(); | ||
| } | ||
| delete (global as any).__e2eDownloadPopup; | ||
| }).catch(() => {}); | ||
|
|
||
| await closeElectronAppFast(app, userDataDir).catch(() => {}); | ||
|
|
||
| if (!fs.existsSync(downloadLocation)) { | ||
| return; | ||
| } | ||
|
|
||
| const timeout = process.platform === 'win32' ? 10_000 : 2_000; | ||
| const deadline = Date.now() + timeout; | ||
| let lastError: unknown; | ||
| while (Date.now() < deadline) { | ||
| try { | ||
| fs.rmSync(downloadLocation, {recursive: true, force: true, maxRetries: 3, retryDelay: 200}); | ||
| return; | ||
| } catch (error) { | ||
| lastError = error; | ||
| const code = (error as NodeJS.ErrnoException).code; | ||
| if (code !== 'EBUSY' && code !== 'EPERM' && code !== 'ENOTEMPTY') { | ||
| throw error; | ||
| } | ||
| await new Promise((resolve) => setTimeout(resolve, 250)); | ||
| } | ||
| } | ||
| throw lastError ?? new Error(`Failed to remove download directory: ${downloadLocation}`); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. | ||
| // See LICENSE.txt for license information. | ||
|
|
||
| import type {ElectronApplication} from 'playwright'; | ||
|
|
||
| const CLOSE_DOWNLOADS_DROPDOWN = 'close-downloads-dropdown'; | ||
| const CLOSE_DOWNLOADS_DROPDOWN_MENU = 'close-downloads-dropdown-menu'; | ||
|
|
||
| /** | ||
| * Close the downloads dropdown WebContentsView if it is open. | ||
| * Parallel download specs can leave this overlay focused and block other UI flows. | ||
| */ | ||
| export async function closeDownloadsDropdownIfOpen(app: ElectronApplication): Promise<void> { | ||
| const deadline = Date.now() + 15_000; | ||
| while (Date.now() < deadline) { | ||
| try { | ||
| await app.evaluate(({ipcMain}, channels) => { | ||
| ipcMain.emit(channels.menu); | ||
| ipcMain.emit(channels.dropdown); | ||
| }, {dropdown: CLOSE_DOWNLOADS_DROPDOWN, menu: CLOSE_DOWNLOADS_DROPDOWN_MENU}); | ||
| return; | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| if (!message.includes('Execution context was destroyed')) { | ||
| throw error; | ||
| } | ||
| await new Promise((resolve) => setTimeout(resolve, 100)); | ||
| } | ||
| } | ||
|
|
||
| throw new Error('Timed out closing downloads dropdown after navigation'); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. | ||
| // See LICENSE.txt for license information. | ||
|
|
||
| import * as path from 'path'; | ||
|
|
||
| import {test, expect} from '../../fixtures/index'; | ||
| import { | ||
| closeDownloadTestApp, | ||
| launchAppWithDownloadsDir, | ||
| openDownloadsDropdown, | ||
| readDownloadsState, | ||
| startDownloadServer, | ||
| triggerDownloadFromPopup, | ||
| waitForDownloadState, | ||
| } from '../../helpers/downloads'; | ||
|
|
||
| test( | ||
| 'DL-06 in-progress download can be cancelled from the downloads dropdown menu', | ||
| {tag: ['@P1', '@all']}, | ||
| async ({}, testInfo) => { | ||
| const filename = 'slow-cancel.txt'; | ||
| const {url, close} = await startDownloadServer(filename, {slow: true}); | ||
|
|
||
| const userDataDir = path.join(testInfo.outputDir, 'userdata'); | ||
| const downloadLocation = path.join(testInfo.outputDir, 'Downloads'); | ||
| const app = await launchAppWithDownloadsDir(userDataDir, downloadLocation); | ||
|
|
||
| try { | ||
| await Promise.all([ | ||
| triggerDownloadFromPopup(app, url), | ||
| waitForDownloadState(userDataDir, filename, 'progressing'), | ||
| ]); | ||
|
|
||
| const {downloadsWindow} = await openDownloadsDropdown(app); | ||
| await downloadsWindow.hover('.DownloadsDropdown__File'); | ||
| await downloadsWindow.click('.DownloadsDropdown__File__Body__ThreeDotButton'); | ||
|
|
||
| let menuWindow = app.windows().find((window) => window.url().includes('downloadsDropdownMenu.html')); | ||
| if (!menuWindow) { | ||
| menuWindow = await app.waitForEvent('window', { | ||
| predicate: (window) => window.url().includes('downloadsDropdownMenu.html'), | ||
| timeout: 10_000, | ||
| }); | ||
| } | ||
| await menuWindow.waitForLoadState(); | ||
| await menuWindow.click('text=Cancel Download'); | ||
|
|
||
| await expect.poll( | ||
| () => readDownloadsState(userDataDir)[filename]?.state, | ||
| {timeout: 15_000, message: 'Cancelled download should be marked cancelled in downloads.json'}, | ||
| ).toMatch(/cancelled|interrupted/); | ||
| } finally { | ||
| await Promise.allSettled([ | ||
| closeDownloadTestApp(app, userDataDir, downloadLocation), | ||
| close(), | ||
| ]); | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }, | ||
| ); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.