forked from mozilla/pdf.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.mjs
1116 lines (1040 loc) · 31 KB
/
test.mjs
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
/*
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable no-var */
import { copySubtreeSync, ensureDirSync } from "./testutils.mjs";
import {
downloadManifestFiles,
verifyManifestFiles,
} from "./downloadutils.mjs";
import fs from "fs";
import os from "os";
import path from "path";
import puppeteer from "puppeteer";
import readline from "readline";
import { translateFont } from "./font/ttxdriver.mjs";
import url from "url";
import { WebServer } from "./webserver.mjs";
import yargs from "yargs";
function parseOptions() {
const parsedArgs = yargs(process.argv)
.usage("Usage: $0")
.option("downloadOnly", {
default: false,
describe: "Download test PDFs without running the tests.",
type: "boolean",
})
.option("fontTest", {
default: false,
describe: "Run the font tests.",
type: "boolean",
})
.option("help", {
alias: "h",
default: false,
describe: "Show this help message.",
type: "boolean",
})
.option("integration", {
default: false,
describe: "Run the integration tests.",
type: "boolean",
})
.option("manifestFile", {
default: "test_manifest.json",
describe: "A path to JSON file in the form of `test_manifest.json`.",
type: "string",
})
.option("masterMode", {
alias: "m",
default: false,
describe: "Run the script in master mode.",
type: "boolean",
})
.option("noChrome", {
default: false,
describe: "Skip Chrome when running tests.",
type: "boolean",
})
.option("noDownload", {
default: false,
describe: "Skip downloading of test PDFs.",
type: "boolean",
})
.option("noPrompts", {
default: false,
describe: "Uses default answers (intended for CLOUD TESTS only!).",
type: "boolean",
})
.option("headless", {
default: false,
describe:
"Run the tests in headless mode, i.e. without visible browser windows.",
type: "boolean",
})
.option("port", {
default: 0,
describe: "The port the HTTP server should listen on.",
type: "number",
})
.option("reftest", {
default: false,
describe:
"Automatically start reftest showing comparison test failures, if there are any.",
type: "boolean",
})
.option("statsDelay", {
default: 0,
describe:
"The amount of time in milliseconds the browser should wait before starting stats.",
type: "number",
})
.option("statsFile", {
default: "",
describe: "The file where to store stats.",
type: "string",
})
.option("strictVerify", {
default: false,
describe: "Error if verifying the manifest files fails.",
type: "boolean",
})
.option("testfilter", {
alias: "t",
default: [],
describe: "Run specific reftest(s).",
type: "array",
})
.example(
"testfilter",
"$0 -t=issue5567 -t=issue5909\n" +
"Run the reftest identified by issue5567 and issue5909."
)
.option("unitTest", {
default: false,
describe: "Run the unit tests.",
type: "boolean",
})
.option("xfaOnly", {
default: false,
describe: "Only run the XFA reftest(s).",
type: "boolean",
})
.check(argv => {
if (
+argv.reftest + argv.unitTest + argv.fontTest + argv.masterMode <=
1
) {
return true;
}
throw new Error(
"--reftest, --unitTest, --fontTest, and --masterMode must not be specified together."
);
})
.check(argv => {
if (
+argv.unitTest + argv.fontTest + argv.integration + argv.xfaOnly <=
1
) {
return true;
}
throw new Error(
"--unitTest, --fontTest, --integration, and --xfaOnly must not be specified together."
);
})
.check(argv => {
if (argv.testfilter && argv.testfilter.length > 0 && argv.xfaOnly) {
throw new Error("--testfilter and --xfaOnly cannot be used together.");
}
return true;
})
.check(argv => {
if (!argv.noDownload || !argv.downloadOnly) {
return true;
}
throw new Error(
"--noDownload and --downloadOnly cannot be used together."
);
})
.check(argv => {
if (!argv.masterMode || argv.manifestFile === "test_manifest.json") {
return true;
}
throw new Error(
"when --masterMode is specified --manifestFile shall be equal to `test_manifest.json`."
);
});
const result = parsedArgs.argv;
result.testfilter = Array.isArray(result.testfilter)
? result.testfilter
: [result.testfilter];
return result;
}
var refsTmpDir = "tmp";
var testResultDir = "test_snapshots";
var refsDir = "ref";
var eqLog = "eq.log";
var browserTimeout = 120;
function monitorBrowserTimeout(session, onTimeout) {
if (session.timeoutMonitor) {
clearTimeout(session.timeoutMonitor);
}
if (!onTimeout) {
session.timeoutMonitor = null;
return;
}
session.timeoutMonitor = setTimeout(function () {
onTimeout(session);
}, browserTimeout * 1000);
}
function updateRefImages() {
function sync(removeTmp) {
console.log(" Updating ref/ ... ");
copySubtreeSync(refsTmpDir, refsDir);
if (removeTmp) {
fs.rmSync(refsTmpDir, { recursive: true, force: true });
}
console.log("done");
}
if (options.noPrompts) {
sync(false); // don't remove tmp/ for botio
return;
}
const reader = readline.createInterface(process.stdin, process.stdout);
reader.question(
"Would you like to update the master copy in ref/? [yn] ",
function (answer) {
if (answer.toLowerCase() === "y") {
sync(true);
} else {
console.log(" OK, not updating.");
}
reader.close();
}
);
}
function examineRefImages() {
startServer();
startBrowser({
browserName: "firefox",
headless: false,
startUrl: `http://${host}:${server.port}/test/resources/reftest-analyzer.html#web=/test/eq.log`,
}).then(function (browser) {
browser.on("disconnected", function () {
stopServer();
process.exit(0);
});
});
}
async function startRefTest(masterMode, showRefImages) {
function finalize() {
stopServer();
let numRuns = 0;
var numErrors = 0;
var numFBFFailures = 0;
var numEqFailures = 0;
var numEqNoSnapshot = 0;
sessions.forEach(function (session) {
numRuns += session.numRuns;
numErrors += session.numErrors;
numFBFFailures += session.numFBFFailures;
numEqFailures += session.numEqFailures;
numEqNoSnapshot += session.numEqNoSnapshot;
});
var numFatalFailures = numErrors + numFBFFailures;
console.log();
if (!numRuns) {
console.log(`OHNOES! No tests ran!`);
} else if (numFatalFailures + numEqFailures > 0) {
console.log("OHNOES! Some tests failed!");
if (numErrors > 0) {
console.log(" errors: " + numErrors);
}
if (numEqFailures > 0) {
console.log(" different ref/snapshot: " + numEqFailures);
}
if (numFBFFailures > 0) {
console.log(" different first/second rendering: " + numFBFFailures);
}
} else {
console.log("All regression tests passed.");
}
var runtime = (Date.now() - startTime) / 1000;
console.log("Runtime was " + runtime.toFixed(1) + " seconds");
if (options.statsFile) {
fs.writeFileSync(options.statsFile, JSON.stringify(stats, null, 2));
}
if (masterMode) {
if (numEqFailures + numEqNoSnapshot > 0) {
console.log();
console.log("Some eq tests failed or didn't have snapshots.");
console.log("Checking to see if master references can be updated...");
if (numFatalFailures > 0) {
console.log(" No. Some non-eq tests failed.");
} else {
console.log(
" Yes! The references in tmp/ can be synced with ref/."
);
updateRefImages();
}
}
} else if (showRefImages && numEqFailures > 0) {
console.log();
console.log(
`Starting reftest harness to examine ${numEqFailures} eq test failures.`
);
examineRefImages();
}
}
async function setup() {
if (fs.existsSync(refsTmpDir)) {
console.error("tmp/ exists -- unable to proceed with testing");
process.exit(1);
}
if (fs.existsSync(eqLog)) {
fs.unlinkSync(eqLog);
}
if (fs.existsSync(testResultDir)) {
fs.rmSync(testResultDir, { recursive: true, force: true });
}
startTime = Date.now();
startServer();
server.hooks.POST.push(refTestPostHandler);
onAllSessionsClosed = finalize;
await startBrowsers({
baseUrl: `http://${host}:${server.port}/test/test_slave.html`,
initializeSession: session => {
session.masterMode = masterMode;
session.taskResults = {};
session.tasks = {};
session.remaining = manifest.length;
manifest.forEach(function (item) {
var rounds = item.rounds || 1;
var roundsResults = [];
roundsResults.length = rounds;
session.taskResults[item.id] = roundsResults;
session.tasks[item.id] = item;
});
session.numRuns = 0;
session.numErrors = 0;
session.numFBFFailures = 0;
session.numEqNoSnapshot = 0;
session.numEqFailures = 0;
monitorBrowserTimeout(session, handleSessionTimeout);
},
});
}
function checkRefsTmp() {
if (masterMode && fs.existsSync(refsTmpDir)) {
if (options.noPrompts) {
fs.rmSync(refsTmpDir, { recursive: true, force: true });
setup();
return;
}
console.log("Temporary snapshot dir tmp/ is still around.");
console.log("tmp/ can be removed if it has nothing you need.");
const reader = readline.createInterface(process.stdin, process.stdout);
reader.question(
"SHOULD THIS SCRIPT REMOVE tmp/? THINK CAREFULLY [yn] ",
function (answer) {
if (answer.toLowerCase() === "y") {
fs.rmSync(refsTmpDir, { recursive: true, force: true });
}
setup();
reader.close();
}
);
} else {
setup();
}
}
var startTime;
var manifest = getTestManifest();
if (!manifest) {
return;
}
if (!options.noDownload) {
await ensurePDFsDownloaded();
}
checkRefsTmp();
}
function handleSessionTimeout(session) {
if (session.closed) {
return;
}
var browser = session.name;
console.log(
"TEST-UNEXPECTED-FAIL | test failed " +
browser +
" has not responded in " +
browserTimeout +
"s"
);
session.numErrors += session.remaining;
session.remaining = 0;
closeSession(browser);
}
function getTestManifest() {
var manifest = JSON.parse(fs.readFileSync(options.manifestFile));
const testFilter = options.testfilter.slice(0),
xfaOnly = options.xfaOnly;
if (testFilter.length || xfaOnly) {
manifest = manifest.filter(function (item) {
var i = testFilter.indexOf(item.id);
if (i !== -1) {
testFilter.splice(i, 1);
return true;
}
if (xfaOnly && item.enableXfa) {
return true;
}
return false;
});
if (testFilter.length) {
console.error("Unrecognized test IDs: " + testFilter.join(" "));
return undefined;
}
}
return manifest;
}
function checkEq(task, results, browser, masterMode) {
var taskId = task.id;
var refSnapshotDir = path.join(refsDir, os.platform(), browser, taskId);
var testSnapshotDir = path.join(
testResultDir,
os.platform(),
browser,
taskId
);
var pageResults = results[0];
var taskType = task.type;
var numEqNoSnapshot = 0;
var numEqFailures = 0;
for (var page = 0; page < pageResults.length; page++) {
if (!pageResults[page]) {
continue;
}
const pageResult = pageResults[page];
let testSnapshot = pageResult.snapshot;
if (testSnapshot?.startsWith("data:image/png;base64,")) {
testSnapshot = Buffer.from(testSnapshot.substring(22), "base64");
} else {
console.error("Valid snapshot was not found.");
}
var refSnapshot = null;
var eq = false;
var refPath = path.join(refSnapshotDir, page + 1 + ".png");
if (!fs.existsSync(refPath)) {
numEqNoSnapshot++;
if (!masterMode) {
console.log("WARNING: no reference snapshot " + refPath);
}
} else {
refSnapshot = fs.readFileSync(refPath);
eq = refSnapshot.toString("hex") === testSnapshot.toString("hex");
if (!eq) {
console.log(
"TEST-UNEXPECTED-FAIL | " +
taskType +
" " +
taskId +
" | in " +
browser +
" | rendering of page " +
(page + 1) +
" != reference rendering"
);
ensureDirSync(testSnapshotDir);
fs.writeFileSync(
path.join(testSnapshotDir, page + 1 + ".png"),
testSnapshot
);
fs.writeFileSync(
path.join(testSnapshotDir, page + 1 + "_ref.png"),
refSnapshot
);
// This no longer follows the format of Mozilla reftest output.
const viewportString = `(${pageResult.viewportWidth}x${pageResult.viewportHeight}x${pageResult.outputScale})`;
fs.appendFileSync(
eqLog,
"REFTEST TEST-UNEXPECTED-FAIL | " +
browser +
"-" +
taskId +
"-page" +
(page + 1) +
" | image comparison (==)\n" +
`REFTEST IMAGE 1 (TEST)${viewportString}: ` +
path.join(testSnapshotDir, page + 1 + ".png") +
"\n" +
`REFTEST IMAGE 2 (REFERENCE)${viewportString}: ` +
path.join(testSnapshotDir, page + 1 + "_ref.png") +
"\n"
);
numEqFailures++;
}
}
if (masterMode && (!refSnapshot || !eq)) {
var tmpSnapshotDir = path.join(
refsTmpDir,
os.platform(),
browser,
taskId
);
ensureDirSync(tmpSnapshotDir);
fs.writeFileSync(
path.join(tmpSnapshotDir, page + 1 + ".png"),
testSnapshot
);
}
}
var session = getSession(browser);
session.numEqNoSnapshot += numEqNoSnapshot;
if (numEqFailures > 0) {
session.numEqFailures += numEqFailures;
} else {
console.log(
"TEST-PASS | " + taskType + " test " + taskId + " | in " + browser
);
}
}
function checkFBF(task, results, browser, masterMode) {
var numFBFFailures = 0;
var round0 = results[0],
round1 = results[1];
if (round0.length !== round1.length) {
console.error("round 1 and 2 sizes are different");
}
for (var page = 0; page < round1.length; page++) {
var r0Page = round0[page],
r1Page = round1[page];
if (!r0Page) {
continue;
}
if (r0Page.snapshot !== r1Page.snapshot) {
// The FBF tests fail intermittently in Firefox and Google Chrome when run
// on the bots, ignoring `makeref` failures for now; see
// - https://github.com/mozilla/pdf.js/pull/12368
// - https://github.com/mozilla/pdf.js/pull/11491
//
// TODO: Figure out why this happens, so that we can remove the hack; see
// https://github.com/mozilla/pdf.js/issues/12371
if (masterMode) {
console.log(
"TEST-SKIPPED | forward-back-forward test " +
task.id +
" | in " +
browser +
" | page" +
(page + 1)
);
continue;
}
console.log(
"TEST-UNEXPECTED-FAIL | forward-back-forward test " +
task.id +
" | in " +
browser +
" | first rendering of page " +
(page + 1) +
" != second"
);
numFBFFailures++;
}
}
if (numFBFFailures > 0) {
getSession(browser).numFBFFailures += numFBFFailures;
} else {
console.log(
"TEST-PASS | forward-back-forward test " + task.id + " | in " + browser
);
}
}
function checkLoad(task, results, browser) {
// Load just checks for absence of failure, so if we got here the
// test has passed
console.log("TEST-PASS | load test " + task.id + " | in " + browser);
}
function checkRefTestResults(browser, id, results) {
var failed = false;
var session = getSession(browser);
var task = session.tasks[id];
session.numRuns++;
results.forEach(function (roundResults, round) {
roundResults.forEach(function (pageResult, page) {
if (!pageResult) {
return; // no results
}
if (pageResult.failure) {
failed = true;
if (fs.existsSync(task.file + ".error")) {
console.log(
"TEST-SKIPPED | PDF was not downloaded " +
id +
" | in " +
browser +
" | page" +
(page + 1) +
" round " +
(round + 1) +
" | " +
pageResult.failure
);
} else {
session.numErrors++;
console.log(
"TEST-UNEXPECTED-FAIL | test failed " +
id +
" | in " +
browser +
" | page" +
(page + 1) +
" round " +
(round + 1) +
" | " +
pageResult.failure
);
}
}
});
});
if (failed) {
return;
}
switch (task.type) {
case "eq":
case "text":
case "highlight":
checkEq(task, results, browser, session.masterMode);
break;
case "fbf":
checkFBF(task, results, browser, session.masterMode);
break;
case "load":
checkLoad(task, results, browser);
break;
default:
throw new Error("Unknown test type");
}
// clear memory
results.forEach(function (roundResults, round) {
roundResults.forEach(function (pageResult, page) {
pageResult.snapshot = null;
});
});
}
function refTestPostHandler(req, res) {
var parsedUrl = url.parse(req.url, true);
var pathname = parsedUrl.pathname;
if (
pathname !== "/tellMeToQuit" &&
pathname !== "/info" &&
pathname !== "/submit_task_results"
) {
return false;
}
var body = "";
req.on("data", function (data) {
body += data;
});
req.on("end", function () {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end();
var session;
if (pathname === "/tellMeToQuit") {
session = getSession(parsedUrl.query.browser);
monitorBrowserTimeout(session, null);
closeSession(session.name);
return;
}
var data = JSON.parse(body);
if (pathname === "/info") {
console.log(data.message);
return;
}
var browser = data.browser;
var round = data.round;
var id = data.id;
var page = data.page - 1;
var failure = data.failure;
var snapshot = data.snapshot;
var lastPageNum = data.lastPageNum;
session = getSession(browser);
monitorBrowserTimeout(session, handleSessionTimeout);
var taskResults = session.taskResults[id];
if (!taskResults[round]) {
taskResults[round] = [];
}
if (taskResults[round][page]) {
console.error(
"Results for " +
browser +
":" +
id +
":" +
round +
":" +
page +
" were already submitted"
);
// TODO abort testing here?
}
taskResults[round][page] = {
failure,
snapshot,
viewportWidth: data.viewportWidth,
viewportHeight: data.viewportHeight,
outputScale: data.outputScale,
};
if (stats) {
stats.push({
browser,
pdf: id,
page,
round,
stats: data.stats,
});
}
var isDone = taskResults.at(-1)?.[lastPageNum - 1];
if (isDone) {
checkRefTestResults(browser, id, taskResults);
session.remaining--;
}
});
return true;
}
function onAllSessionsClosedAfterTests(name) {
const startTime = Date.now();
return function () {
stopServer();
var numRuns = 0,
numErrors = 0;
sessions.forEach(function (session) {
numRuns += session.numRuns;
numErrors += session.numErrors;
});
console.log();
console.log("Run " + numRuns + " tests");
if (!numRuns) {
console.log(`OHNOES! No ${name} tests ran!`);
} else if (numErrors > 0) {
console.log("OHNOES! Some " + name + " tests failed!");
console.log(" " + numErrors + " of " + numRuns + " failed");
} else {
console.log("All " + name + " tests passed.");
}
var runtime = (Date.now() - startTime) / 1000;
console.log(name + " tests runtime was " + runtime.toFixed(1) + " seconds");
};
}
async function startUnitTest(testUrl, name) {
onAllSessionsClosed = onAllSessionsClosedAfterTests(name);
startServer();
server.hooks.POST.push(unitTestPostHandler);
await startBrowsers({
baseUrl: `http://${host}:${server.port}${testUrl}`,
initializeSession: session => {
session.numRuns = 0;
session.numErrors = 0;
},
});
}
async function startIntegrationTest() {
onAllSessionsClosed = onAllSessionsClosedAfterTests("integration");
startServer();
const { runTests } = await import("./integration-boot.mjs");
await startBrowsers({
baseUrl: null,
initializeSession: session => {
session.numRuns = 0;
session.numErrors = 0;
},
});
global.integrationBaseUrl = `http://${host}:${server.port}/build/generic/web/viewer.html`;
global.integrationSessions = sessions;
const results = { runs: 0, failures: 0 };
await runTests(results);
sessions[0].numRuns = results.runs;
sessions[0].numErrors = results.failures;
await Promise.all(sessions.map(session => closeSession(session.name)));
}
function unitTestPostHandler(req, res) {
var parsedUrl = url.parse(req.url);
var pathname = parsedUrl.pathname;
if (
pathname !== "/tellMeToQuit" &&
pathname !== "/info" &&
pathname !== "/ttx" &&
pathname !== "/submit_task_results"
) {
return false;
}
var body = "";
req.on("data", function (data) {
body += data;
});
req.on("end", async function () {
if (pathname === "/ttx") {
res.writeHead(200, { "Content-Type": "text/xml" });
try {
res.end(await translateFont(body));
} catch (error) {
res.end(`<error>${error}</error>`);
}
return;
}
res.writeHead(200, { "Content-Type": "text/plain" });
res.end();
var data = JSON.parse(body);
if (pathname === "/tellMeToQuit") {
closeSession(data.browser);
return;
}
if (pathname === "/info") {
console.log(data.message);
return;
}
var session = getSession(data.browser);
session.numRuns++;
var message =
data.status + " | " + data.description + " | in " + session.name;
if (data.status === "TEST-UNEXPECTED-FAIL") {
session.numErrors++;
}
if (data.error) {
message += " | " + data.error;
}
console.log(message);
});
return true;
}
async function startBrowser({
browserName,
headless = options.headless,
startUrl,
extraPrefsFirefox = {},
}) {
const options = {
product: browserName,
protocol: "webDriverBiDi",
headless,
dumpio: true,
defaultViewport: null,
ignoreDefaultArgs: ["--disable-extensions"],
// The timeout for individual protocol (BiDi) calls should always be lower
// than the Jasmine timeout. This way protocol errors are always raised in
// the context of the tests that actually triggered them and don't leak
// through to other tests (causing unrelated failures or tracebacks). The
// timeout is set to 75% of the Jasmine timeout to catch operation errors
// later in the test run and because if a single operation takes that long
// it can't possibly succeed anymore.
protocolTimeout: 0.75 * /* jasmine.DEFAULT_TIMEOUT_INTERVAL = */ 30000,
};
if (!tempDir) {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pdfjs-"));
}
const printFile = path.join(tempDir, "print.pdf");
if (browserName === "chrome") {
// Run tests with the CDP protocol for Chrome only given that the Linux bot
// crashes with timeouts or OOM if WebDriver BiDi is used (issue #17961).
options.protocol = "cdp";
// avoid crash
options.args = ["--no-sandbox", "--disable-setuid-sandbox"];
// silent printing in a pdf
options.args.push("--kiosk-printing");
}
if (browserName === "firefox") {
options.extraPrefsFirefox = {
// Disable system addon updates.
"extensions.systemAddon.update.enabled": false,
// avoid to have a prompt when leaving a page with a form
"dom.disable_beforeunload": true,
// Disable dialog when saving a pdf
"pdfjs.disabled": true,
"browser.helperApps.neverAsk.saveToDisk": "application/pdf",
// Avoid popup when saving is done
"browser.download.always_ask_before_handling_new_types": true,
"browser.download.panel.shown": true,
"browser.download.alwaysOpenPanel": false,
// Save file in output
"browser.download.folderList": 2,
"browser.download.dir": tempDir,
// Print silently in a pdf
"print.always_print_silent": true,
"print.show_print_progress": false,
print_printer: "PDF",
"print.printer_PDF.print_to_file": true,
"print.printer_PDF.print_to_filename": printFile,
// Enable OffscreenCanvas
"gfx.offscreencanvas.enabled": true,
// Disable gpu acceleration
"gfx.canvas.accelerated": false,
// Enable the `round` CSS function.
"layout.css.round.enabled": true,
// This allow to copy some data in the clipboard.
"dom.events.asyncClipboard.clipboardItem": true,
// It's helpful to see where the caret is.
"accessibility.browsewithcaret": true,
// Disable the newtabpage stuff.
"browser.newtabpage.enabled": false,
// Disable network connections to Contile.
"browser.topsites.contile.enabled": false,
...extraPrefsFirefox,
};
}
const browser = await puppeteer.launch(options);
if (startUrl) {
const pages = await browser.pages();
const page = pages[0];
await page.goto(startUrl, { timeout: 0, waitUntil: "domcontentloaded" });
}
return browser;
}
async function startBrowsers({ baseUrl, initializeSession }) {
// Remove old browser revisions from Puppeteer's cache. Updating Puppeteer can
// cause new browser revisions to be downloaded, so trimming the cache will
// prevent the disk from filling up over time.
await puppeteer.trimCache();
const browserNames = options.noChrome ? ["firefox"] : ["firefox", "chrome"];
for (const browserName of browserNames) {
// The session must be pushed first and augmented with the browser once
// it's initialized. The reason for this is that browser initialization
// takes more time when the browser is not found locally yet and we don't
// want `onAllSessionsClosed` to trigger if one of the browsers is done
// and the other one is still initializing, since that would mean that
// once the browser is initialized the server would have stopped already.
// Pushing the session first ensures that `onAllSessionsClosed` will
// only trigger once all browsers are initialized and done.
const session = {
name: browserName,
browser: undefined,
closed: false,
};
sessions.push(session);
// Construct the start URL from the base URL by appending query parameters
// for the runner if necessary.
let startUrl = "";
if (baseUrl) {
const queryParameters =
`?browser=${encodeURIComponent(browserName)}` +
`&manifestFile=${encodeURIComponent("/test/" + options.manifestFile)}` +
`&testFilter=${JSON.stringify(options.testfilter)}` +
`&xfaOnly=${options.xfaOnly}` +
`&delay=${options.statsDelay}` +