/
testItemCollection.ts
723 lines (606 loc) · 20 KB
/
testItemCollection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Barrier, isThenable, RunOnceScheduler } from 'vs/base/common/async';
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { assertNever } from 'vs/base/common/assert';
import { applyTestItemUpdate, ITestItem, ITestTag, namespaceTestTag, TestDiffOpType, TestItemExpandState, TestsDiff, TestsDiffOp } from 'vs/workbench/contrib/testing/common/testTypes';
import { TestId } from 'vs/workbench/contrib/testing/common/testId';
import { URI } from 'vs/base/common/uri';
/**
* @private
*/
interface CollectionItem<T> {
readonly fullId: TestId;
actual: T;
expand: TestItemExpandState;
/**
* Number of levels of items below this one that are expanded. May be infinite.
*/
expandLevels?: number;
resolveBarrier?: Barrier;
}
export const enum TestItemEventOp {
Upsert,
SetTags,
UpdateCanResolveChildren,
RemoveChild,
SetProp,
Bulk,
DocumentSynced,
}
export interface ITestItemUpsertChild {
op: TestItemEventOp.Upsert;
item: ITestItemLike;
}
export interface ITestItemUpdateCanResolveChildren {
op: TestItemEventOp.UpdateCanResolveChildren;
state: boolean;
}
export interface ITestItemSetTags {
op: TestItemEventOp.SetTags;
new: ITestTag[];
old: ITestTag[];
}
export interface ITestItemRemoveChild {
op: TestItemEventOp.RemoveChild;
id: string;
}
export interface ITestItemSetProp {
op: TestItemEventOp.SetProp;
update: Partial<ITestItem>;
}
export interface ITestItemBulkReplace {
op: TestItemEventOp.Bulk;
ops: (ITestItemUpsertChild | ITestItemRemoveChild)[];
}
export interface ITestItemDocumentSynced {
op: TestItemEventOp.DocumentSynced;
}
export type ExtHostTestItemEvent =
| ITestItemSetTags
| ITestItemUpsertChild
| ITestItemRemoveChild
| ITestItemUpdateCanResolveChildren
| ITestItemSetProp
| ITestItemBulkReplace
| ITestItemDocumentSynced;
export interface ITestItemApi<T> {
controllerId: string;
parent?: T;
listener?: (evt: ExtHostTestItemEvent) => void;
}
export interface ITestItemCollectionOptions<T> {
/** Controller ID to use to prefix these test items. */
controllerId: string;
/** Gets the document version at the given URI, if it's open */
getDocumentVersion(uri: URI | undefined): number | undefined;
/** Gets API for the given test item, used to listen for events and set parents. */
getApiFor(item: T): ITestItemApi<T>;
/** Converts the full test item to the common interface. */
toITestItem(item: T): ITestItem;
/** Gets children for the item. */
getChildren(item: T): ITestChildrenLike<T>;
/** Root to use for the new test collection. */
root: T;
}
const strictEqualComparator = <T>(a: T, b: T) => a === b;
const diffableProps: { [K in keyof ITestItem]?: (a: ITestItem[K], b: ITestItem[K]) => boolean } = {
range: (a, b) => {
if (a === b) { return true; }
if (!a || !b) { return false; }
return a.equalsRange(b);
},
busy: strictEqualComparator,
label: strictEqualComparator,
description: strictEqualComparator,
error: strictEqualComparator,
tags: (a, b) => {
if (a.length !== b.length) {
return false;
}
if (a.some(t1 => !b.includes(t1))) {
return false;
}
return true;
},
};
const diffTestItems = (a: ITestItem, b: ITestItem) => {
let output: Record<string, unknown> | undefined;
for (const [key, cmp] of Object.entries(diffableProps) as [keyof ITestItem, (a: any, b: any) => boolean][]) {
if (!cmp(a[key], b[key])) {
if (output) {
output[key] = b[key];
} else {
output = { [key]: b[key] };
}
}
}
return output as Partial<ITestItem> | undefined;
};
export interface ITestChildrenLike<T> extends Iterable<[string, T]> {
get(id: string): T | undefined;
delete(id: string): void;
}
export interface ITestItemLike {
id: string;
tags: readonly ITestTag[];
uri?: URI;
canResolveChildren: boolean;
}
/**
* Maintains a collection of test items for a single controller.
*/
export class TestItemCollection<T extends ITestItemLike> extends Disposable {
private readonly debounceSendDiff = this._register(new RunOnceScheduler(() => this.flushDiff(), 200));
private readonly diffOpEmitter = this._register(new Emitter<TestsDiff>());
private _resolveHandler?: (item: T | undefined) => Promise<void> | void;
public get root() {
return this.options.root;
}
public readonly tree = new Map</* full test id */string, CollectionItem<T>>();
private readonly tags = new Map<string, { label?: string; refCount: number }>();
protected diff: TestsDiff = [];
constructor(private readonly options: ITestItemCollectionOptions<T>) {
super();
this.root.canResolveChildren = true;
this.upsertItem(this.root, undefined);
}
/**
* Handler used for expanding test items.
*/
public set resolveHandler(handler: undefined | ((item: T | undefined) => void)) {
this._resolveHandler = handler;
for (const test of this.tree.values()) {
this.updateExpandability(test);
}
}
/**
* Fires when an operation happens that should result in a diff.
*/
public readonly onDidGenerateDiff = this.diffOpEmitter.event;
/**
* Gets a diff of all changes that have been made, and clears the diff queue.
*/
public collectDiff() {
const diff = this.diff;
this.diff = [];
return diff;
}
/**
* Pushes a new diff entry onto the collected diff list.
*/
public pushDiff(diff: TestsDiffOp) {
switch (diff.op) {
case TestDiffOpType.DocumentSynced: {
for (const existing of this.diff) {
if (existing.op === TestDiffOpType.DocumentSynced && existing.uri === diff.uri) {
existing.docv = diff.docv;
return;
}
}
break;
}
case TestDiffOpType.Update: {
// Try to merge updates, since they're invoked per-property
const last = this.diff[this.diff.length - 1];
if (last) {
if (last.op === TestDiffOpType.Update && last.item.extId === diff.item.extId) {
applyTestItemUpdate(last.item, diff.item);
return;
}
if (last.op === TestDiffOpType.Add && last.item.item.extId === diff.item.extId) {
applyTestItemUpdate(last.item, diff.item);
return;
}
}
break;
}
}
this.diff.push(diff);
if (!this.debounceSendDiff.isScheduled()) {
this.debounceSendDiff.schedule();
}
}
/**
* Expands the test and the given number of `levels` of children. If levels
* is < 0, then all children will be expanded. If it's 0, then only this
* item will be expanded.
*/
public expand(testId: string, levels: number): Promise<void> | void {
const internal = this.tree.get(testId);
if (!internal) {
return;
}
if (internal.expandLevels === undefined || levels > internal.expandLevels) {
internal.expandLevels = levels;
}
// try to avoid awaiting things if the provider returns synchronously in
// order to keep everything in a single diff and DOM update.
if (internal.expand === TestItemExpandState.Expandable) {
const r = this.resolveChildren(internal);
return !r.isOpen()
? r.wait().then(() => this.expandChildren(internal, levels - 1))
: this.expandChildren(internal, levels - 1);
} else if (internal.expand === TestItemExpandState.Expanded) {
return internal.resolveBarrier?.isOpen() === false
? internal.resolveBarrier.wait().then(() => this.expandChildren(internal, levels - 1))
: this.expandChildren(internal, levels - 1);
}
}
public override dispose() {
for (const item of this.tree.values()) {
this.options.getApiFor(item.actual).listener = undefined;
}
this.tree.clear();
this.diff = [];
super.dispose();
}
private onTestItemEvent(internal: CollectionItem<T>, evt: ExtHostTestItemEvent) {
switch (evt.op) {
case TestItemEventOp.RemoveChild:
this.removeItem(TestId.joinToString(internal.fullId, evt.id));
break;
case TestItemEventOp.Upsert:
this.upsertItem(evt.item as T, internal);
break;
case TestItemEventOp.Bulk:
for (const op of evt.ops) {
this.onTestItemEvent(internal, op);
}
break;
case TestItemEventOp.SetTags:
this.diffTagRefs(evt.new, evt.old, internal.fullId.toString());
break;
case TestItemEventOp.UpdateCanResolveChildren:
this.updateExpandability(internal);
break;
case TestItemEventOp.SetProp:
this.pushDiff({
op: TestDiffOpType.Update,
item: {
extId: internal.fullId.toString(),
item: evt.update,
}
});
break;
case TestItemEventOp.DocumentSynced:
this.documentSynced(internal.actual.uri);
break;
default:
assertNever(evt);
}
}
private documentSynced(uri: URI | undefined) {
if (uri) {
this.pushDiff({
op: TestDiffOpType.DocumentSynced,
uri,
docv: this.options.getDocumentVersion(uri)
});
}
}
private upsertItem(actual: T, parent: CollectionItem<T> | undefined) {
const fullId = TestId.fromExtHostTestItem(actual, this.root.id, parent?.actual);
// If this test item exists elsewhere in the tree already (exists at an
// old ID with an existing parent), remove that old item.
const privateApi = this.options.getApiFor(actual);
if (privateApi.parent && privateApi.parent !== parent?.actual) {
this.options.getChildren(privateApi.parent).delete(actual.id);
}
let internal = this.tree.get(fullId.toString());
// Case 1: a brand new item
if (!internal) {
internal = {
fullId,
actual,
expandLevels: parent?.expandLevels /* intentionally undefined or 0 */ ? parent.expandLevels - 1 : undefined,
expand: TestItemExpandState.NotExpandable, // updated by `connectItemAndChildren`
};
actual.tags.forEach(this.incrementTagRefs, this);
this.tree.set(internal.fullId.toString(), internal);
this.setItemParent(actual, parent);
this.pushDiff({
op: TestDiffOpType.Add,
item: {
controllerId: this.options.controllerId,
expand: internal.expand,
item: this.options.toITestItem(actual),
},
});
this.connectItemAndChildren(actual, internal, parent);
return;
}
// Case 2: re-insertion of an existing item, no-op
if (internal.actual === actual) {
this.connectItem(actual, internal, parent); // re-connect in case the parent changed
return; // no-op
}
// Case 3: upsert of an existing item by ID, with a new instance
const oldChildren = this.options.getChildren(internal.actual);
const oldActual = internal.actual;
const update = diffTestItems(this.options.toITestItem(oldActual), this.options.toITestItem(actual));
this.options.getApiFor(oldActual).listener = undefined;
internal.actual = actual;
internal.expand = TestItemExpandState.NotExpandable; // updated by `connectItemAndChildren`
if (update) {
// tags are handled in a special way
if (update.hasOwnProperty('tags')) {
this.diffTagRefs(actual.tags, oldActual.tags, fullId.toString());
delete update.tags;
}
this.onTestItemEvent(internal, { op: TestItemEventOp.SetProp, update });
}
this.connectItemAndChildren(actual, internal, parent);
// Remove any orphaned children.
for (const [_, child] of oldChildren) {
if (!this.options.getChildren(actual).get(child.id)) {
this.removeItem(TestId.joinToString(fullId, child.id));
}
}
// Mark ranges in the document as synced (#161320)
this.documentSynced(internal.actual.uri);
}
private diffTagRefs(newTags: readonly ITestTag[], oldTags: readonly ITestTag[], extId: string) {
const toDelete = new Set(oldTags.map(t => t.id));
for (const tag of newTags) {
if (!toDelete.delete(tag.id)) {
this.incrementTagRefs(tag);
}
}
this.pushDiff({
op: TestDiffOpType.Update,
item: { extId, item: { tags: newTags.map(v => namespaceTestTag(this.options.controllerId, v.id)) } }
});
toDelete.forEach(this.decrementTagRefs, this);
}
private incrementTagRefs(tag: ITestTag) {
const existing = this.tags.get(tag.id);
if (existing) {
existing.refCount++;
} else {
this.tags.set(tag.id, { refCount: 1 });
this.pushDiff({
op: TestDiffOpType.AddTag, tag: {
id: namespaceTestTag(this.options.controllerId, tag.id),
}
});
}
}
private decrementTagRefs(tagId: string) {
const existing = this.tags.get(tagId);
if (existing && !--existing.refCount) {
this.tags.delete(tagId);
this.pushDiff({ op: TestDiffOpType.RemoveTag, id: namespaceTestTag(this.options.controllerId, tagId) });
}
}
private setItemParent(actual: T, parent: CollectionItem<T> | undefined) {
this.options.getApiFor(actual).parent = parent && parent.actual !== this.root ? parent.actual : undefined;
}
private connectItem(actual: T, internal: CollectionItem<T>, parent: CollectionItem<T> | undefined) {
this.setItemParent(actual, parent);
const api = this.options.getApiFor(actual);
api.parent = parent?.actual;
api.listener = evt => this.onTestItemEvent(internal, evt);
this.updateExpandability(internal);
}
private connectItemAndChildren(actual: T, internal: CollectionItem<T>, parent: CollectionItem<T> | undefined) {
this.connectItem(actual, internal, parent);
// Discover any existing children that might have already been added
for (const [_, child] of this.options.getChildren(actual)) {
this.upsertItem(child, internal);
}
}
/**
* Updates the `expand` state of the item. Should be called whenever the
* resolved state of the item changes. Can automatically expand the item
* if requested by a consumer.
*/
private updateExpandability(internal: CollectionItem<T>) {
let newState: TestItemExpandState;
if (!this._resolveHandler) {
newState = TestItemExpandState.NotExpandable;
} else if (internal.resolveBarrier) {
newState = internal.resolveBarrier.isOpen()
? TestItemExpandState.Expanded
: TestItemExpandState.BusyExpanding;
} else {
newState = internal.actual.canResolveChildren
? TestItemExpandState.Expandable
: TestItemExpandState.NotExpandable;
}
if (newState === internal.expand) {
return;
}
internal.expand = newState;
this.pushDiff({ op: TestDiffOpType.Update, item: { extId: internal.fullId.toString(), expand: newState } });
if (newState === TestItemExpandState.Expandable && internal.expandLevels !== undefined) {
this.resolveChildren(internal);
}
}
/**
* Expands all children of the item, "levels" deep. If levels is 0, only
* the children will be expanded. If it's 1, the children and their children
* will be expanded. If it's <0, it's a no-op.
*/
private expandChildren(internal: CollectionItem<T>, levels: number): Promise<void> | void {
if (levels < 0) {
return;
}
const expandRequests: Promise<void>[] = [];
for (const [_, child] of this.options.getChildren(internal.actual)) {
const promise = this.expand(TestId.joinToString(internal.fullId, child.id), levels);
if (isThenable(promise)) {
expandRequests.push(promise);
}
}
if (expandRequests.length) {
return Promise.all(expandRequests).then(() => { });
}
}
/**
* Calls `discoverChildren` on the item, refreshing all its tests.
*/
private resolveChildren(internal: CollectionItem<T>) {
if (internal.resolveBarrier) {
return internal.resolveBarrier;
}
if (!this._resolveHandler) {
const b = new Barrier();
b.open();
return b;
}
internal.expand = TestItemExpandState.BusyExpanding;
this.pushExpandStateUpdate(internal);
const barrier = internal.resolveBarrier = new Barrier();
const applyError = (err: Error) => {
console.error(`Unhandled error in resolveHandler of test controller "${this.options.controllerId}"`, err);
};
let r: Thenable<void> | void;
try {
r = this._resolveHandler(internal.actual === this.root ? undefined : internal.actual);
} catch (err) {
applyError(err);
}
if (isThenable(r)) {
r.catch(applyError).then(() => {
barrier.open();
this.updateExpandability(internal);
});
} else {
barrier.open();
this.updateExpandability(internal);
}
return internal.resolveBarrier;
}
private pushExpandStateUpdate(internal: CollectionItem<T>) {
this.pushDiff({ op: TestDiffOpType.Update, item: { extId: internal.fullId.toString(), expand: internal.expand } });
}
private removeItem(childId: string) {
const childItem = this.tree.get(childId);
if (!childItem) {
throw new Error('attempting to remove non-existent child');
}
this.pushDiff({ op: TestDiffOpType.Remove, itemId: childId });
const queue: (CollectionItem<T> | undefined)[] = [childItem];
while (queue.length) {
const item = queue.pop();
if (!item) {
continue;
}
this.options.getApiFor(item.actual).listener = undefined;
for (const tag of item.actual.tags) {
this.decrementTagRefs(tag.id);
}
this.tree.delete(item.fullId.toString());
for (const [_, child] of this.options.getChildren(item.actual)) {
queue.push(this.tree.get(TestId.joinToString(item.fullId, child.id)));
}
}
}
/**
* Immediately emits any pending diffs on the collection.
*/
public flushDiff() {
const diff = this.collectDiff();
if (diff.length) {
this.diffOpEmitter.fire(diff);
}
}
}
/** Implementation of vscode.TestItemCollection */
export interface ITestItemChildren<T extends ITestItemLike> extends Iterable<[string, T]> {
readonly size: number;
replace(items: readonly T[]): void;
forEach(callback: (item: T, collection: this) => unknown, thisArg?: unknown): void;
add(item: T): void;
delete(itemId: string): void;
get(itemId: string): T | undefined;
toJSON(): readonly T[];
}
export class DuplicateTestItemError extends Error {
constructor(id: string) {
super(`Attempted to insert a duplicate test item ID ${id}`);
}
}
export class InvalidTestItemError extends Error {
constructor(id: string) {
super(`TestItem with ID "${id}" is invalid. Make sure to create it from the createTestItem method.`);
}
}
export class MixedTestItemController extends Error {
constructor(id: string, ctrlA: string, ctrlB: string) {
super(`TestItem with ID "${id}" is from controller "${ctrlA}" and cannot be added as a child of an item from controller "${ctrlB}".`);
}
}
export const createTestItemChildren = <T extends ITestItemLike>(api: ITestItemApi<T>, getApi: (item: T) => ITestItemApi<T>, checkCtor: Function): ITestItemChildren<T> => {
let mapped = new Map<string, T>();
return {
/** @inheritdoc */
get size() {
return mapped.size;
},
/** @inheritdoc */
forEach(callback: (item: T, collection: ITestItemChildren<T>) => unknown, thisArg?: unknown) {
for (const item of mapped.values()) {
callback.call(thisArg, item, this);
}
},
/** @inheritdoc */
[Symbol.iterator](): IterableIterator<[string, T]> {
return mapped.entries();
},
/** @inheritdoc */
replace(items: Iterable<T>) {
const newMapped = new Map<string, T>();
const toDelete = new Set(mapped.keys());
const bulk: ITestItemBulkReplace = { op: TestItemEventOp.Bulk, ops: [] };
for (const item of items) {
if (!(item instanceof checkCtor)) {
throw new InvalidTestItemError(item.id);
}
const itemController = getApi(item).controllerId;
if (itemController !== api.controllerId) {
throw new MixedTestItemController(item.id, itemController, api.controllerId);
}
if (newMapped.has(item.id)) {
throw new DuplicateTestItemError(item.id);
}
newMapped.set(item.id, item);
toDelete.delete(item.id);
bulk.ops.push({ op: TestItemEventOp.Upsert, item });
}
for (const id of toDelete.keys()) {
bulk.ops.push({ op: TestItemEventOp.RemoveChild, id });
}
api.listener?.(bulk);
// important mutations come after firing, so if an error happens no
// changes will be "saved":
mapped = newMapped;
},
/** @inheritdoc */
add(item: T) {
if (!(item instanceof checkCtor)) {
throw new InvalidTestItemError(item.id);
}
mapped.set(item.id, item);
api.listener?.({ op: TestItemEventOp.Upsert, item });
},
/** @inheritdoc */
delete(id: string) {
if (mapped.delete(id)) {
api.listener?.({ op: TestItemEventOp.RemoveChild, id });
}
},
/** @inheritdoc */
get(itemId: string) {
return mapped.get(itemId);
},
/** JSON serialization function. */
toJSON() {
return Array.from(mapped.values());
},
};
};