-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathutils.ts
513 lines (426 loc) · 20 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
import fs from 'fs'
import { Context } from '../types.js'
import { chromium, firefox, webkit, Browser } from '@playwright/test'
import constants from './constants.js';
import chalk from 'chalk';
import axios from 'axios';
import { globalAgent } from 'http';
import { promisify } from 'util'
const sleep = promisify(setTimeout);
let isPollingActive = false;
let globalContext: Context;
export const setGlobalContext = (newContext: Context): void => {
globalContext = newContext;
};
export function delDir(dir: string): void {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true });
}
}
export function scrollToBottomAndBackToTop({
frequency = 100,
timing = 8,
remoteWindow = window
} = {}): Promise<void> {
return new Promise(resolve => {
let scrolls = 1;
let scrollLength = remoteWindow.document.body.scrollHeight / frequency;
(function scroll() {
let scrollBy = scrollLength * scrolls;
remoteWindow.setTimeout(() => {
remoteWindow.scrollTo(0, scrollBy);
if (scrolls < frequency) {
scrolls += 1;
scroll();
}
if (scrolls === frequency) {
remoteWindow.setTimeout(() => {
remoteWindow.scrollTo(0,0)
resolve();
}, timing);
}
}, timing);
})();
});
}
export async function launchBrowsers(ctx: Context): Promise<Record<string, Browser>> {
let browsers: Record<string, Browser> = {};
const isHeadless = process.env.HEADLESS?.toLowerCase() === 'false' ? false : true;
let launchOptions: Record<string, any> = { headless: isHeadless };
if (ctx.config.web) {
for (const browser of ctx.config.web.browsers) {
switch (browser) {
case constants.CHROME:
browsers[constants.CHROME] = await chromium.launch(launchOptions);
break;
case constants.SAFARI:
browsers[constants.SAFARI] = await webkit.launch(launchOptions);
break;
case constants.FIREFOX:
browsers[constants.FIREFOX] = await firefox.launch(launchOptions);
break;
case constants.EDGE:
launchOptions.args = ['--headless=new'];
browsers[constants.EDGE] = await chromium.launch({channel: constants.EDGE_CHANNEL, ...launchOptions});
break;
}
}
}
if (ctx.config.mobile) {
for (const device of ctx.config.mobile.devices) {
if (constants.SUPPORTED_MOBILE_DEVICES[device].os === 'android' && !browsers[constants.CHROME]) browsers[constants.CHROME] = await chromium.launch(launchOptions);
else if (constants.SUPPORTED_MOBILE_DEVICES[device].os === 'ios' && !browsers[constants.SAFARI]) browsers[constants.SAFARI] = await webkit.launch(launchOptions);
}
}
return browsers;
}
export async function closeBrowsers(browsers: Record<string, Browser>): Promise<void> {
for (const browserName of Object.keys(browsers)) await browsers[browserName]?.close();
}
export function getWebRenderViewports(ctx: Context): Array<Record<string,any>> {
let webRenderViewports: Array<Record<string,any>> = [];
if (ctx.config.web) {
for (const viewport of ctx.config.web.viewports) {
webRenderViewports.push({
viewport,
viewportString: `${viewport.width}${viewport.height ? 'x'+viewport.height : ''}`,
fullPage: viewport.height ? false : true,
device: false
})
}
}
return webRenderViewports
}
export function getWebRenderViewportsForOptions(options: any): Array<Record<string,any>> {
let webRenderViewports: Array<Record<string,any>> = [];
if (options.web && Array.isArray(options.web.viewports)) {
for (const viewport of options.web.viewports) {
if (Array.isArray(viewport) && viewport.length > 0) {
let viewportObj: { width: number; height?: number } = {
width: viewport[0]
};
if (viewport.length > 1) {
viewportObj.height = viewport[1];
}
webRenderViewports.push({
viewport: viewportObj,
viewportString: `${viewport[0]}${viewport[1] ? 'x'+viewport[1] : ''}`,
fullPage: viewport.length === 1,
device: false
});
}
}
}
return webRenderViewports;
}
export function getMobileRenderViewports(ctx: Context): Record<string,any> {
let mobileRenderViewports: Record<string, Array<Record<string, any>>> = {}
mobileRenderViewports[constants.MOBILE_OS_IOS] = [];
mobileRenderViewports[constants.MOBILE_OS_ANDROID] = [];
if (ctx.config.mobile) {
for (const device of ctx.config.mobile.devices) {
let os = constants.SUPPORTED_MOBILE_DEVICES[device].os;
let { width, height } = constants.SUPPORTED_MOBILE_DEVICES[device].viewport;
let portrait = (ctx.config.mobile.orientation === constants.MOBILE_ORIENTATION_PORTRAIT) ? true : false;
mobileRenderViewports[os]?.push({
viewport: { width: portrait ? width : height, height: portrait ? height : width },
viewportString: `${device} (${ctx.config.mobile.orientation})`,
fullPage: ctx.config.mobile.fullPage,
device: true,
os: os
})
}
}
return mobileRenderViewports
}
export function getMobileRenderViewportsForOptions(options: any): Record<string,any> {
let mobileRenderViewports: Record<string, Array<Record<string, any>>> = {}
mobileRenderViewports[constants.MOBILE_OS_IOS] = [];
mobileRenderViewports[constants.MOBILE_OS_ANDROID] = [];
if (options.mobile) {
for (const device of options.mobile.devices) {
let os = constants.SUPPORTED_MOBILE_DEVICES[device].os;
let { width, height } = constants.SUPPORTED_MOBILE_DEVICES[device].viewport;
let orientation = options.mobile.orientation || constants.MOBILE_ORIENTATION_PORTRAIT;
let portrait = (orientation === constants.MOBILE_ORIENTATION_PORTRAIT);
// Check if fullPage is specified, otherwise use default
let fullPage
if (options.mobile.fullPage === undefined || options.mobile.fullPage){
fullPage = true
} else {
fullPage = false
}
mobileRenderViewports[os]?.push({
viewport: { width: portrait ? width : height, height: portrait ? height : width },
viewportString: `${device} (${orientation})`,
fullPage: fullPage,
device: true,
os: os
})
}
}
return mobileRenderViewports
}
export function getRenderViewports(ctx: Context): Array<Record<string,any>> {
let mobileRenderViewports = getMobileRenderViewports(ctx);
let webRenderViewports = getWebRenderViewports(ctx);
// Combine arrays ensuring web viewports are first
return [
...webRenderViewports,
...mobileRenderViewports[constants.MOBILE_OS_IOS],
...mobileRenderViewports[constants.MOBILE_OS_ANDROID]
];
}
export function getRenderViewportsForOptions(options: any): Array<Record<string,any>> {
let mobileRenderViewports = getMobileRenderViewportsForOptions(options);
let webRenderViewports = getWebRenderViewportsForOptions(options);
// Combine arrays ensuring web viewports are first
return [
...webRenderViewports,
...mobileRenderViewports[constants.MOBILE_OS_IOS],
...mobileRenderViewports[constants.MOBILE_OS_ANDROID]
];
}
// Global SIGINT handler
process.on('SIGINT', async () => {
if (isPollingActive) {
console.log('Fetching results interrupted. Exiting...');
isPollingActive = false;
} else {
console.log('\nExiting gracefully...');
}
process.exit(0);
});
// Background polling function
export async function startPolling(ctx: Context): Promise<void> {
ctx.log.info('Fetching results in progress....');
isPollingActive = true;
const intervalId = setInterval(async () => {
if (!isPollingActive) {
clearInterval(intervalId);
return;
}
try {
const resp = await ctx.client.getScreenshotData(ctx.build.id, ctx.build.baseline, ctx.log);
if (!resp.build) {
ctx.log.info("Error: Build data is null.");
clearInterval(intervalId);
isPollingActive = false;
}
fs.writeFileSync(ctx.options.fetchResultsFileName, JSON.stringify(resp, null, 2));
ctx.log.debug(`Updated results in ${ctx.options.fetchResultsFileName}`);
if (resp.build.build_status_ind === constants.BUILD_COMPLETE || resp.build.build_status_ind === constants.BUILD_ERROR) {
clearInterval(intervalId);
ctx.log.info(`Fetching results completed. Final results written to ${ctx.options.fetchResultsFileName}`);
isPollingActive = false;
// Evaluating Summary
let totalScreenshotsWithMismatches = 0;
let totalVariantsWithMismatches = 0;
const totalScreenshots = Object.keys(resp.screenshots || {}).length;
let totalVariants = 0;
for (const [screenshot, variants] of Object.entries(resp.screenshots || {})) {
let screenshotHasMismatch = false;
let variantMismatchCount = 0;
totalVariants += variants.length; // Add to total variants count
for (const variant of variants) {
if (variant.mismatch_percentage > 0) {
screenshotHasMismatch = true;
variantMismatchCount++;
}
}
if (screenshotHasMismatch) {
totalScreenshotsWithMismatches++;
totalVariantsWithMismatches += variantMismatchCount;
}
}
// Display summary
ctx.log.info(
chalk.green.bold(
`\nSummary of Mismatches:\n` +
`${chalk.yellow('Total Variants with Mismatches:')} ${chalk.white(totalVariantsWithMismatches)} out of ${chalk.white(totalVariants)}\n` +
`${chalk.yellow('Total Screenshots with Mismatches:')} ${chalk.white(totalScreenshotsWithMismatches)} out of ${chalk.white(totalScreenshots)}\n` +
`${chalk.yellow('Branch Name:')} ${chalk.white(resp.build.branch)}\n` +
`${chalk.yellow('Project Name:')} ${chalk.white(resp.project.name)}\n` +
`${chalk.yellow('Build ID:')} ${chalk.white(resp.build.build_id)}\n`
)
);
}
} catch (error: any) {
if (error.message.includes('ENOTFOUND')) {
ctx.log.error('Error: Network error occurred while fetching build results. Please check your connection and try again.');
clearInterval(intervalId);
} else {
ctx.log.error(`Error fetching screenshot data: ${error.message}`);
}
clearInterval(intervalId);
isPollingActive = false;
}
}, 5000);
}
export let pingIntervalId: NodeJS.Timeout | null = null;
export async function startPingPolling(ctx: Context): Promise<void> {
try {
ctx.log.debug('Sending initial ping to server...');
await ctx.client.ping(ctx.build.id, ctx.log);
ctx.log.debug('Initial ping sent successfully.');
} catch (error: any) {
ctx.log.error(`Error during initial ping: ${error.message}`);
}
// Start the polling interval
pingIntervalId = setInterval(async () => {
try {
ctx.log.debug('Sending ping to server...');
await ctx.client.ping(ctx.build.id, ctx.log);
ctx.log.debug('Ping sent successfully.');
} catch (error: any) {
ctx.log.error(`Error during ping polling: ${error.message}`);
}
}, 10 * 60 * 1000); // 10 minutes interval
}
export function startPdfPolling(ctx: Context) {
console.log(chalk.yellow('\nFetching PDF test results...'));
// Use buildId if available, otherwise use buildName
const buildName = ctx.options.buildName || ctx.pdfBuildName;
const buildId = ctx.pdfBuildId;
if (!buildId && !buildName) {
console.log(chalk.red('Error: Build information not found for fetching results'));
return;
}
// Verify authentication credentials
if (!ctx.env.LT_USERNAME || !ctx.env.LT_ACCESS_KEY) {
console.log(chalk.red('Error: LT_USERNAME and LT_ACCESS_KEY environment variables are required for fetching results'));
return;
}
let attempts = 0;
const maxAttempts = 30; // 5 minutes (10 seconds * 30)
console.log(chalk.yellow('Waiting for results...'));
const interval = setInterval(async () => {
attempts++;
try {
const response = await ctx.client.fetchPdfResults(buildName, buildId, ctx.log);
if (response.status === 'success' && response.data && response.data.Screenshots) {
clearInterval(interval);
// Group screenshots by PDF name
const pdfGroups = groupScreenshotsByPdf(response.data.Screenshots);
// Count PDFs with mismatches
const pdfsWithMismatches = countPdfsWithMismatches(pdfGroups);
const pagesWithMismatches = countPagesWithMismatches(response.data.Screenshots);
// Display summary in terminal
console.log(chalk.green('\n✓ PDF Test Results:'));
console.log(chalk.green(`Build Name: ${response.data.buildName}`));
console.log(chalk.green(`Project Name: ${response.data.projectName}`));
console.log(chalk.green(`Total PDFs: ${Object.keys(pdfGroups).length}`));
console.log(chalk.green(`Total Pages: ${response.data.Screenshots.length}`));
if (pdfsWithMismatches > 0 || pagesWithMismatches > 0) {
console.log(chalk.yellow(`${pdfsWithMismatches} PDFs and ${pagesWithMismatches} Pages in build ${response.data.buildName} have changes present.`));
} else {
console.log(chalk.green('All PDFs match the baseline.'));
}
// Display each PDF and its pages
Object.entries(pdfGroups).forEach(([pdfName, pages]) => {
const hasMismatch = pages.some(page => page.mismatchPercentage > 0);
const statusColor = hasMismatch ? chalk.yellow : chalk.green;
console.log(statusColor(`\n📄 ${pdfName} (${pages.length} pages)`));
pages.forEach(page => {
const pageStatusColor = page.mismatchPercentage > 0 ? chalk.yellow : chalk.green;
console.log(pageStatusColor(` - Page ${getPageNumber(page.screenshotName)}: ${page.status} (Mismatch: ${page.mismatchPercentage}%)`));
});
});
// Format the results for JSON output
const formattedResults = {
status: response.status,
data: {
buildId: response.data.buildId,
buildName: response.data.buildName,
projectName: response.data.projectName,
buildStatus: response.data.buildStatus,
pdfs: formatPdfsForOutput(pdfGroups)
}
};
// Save results to file if filename provided
const filename = typeof ctx.options.fetchResults === 'string'
? ctx.options.fetchResults
: 'pdf-results.json';
fs.writeFileSync(filename, JSON.stringify(formattedResults, null, 2));
console.log(chalk.green(`\nResults saved to ${filename}`));
return;
} else if (response.status === 'error') {
// Handle API error response
clearInterval(interval);
console.log(chalk.red(`\nError fetching results: ${response.message || 'Unknown error'}`));
return;
} else {
// If we get a response but it's not complete yet
process.stdout.write(chalk.yellow('.'));
}
if (attempts >= maxAttempts) {
clearInterval(interval);
console.log(chalk.red('\nTimeout: Could not fetch PDF results after 5 minutes'));
return;
}
} catch (error: any) {
// Log the error but continue polling unless max attempts reached
ctx.log.debug(`Error during polling: ${error.message}`);
if (attempts >= maxAttempts) {
clearInterval(interval);
console.log(chalk.red('\nTimeout: Could not fetch PDF results after 5 minutes'));
if (error.response && error.response.data) {
console.log(chalk.red(`Error details: ${JSON.stringify(error.response.data)}`));
} else {
console.log(chalk.red(`Error details: ${error.message}`));
}
return;
}
process.stdout.write(chalk.yellow('.'));
}
}, 10000); // Poll every 10 seconds
}
// Helper function to group screenshots by PDF name
function groupScreenshotsByPdf(screenshots: any[]): Record<string, any[]> {
const pdfGroups: Record<string, any[]> = {};
screenshots.forEach(screenshot => {
// Extract PDF name from screenshot name (format: "pdfname.pdf#pagenumber")
const pdfName = screenshot.screenshotName.split('#')[0];
if (!pdfGroups[pdfName]) {
pdfGroups[pdfName] = [];
}
pdfGroups[pdfName].push(screenshot);
});
return pdfGroups;
}
// Helper function to count PDFs with mismatches
function countPdfsWithMismatches(pdfGroups: Record<string, any[]>): number {
let count = 0;
Object.values(pdfGroups).forEach(pages => {
if (pages.some(page => page.mismatchPercentage > 0)) {
count++;
}
});
return count;
}
// Helper function to count pages with mismatches
function countPagesWithMismatches(screenshots: any[]): number {
return screenshots.filter(screenshot => screenshot.mismatchPercentage > 0).length;
}
// Helper function to extract page number from screenshot name
function getPageNumber(screenshotName: string): string {
const parts = screenshotName.split('#');
return parts.length > 1 ? parts[1] : '1';
}
// Helper function to format PDFs for JSON output
function formatPdfsForOutput(pdfGroups: Record<string, any[]>): any[] {
return Object.entries(pdfGroups).map(([pdfName, pages]) => {
return {
pdfName,
pageCount: pages.length,
pages: pages.map(page => ({
pageNumber: getPageNumber(page.screenshotName),
screenshotId: page.screenshotId,
mismatchPercentage: page.mismatchPercentage,
threshold: page.threshold,
status: page.status,
screenshotUrl: page.screenshotUrl
}))
};
});
}