|
| 1 | +import fs from 'fs'; |
| 2 | +import path from 'path'; |
| 3 | + |
| 4 | +import type {eventWithTime as RrwebEvent} from '@rrweb/types'; |
| 5 | +import fsExtra from 'fs-extra'; |
| 6 | +import _ from 'lodash'; |
| 7 | +import type Testplane from 'testplane'; |
| 8 | +import {RecordMode} from 'testplane'; |
| 9 | +import yazl from 'yazl'; |
| 10 | + |
| 11 | +import {ReporterTestResult} from '../../test-result'; |
| 12 | +import {SNAPSHOTS_PATH} from '../../../constants'; |
| 13 | +import {AttachmentType, SnapshotAttachment} from '../../../types'; |
| 14 | +import {EventSource} from '../../../gui/event-source'; |
| 15 | +import {ClientEvents} from '../../../gui/constants'; |
| 16 | + |
| 17 | +export interface TestContext { |
| 18 | + testPath: string[]; |
| 19 | + browserId: string; |
| 20 | +} |
| 21 | + |
| 22 | +export interface SnapshotsData { |
| 23 | + rrwebSnapshots: RrwebEvent[]; |
| 24 | +} |
| 25 | + |
| 26 | +export const snapshotsInProgress: Record<string, RrwebEvent[]> = {}; |
| 27 | + |
| 28 | +export const getSnapshotHashWithoutAttempt = (context: TestContext): string => { |
| 29 | + return `${context.testPath.join()}.${context.browserId}`; |
| 30 | +}; |
| 31 | + |
| 32 | +interface CreateSnapshotFilePathParams { |
| 33 | + attempt: number; |
| 34 | + hash: string; |
| 35 | + browserId: string; |
| 36 | +} |
| 37 | + |
| 38 | +export function createSnapshotFilePath({attempt: attemptInput, hash, browserId}: CreateSnapshotFilePathParams): string { |
| 39 | + const attempt: number = attemptInput || 0; |
| 40 | + const imageDir = _.compact([SNAPSHOTS_PATH, hash]); |
| 41 | + const components = imageDir.concat(`${browserId}_${attempt}.zip`); |
| 42 | + |
| 43 | + return path.join(...components); |
| 44 | +} |
| 45 | + |
| 46 | +export const handleDomSnapshotsEvent = (client: EventSource | null, context: TestContext, data: SnapshotsData): void => { |
| 47 | + try { |
| 48 | + const hash = getSnapshotHashWithoutAttempt(context); |
| 49 | + if (!snapshotsInProgress[hash]) { |
| 50 | + snapshotsInProgress[hash] = []; |
| 51 | + } |
| 52 | + |
| 53 | + // We need to number snapshots during live streaming for a case when user switches in UI to some test while it's running |
| 54 | + // In this case we need to merge 2 parts: snapshots that were taken before user switched and ones that we receive live |
| 55 | + // Since they can overlap, we introduce sequence numbering to guarantee smooth experience |
| 56 | + let seqNo = snapshotsInProgress[hash].length; |
| 57 | + const rrwebSnapshotsNumbered = data.rrwebSnapshots.map(snapshot => Object.assign({}, snapshot, {seqNo: seqNo++})); |
| 58 | + |
| 59 | + snapshotsInProgress[hash].push(...rrwebSnapshotsNumbered); |
| 60 | + |
| 61 | + if (client) { |
| 62 | + client.emit(ClientEvents.DOM_SNAPSHOTS, {context, data: {rrwebSnapshots: rrwebSnapshotsNumbered}}); |
| 63 | + } |
| 64 | + } catch (e) { |
| 65 | + console.warn(`Failed to handle DOM_SNAPSHOTS event for test "${context?.testPath?.join(' ')}.${context?.browserId}" in html-reporter due to an error.`, e); |
| 66 | + } |
| 67 | +}; |
| 68 | + |
| 69 | +interface FinalizeSnapshotsParams { |
| 70 | + testResult: ReporterTestResult; |
| 71 | + attempt: number; |
| 72 | + recordConfig: Testplane['config']['record']; |
| 73 | + reportPath: string; |
| 74 | + eventName: Testplane['events'][keyof Testplane['events']]; |
| 75 | + events: Testplane['events']; |
| 76 | +} |
| 77 | + |
| 78 | +export const finalizeSnapshotsForTest = async ({testResult, attempt, reportPath, recordConfig, events, eventName}: FinalizeSnapshotsParams): Promise<SnapshotAttachment[]> => { |
| 79 | + try { |
| 80 | + const hash = getSnapshotHashWithoutAttempt(testResult); |
| 81 | + const snapshots = snapshotsInProgress[hash]; |
| 82 | + |
| 83 | + delete snapshotsInProgress[hash]; |
| 84 | + |
| 85 | + if (!snapshots || snapshots.length === 0) { |
| 86 | + console.warn(`No snapshots found for test hash: ${hash}`); |
| 87 | + return []; |
| 88 | + } |
| 89 | + |
| 90 | + const shouldSave = recordConfig.mode !== RecordMode.LastFailedRun || (eventName === events.TEST_FAIL); |
| 91 | + if (!shouldSave) { |
| 92 | + return []; |
| 93 | + } |
| 94 | + |
| 95 | + const snapshotsSerialized = snapshots.map(s => JSON.stringify(s)).join('\n'); |
| 96 | + |
| 97 | + const zipFilePath = createSnapshotFilePath({ |
| 98 | + attempt, |
| 99 | + hash: testResult.imageDir, |
| 100 | + browserId: testResult.browserId |
| 101 | + }); |
| 102 | + const absoluteZipFilePath = path.resolve(reportPath, zipFilePath); |
| 103 | + await fsExtra.ensureDir(path.dirname(absoluteZipFilePath)); |
| 104 | + |
| 105 | + // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 106 | + let done = (_attachments: SnapshotAttachment[]): void => { |
| 107 | + }; |
| 108 | + const resultPromise = new Promise<SnapshotAttachment[]>((resolve) => { |
| 109 | + done = resolve; |
| 110 | + }); |
| 111 | + |
| 112 | + const zipfile = new yazl.ZipFile(); |
| 113 | + const output = fs.createWriteStream(absoluteZipFilePath); |
| 114 | + zipfile.outputStream.pipe(output).on('close', () => { |
| 115 | + done([{ |
| 116 | + type: AttachmentType.Snapshot, |
| 117 | + path: zipFilePath |
| 118 | + }]); |
| 119 | + }); |
| 120 | + |
| 121 | + zipfile.addBuffer(Buffer.from(snapshotsSerialized), 'snapshots.json'); |
| 122 | + |
| 123 | + zipfile.end(); |
| 124 | + |
| 125 | + return resultPromise; |
| 126 | + } catch (e) { |
| 127 | + console.warn(`Failed to finalize DOM snapshots for test "${testResult?.testPath?.join(' ')}.${testResult?.browserId}" in html-reporter due to an error.`, e); |
| 128 | + return []; |
| 129 | + } |
| 130 | +}; |
0 commit comments