-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathprocess-test-directory-v1.js
1404 lines (1245 loc) · 41.3 KB
/
process-test-directory-v1.js
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
/// <reference path="../../types/aria-at-csv.js" />
/// <reference path="../../types/aria-at-parsed.js" />
/// <reference path="../../types/aria-at-validated.js" />
/// <reference path="../../types/aria-at-file.js" />
/// <reference path="../util/file-record-types.js" />
'use strict';
const path = require('path');
const { Readable } = require('stream');
const {
types: { isArrayBufferView, isArrayBuffer },
} = require('util');
const csv = require('csv-parser');
const beautify = require('json-beautify');
const { validate } = require('../util/error');
const { reindent } = require('../util/lines');
const { Queryable } = require('../util/queryable');
const { FileRecordChain } = require('../util/file-record-chain');
const { parseSupport } = require('./parse-support');
const { parseTestCSVRow } = require('./parse-test-csv-row');
const { parseCommandCSVRow } = require('./parse-command-csv-row');
const { createCommandTuplesATModeTaskLookup } = require('./command-tuples-at-mode-task-lookup');
const { renderHTML: renderCollectedTestHtml } = require('./templates/collected-test.html');
const { createExampleScriptsTemplate } = require('./example-scripts-template');
/**
* @param {string} directory - path to directory of data to be used to generate test
* @param {string} buildOutputDirectory - path to build directory. Defaults to '<root>/build'
* @param {object} args={}
*/
const processTestDirectory = async ({ directory, buildOutputDirectory, args = {} }) => {
let VERBOSE_CHECK = false;
let VALIDATE_CHECK = false;
let TEST_MODE = false;
let suppressedMessages = 0;
/**
* @param {string} message - message to be logged
* @param {object} [options]
* @param {boolean} [options.severe=false] - indicates whether the message should be viewed as an error or not
* @param {boolean} [options.force=false] - indicates whether this message should be forced to be outputted regardless of verbosity level
*/
const log = (message, { severe = false, force = false } = {}) => {
if (VERBOSE_CHECK || force) {
if (severe) console.error(message);
else console.log(message);
} else {
// Output no logs
suppressedMessages += 1; // counter to indicate how many messages were hidden
}
};
/**
* @param {string} message - error message
*/
log.warning = message => log(message, { severe: true, force: true });
/**
* Log error then exit the process.
* @param {string} message - error message
*/
log.error = message => {
log.warning(message);
process.exit(1);
};
// setup from arguments passed to npm script or test runner
VERBOSE_CHECK = !!args.verbose;
VALIDATE_CHECK = !!args.validate;
TEST_MODE = !!args.testMode;
const validModes = ['reading', 'interaction', 'item'];
/** Name of the test plan. */
const testPlanName = path.basename(directory);
// cwd; @param rootDirectory is dependent on this file not moving from the `lib/data` folder
const libDataDirectory = path.dirname(__filename);
const rootDirectory = path.join(libDataDirectory, '../..');
const testsDirectory = path.join(rootDirectory, 'tests');
const testPlanDirectory = path.join(rootDirectory, 'tests', testPlanName);
const resourcesDirectory = path.join(testsDirectory, 'resources');
const supportFilePath = path.join(testsDirectory, 'support.json');
const atCommandsCsvFilePath = path.join(testPlanDirectory, 'data', 'commands.csv');
const testsCsvFilePath = path.join(testPlanDirectory, 'data', 'testsV1.csv');
const referencesCsvFilePath = path.join(testPlanDirectory, 'data', 'referencesV1.csv');
// build output folders and file paths setup
const buildDirectory = buildOutputDirectory ?? path.join(rootDirectory, 'build');
const buildTestsDirectory = path.join(buildDirectory, 'tests');
const testPlanBuildDirectory = path.join(buildTestsDirectory, testPlanName);
const indexFileBuildOutputPath = path.join(testPlanBuildDirectory, 'index.html');
let backupTestsCsvFile, backupReferencesCsvFile;
const existingBuildPromise = FileRecordChain.read(buildDirectory, {
glob: [
'',
'tests',
`tests/${testPlanName}`,
`tests/${testPlanName}/**`,
'tests/resources',
'tests/resources/*',
'tests/support.json',
].join(','),
});
const [testPlanRecord, resourcesOriginalRecord, supportRecord] = await Promise.all(
[testPlanDirectory, resourcesDirectory, supportFilePath].map(filepath =>
FileRecordChain.read(filepath)
)
);
const scriptsRecord = testPlanRecord.find('data/js');
const resourcesRecord = resourcesOriginalRecord.filter({ glob: '{aria-at-*,keys,vrender}.mjs' });
// Filter out reference html files with inline scripts. Files that are not
// regenerated will be removed from the filesystem.
const testPlanUpdate = await testPlanRecord.walk(record => {
if (record.entries) {
return {
...record,
entries: record.entries.filter(record => !isScriptedReferenceRecord(record)),
};
}
return record;
});
const newBuild = new FileRecordChain({
entries: [
{
name: 'tests',
entries: [
{
name: testPlanName,
entries: testPlanUpdate.filter({ glob: 'reference{,/**}' }).record.entries,
},
{ name: 'resources', ...resourcesRecord.record },
{ name: 'support.json', ...supportRecord.record },
],
},
],
});
const keyDefs = {};
const supportJson = JSON.parse(supportRecord.text);
let allATKeys = supportJson.ats.map(({ key }) => key);
let allATNames = supportJson.ats.map(({ name }) => name);
const validAppliesTo = ['Screen Readers', 'Desktop Screen Readers'].concat(allATKeys);
if (!testPlanRecord.isDirectory()) {
log.error(`The test directory '${testPlanDirectory}' does not exist. Check the path to tests.`);
}
if (!testPlanRecord.find('data/commands.csv').isFile()) {
log.error(
`The at-commands.csv file does not exist. Please create '${atCommandsCsvFilePath}' file.`
);
}
if (!testPlanRecord.find('data/testsV1.csv').isFile()) {
// Check if original file can be processed
if (!testPlanRecord.find('data/tests.csv').isFile()) {
log.error(`The testsV1.csv file does not exist. Please create '${testsCsvFilePath}' file.`);
} else {
backupTestsCsvFile = 'data/tests.csv';
}
}
if (!testPlanRecord.find('data/referencesV1.csv').isFile()) {
// Check if original file can be processed
if (!testPlanRecord.find('data/references.csv').isFile()) {
log.error(
`The referencesV1.csv file does not exist. Please create '${referencesCsvFilePath}' file.`
);
} else {
backupReferencesCsvFile = 'data/references.csv';
}
}
// get Keys that are defined
try {
// read contents of the file
const keys = resourcesRecord.find('keys.mjs').text;
// split the contents by new line
const lines = keys.split(/\r?\n/);
// print all lines
lines.forEach(line => {
let parts1 = line.split(' ');
let parts2 = line.split('"');
if (parts1.length > 3) {
let code = parts1[2].trim();
keyDefs[code] = parts2[1].trim();
}
});
} catch (err) {
log.warning(err);
}
function cleanTask(task) {
return task.replace(/'/g, '').replace(/;/g, '').trim().toLowerCase();
}
/**
* Create Test File
* @param {AriaATCSV.Test} test
* @param refs
* @param commands
* @returns {(string|*[])[]}
*/
function createTestFile(
test,
refs,
commands,
{ addTestError, emitFile, scriptsRecord, exampleScriptedFilesQueryable }
) {
let scripts = [];
// default setupScript if test has undefined setupScript
if (!scriptsRecord.find(`${test.setupScript}.js`).isFile()) test.setupScript = '';
function getModeValue(value) {
let v = value.trim().toLowerCase();
if (!validModes.includes(v)) {
addTestError(test.testId, '"' + value + '" is not valid value for "mode" property.');
}
return v;
}
function getTask(t) {
let task = cleanTask(t);
if (typeof commands[task] !== 'object') {
addTestError(test.testId, '"' + task + '" does not exist in commands.csv file.');
}
return task;
}
function getAppliesToValues(values) {
function checkValue(value) {
let v1 = value.trim().toLowerCase();
for (let i = 0; i < validAppliesTo.length; i++) {
let v2 = validAppliesTo[i];
if (v1 === v2.toLowerCase()) {
return v2;
}
}
return false;
}
// check for individual assistive technologies
let items = values.split(',');
let newValues = [];
items.filter(item => {
let value = checkValue(item);
if (!value) {
addTestError(test.testId, '"' + item + '" is not valid value for "appliesTo" property.');
}
newValues.push(value);
});
return newValues;
}
/**
* Determines priority level (default is 1) of assertion string, then adds it to the collection of assertions for
* the test plan
* @param {string} a - Assertion string to be evaluated
*/
function addAssertion(a) {
let level = '1';
let str = a;
a = a.trim();
// matches a 'colon' when preceded by either of the digits 1 OR 2 (SINGLE CHARACTER), at the start of the string
let parts = a.split(/(?<=^[1-2]):/g);
if (parts.length === 2) {
level = parts[0];
str = parts[1].substring(0);
if (level !== '1' && level !== '2') {
addTestError(
test.testId,
"Level value must be 1 or 2, value found was '" +
level +
"' for assertion '" +
str +
"' (NOTE: level 2 defined for this assertion)."
);
level = '2';
}
}
if (a.length) {
assertions.push([level, str]);
}
}
function getReferences(example, testRefs) {
let links = '';
if (typeof example === 'string' && example.length) {
links += `<link rel="help" href="${refs.example}">\n`;
}
let items = test.refs.split(' ');
items.forEach(function (item) {
item = item.trim();
if (item.length) {
if (typeof refs[item] === 'string') {
links += `<link rel="help" href="${refs[item]}">\n`;
} else {
addTestError(test.testId, 'Reference does not exist: ' + item);
}
}
});
return links;
}
function addSetupScript(scriptName) {
let script = '';
if (scriptName) {
if (!scriptsRecord.find(`${scriptName}.js`).isFile()) {
addTestError(test.testId, `Setup script does not exist: ${scriptName}.js`);
return '';
}
try {
const data = scriptsRecord.find(`${scriptName}.js`).text;
const lines = data.split(/\r?\n/);
lines.forEach(line => {
if (line.trim().length) script += '\t\t\t' + line.trim() + '\n';
});
} catch (err) {
log.warning(err);
}
scripts.push(`\t\t${scriptName}: function(testPageDocument){\n${script}\t\t}`);
}
return script;
}
function getSetupScriptDescription(desc) {
let str = '';
if (typeof desc === 'string') {
let d = desc.trim();
if (d.length) {
str = d;
}
}
return str;
}
function getScripts() {
let js = 'var scripts = {\n';
js += scripts.join(',\n');
js += '\n\t};';
return js;
}
let task = getTask(test.task);
let appliesTo = getAppliesToValues(test.appliesTo);
let mode = getModeValue(test.mode);
appliesTo.forEach(at => {
if (commands[task]) {
if (!commands[task][mode][at.toLowerCase()]) {
addTestError(
test.testId,
'command is missing for the combination of task: "' +
task +
'", mode: "' +
mode +
'", and AT: "' +
at.toLowerCase() +
'" '
);
}
}
});
let assertions = [];
let id = test.testId;
if (parseInt(test.testId) < 10) {
id = '0' + id;
}
const cleanTaskName = cleanTask(test.task).replace(/\s+/g, '-');
let testFileName = `test-${id}-${cleanTaskName}-${mode}.html`;
let testJSONFileName = `test-${id}-${cleanTaskName}-${mode}.json`;
let testPlanHtmlFileBuildPath = path.join(testPlanBuildDirectory, testFileName);
let testPlanJsonFileBuildPath = path.join(testPlanBuildDirectory, testJSONFileName);
let references = getReferences(refs.example, test.refs);
addSetupScript(test.setupScript);
for (let i = 1; i < 31; i++) {
if (!test['assertion' + i]) {
continue;
}
addAssertion(test['assertion' + i]);
}
/** @type {AriaATFile.Behavior} */
let testData = {
setup_script_description: getSetupScriptDescription(test.setupScriptDescription),
setupTestPage: test.setupScript,
applies_to: appliesTo,
mode: mode,
task: task,
testPlanStrings: supportJson.testPlanStrings,
specific_user_instruction: test.instructions,
output_assertions: assertions,
};
emitFile(testPlanJsonFileBuildPath, JSON.stringify(testData, null, 2), 'utf8');
function getTestJson() {
return JSON.stringify(testData, null, 2);
}
function getCommandsJson() {
return beautify({ [task]: commands[task] }, null, 2, 40);
}
let testHTML = `
<!DOCTYPE html>
<meta charset="utf-8">
<title>${test.title}</title>
${references}
<script>
${getScripts()}
</script>
<script type="module">
import { initialize, verifyATBehavior, displayTestPageAndInstructions } from "../resources/aria-at-harness.mjs";
new Promise((resolve) => {
fetch('../support.json')
.then(response => resolve(response.json()))
})
.then(supportJson => {
const testJson = ${getTestJson()};
const commandJson = ${getCommandsJson()};
initialize(supportJson, commandJson);
verifyATBehavior(testJson);
displayTestPageAndInstructions(${JSON.stringify(
exampleScriptedFilesQueryable.where({ name: test.setupScript ? test.setupScript : '' }).path
)});
});
</script>
`;
emitFile(testPlanHtmlFileBuildPath, testHTML, 'utf8');
/** @type {AriaATFile.CollectedTest} */
const collectedTest = {};
const applies_to_at = [];
allATKeys.forEach(at => applies_to_at.push(testData.applies_to.indexOf(at) >= 0));
return [testFileName, applies_to_at];
}
/**
* Create an index file for a local server
* @param tasks
*/
function createIndexFile(tasks, { emitFile }) {
let rows = '';
let all_ats = '';
allATNames.forEach(at => (all_ats += '<th>' + at + '</th>\n'));
tasks.forEach(function (task) {
rows += `<tr><td>${task.id}</td>`;
rows += `<td scope="row">${task.title}</td>`;
for (let i = 0; i < allATKeys.length; i++) {
if (task.applies_to_at[i]) {
rows += `<td class="test"><a href="${task.href}?at=${allATKeys[i]}" aria-label="${allATNames[i]} test for task ${task.id}">${allATNames[i]}</a></td>`;
} else {
rows += `<td class="test none">not included</td>`;
}
}
rows += `<td>${task.script}</td></tr>\n`;
});
let indexHTML = `
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Index of Assistive Technology Test Files</title>
<style>
table {
display: table;
border-collapse: collapse;
border-spacing: 2px;
border-color: gray;
}
thead {
display: table-row-group;
vertical-align: middle;
border-bottom: black solid 2px;
}
tbody {
display: table-row-group;
vertical-align: middle;
border-color: gray;
}
tr:nth-child(even) {background: #DDD}
tr:nth-child(odd) {background: #FFF}
tr {
display: table-row;
vertical-align: inherit;
border-color: gray;
}
td {
padding: 3px;
display: table-cell;
}
td.test {
text-align: center;
}
td.none {
color: #333;
}
th {
padding: 3px;
font-weight: bold;
display: table-cell;
}
</style>
</head>
<body>
<main>
<h1>Index of Assistive Technology Test Files</h1>
<p>This is useful for viewing the local files on a local web server.</p>
<table>
<thead>
<tr>
<th>Task ID</th>
<th>Testing Task</th>
${all_ats}
<th>Setup Script Reference</th>
</tr>
</thead>
<tbody>
${rows}
</tbody>
</table>
</main>
</body>
`;
emitFile(indexFileBuildOutputPath, indexHTML, 'utf8');
}
// Process CSV files
var refs = {};
var errorCount = 0;
var errors = '';
var indexOfURLs = [];
function addTestError(id, error) {
errorCount += 1;
errors += '[Test ' + id + ']: ' + error + '\n';
}
function addCommandError({ testId, task }, key) {
errorCount += 1;
errors += `[Command]: The key reference "${key}" found in "tests/${testPlanName}/data/commands.csv" for "test id ${testId}: ${task}" is invalid. Command may not be defined in "tests/resources/keys.mjs".\n`;
}
const newTestPlan = newBuild.find(`tests/${testPlanName}`);
function emitFile(filepath, content) {
newTestPlan.add(path.relative(testPlanBuildDirectory, filepath), {
buffer: toBuffer(content),
});
}
function generateSourceHtmlScriptFile(filePath, content) {
testPlanUpdate.add(path.relative(testPlanDirectory, filePath), {
buffer: toBuffer(content),
});
}
// intended to be an internal helper to reduce some code duplication and make logging for csv errors simpler
async function readCSVFile(filePath, rowValidator = identity => identity) {
const rawCSV = await readCSV(testPlanRecord.find(filePath));
let index = 0;
function printError(message) {
// line number is index+2
log.warning(
`WARNING: Error parsing ${path.join(testPlanDirectory, filePath)} line ${
index + 2
}: ${message}`
);
}
try {
const firstRowKeysLength = Object.keys(rawCSV[0]).length;
for (; index < rawCSV.length; index++) {
const keysLength = Object.keys(rawCSV[index]).length;
if (keysLength != firstRowKeysLength) {
printError(
`column number mismatch, please include empty cells to match headers. Expected ${firstRowKeysLength} columns, found ${keysLength}`
);
}
if (!rowValidator(rawCSV[index])) {
printError('validator returned false result');
return;
}
}
} catch (err) {
printError(err);
return;
}
log(`Successfully parsed ${path.join(testPlanDirectory, filePath)}`);
return rawCSV;
}
function validateReferencesKeys(row) {
if (typeof row.refId !== 'string' || typeof row.value !== 'string') {
throw new Error('Row missing refId or value');
}
return row;
}
const validCommandKeys = /^(?:testId|task|mode|at|command[A-Z])$/;
const numericKeyFormat = /^_(\d+)$/;
function validateCommandsKeys(row) {
// example header:
// testId,task,mode,at,commandA,commandB,commandC,commandD,commandE,commandF
for (const key of Object.keys(row)) {
if (numericKeyFormat.test(key)) {
throw new Error(`Column found without header row, ${+key.substring(1) + 1}`);
} else if (!validCommandKeys.test(key)) {
throw new Error(`Unknown commands.csv key: ${key} - check header row?`);
}
}
if (
!(
row.testId?.length &&
row.task?.length &&
row.mode?.length &&
row.at?.length &&
row.commandA?.length
)
) {
throw new Error('Missing one of required testId, task, mode, at, commandA');
}
return row;
}
const validTestsKeys =
/^(?:testId|title|appliesTo|mode|task|setupScript|setupScriptDescription|refs|instructions|assertion(?:[1-9]|[1-2][0-9]|30))$/;
function validateTestsKeys(row) {
// example header:
// testId,title,appliesTo,mode,task,setupScript,setupScriptDescription,refs,instructions,assertion1,assertion2,assertion3,assertion4,assertion5,assertion6,assertion7
for (const key of Object.keys(row)) {
if (numericKeyFormat.test(key)) {
throw new Error(`Column found without header row, ${+key.substring(1) + 1}`);
} else if (!validTestsKeys.test(key)) {
throw new Error(`Unknown testsV1.csv key: ${key} - check header row?`);
}
}
if (
!(
row.testId?.length &&
row.title?.length &&
row.appliesTo?.length &&
row.mode?.length &&
row.task?.length
)
) {
throw new Error('Missing one of required testId, title, appliesTo, mode, task');
}
return row;
}
const [atCommands, refRows, tests] = await Promise.all([
readCSVFile('data/commands.csv', validateCommandsKeys),
readCSVFile(backupReferencesCsvFile || 'data/referencesV1.csv', validateReferencesKeys),
readCSVFile(backupTestsCsvFile || 'data/testsV1.csv', validateTestsKeys),
]);
for (const row of refRows) {
refs[row.refId] = row.value.trim();
}
const scripts = loadScripts(scriptsRecord);
const commandsParsed = atCommands.map(parseCommandCSVRow);
const testsParsed = tests.map(parseTestCSVRow);
const referencesParsed = parseReferencesCSV(refRows);
const keysParsed = parseKeyMap(keyDefs);
const supportParsed = parseSupport(supportJson);
const keysValidated = validateKeyMap(keysParsed, {
addKeyMapError(reason) {
errorCount += 1;
errors += `[resources/keys.mjs]: ${reason}\n`;
},
});
const supportQueryables = {
at: Queryable.from('at', supportParsed.ats),
atGroup: Queryable.from('atGroup', supportParsed.atGroups),
};
const keyQueryable = Queryable.from('key', keysValidated);
const commandLookups = {
key: keyQueryable,
support: supportQueryables,
};
const commandsValidated = commandsParsed.map(command =>
validateCommand(command, commandLookups, { addCommandError })
);
const referenceQueryable = Queryable.from('reference', referencesParsed);
const examplePathOriginal = referenceQueryable.where({ refId: 'reference' })
? referenceQueryable.where({ refId: 'reference' }).value
: '';
if (!examplePathOriginal) {
log.error(
`ERROR: Valid 'reference' value not found in "tests/${testPlanName}/data/referencesV1.csv".`
);
}
const exampleRecord = testPlanRecord.find(examplePathOriginal);
if (!exampleRecord.isFile()) {
log.error(
`ERROR: Invalid 'reference' value path "${examplePathOriginal}" found in "tests/${testPlanName}/data/referencesV1.csv".`
);
}
const testLookups = {
command: Queryable.from('command', commandsValidated),
mode: Queryable.from('mode', validModes),
reference: referenceQueryable,
script: Queryable.from('script', scripts),
support: supportQueryables,
};
const testsValidated = testsParsed.map(test =>
validateTest(test, testLookups, {
addTestError: addTestError.bind(null, test.testId),
})
);
const examplePathDirectory = path.dirname(examplePathOriginal);
const examplePathBaseName = path.basename(examplePathOriginal, '.html');
/** @type {function(string): string} */
const examplePathTemplate = scriptName =>
path.join(
examplePathDirectory,
`${examplePathBaseName}${scriptName ? `.${scriptName}` : ''}.html`
);
const exampleTemplate = validate.reportTo(
reason => log.warning(`[${examplePathOriginal}]: ${reason.message}`),
() => createExampleScriptsTemplate(exampleRecord)
);
const plainScriptedFile = createExampleScriptedFile('', examplePathTemplate, exampleTemplate, '');
const scriptedFiles = scripts.map(({ name, source }) =>
createExampleScriptedFile(name, examplePathTemplate, exampleTemplate, source)
);
const exampleScriptedFiles = [plainScriptedFile, ...scriptedFiles];
const exampleScriptedFilesQueryable = Queryable.from('example', exampleScriptedFiles);
const commandQueryable = Queryable.from('command', commandsValidated);
const testsCollected = testsValidated.flatMap(test => {
return test.target.at.map(({ key }) =>
collectTestData({
test,
command: commandQueryable.where({
testId: test.testId,
target: { at: { key } },
}),
reference: referenceQueryable,
example: exampleScriptedFilesQueryable,
key: keyQueryable,
modeInstructionTemplate: MODE_INSTRUCTION_TEMPLATES_QUERYABLE,
})
);
});
const buildFiles = [
...createScriptFiles(scripts, testPlanBuildDirectory),
...exampleScriptedFiles.map(({ path: pathSuffix, content }) => ({
path: path.join(buildTestsDirectory, testPlanName, pathSuffix),
content,
})),
...testsCollected.map(collectedTest =>
createCollectedTestFile(collectedTest, testPlanBuildDirectory)
),
...testsCollected.map(collectedTest =>
createCollectedTestHtmlFile(collectedTest, testPlanBuildDirectory)
),
];
buildFiles.forEach(file => {
emitFile(file.path, file.content);
});
scriptedFiles.forEach(file => {
generateSourceHtmlScriptFile(path.join('tests', testPlanName, file.path), file.content);
});
const atCommandsMap = createCommandTuplesATModeTaskLookup(commandsValidated);
emitFile(
path.join(testPlanBuildDirectory, 'commands.json'),
beautify(atCommandsMap, null, 2, 40)
);
log('Creating the following test files: ');
tests.forEach(function (test) {
try {
const [url, applies_to_at] = createTestFile(test, refs, atCommandsMap, {
addTestError,
emitFile,
scriptsRecord,
exampleScriptedFilesQueryable,
});
indexOfURLs.push({
id: test.testId,
title: test.title,
href: url,
script: test.setupScript,
applies_to_at: applies_to_at,
});
log('[Test ' + test.testId + ']: ' + url);
} catch (err) {
log.warning(err);
}
});
createIndexFile(indexOfURLs, {
emitFile,
});
const prefixBuildPath = TEST_MODE ? '__test__/' : '';
const prefixTestsPath = TEST_MODE ? '__test__/__mocks__/' : '';
const existingRoot = new FileRecordChain({});
existingRoot.add(`${prefixBuildPath}build`, await existingBuildPromise);
existingRoot.add(`${prefixTestsPath}tests/${testPlanName}`, testPlanRecord);
const newRoot = new FileRecordChain({});
newRoot.add(`${prefixBuildPath}build`, newBuild);
newRoot.add(`${prefixTestsPath}tests/${testPlanName}`, testPlanUpdate);
const buildChanges = newRoot.changesAfter(existingRoot);
if (!VALIDATE_CHECK) {
await buildChanges.commit(rootDirectory);
}
if (errorCount) {
log.warning(
`*** ${errorCount} Errors in tests and/or commands in test plan [tests/${testPlanName}] ***`
);
log.warning(errors);
} else {
log('No validation errors detected\n');
}
return { isSuccessfulRun: errorCount === 0, suppressedMessages };
};
exports.processTestDirectory = processTestDirectory;
/**
* @param {FileRecord.Record} record
* @returns {Promise<string[][]>}
*/
function readCSV(record) {
const rows = [];
return new Promise(resolve => {
Readable.from(record.buffer)
.pipe(
csv({
mapHeaders: ({ header, index }) => {
if (header.toLowerCase().includes('\ufeff'))
console.error(
`Unwanted U+FEFF found for key ${header} at index ${index} while processing CSV.`
);
return header.replace(/^\uFEFF/g, '');
},
mapValues: ({ header, value }) => {
if (value.toLowerCase().includes('\ufeff'))
console.error(
`Unwanted U+FEFF found for value in key, value pair (${header}: ${value}) while processing CSV.`
);
return value.replace(/^\uFEFF/g, '');
},
})
)
.on('data', row => {
rows.push(row);
})
.on('end', () => {
resolve(rows);
});
});
}
/**
* @param {FileRecordChain} testPlanJS
* @returns {AriaATParsed.ScriptSource[]}
*/
function loadScripts(testPlanJS) {
return testPlanJS.filter({ glob: ',*.js' }).entries.map(({ name: fileName, text: source }) => {
const name = path.basename(fileName, '.js');
const modulePath = path.posix.join('scripts', `${name}.module.js`);
const jsonpPath = path.posix.join('scripts', `${name}.jsonp.js`);
/** @type {AriaATFile.ScriptSource} */
return {
name,
source,
modulePath,
jsonpPath,
};
});
}
/**
* @param {AriaATFile.ScriptSource[]} scripts
* @param {string} testPlanBuildDirectory
* @returns {{path: string, content: Uint8Array}[]}
*/
function createScriptFiles(scripts, testPlanBuildDirectory) {
const jsonpFunction = 'scriptsJsonpLoaded';
return [
...scripts.reduce((files, script) => {
const { modulePath, jsonpPath } = script;
const oneScript = [script];
return [...files, ...renderFileVariants(oneScript, modulePath, jsonpPath)];
}, []),
...renderFileVariants(scripts, 'scripts.module.js', 'scripts.jsonp.js'),
];
function renderFileVariants(scripts, modulePath, jsonpPath) {
return [
{
path: path.join(testPlanBuildDirectory, modulePath),
content: encodeText(renderModule(scripts).toString()),
},
{
path: path.join(testPlanBuildDirectory, jsonpPath),
content: encodeText(renderJsonp(scripts).toString()),
},
];
}
function renderJsonp(scripts) {
return reindent`window[document.currentScript.getAttribute("jsonpFunction") || "${jsonpFunction}"]({
${scripts.map(renderJsonpExport).join(',\n')}
});
`;
}
function renderJsonpExport({ name, source }) {
return reindent`${name}(testPageDocument) {
${source.trim()}
}`;
}
function renderModule(scripts) {
return reindent`${scripts.map(renderModuleExport).join('\n\n')}
`;
}
function renderModuleExport({ name, source }) {