This repository was archived by the owner on Jan 28, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvisual-regression.js
More file actions
1415 lines (1224 loc) · 51.9 KB
/
visual-regression.js
File metadata and controls
1415 lines (1224 loc) · 51.9 KB
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* visual-regression.js
* FIXED: Properly extracts test names from Playwright HTML reports
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const ART = 'artifacts';
/* ────────────────────────────────────────────────────────── *
* Parse Playwright HTML report to extract test metadata
* ────────────────────────────────────────────────────────── */
function parsePlaywrightReport(reportPath) {
const screenshots = new Map();
const indexPath = path.join(reportPath, 'index.html');
if (!fs.existsSync(indexPath)) {
console.log(`❌ No index.html found at ${indexPath}`);
return screenshots;
}
try {
const html = fs.readFileSync(indexPath, 'utf8');
// Method 1: Try to extract from window.playwrightReport
const reportRegex = /window\.playwrightReport\s*=\s*({[\s\S]*?});/;
const reportMatch = html.match(reportRegex);
if (reportMatch) {
try {
console.log('Found window.playwrightReport, parsing...');
// Parse the JavaScript object
const reportStr = reportMatch[1];
// Use Function constructor to safely evaluate
const reportData = new Function('return ' + reportStr)();
if (reportData && reportData.files) {
console.log(`Found ${reportData.files.length} test files`);
processReportData(reportData, reportPath, screenshots);
console.log(`📋 Extracted ${screenshots.size} screenshots from window.playwrightReport`);
return screenshots;
}
} catch (e) {
console.log('Failed to parse window.playwrightReport:', e.message);
}
}
// Method 2: Try to extract from the embedded app data
const appDataRegex = /window\.playwrightReportBase64\s*=\s*"([^"]+)"/;
const appDataMatch = html.match(appDataRegex);
if (appDataMatch) {
try {
const decodedData = Buffer.from(appDataMatch[1], 'base64').toString('utf8');
const reportData = JSON.parse(decodedData);
if (reportData.files) {
reportData.files.forEach(file => {
file.tests?.forEach(test => {
test.results?.forEach(result => {
result.attachments?.forEach(attachment => {
if (attachment.contentType?.startsWith('image/')) {
const filename = path.basename(attachment.path || '');
if (filename) {
screenshots.set(filename, {
filename,
path: path.join(reportPath, attachment.path || `data/${filename}`),
testName: test.title || 'Unknown Test',
testLocation: test.location?.file || file.fileName || '',
status: result.status,
type: attachment.name || 'screenshot'
});
}
}
});
});
});
});
}
console.log(`📋 Extracted ${screenshots.size} screenshots from base64 data`);
return screenshots;
} catch (e) {
console.log('Failed to parse base64 data, trying alternative methods...');
}
}
// Method 2: Try to find the bundled data object
const dataRegex = /window\.playwrightReportData\s*=\s*({[\s\S]*?});/;
const dataMatch = html.match(dataRegex);
if (dataMatch) {
try {
// Use Function constructor to safely evaluate the JavaScript object
const reportData = new Function('return ' + dataMatch[1])();
processReportData(reportData, reportPath, screenshots);
console.log(`📋 Extracted ${screenshots.size} screenshots from report data`);
return screenshots;
} catch (e) {
console.log('Failed to parse report data object');
}
}
// Method 3: Look for JSON data in script tags
const scriptTags = html.match(/<script[^>]*>([\s\S]*?)<\/script>/gi) || [];
for (const scriptTag of scriptTags) {
const scriptContent = scriptTag.replace(/<\/?script[^>]*>/gi, '');
// Look for report data assignment
const dataAssignmentRegex = /(?:window\.)?(?:playwrightReport|__playwright_report__|report)\s*=\s*({[\s\S]*?});/;
const dataMatch = scriptContent.match(dataAssignmentRegex);
if (dataMatch) {
try {
console.log('Found report data in script tag, attempting to parse...');
// Clean up the JavaScript object string
let jsonStr = dataMatch[1];
// Handle JavaScript object notation to JSON
jsonStr = jsonStr
.replace(/(\w+):/g, '"$1":') // Add quotes to keys
.replace(/'/g, '"') // Replace single quotes with double quotes
.replace(/,\s*}/g, '}') // Remove trailing commas
.replace(/,\s*]/g, ']') // Remove trailing commas in arrays
.replace(/undefined/g, 'null'); // Replace undefined with null
const reportData = JSON.parse(jsonStr);
if (reportData) {
processReportData(reportData, reportPath, screenshots);
console.log(`📋 Extracted ${screenshots.size} screenshots from script data`);
if (screenshots.size > 0) {
return screenshots;
}
}
} catch (e) {
console.log('Failed to parse script data:', e.message);
}
}
}
// Method 4: Parse Playwright's app bundle
const appBundleRegex = /\bconst\s+(?:jsonReport|reportData|data)\s*=\s*({[\s\S]*?})\s*;/;
const bundleMatch = html.match(appBundleRegex);
if (bundleMatch) {
try {
const reportData = new Function('return ' + bundleMatch[1])();
processReportData(reportData, reportPath, screenshots);
console.log(`📋 Extracted ${screenshots.size} screenshots from app bundle`);
return screenshots;
} catch (e) {
console.log('Failed to parse app bundle data');
}
}
// Fallback: Just find image references without test names
const imgRegex = /data\/([a-f0-9]{40})(-[a-z]+)?\.png/gi;
let match;
const imageRefs = new Map();
while ((match = imgRegex.exec(html)) !== null) {
const hash = match[1];
const suffix = match[2] || '';
const filename = `${hash}${suffix}.png`;
imageRefs.set(filename, true);
}
// Enhanced: Try to find test names by looking for test result blocks
const testResultRegex = /<div[^>]*class="[^"]*test-result[^"]*"[^>]*>([\s\S]*?)<\/div>/gi;
const testTitleRegex = /<span[^>]*class="[^"]*test-title[^"]*"[^>]*>([^<]+)<\/span>/gi;
// Map to store test name associations
const testNameMap = new Map();
// Look for test blocks that contain both title and image references
const testBlockRegex = /<div[^>]*data-testid="test-case-title"[^>]*>([^<]+)<\/div>[\s\S]*?<img[^>]*src="([^"]+)"/gi;
let testBlockMatch;
while ((testBlockMatch = testBlockRegex.exec(html)) !== null) {
const testName = testBlockMatch[1].trim();
const imagePath = testBlockMatch[2];
const imageFilename = path.basename(imagePath);
if (imageFilename && testName) {
testNameMap.set(imageFilename, testName);
console.log(` Mapped ${imageFilename} to test: "${testName}"`);
}
}
// Alternative: Look for attachment links with nearby test titles
const attachmentRegex = /<a[^>]*href="([^"]*\.png)"[^>]*>[\s\S]*?<\/a>/gi;
let attachmentMatch;
let lastTestName = 'Unknown Test';
// First pass: collect all test names
const allTestNames = [];
let titleMatch;
while ((titleMatch = testTitleRegex.exec(html)) !== null) {
allTestNames.push(titleMatch[1].trim());
}
// For each image reference, try to find associated test name
for (const [filename, _] of imageRefs) {
const fullPath = path.join(reportPath, 'data', filename);
if (fs.existsSync(fullPath)) {
let testName = testNameMap.get(filename) || 'Unknown Test';
// If we don't have a mapped name, try to find it in the HTML context
if (testName === 'Unknown Test') {
// Look for the filename in the HTML and find the nearest test title before it
const fileIndex = html.indexOf(filename);
if (fileIndex !== -1) {
// Find the last test title that appears before this image
let nearestTestName = 'Unknown Test';
let nearestDistance = Infinity;
for (const title of allTestNames) {
const titleIndex = html.lastIndexOf(title, fileIndex);
if (titleIndex !== -1 && titleIndex < fileIndex) {
const distance = fileIndex - titleIndex;
if (distance < nearestDistance && distance < 5000) { // Within reasonable distance
nearestDistance = distance;
nearestTestName = title;
}
}
}
if (nearestTestName !== 'Unknown Test') {
testName = nearestTestName;
console.log(` Associated ${filename} with nearby test: "${testName}"`);
}
}
}
screenshots.set(filename, {
filename,
path: fullPath,
testName,
type: filename.includes('-diff') ? 'diff' :
filename.includes('-expected') ? 'expected' : 'actual'
});
}
}
} catch (error) {
console.error('Error parsing report:', error.message);
}
// Final fallback: scan data directory
const dataPath = path.join(reportPath, 'data');
if (fs.existsSync(dataPath)) {
const files = fs.readdirSync(dataPath);
files.forEach(file => {
if (file.endsWith('.png') && !screenshots.has(file)) {
screenshots.set(file, {
filename: file,
path: path.join(dataPath, file),
testName: 'Unknown Test',
type: file.includes('-diff') ? 'diff' :
file.includes('-expected') ? 'expected' : 'actual'
});
}
});
}
return screenshots;
}
/* ────────────────────────────────────────────────────────── *
* Process report data structure
* ────────────────────────────────────────────────────────── */
function processReportData(data, reportPath, screenshots) {
// Handle files array (most common structure)
if (data.files && Array.isArray(data.files)) {
console.log(`Processing ${data.files.length} files from report data`);
data.files.forEach((file, fileIdx) => {
const fileName = file.fileName || file.file || `file-${fileIdx}`;
console.log(` Processing file: ${fileName}`);
if (file.tests && Array.isArray(file.tests)) {
file.tests.forEach((test, testIdx) => {
// Process each test with proper title extraction
processTestWithContext(test, fileName, reportPath, screenshots);
});
}
// Also check for specs at file level
if (file.specs && Array.isArray(file.specs)) {
file.specs.forEach(spec => {
processTestWithContext(spec, fileName, reportPath, screenshots);
});
}
// Check for suites at file level
if (file.suites && Array.isArray(file.suites)) {
processSuites(file.suites, reportPath, screenshots, fileName);
}
});
}
// Handle tests array directly
if (data.tests && Array.isArray(data.tests)) {
data.tests.forEach(test => {
processTest(test, '', reportPath, screenshots);
});
}
// Handle suites structure
if (data.suites && Array.isArray(data.suites)) {
processSuites(data.suites, reportPath, screenshots);
}
// Handle projects structure (Playwright 1.20+)
if (data.projects && Array.isArray(data.projects)) {
data.projects.forEach(project => {
if (project.suites) {
processSuites(project.suites, reportPath, screenshots, project.name);
}
});
}
}
/* ────────────────────────────────────────────────────────── *
* Process test with context to extract proper title
* ────────────────────────────────────────────────────────── */
function processTestWithContext(test, fileName, reportPath, screenshots) {
// Extract all title parts from the test path
const titleParts = [];
// Get file name without extension
const fileBaseName = path.basename(fileName).replace(/\.(spec|test)\.(js|ts|jsx|tsx)$/, '');
// Add parent titles if available
if (test.parent) {
let current = test.parent;
const parentTitles = [];
while (current && current.title) {
parentTitles.unshift(current.title);
current = current.parent;
}
titleParts.push(...parentTitles);
}
// Add test title
const testTitle = test.title || test.name || test.fullTitle || 'Unknown Test';
titleParts.push(testTitle);
// Join all parts for display
const displayTitle = titleParts.length > 1 ? titleParts.join(' › ') : testTitle;
console.log(` Processing test: "${displayTitle}"`);
// Process test results
const results = test.results || test.runs || [];
if (Array.isArray(results)) {
results.forEach((result, resultIdx) => {
const attachments = result.attachments || [];
if (Array.isArray(attachments)) {
attachments.forEach(attachment => {
if (attachment.contentType && attachment.contentType.startsWith('image/')) {
const attachmentPath = attachment.path || attachment.name || '';
const filename = path.basename(attachmentPath);
if (filename && filename.match(/\.(png|jpe?g)$/i)) {
const fullPath = path.join(reportPath, attachmentPath);
// Determine screenshot type
let type = 'actual';
const attachmentName = (attachment.name || '').toLowerCase();
if (attachmentName.includes('expected') || filename.includes('-expected')) {
type = 'expected';
} else if (attachmentName.includes('diff') || filename.includes('-diff')) {
type = 'diff';
} else if (attachmentName.includes('actual') || filename.includes('-actual')) {
type = 'actual';
}
screenshots.set(filename, {
filename,
path: fs.existsSync(fullPath) ? fullPath : path.join(reportPath, 'data', filename),
testName: testTitle, // Use the clean test title
displayTitle: displayTitle, // Full display title with context
fullTestName: `${fileBaseName} > ${displayTitle}`,
testLocation: test.location?.file || fileName || '',
status: result.status || 'unknown',
type,
attachmentName: attachment.name
});
console.log(` Found ${type} screenshot: ${filename} for test: "${testTitle}"`);
}
}
});
}
});
}
// Also check if test has direct attachments
if (test.attachments && Array.isArray(test.attachments)) {
test.attachments.forEach(attachment => {
if (attachment.contentType && attachment.contentType.startsWith('image/')) {
const filename = path.basename(attachment.path || attachment.name || '');
if (filename) {
screenshots.set(filename, {
filename,
path: path.join(reportPath, attachment.path || `data/${filename}`),
testName: testTitle,
displayTitle: displayTitle,
fullTestName: `${fileBaseName} > ${displayTitle}`,
type: attachment.name || 'screenshot'
});
}
}
});
}
}
/* ────────────────────────────────────────────────────────── *
* Process test suites recursively
* ────────────────────────────────────────────────────────── */
function processSuites(suites, reportPath, screenshots, parentPath = '') {
if (!Array.isArray(suites)) return;
suites.forEach(suite => {
const suitePath = parentPath ? `${parentPath} > ${suite.title}` : suite.title;
// Process tests in this suite
if (suite.tests && Array.isArray(suite.tests)) {
suite.tests.forEach(test => {
processTest(test, suitePath, reportPath, screenshots);
});
}
// Process specs (another common structure)
if (suite.specs && Array.isArray(suite.specs)) {
suite.specs.forEach(spec => {
processTest(spec, suitePath, reportPath, screenshots);
});
}
// Recursively process nested suites
if (suite.suites && Array.isArray(suite.suites)) {
processSuites(suite.suites, reportPath, screenshots, suitePath);
}
});
}
/* ────────────────────────────────────────────────────────── *
* Process individual test
* ────────────────────────────────────────────────────────── */
function processTest(test, suitePath, reportPath, screenshots) {
// Get the test title - check multiple possible properties
const testTitle = test.title || test.name || test.fullTitle || 'Unknown Test';
const fullTestName = suitePath ? `${suitePath} > ${testTitle}` : testTitle;
// Process test results
const results = test.results || test.runs || [];
if (Array.isArray(results)) {
results.forEach(result => {
const attachments = result.attachments || [];
if (Array.isArray(attachments)) {
attachments.forEach(attachment => {
if (attachment.contentType && attachment.contentType.startsWith('image/')) {
const attachmentPath = attachment.path || attachment.name || '';
const filename = path.basename(attachmentPath);
if (filename && filename.match(/\.(png|jpe?g)$/i)) {
const fullPath = path.join(reportPath, attachmentPath);
// Determine screenshot type
let type = 'actual';
const attachmentName = (attachment.name || '').toLowerCase();
if (attachmentName.includes('expected') || filename.includes('-expected')) {
type = 'expected';
} else if (attachmentName.includes('diff') || filename.includes('-diff')) {
type = 'diff';
} else if (attachmentName.includes('actual') || filename.includes('-actual')) {
type = 'actual';
}
screenshots.set(filename, {
filename,
path: fs.existsSync(fullPath) ? fullPath : path.join(reportPath, 'data', filename),
testName: testTitle, // Use just the test title, not the full path
fullTestName: fullTestName, // Keep full path for reference
testLocation: test.location?.file || suitePath || '',
status: result.status || 'unknown',
type,
attachmentName: attachment.name
});
console.log(` Found screenshot for test: "${testTitle}"`);
}
}
});
}
});
}
// Also check if test has direct attachments (some Playwright versions)
if (test.attachments && Array.isArray(test.attachments)) {
test.attachments.forEach(attachment => {
if (attachment.contentType && attachment.contentType.startsWith('image/')) {
const filename = path.basename(attachment.path || attachment.name || '');
if (filename) {
screenshots.set(filename, {
filename,
path: path.join(reportPath, attachment.path || `data/${filename}`),
testName: testTitle,
fullTestName: fullTestName,
type: attachment.name || 'screenshot'
});
}
}
});
}
}
/* ────────────────────────────────────────────────────────── *
* Enhanced screenshot discovery with test name extraction
* ────────────────────────────────────────────────────────── */
function findAllScreenshots(reportPath) {
console.log(`\n🔍 Searching for screenshots in: ${reportPath}`);
// First try to parse from HTML report
const screenshots = parsePlaywrightReport(reportPath);
// If we found screenshots with proper test names, return them
if (screenshots.size > 0) {
const knownTests = Array.from(screenshots.values()).filter(s => s.testName !== 'Unknown Test');
console.log(` Found ${screenshots.size} screenshots (${knownTests.length} with test names)`);
return screenshots;
}
// Fallback: scan directory and try to match with trace files
const dataPath = path.join(reportPath, 'data');
if (fs.existsSync(dataPath)) {
const files = fs.readdirSync(dataPath);
// Look for trace files which might contain test information
const traceFiles = files.filter(f => f.endsWith('.zip'));
console.log(` Found ${traceFiles.length} trace files`);
// Process PNG files
files.forEach(file => {
if (file.endsWith('.png') && !screenshots.has(file)) {
screenshots.set(file, {
filename: file,
path: path.join(dataPath, file),
testName: 'Unknown Test',
type: file.includes('-diff') ? 'diff' :
file.includes('-expected') ? 'expected' : 'actual'
});
}
});
}
return screenshots;
}
/* ────────────────────────────────────────────────────────── *
* Image comparison function (unchanged)
* ────────────────────────────────────────────────────────── */
async function compareImages(img1Path, img2Path, diffPath) {
try {
if (!fs.existsSync(img1Path) || !fs.existsSync(img2Path)) {
return null;
}
// Quick binary comparison
const buf1 = fs.readFileSync(img1Path);
const buf2 = fs.readFileSync(img2Path);
if (buf1.length === buf2.length && buf1.equals(buf2)) {
return { hasDiff: false, diffPercent: 0, identical: true };
}
// Check if ImageMagick is available
try {
execSync('which compare', { stdio: 'ignore' });
} catch {
console.warn('⚠️ ImageMagick not found, using size comparison only');
const sizeDiff = Math.abs(buf1.length - buf2.length) / Math.max(buf1.length, buf2.length);
return {
hasDiff: true,
diffPercent: sizeDiff * 100,
method: 'size-only'
};
}
// Use ImageMagick for detailed comparison
fs.mkdirSync(path.dirname(diffPath), { recursive: true });
try {
const result = execSync(
`compare -metric AE -fuzz 5% "${img1Path}" "${img2Path}" "${diffPath}" 2>&1`,
{ encoding: 'utf8', stdio: 'pipe' }
);
const pixels = parseInt(result) || 0;
// Get dimensions
const identify = execSync(`identify -format "%w %h" "${img1Path}"`, { encoding: 'utf8' });
const [width, height] = identify.trim().split(' ').map(Number);
const totalPixels = width * height;
const diffPercent = totalPixels > 0 ? (pixels / totalPixels) * 100 : 0;
return {
hasDiff: pixels > 0,
diffPercent: Math.round(diffPercent * 100) / 100,
diffImage: diffPath,
pixelDiff: pixels,
totalPixels,
dimensions: { width, height },
method: 'imagemagick'
};
} catch (err) {
// ImageMagick returns non-zero exit code when images differ
const stderr = err.stderr || err.stdout || '';
const pixels = parseInt(stderr) || 1;
return {
hasDiff: true,
diffPercent: 50,
diffImage: diffPath,
pixelDiff: pixels,
method: 'imagemagick-error'
};
}
} catch (err) {
console.error('Error comparing images:', err.message);
return null;
}
}
/* ────────────────────────────────────────────────────────── *
* Match and compare screenshots (updated)
* ────────────────────────────────────────────────────────── */
async function matchAndCompareScreenshots(prScreenshots, mainScreenshots) {
const comparisons = [];
const unmatchedPR = new Set(prScreenshots.keys());
const unmatchedMain = new Set(mainScreenshots.keys());
// Filter to actual screenshots only
const prActual = new Map();
const mainActual = new Map();
for (const [filename, info] of prScreenshots) {
if (info.type === 'actual' || (!info.type && !filename.includes('-diff') && !filename.includes('-expected'))) {
prActual.set(filename, info);
}
}
for (const [filename, info] of mainScreenshots) {
if (info.type === 'actual' || (!info.type && !filename.includes('-diff') && !filename.includes('-expected'))) {
mainActual.set(filename, info);
}
}
console.log(`\n📊 Actual screenshots to compare:`);
console.log(` PR: ${prActual.size}`);
console.log(` Main: ${mainActual.size}`);
// Try content-based matching
const matches = [];
const prList = Array.from(prActual.values());
const mainList = Array.from(mainActual.values());
for (let i = 0; i < prList.length; i++) {
const prShot = prList[i];
let bestMatch = null;
let bestScore = Infinity;
for (let j = 0; j < mainList.length; j++) {
const mainShot = mainList[j];
// Skip if already matched
if (matches.some(m => m.main === mainShot)) continue;
// Quick size comparison
try {
const prStat = fs.statSync(prShot.path);
const mainStat = fs.statSync(mainShot.path);
const sizeDiff = Math.abs(prStat.size - mainStat.size) / Math.max(prStat.size, mainStat.size);
// If size difference is too large, skip
if (sizeDiff > 0.3) continue;
// Use size difference as initial score
if (sizeDiff < bestScore) {
bestScore = sizeDiff;
bestMatch = mainShot;
}
} catch (e) {
// Skip if can't read file
}
}
if (bestMatch && bestScore < 0.2) {
matches.push({ pr: prShot, main: bestMatch });
unmatchedPR.delete(prShot.filename);
unmatchedMain.delete(bestMatch.filename);
}
}
console.log(`\n🔗 Matched ${matches.length} screenshot pairs`);
// Process matched screenshots
const diffDir = path.join(ART, 'visual-diffs');
fs.mkdirSync(diffDir, { recursive: true });
for (const match of matches) {
// Use the test name from PR screenshot (should be the actual test title now)
const testName = match.pr.testName || match.main.testName || 'Unknown Test';
const displayTitle = match.pr.displayTitle || match.pr.testName || match.main.displayTitle || match.main.testName || 'Unknown Test';
const diffPath = path.join(diffDir, `diff-${path.basename(match.pr.filename)}`);
console.log(` Comparing: ${displayTitle}`);
const result = await compareImages(match.main.path, match.pr.path, diffPath);
if (result) {
const diffPercent = result.diffPercent || 0;
comparisons.push({
testName: displayTitle, // Use the full display title for better context
filename: match.pr.filename,
prImage: match.pr.path,
mainImage: match.main.path,
...result,
status: diffPercent === 0 ? 'identical' :
diffPercent < 0.1 ? 'negligible' :
diffPercent < 1 ? 'minor' : 'major'
});
console.log(` -> ${result.diffPercent}% difference`);
}
}
// Handle unmatched screenshots
for (const filename of unmatchedPR) {
const info = prActual.get(filename);
if (info) {
comparisons.push({
testName: info.testName || 'Unknown Test',
filename: info.filename,
prImage: info.path,
mainImage: null,
hasDiff: true,
diffPercent: 100,
status: 'new'
});
}
}
for (const filename of unmatchedMain) {
const info = mainActual.get(filename);
if (info) {
comparisons.push({
testName: info.testName || 'Unknown Test',
filename: info.filename,
prImage: null,
mainImage: info.path,
hasDiff: true,
diffPercent: 100,
status: 'removed'
});
}
}
return comparisons;
}
/* ────────────────────────────────────────────────────────── *
* HTML report generation (complete version)
* ────────────────────────────────────────────────────────── */
function generateHTMLReport(report) {
const getStatusColor = (status) => {
switch (status) {
case 'identical': return '#10b981';
case 'negligible': return '#06b6d4';
case 'minor': return '#f59e0b';
case 'major': return '#ef4444';
case 'new': return '#3b82f6';
case 'removed': return '#8b5cf6';
default: return '#6b7280';
}
};
const getStatusIcon = (status) => {
switch (status) {
case 'identical': return '✅';
case 'negligible': return '✓';
case 'minor': return '⚠️';
case 'major': return '❌';
case 'new': return '🆕';
case 'removed': return '🗑️';
default: return '❓';
}
};
const getStatusLabel = (status, diffPercent) => {
switch (status) {
case 'identical': return 'No changes';
case 'negligible': return `${diffPercent}% diff (negligible)`;
case 'minor': return `${diffPercent}% diff (minor)`;
case 'major': return `${diffPercent}% diff (major)`;
case 'new': return 'New screenshot';
case 'removed': return 'Removed';
default: return 'Unknown';
}
};
return `
<div class="visual-regression-container">
<style>
.visual-regression-container {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #1e293b;
color: #f1f5f9;
padding: 2rem;
border-radius: 12px;
}
.vr-header {
margin-bottom: 2rem;
}
.vr-header h2 {
font-size: 2rem;
font-weight: 700;
margin-bottom: 0.5rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.vr-summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 1rem;
margin-bottom: 2rem;
}
.vr-stat {
background: rgba(255, 255, 255, 0.05);
padding: 1rem;
border-radius: 8px;
text-align: center;
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.2s;
}
.vr-stat:hover {
border-color: rgba(255, 255, 255, 0.2);
background: rgba(255, 255, 255, 0.08);
}
.vr-stat-value {
font-size: 2rem;
font-weight: bold;
margin-bottom: 0.5rem;
}
.vr-stat-label {
font-size: 0.875rem;
color: #94a3b8;
}
.vr-filters {
display: flex;
gap: 0.5rem;
margin-bottom: 1.5rem;
flex-wrap: wrap;
}
.vr-filter {
padding: 0.5rem 1rem;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
color: #f1f5f9;
font-size: 0.875rem;
}
.vr-filter:hover {
background: rgba(255, 255, 255, 0.1);
}
.vr-filter.active {
background: #3b82f6;
border-color: #3b82f6;
}
.vr-comparisons {
display: grid;
gap: 1.5rem;
}
.vr-comparison {
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
padding: 1.5rem;
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.2s;
}
.vr-comparison:hover {
border-color: rgba(255, 255, 255, 0.2);
}
.vr-comparison-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1rem;
flex-wrap: wrap;
gap: 1rem;
}
.vr-comparison-title {
font-size: 1.1rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
}
.vr-status-badge {
padding: 0.25rem 0.75rem;
border-radius: 9999px;
font-size: 0.875rem;
font-weight: 500;
}
.vr-images {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1rem;
margin-top: 1rem;
}
.vr-image-container {
position: relative;
background: #0f172a;
border-radius: 8px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.vr-image-label {
position: absolute;
top: 0.5rem;
left: 0.5rem;
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 0.75rem;
font-weight: 500;
z-index: 1;
}
.vr-image {
width: 100%;
height: auto;
display: block;
cursor: zoom-in;
}
.vr-image:hover {
opacity: 0.9;
}
.vr-no-changes {
text-align: center;
padding: 3rem;
color: #10b981;
}
.vr-details {
margin-top: 1rem;
font-size: 0.875rem;
color: #94a3b8;
}
.vr-details-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 0.5rem;
margin-top: 0.5rem;
}
.vr-no-screenshots {
text-align: center;