-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathx-test.js
1483 lines (1380 loc) · 50.9 KB
/
x-test.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
/**
* Simple assertion which throws exception when not "ok".
* assert('foo' === 'bar', 'foo does not equal bar');
*/
export const assert = (ok, text) => XTestSuite.assert(suiteContext, ok, text);
/**
* Register coverage percentage goal for a given file.
* coverage('../foo.js', 87);
*/
export const coverage = (href, goal) => XTestSuite.coverage(suiteContext, href, goal);
/**
* Force test suite registration to remain open until promise resolves.
* const barsPromise = fetch('https://foo/api/v2/bars').then(response => response.json());
* waitFor(barsPromise);
*/
export const waitFor = promise => XTestSuite.waitFor(suiteContext, promise);
/**
* Register a test to be run as a subsequent test suite.
* test('./test-sibling.html');
*/
export const test = href => XTestSuite.test(suiteContext, href);
/**
* Register a grouping. Alternatively, mark with flags.
*/
export const describe = (text, callback) => XTestSuite.describe(suiteContext, text, callback);
describe.skip = (text, callback) => XTestSuite.describeSkip(suiteContext, text, callback);
describe.only = (text, callback) => XTestSuite.describeOnly(suiteContext, text, callback);
describe.todo = (text, callback) => XTestSuite.describeTodo(suiteContext, text, callback);
/**
* Register an individual test lint. Alternatively, mark with flags.
*/
export const it = (text, callback, interval) => XTestSuite.it(suiteContext, text, callback, interval);
it.skip = (text, callback, interval) => XTestSuite.itSkip(suiteContext, text, callback, interval);
it.only = (text, callback, interval) => XTestSuite.itOnly(suiteContext, text, callback, interval);
it.todo = (text, callback, interval) => XTestSuite.itTodo(suiteContext, text, callback, interval);
// Internal Interface. This is exposed for testing purposes only.
export { XTestRoot as __XTestRoot__, XTestReporter as __XTestReporter__, XTestTap as __XTestTap__, XTestSuite as __XTestSuite__ };
// https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
function uuid() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
);
}
function publish(type, data) {
top.postMessage({ type, data }, '*');
}
function subscribe(callback) {
top.addEventListener('message', callback);
}
function addErrorListener(callback) {
addEventListener('error', callback);
}
function addUnhandledrejectionListener(callback) {
addEventListener('unhandledrejection', callback);
}
async function timeout(interval) {
interval = interval ?? 30000;
await new Promise((resolve, reject) => {
setTimeout(() => { reject(new Error(`timeout after ${interval}ms`)); }, interval);
});
}
const styleSheet = new CSSStyleSheet();
styleSheet.replaceSync(`
:host {
display: flex;
flex-direction: column;
justify-content: flex-end;
position: fixed;
z-index: 1;
left: 0;
bottom: 0;
width: 100vw;
height: 400px;
background-color: var(--black);
max-height: 100vh;
min-height: var(--header-height);
font-family: monospace;
--header-height: 40px;
--black: #111111;
--white: white;
--subdued: #8C8C8C;
--version: #39CCCC;
--todo: #FF851B;
--todone: #FFDC00;
--skip: #FF851B;
--ok: #2ECC40;
--not-ok: #FF4136;
--subtest: #4D4D4D;
--plan: #39CCCC;
--link: #0085ff;
}
:host(:not([open])) {
max-height: var(--header-height);
}
#header {
display: flex;
justify-content: space-between;
align-items: center;
height: var(--header-height);
flex-shrink: 0;
box-shadow: inset 0 -1px 0 0 #484848, 0 1px 2px 0 #484848;
padding-right: 38px;
background-color: var(--x-test-reporter-background-color);
}
:host([open]) #header {
cursor: grab;
}
:host([open][dragging]) #header {
cursor: grabbing;
}
#toggle {
position: fixed;
bottom: 7px;
right: 12px;
font: inherit;
margin: 0;
border: none;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
height: 26px;
width: 26px;
cursor: pointer;
--color: var(--subdued);
color: var(--color);
background-color: transparent;
box-shadow: inset 0 0 0 1px var(--color);
}
#toggle:hover,
#toggle:focus-visible {
--color: var(--white);
}
#toggle:active {
--color: var(--subdued);
}
#toggle::before {
content: "↑";
}
:host([open]) #toggle::before {
content: "↓";
}
#result {
margin: auto 12px;
padding: 6px 16px;
border-radius: 4px;
line-height: 14px;
color: var(--white);
background-color: var(--todo);
user-select: none;
pointer-events: none;
white-space: nowrap;
}
#result::before {
content: "TESTING...";
}
:host(:not([ok])) #result {
background-color: var(--not-ok);
}
:host(:not([ok])) #result::before {
content: "NOT OK!";
}
:host([ok]:not([testing])) #result {
background-color: var(--ok);
}
:host([ok]:not([testing])) #result::before {
content: "OK!";
}
#tag-line {
margin: auto 12px;
color: var(--subdued);
cursor: default;
user-select: none;
pointer-events: none;
}
#body {
flex: 1;
overflow: auto;
display: flex;
/* Flip top/bottom for console-like scroll behavior. */
flex-direction: column-reverse;
box-sizing: border-box;
}
:host([dragging]) #body {
pointer-events: none;
}
#spacer {
flex: 1;
}
[output] {
white-space: pre;
color: var(--subdued);
line-height: 20px;
padding: 0 12px;
cursor: default;
}
[output]:first-child {
padding-top: 12px;
}
[output]:last-child {
padding-bottom: 12px;
}
[yaml] {
line-height: 16px;
}
a[output]:any-link {
display: block;
width: min-content;
cursor: pointer;
}
[it][ok]:not([directive]) {
color: var(--ok);
}
[it]:not([ok]):not([directive]),
[bail] {
color: var(--not-ok);
}
[it][ok][directive="skip"] {
color: var(--skip);
}
[it]:not([ok])[directive="todo"] {
color: var(--todo);
}
[it][ok][directive="todo"] {
color: var(--todone);
}
[plan][indent],
[plan] + [it][ok]:not([directive]),
[plan] + [it]:not([ok]):not([directive]),
[plan] + [it][ok][directive="skip"],
[plan] + [it]:not([ok])[directive="todo"],
[plan] + [it][ok][directive="todo"] {
color: var(--subdued);
}
[version] {
color: var(--version);
}
[plan] {
color: var(--plan);
}
a[subtest]:not([bail]) {
color: var(--link);
}
[subtest]:not([bail]) {
color: var(--subdued);
}
[indent] {
position: relative;
}
[indent]::before {
position: absolute;
content: attr(indent);
color: var(--subdued);
opacity: 0.25;
}
`);
const template = document.createElement('template');
template.setHTMLUnsafe(`
<div id="header"><div id="result"></div><div id="tag-line">x-test - a simple, tap-compliant test runner for the browser.</div></div>
<div id="body"><div id="spacer"></div><div id="container"></div></div>
<button id="toggle" type="button"></button>
`);
class XTestReporter extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.adoptedStyleSheets = [styleSheet];
this.shadowRoot.append(template.content.cloneNode(true));
}
connectedCallback() {
this.setAttribute('ok', '');
this.setAttribute('testing', '');
this.style.height = localStorage.getItem('x-test-reporter-height');
if (localStorage.getItem('x-test-reporter-closed') !== 'true') {
this.setAttribute('open', '');
}
this.shadowRoot.getElementById('toggle').addEventListener('click', () => {
this.hasAttribute('open') ? this.removeAttribute('open') : this.setAttribute('open', '');
localStorage.setItem('x-test-reporter-closed', String(!this.hasAttribute('open')));
});
const resize = event => {
const nextHeaderY = event.clientY - Number(this.getAttribute('dragging'));
const currentHeaderY = this.shadowRoot.getElementById('header').getBoundingClientRect().y;
const currentHeight = this.getBoundingClientRect().height;
this.style.height = `${Math.round(currentHeight + currentHeaderY - nextHeaderY)}px`;
localStorage.setItem('x-test-reporter-height', this.style.height);
};
this.shadowRoot.getElementById('header').addEventListener('pointerdown', event => {
if (this.hasAttribute('open')) {
const headerY = this.shadowRoot.getElementById('header').getBoundingClientRect().y;
const clientY = event.clientY;
this.setAttribute('dragging', String(clientY - headerY));
addEventListener('pointermove', resize);
for (const iframe of document.querySelectorAll('iframe')) {
iframe.style.pointerEvents = 'none';
}
}
});
addEventListener('pointerup', () => {
removeEventListener('pointermove', resize);
this.removeAttribute('dragging');
for (const iframe of document.querySelectorAll('iframe')) {
iframe.style.pointerEvents = null;
}
});
}
tap(...tap) {
const items = [];
const container = this.shadowRoot.getElementById('container');
for (const text of tap) {
const { tag, properties, attributes, failed, done } = XTestReporter.parse(text);
const element = document.createElement(tag);
Object.assign(element, properties);
for (const [attribute, value] of Object.entries(attributes)) {
element.setAttribute(attribute, value);
}
if (done) {
this.removeAttribute('testing');
}
if (failed) {
this.removeAttribute('ok');
}
items.push(element);
}
container.append(...items);
}
static parse(text) {
const result = { tag: '', properties: {}, attributes: {}, failed: false, done: false };
result.properties.innerText = text;
const indentMatch = text.match(/^((?: {4})+)/);
if (indentMatch) {
const lines = text.split('\n').length - 1;
const indent = indentMatch[1].replace(/ {4}/g, '\u00a6 ');
result.attributes.indent = lines ? `${`${indent}\n`.repeat(lines)}${indent}` : indent;
}
if (text.match(/^(?: {4})*# Subtest: https?:.*/)) {
result.tag = 'a';
const href = text.replace(/^(?: {4})*# Subtest: /, '');
result.properties.href = href;
Object.assign(result.attributes, { output: '', subtest: '' });
} else if (text.match(/^Bail out! https?:.*/)) {
result.tag = 'a';
result.failed = true;
const href = text.replace(/Bail out! /, '');
result.properties.href = href;
Object.assign(result.attributes, { output: '', subtest: '', bail: '' });
} else {
result.tag = 'div';
result.attributes.output = '';
if (text.match(/^(?: {4})*# Subtest:/)) {
result.attributes.subtest = '';
} else if (text.match(/^(?: {4})*# /)) {
result.attributes.diagnostic = '';
} else if (text.match(/^(?: {4})*ok /)) {
Object.assign(result.attributes, { it: '', ok: '' });
if (text.match(/^(?: {4})*[^ #][^#]* # SKIP/)) {
result.attributes.directive = 'skip';
} else if (text.match(/^(?: {4})*[^ #][^#]* # TODO/)) {
result.attributes.directive = 'todo';
}
} else if (text.match(/^(?: {4})*not ok /)) {
result.attributes.it = '';
if (text.match(/^(?: {4})*[^ #][^#]* # TODO/)) {
result.attributes.directive = 'todo';
} else {
result.failed = true;
}
} else if (text.match(/^(?: {4})* {2}---/)) {
result.attributes.yaml = '';
} else if (text.match(/^TAP/)) {
result.attributes.version = '';
} else if (text.match(/^(?: {4})*1\.\.\d*/)) {
result.attributes.plan = '';
if (!indentMatch) {
result.done = true;
}
} else if (text.match(/^(?: {4})*Bail out!.*/)) {
result.attributes.bail = '';
result.failed = true;
}
}
return result;
}
}
customElements.define('x-test-reporter', XTestReporter);
class XTestRoot {
static initialize(context, href) {
const url = new URL(href);
if (!url.searchParams.get('x-test-no-reporter')) {
context.state.reporter = new XTestReporter();
document.body.append(context.state.reporter);
}
context.state.coverage = url.searchParams.get('x-test-run-coverage') === '';
context.state.coverageValuePromise = new Promise(resolve => {
context.state.resolveCoverageValuePromise = value => {
context.state.coverageValue = value;
resolve(context.state.coverageValue);
};
});
const versionStepId = context.uuid();
const exitStepId = context.uuid();
context.state.stepIds.push(versionStepId, exitStepId);
context.state.steps[versionStepId] = { stepId: versionStepId, type: 'version', status: 'waiting' };
context.state.steps[exitStepId] = { stepId: exitStepId, type: 'exit', status: 'waiting' };
context.subscribe(event => {
switch (event.data.type) {
case 'x-test-client-ping':
XTestRoot.onPing(context, event);
break;
case 'x-test-client-coverage-result':
XTestRoot.onCoverageResult(context, event);
break;
case 'x-test-suite-register':
XTestRoot.onRegister(context, event);
break;
case 'x-test-suite-ready':
XTestRoot.onReady(context, event);
break;
case 'x-test-suite-result':
XTestRoot.onResult(context, event);
break;
case 'x-test-suite-bail':
XTestRoot.onBail(context, event);
break;
}
XTestRoot.check(context);
});
// Run own tests in iframe.
url.searchParams.delete('x-test-no-reporter');
url.searchParams.delete('x-test-run-coverage');
context.publish('x-test-suite-register', { type: 'test', testId: context.uuid(), href: url.href });
}
static onPing(context/*, event*/) {
context.publish('x-test-root-pong', { ended: context.state.ended, waiting: context.state.waiting });
}
static onBail(context, event) {
if (!context.state.ended) {
XTestRoot.bail(context, event.data.data.error, { testId: event.data.data.testId });
}
}
static registerTest(context, data) {
if (!context.state.ended) {
const testId = data.testId;
// New "test" (to be opened in its own iframe). Queue it up.
const initiatorTestId = data.initiatorTestId;
const siblingTestEndIndex = context.state.stepIds.findLastIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'test-end' && context.state.tests[candidate.testId].initiatorTestId === initiatorTestId) {
return true;
}
});
const parentTestEndIndex = context.state.stepIds.findLastIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'test-end' && context.state.tests[candidate.testId].testId === initiatorTestId) {
return true;
}
});
const coverageIndex = context.state.stepIds.findIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'coverage') {
return true;
}
});
const exitIndex = context.state.stepIds.findLastIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'exit') {
return true;
}
});
const index = siblingTestEndIndex === -1
? parentTestEndIndex === -1
? coverageIndex === -1
? exitIndex
: coverageIndex
: parentTestEndIndex + 1
: siblingTestEndIndex + 1;
const lastSiblingChildrenIndex = context.state.children.findLastIndex(candidate => {
return candidate.type === 'test' && context.state.tests[candidate.testId].initiatorTestId === initiatorTestId;
});
const parentTestChildrenIndex = context.state.children.findLastIndex(candidate => {
return candidate.type === 'test' && context.state.tests[candidate.testId].testId === initiatorTestId;
});
const firstCoverageChildrenIndex = context.state.children.findIndex(candidate => {
return candidate.type === 'coverage';
});
const childrenIndex = lastSiblingChildrenIndex === -1
? parentTestChildrenIndex === -1
? firstCoverageChildrenIndex === -1
? context.state.children.length
: firstCoverageChildrenIndex
: parentTestChildrenIndex + 1
: lastSiblingChildrenIndex + 1;
const testStartStepId = context.uuid();
const testPlanStepId = context.uuid();
const testEndStepId = context.uuid();
context.state.stepIds.splice(index, 0, testStartStepId, testPlanStepId, testEndStepId);
context.state.steps[testStartStepId] = { stepId: testStartStepId, type: 'test-start', testId, status: 'waiting' };
context.state.steps[testPlanStepId] = { stepId: testPlanStepId, type: 'test-plan', testId, status: 'waiting' };
context.state.steps[testEndStepId] = { stepId: testEndStepId, type: 'test-end', testId, status: 'waiting' };
context.state.tests[testId] = { ...data, children: [] };
context.state.children.splice(childrenIndex, 0, { type: 'test', testId });
}
}
static registerDescribeStart(context, data) {
if (!context.state.ended) {
// New "describe-start" (to mark the start of a subtest). Queue it up.
const stepId = context.uuid();
const describeId = data.describeId;
const index = context.state.stepIds.findLastIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'test-plan' && candidate.testId === data.parents[0].testId) {
return true;
}
});
context.state.stepIds.splice(index, 0, stepId);
context.state.steps[stepId] = { stepId, type: 'describe-start', describeId: data.describeId, status: 'waiting' };
context.state.describes[describeId] = { ...data, children: [] };
if (data.parents.at(-1)?.type === 'describe') {
context.state.describes[data.parents.at(-1).describeId].children.push({ type: 'describe', describeId });
} else {
context.state.tests[data.parents.at(-1).testId].children.push({ type: 'describe', describeId });
}
}
}
static registerDescribeEnd(context, data) {
if (!context.state.ended) {
// Completed "describe-end" (to mark the end of a subtest). Queue it up.
const planStepId = context.uuid();
const endStepId = context.uuid();
const describe = context.state.describes[data.describeId]; // eslint-disable-line no-shadow
const index = context.state.stepIds.findLastIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'test-plan' && candidate.testId === describe.parents[0].testId) {
return true;
}
});
context.state.stepIds.splice(index, 0, planStepId, endStepId);
context.state.steps[planStepId] = { stepId: planStepId, type: 'describe-plan', describeId: data.describeId, status: 'waiting' };
context.state.steps[endStepId] = { stepId: endStepId, type: 'describe-end', describeId: data.describeId, status: 'waiting' };
}
}
static registerIt(context, data) {
if (!context.state.ended) {
// New "it" (to be run as part of a test suite). Queue it up.
const stepId = context.uuid();
const itId = data.itId;
const index = context.state.stepIds.findLastIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'test-plan' && candidate.testId === data.parents[0].testId) {
return true;
}
});
context.state.stepIds.splice(index, 0, stepId);
context.state.steps[stepId] = { stepId, type: 'it', itId: data.itId, status: 'waiting' };
context.state.its[itId] = data;
if (data.parents.at(-1)?.type === 'describe') {
context.state.describes[data.parents.at(-1).describeId].children.push({ type: 'it', itId });
} else {
context.state.tests[data.parents.at(-1).testId].children.push({ type: 'it', itId });
}
}
}
static registerCoverage(context, data) {
if (!context.state.ended) {
// New "coverage" goal. Queue it up.
const stepId = context.uuid();
const coverageId = data.coverageId;
const index = context.state.stepIds.findLastIndex(candidateId => {
const candidate = context.state.steps[candidateId];
if (candidate.type === 'exit') {
return true;
}
});
context.state.stepIds.splice(index, 0, stepId);
context.state.steps[stepId] = { stepId, type: 'coverage', coverageId: coverageId, status: 'waiting' };
context.state.coverages[coverageId] = data;
const childrenIndex = context.state.children.length;
context.state.children.splice(childrenIndex, 0, { type: 'coverage', coverageId });
}
}
static onRegister(context, event) {
if (!context.state.ended) {
const data = event.data.data;
switch(data.type) {
case 'test':
XTestRoot.registerTest(context, data);
break;
case 'describe-start':
XTestRoot.registerDescribeStart(context, data);
break;
case 'describe-end':
XTestRoot.registerDescribeEnd(context, data);
break;
case 'it':
XTestRoot.registerIt(context, data);
break;
case 'coverage':
XTestRoot.registerCoverage(context, data);
break;
default:
throw new Error(`Unexpected registration type "${data.type}".`);
}
}
}
static onReady(context, event) {
if (!context.state.ended) {
const data = event.data.data;
const only = (
Object.values(context.state.its).some(candidate => {
return candidate.only && candidate.parents[0].testId === data.testId;
}) ||
Object.values(context.state.describes).some(candidate => {
return candidate.only && candidate.parents[0].testId === data.testId;
})
);
if (only) {
for (const it of Object.values(context.state.its)) { // eslint-disable-line no-shadow
if (it.parents[0].testId === data.testId) {
if (!it.only) {
const describeParents = it.parents
.filter(candidate => candidate.type === 'describe')
.map(parent => context.state.describes[parent.describeId]);
const hasOnlyDescribeParent = describeParents.some(candidate => candidate.only);
if (!hasOnlyDescribeParent) {
it.directive = 'SKIP';
} else if (!it.directive) {
const lastDescribeParentWithDirective = describeParents.findLast(candidate => !!candidate.directive);
if (lastDescribeParentWithDirective) {
it.directive = lastDescribeParentWithDirective.directive;
}
}
}
}
}
} else {
for (const it of Object.values(context.state.its)) { // eslint-disable-line no-shadow
if (it.parents[0].testId === data.testId) {
if (!it.directive) {
const describeParents = it.parents
.filter(candidate => candidate.type === 'describe')
.map(parent => context.state.describes[parent.describeId]);
const lastDescribeParentWithDirective = describeParents.findLast(candidate => !!candidate.directive);
if (lastDescribeParentWithDirective) {
it.directive = lastDescribeParentWithDirective.directive;
}
}
}
}
}
const stepId = context.state.stepIds.find(candidateId => {
const candidate = context.state.steps[candidateId];
return candidate.type === 'test-start' && candidate.testId === data.testId;
});
const step = context.state.steps[stepId];
if (step.status !== 'running') {
throw new Error('test to ready is not running');
}
const href = XTestRoot.href(context, stepId);
const level = XTestRoot.level(context, stepId);
const tap = XTestTap.subtest(href, level);
XTestRoot.output(context, stepId, tap);
step.status = 'done';
}
}
static onResult(context, event) {
if (!context.state.ended) {
const data = event.data.data;
const it = context.state.its[data.itId]; // eslint-disable-line no-shadow
const stepId = context.state.stepIds.find(candidateId => {
const candidate = context.state.steps[candidateId];
return candidate.type === 'it' && candidate.itId === it.itId;
});
const step = context.state.steps[stepId];
if (step.status !== 'running') {
throw new Error('step to complete is not running');
}
Object.assign(it, { ok: data.ok, error: data.error });
step.status = 'done';
const ok = XTestRoot.ok(context, stepId);
const number = XTestRoot.number(context, stepId);
const text = XTestRoot.text(context, stepId);
const directive = XTestRoot.directive(context, stepId);
const level = XTestRoot.level(context, stepId);
const tap = XTestTap.testLine(ok, number, text, directive, level);
if (!data.error) {
XTestRoot.output(context, stepId, tap);
} else {
const yaml = XTestRoot.yaml(context, stepId);
const errorTap = XTestTap.yaml(yaml.message, yaml.severity, yaml.data, level);
XTestRoot.output(context, stepId, tap, errorTap);
}
}
}
static onCoverageResult(context, event) {
if (!context.state.ended) {
context.state.resolveCoverageValuePromise(event.data.data);
}
}
static kickoffVersion(context, stepId) {
const tap = XTestTap.version();
XTestRoot.output(context, stepId, tap);
context.state.steps[stepId].status = 'done';
}
static kickoffDescribeStart(context, stepId) {
const level = XTestRoot.level(context, stepId);
const text = XTestRoot.text(context, stepId);
const tap = XTestTap.subtest(text, level);
XTestRoot.output(context, stepId, tap);
context.state.steps[stepId].status = 'done';
}
static kickoffDescribePlan(context, stepId) {
const level = XTestRoot.level(context, stepId);
const count = XTestRoot.count(context, stepId);
const tap = XTestTap.plan(count, level);
XTestRoot.output(context, stepId, tap);
context.state.steps[stepId].status = 'done';
}
static kickoffDescribeEnd(context, stepId) {
const number = XTestRoot.number(context, stepId);
const ok = XTestRoot.ok(context, stepId);
const text = XTestRoot.text(context, stepId);
const directive = XTestRoot.directive(context, stepId);
const level = XTestRoot.level(context, stepId);
const tap = XTestTap.testLine(ok, number, text, directive, level);
XTestRoot.output(context, stepId, tap);
context.state.steps[stepId].status = 'done';
}
static kickoffTestStart(context, stepId) {
// Destroy prior test. This keeps the final test around for debugging.
const lastIframe = document.querySelector('iframe');
lastIframe?.remove();
// Create the new test.
const step = context.state.steps[stepId];
const href = XTestRoot.href(context, stepId);
const iframe = document.createElement('iframe');
iframe.addEventListener('error', () => {
const error = new Error(`Failed to load ${href}`);
XTestRoot.bail(context, error);
});
iframe.setAttribute('data-x-test-test-id', step.testId);
Object.assign(iframe, { src: href });
Object.assign(iframe.style, {
border: 'none', backgroundColor: 'white', height: '100vh',
width: '100vw', position: 'fixed', zIndex: '0', top: '0', left: '0',
});
document.body.append(iframe);
step.status = 'running';
}
static kickoffTestPlan(context, stepId) {
const count = XTestRoot.count(context, stepId);
const level = XTestRoot.level(context, stepId);
const tap = XTestTap.plan(count, level);
XTestRoot.output(context, stepId, tap);
context.state.steps[stepId].status = 'done';
}
static kickoffTestEnd(context, stepId) {
const number = XTestRoot.number(context, stepId);
const ok = XTestRoot.ok(context, stepId);
const text = XTestRoot.text(context, stepId);
const directive = XTestRoot.directive(context, stepId);
const level = XTestRoot.level(context, stepId);
const tap = XTestTap.testLine(ok, number, text, directive, level);
XTestRoot.output(context, stepId, tap);
context.state.steps[stepId].status = 'done';
}
static kickoffIt(context, stepId) {
const step = context.state.steps[stepId];
const { itId, directive, interval } = context.state.its[step.itId];
context.publish('x-test-root-run', { itId, directive, interval });
step.status = 'running';
}
static kickoffCoverage(context, stepId) {
const step = context.state.steps[stepId];
const coverage = context.state.coverages[step.coverageId]; // eslint-disable-line no-shadow
if (context.state.coverageValue) {
try {
const analysis = XTestRoot.analyzeHrefCoverage(context.state.coverageValue.js, coverage.href, coverage.goal);
Object.assign(coverage, { ok: analysis.ok, percent: analysis.percent, output: analysis.output });
} catch (error) {
Object.assign(coverage, { ok: false, percent: 0, output: '' });
XTestRoot.bail(context, error);
}
} else {
Object.assign(coverage, { ok: true, percent: 0, output: '', directive: 'SKIP' });
}
const ok = XTestRoot.ok(context, stepId);
const number = XTestRoot.number(context, stepId);
const text = XTestRoot.text(context, stepId);
const directive = XTestRoot.directive(context, stepId);
const level = XTestRoot.level(context, stepId);
const tap = XTestTap.testLine(ok, number, text, directive, level);
if (!ok) {
const errorTap = XTestTap.diagnostic(coverage.output, level);
XTestRoot.output(context, stepId, tap, errorTap);
} else {
XTestRoot.output(context, stepId, tap);
}
step.status = 'done';
}
static kickoffExit(context, stepId) {
const count = XTestRoot.count(context, stepId);
const tap = XTestTap.plan(count);
XTestRoot.output(context, stepId, tap);
context.state.steps[stepId].status = 'done';
XTestRoot.end(context);
}
static requestCoverageValue(context) {
context.state.waiting = true;
Promise.race([context.state.coverageValuePromise, context.timeout(5000)])
.then(() => { XTestRoot.check(context); })
.catch(error => { XTestRoot.bail(context, error); });
context.publish('x-test-root-coverage-request');
}
static check(context) {
if (!context.state.ended) {
// Look to see if any tests are running.
const runningStepId = context.state.stepIds.find(candidateId => {
return context.state.steps[candidateId].status === 'running';
});
if (!runningStepId) {
// If nothing's running, find the first step that's waiting and run that.
const stepId = context.state.stepIds.find(candidateId => {
return context.state.steps[candidateId].status === 'waiting';
});
if (stepId) {
const waitingStep = context.state.steps[stepId];
switch (waitingStep.type) {
case 'version':
XTestRoot.kickoffVersion(context, stepId);
XTestRoot.check(context);
break;
case 'describe-start':
XTestRoot.kickoffDescribeStart(context, stepId);
XTestRoot.check(context);
break;
case 'describe-plan':
XTestRoot.kickoffDescribePlan(context, stepId);
XTestRoot.check(context);
break;
case 'describe-end':
XTestRoot.kickoffDescribeEnd(context, stepId);
XTestRoot.check(context);
break;
case 'test-start':
XTestRoot.kickoffTestStart(context, stepId);
XTestRoot.check(context);
break;
case 'test-plan':
XTestRoot.kickoffTestPlan(context, stepId);
XTestRoot.check(context);
break;
case 'test-end':
XTestRoot.kickoffTestEnd(context, stepId);
XTestRoot.check(context);
break;
case 'it':
XTestRoot.kickoffIt(context, stepId);
XTestRoot.check(context);
break;
case 'coverage':
if (!context.state.coverage || context.state.coverageValue) {
XTestRoot.kickoffCoverage(context, stepId);
XTestRoot.check(context);
} else if (!context.state.waiting) {
XTestRoot.requestCoverageValue(context);
}
break;
case 'exit':
XTestRoot.kickoffExit(context, stepId);
break;
default:
throw new Error(`Unexpected step type "${waitingStep.type}".`);
}
}
}
}
}
static bail(context, error, options) {
if (!context.state.ended) {
if (error && error.stack) {
XTestRoot.log(context, XTestTap.diagnostic(error.stack));
}
if (options?.testId) {
const test = context.state.tests[options.testId]; // eslint-disable-line no-shadow
test.error = error;
const href = test.href;
XTestRoot.log(context, XTestTap.bailOut(href));
} else {
XTestRoot.log(context, XTestTap.bailOut());
}
XTestRoot.end(context);
}
}
static log(context, ...tap) {
for (const line of tap) {
console.log(line); // eslint-disable-line no-console
}
context.state.reporter?.tap(...tap);
}
static output(context, stepId, ...stepTap) {
const lastIndex = context.state.stepIds.findIndex(candidateId => {
const candidate = context.state.steps[candidateId];
return !candidate.tap;
});
context.state.steps[stepId].tap = stepTap;
const index = context.state.stepIds.findIndex(candidateId => {
const candidate = context.state.steps[candidateId];
return !candidate.tap;
});
if (lastIndex !== index) {
let tap;
if (index === -1) {
// We're done!
tap = context.state.stepIds.slice(lastIndex).map(targetId => context.state.steps[targetId].tap);
} else {
tap = context.state.stepIds.slice(lastIndex, index).map(targetId => context.state.steps[targetId].tap);
}
XTestRoot.log(context, ...tap.flat());
}
}
static childOk(context, child, options) {
switch (child.type) {
case 'test':
return context.state.tests[child.testId].children.every(candidate => XTestRoot.childOk(context, candidate, options));
case 'describe':
return context.state.describes[child.describeId].children.every(candidate => XTestRoot.childOk(context, candidate, options));
case 'it':
return context.state.its[child.itId].ok || options?.todoOk && context.state.its[child.itId].directive === 'TODO';
case 'coverage':
return context.state.coverages[child.coverageId].ok;
default:
throw new Error(`Unexpected type "${child.type}".`);
}
}
static ok(context, stepId) {
const step = context.state.steps[stepId];