-
Notifications
You must be signed in to change notification settings - Fork 31.8k
/
Copy pathtestingOutputPeek.ts
2736 lines (2353 loc) · 92.7 KB
/
testingOutputPeek.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
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 (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { IIdentityProvider } from 'vs/base/browser/ui/list/list';
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { Orientation, Sizing, SplitView } from 'vs/base/browser/ui/splitview/splitview';
import { ICompressedTreeElement, ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel';
import { ICompressibleTreeRenderer } from 'vs/base/browser/ui/tree/objectTree';
import { ITreeContextMenuEvent, ITreeNode } from 'vs/base/browser/ui/tree/tree';
import { Action, IAction, Separator } from 'vs/base/common/actions';
import { Delayer, Limiter, RunOnceScheduler } from 'vs/base/common/async';
import { VSBuffer } from 'vs/base/common/buffer';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { Codicon } from 'vs/base/common/codicons';
import { Color } from 'vs/base/common/color';
import { Emitter, Event } from 'vs/base/common/event';
import { FuzzyScore } from 'vs/base/common/filters';
import { IMarkdownString } from 'vs/base/common/htmlContent';
import { stripIcons } from 'vs/base/common/iconLabels';
import { Iterable } from 'vs/base/common/iterator';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { Lazy } from 'vs/base/common/lazy';
import { Disposable, DisposableStore, IDisposable, IReference, MutableDisposable, combinedDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import { autorun } from 'vs/base/common/observable';
import { count } from 'vs/base/common/strings';
import { ThemeIcon } from 'vs/base/common/themables';
import { isDefined } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import 'vs/css!./testingOutputPeek';
import { ICodeEditor, IDiffEditorConstructionOptions, isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction2 } from 'vs/editor/browser/editorExtensions';
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditor/codeEditorWidget';
import { EmbeddedCodeEditorWidget } from 'vs/editor/browser/widget/codeEditor/embeddedCodeEditorWidget';
import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditor/diffEditorWidget';
import { EmbeddedDiffEditorWidget } from 'vs/editor/browser/widget/diffEditor/embeddedDiffEditorWidget';
import { MarkdownRenderer } from 'vs/editor/browser/widget/markdownRenderer/browser/markdownRenderer';
import { IDiffEditorOptions, IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { IEditor, IEditorContribution, ScrollType } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { IResolvedTextEditorModel, ITextModelService } from 'vs/editor/common/services/resolverService';
import { IPeekViewService, PeekViewWidget, peekViewResultsBackground, peekViewTitleForeground, peekViewTitleInfoForeground } from 'vs/editor/contrib/peekView/browser/peekView';
import { localize, localize2 } from 'vs/nls';
import { Categories } from 'vs/platform/action/common/actionCommonCategories';
import { FloatingClickMenu } from 'vs/platform/actions/browser/floatingMenu';
import { MenuEntryActionViewItem, createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem';
import { Action2, IMenuService, MenuId, MenuItemAction } from 'vs/platform/actions/common/actions';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ContextKeyExpr, IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { ITextEditorOptions, TextEditorSelectionRevealType } from 'vs/platform/editor/common/editor';
import { IHoverService } from 'vs/platform/hover/browser/hover';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { WorkbenchCompressibleObjectTree } from 'vs/platform/list/browser/listService';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IProgressService } from 'vs/platform/progress/common/progress';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { TerminalCapability } from 'vs/platform/terminal/common/capabilities/capabilities';
import { TerminalCapabilityStore } from 'vs/platform/terminal/common/capabilities/terminalCapabilityStore';
import { formatMessageForTerminal } from 'vs/platform/terminal/common/terminalStrings';
import { editorBackground } from 'vs/platform/theme/common/colorRegistry';
import { widgetClose } from 'vs/platform/theme/common/iconRegistry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IViewPaneOptions, ViewPane } from 'vs/workbench/browser/parts/views/viewPane';
import { EditorModel } from 'vs/workbench/common/editor/editorModel';
import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND } from 'vs/workbench/common/theme';
import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views';
import { DetachedProcessInfo } from 'vs/workbench/contrib/terminal/browser/detachedTerminal';
import { IDetachedTerminalInstance, ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';
import { getXtermScaledDimensions } from 'vs/workbench/contrib/terminal/browser/xterm/xtermTerminal';
import { TERMINAL_BACKGROUND_COLOR } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry';
import { getTestItemContextOverlay } from 'vs/workbench/contrib/testing/browser/explorerProjections/testItemContextOverlay';
import * as icons from 'vs/workbench/contrib/testing/browser/icons';
import { colorizeTestMessageInEditor, renderTestMessageAsText } from 'vs/workbench/contrib/testing/browser/testMessageColorizer';
import { testingMessagePeekBorder, testingPeekBorder, testingPeekHeaderBackground, testingPeekMessageHeaderBackground } from 'vs/workbench/contrib/testing/browser/theme';
import { AutoOpenPeekViewWhen, TestingConfigKeys, getTestingConfiguration } from 'vs/workbench/contrib/testing/common/configuration';
import { Testing } from 'vs/workbench/contrib/testing/common/constants';
import { IObservableValue, MutableObservableValue, staticObservableValue } from 'vs/workbench/contrib/testing/common/observableValue';
import { StoredValue } from 'vs/workbench/contrib/testing/common/storedValue';
import { ITestCoverageService } from 'vs/workbench/contrib/testing/common/testCoverageService';
import { ITestExplorerFilterState } from 'vs/workbench/contrib/testing/common/testExplorerFilterState';
import { ITestProfileService } from 'vs/workbench/contrib/testing/common/testProfileService';
import { ITaskRawOutput, ITestResult, ITestRunTaskResults, LiveTestResult, TestResultItemChange, TestResultItemChangeReason, maxCountPriority, resultItemParents } from 'vs/workbench/contrib/testing/common/testResult';
import { ITestResultService, ResultChangeEvent } from 'vs/workbench/contrib/testing/common/testResultService';
import { ITestFollowup, ITestService } from 'vs/workbench/contrib/testing/common/testService';
import { IRichLocation, ITestErrorMessage, ITestItem, ITestItemContext, ITestMessage, ITestMessageMenuArgs, ITestRunTask, ITestTaskState, InternalTestItem, TestMessageType, TestResultItem, TestResultState, TestRunProfileBitset, getMarkId, testResultStateToContextValues } from 'vs/workbench/contrib/testing/common/testTypes';
import { TestingContextKeys } from 'vs/workbench/contrib/testing/common/testingContextKeys';
import { IShowResultOptions, ITestingPeekOpener } from 'vs/workbench/contrib/testing/common/testingPeekOpener';
import { cmpPriority, isFailedState } from 'vs/workbench/contrib/testing/common/testingStates';
import { ParsedTestUri, TestUriType, buildTestUri, parseTestUri } from 'vs/workbench/contrib/testing/common/testingUri';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IViewsService } from 'vs/workbench/services/views/common/viewsService';
const getMessageArgs = (test: TestResultItem, message: ITestMessage): ITestMessageMenuArgs => ({
$mid: MarshalledId.TestMessageMenuArgs,
test: InternalTestItem.serialize(test),
message: ITestMessage.serialize(message),
});
class MessageSubject {
public readonly test: ITestItem;
public readonly message: ITestMessage;
public readonly expectedUri: URI;
public readonly actualUri: URI;
public readonly messageUri: URI;
public readonly revealLocation: IRichLocation | undefined;
public readonly context: ITestMessageMenuArgs | undefined;
public get isDiffable() {
return this.message.type === TestMessageType.Error && isDiffable(this.message);
}
public get contextValue() {
return this.message.type === TestMessageType.Error ? this.message.contextValue : undefined;
}
constructor(public readonly result: ITestResult, test: TestResultItem, public readonly taskIndex: number, public readonly messageIndex: number) {
this.test = test.item;
const messages = test.tasks[taskIndex].messages;
this.messageIndex = messageIndex;
const parts = { messageIndex, resultId: result.id, taskIndex, testExtId: test.item.extId };
this.expectedUri = buildTestUri({ ...parts, type: TestUriType.ResultExpectedOutput });
this.actualUri = buildTestUri({ ...parts, type: TestUriType.ResultActualOutput });
this.messageUri = buildTestUri({ ...parts, type: TestUriType.ResultMessage });
const message = this.message = messages[this.messageIndex];
this.context = getMessageArgs(test, message);
this.revealLocation = message.location ?? (test.item.uri && test.item.range ? { uri: test.item.uri, range: Range.lift(test.item.range) } : undefined);
}
}
class TaskSubject {
public readonly outputUri: URI;
public readonly revealLocation: undefined;
constructor(public readonly result: ITestResult, public readonly taskIndex: number) {
this.outputUri = buildTestUri({ resultId: result.id, taskIndex, type: TestUriType.TaskOutput });
}
}
class TestOutputSubject {
public readonly outputUri: URI;
public readonly revealLocation: undefined;
public readonly task: ITestRunTask;
constructor(public readonly result: ITestResult, public readonly taskIndex: number, public readonly test: TestResultItem) {
this.outputUri = buildTestUri({ resultId: this.result.id, taskIndex: this.taskIndex, testExtId: this.test.item.extId, type: TestUriType.TestOutput });
this.task = result.tasks[this.taskIndex];
}
}
type InspectSubject = MessageSubject | TaskSubject | TestOutputSubject;
const equalsSubject = (a: InspectSubject, b: InspectSubject) => (
(a instanceof MessageSubject && b instanceof MessageSubject && a.message === b.message) ||
(a instanceof TaskSubject && b instanceof TaskSubject && a.result === b.result && a.taskIndex === b.taskIndex) ||
(a instanceof TestOutputSubject && b instanceof TestOutputSubject && a.test === b.test && a.taskIndex === b.taskIndex)
);
/** Iterates through every message in every result */
function* allMessages(results: readonly ITestResult[]) {
for (const result of results) {
for (const test of result.tests) {
for (let taskIndex = 0; taskIndex < test.tasks.length; taskIndex++) {
for (let messageIndex = 0; messageIndex < test.tasks[taskIndex].messages.length; messageIndex++) {
yield { result, test, taskIndex, messageIndex };
}
}
}
}
}
type TestUriWithDocument = ParsedTestUri & { documentUri: URI };
export class TestingPeekOpener extends Disposable implements ITestingPeekOpener {
declare _serviceBrand: undefined;
private lastUri?: TestUriWithDocument;
/** @inheritdoc */
public readonly historyVisible = MutableObservableValue.stored(this._register(new StoredValue<boolean>({
key: 'testHistoryVisibleInPeek',
scope: StorageScope.PROFILE,
target: StorageTarget.USER,
}, this.storageService)), false);
constructor(
@IConfigurationService private readonly configuration: IConfigurationService,
@IEditorService private readonly editorService: IEditorService,
@ICodeEditorService private readonly codeEditorService: ICodeEditorService,
@ITestResultService private readonly testResults: ITestResultService,
@ITestService private readonly testService: ITestService,
@IStorageService private readonly storageService: IStorageService,
@IViewsService private readonly viewsService: IViewsService,
@ICommandService private readonly commandService: ICommandService,
@INotificationService private readonly notificationService: INotificationService,
) {
super();
this._register(testResults.onTestChanged(this.openPeekOnFailure, this));
}
/** @inheritdoc */
public async open() {
let uri: TestUriWithDocument | undefined;
const active = this.editorService.activeTextEditorControl;
if (isCodeEditor(active) && active.getModel()?.uri) {
const modelUri = active.getModel()?.uri;
if (modelUri) {
uri = await this.getFileCandidateMessage(modelUri, active.getPosition());
}
}
if (!uri) {
uri = this.lastUri;
}
if (!uri) {
uri = this.getAnyCandidateMessage();
}
if (!uri) {
return false;
}
return this.showPeekFromUri(uri);
}
/** @inheritdoc */
public tryPeekFirstError(result: ITestResult, test: TestResultItem, options?: Partial<ITextEditorOptions>) {
const candidate = this.getFailedCandidateMessage(test);
if (!candidate) {
return false;
}
this.showPeekFromUri({
type: TestUriType.ResultMessage,
documentUri: candidate.location.uri,
taskIndex: candidate.taskId,
messageIndex: candidate.index,
resultId: result.id,
testExtId: test.item.extId,
}, undefined, { selection: candidate.location.range, selectionRevealType: TextEditorSelectionRevealType.NearTopIfOutsideViewport, ...options });
return true;
}
/** @inheritdoc */
public peekUri(uri: URI, options: IShowResultOptions = {}) {
const parsed = parseTestUri(uri);
const result = parsed && this.testResults.getResult(parsed.resultId);
if (!parsed || !result || !('testExtId' in parsed)) {
return false;
}
if (!('messageIndex' in parsed)) {
return false;
}
const message = result.getStateById(parsed.testExtId)?.tasks[parsed.taskIndex].messages[parsed.messageIndex];
if (!message?.location) {
return false;
}
this.showPeekFromUri({
type: TestUriType.ResultMessage,
documentUri: message.location.uri,
taskIndex: parsed.taskIndex,
messageIndex: parsed.messageIndex,
resultId: result.id,
testExtId: parsed.testExtId,
}, options.inEditor, { selection: message.location.range, ...options.options });
return true;
}
/** @inheritdoc */
public closeAllPeeks() {
for (const editor of this.codeEditorService.listCodeEditors()) {
TestingOutputPeekController.get(editor)?.removePeek();
}
}
public openCurrentInEditor(): void {
const current = this.getActiveControl();
if (!current) {
return;
}
const options = { pinned: false, revealIfOpened: true };
if (current instanceof TaskSubject || current instanceof TestOutputSubject) {
this.editorService.openEditor({ resource: current.outputUri, options });
return;
}
if (current instanceof TestOutputSubject) {
this.editorService.openEditor({ resource: current.outputUri, options });
return;
}
const message = current.message;
if (current.isDiffable) {
this.editorService.openEditor({
original: { resource: current.expectedUri },
modified: { resource: current.actualUri },
options,
});
} else if (typeof message.message === 'string') {
this.editorService.openEditor({ resource: current.messageUri, options });
} else {
this.commandService.executeCommand('markdown.showPreview', current.messageUri).catch(err => {
this.notificationService.error(localize('testing.markdownPeekError', 'Could not open markdown preview: {0}.\n\nPlease make sure the markdown extension is enabled.', err.message));
});
}
}
private getActiveControl(): InspectSubject | undefined {
const editor = getPeekedEditorFromFocus(this.codeEditorService);
const controller = editor && TestingOutputPeekController.get(editor);
return controller?.subject ?? this.viewsService.getActiveViewWithId<TestResultsView>(Testing.ResultsViewId)?.subject;
}
/** @inheritdoc */
private async showPeekFromUri(uri: TestUriWithDocument, editor?: IEditor, options?: ITextEditorOptions) {
if (isCodeEditor(editor)) {
this.lastUri = uri;
TestingOutputPeekController.get(editor)?.show(buildTestUri(this.lastUri));
return true;
}
const pane = await this.editorService.openEditor({
resource: uri.documentUri,
options: { revealIfOpened: true, ...options }
});
const control = pane?.getControl();
if (!isCodeEditor(control)) {
return false;
}
this.lastUri = uri;
TestingOutputPeekController.get(control)?.show(buildTestUri(this.lastUri));
return true;
}
/**
* Opens the peek view on a test failure, based on user preferences.
*/
private openPeekOnFailure(evt: TestResultItemChange) {
if (evt.reason !== TestResultItemChangeReason.OwnStateChange) {
return;
}
const candidate = this.getFailedCandidateMessage(evt.item);
if (!candidate) {
return;
}
if (evt.result.request.continuous && !getTestingConfiguration(this.configuration, TestingConfigKeys.AutoOpenPeekViewDuringContinuousRun)) {
return;
}
const editors = this.codeEditorService.listCodeEditors();
const cfg = getTestingConfiguration(this.configuration, TestingConfigKeys.AutoOpenPeekView);
// don't show the peek if the user asked to only auto-open peeks for visible tests,
// and this test is not in any of the editors' models.
switch (cfg) {
case AutoOpenPeekViewWhen.FailureVisible: {
const editorUris = new Set(editors.map(e => e.getModel()?.uri.toString()));
if (!Iterable.some(resultItemParents(evt.result, evt.item), i => i.item.uri && editorUris.has(i.item.uri.toString()))) {
return;
}
break; //continue
}
case AutoOpenPeekViewWhen.FailureAnywhere:
break; //continue
default:
return; // never show
}
const controllers = editors.map(TestingOutputPeekController.get);
if (controllers.some(c => c?.subject)) {
return;
}
this.tryPeekFirstError(evt.result, evt.item);
}
/**
* Gets the message closest to the given position from a test in the file.
*/
private async getFileCandidateMessage(uri: URI, position: Position | null) {
let best: TestUriWithDocument | undefined;
let bestDistance = Infinity;
// Get all tests for the document. In those, find one that has a test
// message closest to the cursor position.
const demandedUriStr = uri.toString();
for (const test of this.testService.collection.all) {
const result = this.testResults.getStateById(test.item.extId);
if (!result) {
continue;
}
mapFindTestMessage(result[1], (_task, message, messageIndex, taskIndex) => {
if (message.type !== TestMessageType.Error || !message.location || message.location.uri.toString() !== demandedUriStr) {
return;
}
const distance = position ? Math.abs(position.lineNumber - message.location.range.startLineNumber) : 0;
if (!best || distance <= bestDistance) {
bestDistance = distance;
best = {
type: TestUriType.ResultMessage,
testExtId: result[1].item.extId,
resultId: result[0].id,
taskIndex,
messageIndex,
documentUri: uri,
};
}
});
}
return best;
}
/**
* Gets any possible still-relevant message from the results.
*/
private getAnyCandidateMessage() {
const seen = new Set<string>();
for (const result of this.testResults.results) {
for (const test of result.tests) {
if (seen.has(test.item.extId)) {
continue;
}
seen.add(test.item.extId);
const found = mapFindTestMessage(test, (task, message, messageIndex, taskIndex) => (
message.location && {
type: TestUriType.ResultMessage,
testExtId: test.item.extId,
resultId: result.id,
taskIndex,
messageIndex,
documentUri: message.location.uri,
}
));
if (found) {
return found;
}
}
}
return undefined;
}
/**
* Gets the first failed message that can be displayed from the result.
*/
private getFailedCandidateMessage(test: TestResultItem) {
const fallbackLocation = test.item.uri && test.item.range
? { uri: test.item.uri, range: test.item.range }
: undefined;
let best: { taskId: number; index: number; message: ITestMessage; location: IRichLocation } | undefined;
mapFindTestMessage(test, (task, message, messageIndex, taskId) => {
const location = message.location || fallbackLocation;
if (!isFailedState(task.state) || !location) {
return;
}
if (best && message.type !== TestMessageType.Error) {
return;
}
best = { taskId, index: messageIndex, message, location };
});
return best;
}
}
const mapFindTestMessage = <T>(test: TestResultItem, fn: (task: ITestTaskState, message: ITestMessage, messageIndex: number, taskIndex: number) => T | undefined) => {
for (let taskIndex = 0; taskIndex < test.tasks.length; taskIndex++) {
const task = test.tasks[taskIndex];
for (let messageIndex = 0; messageIndex < task.messages.length; messageIndex++) {
const r = fn(task, task.messages[messageIndex], messageIndex, taskIndex);
if (r !== undefined) {
return r;
}
}
}
return undefined;
};
/**
* Adds output/message peek functionality to code editors.
*/
export class TestingOutputPeekController extends Disposable implements IEditorContribution {
/**
* Gets the controller associated with the given code editor.
*/
public static get(editor: ICodeEditor): TestingOutputPeekController | null {
return editor.getContribution<TestingOutputPeekController>(Testing.OutputPeekContributionId);
}
/**
* Currently-shown peek view.
*/
private readonly peek = this._register(new MutableDisposable<TestResultsPeek>());
/**
* URI of the currently-visible peek, if any.
*/
private currentPeekUri: URI | undefined;
/**
* Context key updated when the peek is visible/hidden.
*/
private readonly visible: IContextKey<boolean>;
/**
* Gets the currently display subject. Undefined if the peek is not open.
*/
public get subject() {
return this.peek.value?.current;
}
constructor(
private readonly editor: ICodeEditor,
@ICodeEditorService private readonly codeEditorService: ICodeEditorService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ITestResultService private readonly testResults: ITestResultService,
@IContextKeyService contextKeyService: IContextKeyService,
) {
super();
this.visible = TestingContextKeys.isPeekVisible.bindTo(contextKeyService);
this._register(editor.onDidChangeModel(() => this.peek.clear()));
this._register(testResults.onResultsChanged(this.closePeekOnCertainResultEvents, this));
this._register(testResults.onTestChanged(this.closePeekOnTestChange, this));
}
/**
* Toggles peek visibility for the URI.
*/
public toggle(uri: URI) {
if (this.currentPeekUri?.toString() === uri.toString()) {
this.peek.clear();
} else {
this.show(uri);
}
}
/**
* Shows a peek for the message in the editor.
*/
public async show(uri: URI) {
const subject = this.retrieveTest(uri);
if (!subject) {
return;
}
if (!this.peek.value) {
this.peek.value = this.instantiationService.createInstance(TestResultsPeek, this.editor);
this.peek.value.onDidClose(() => {
this.visible.set(false);
this.currentPeekUri = undefined;
this.peek.value = undefined;
});
this.visible.set(true);
this.peek.value.create();
}
if (subject instanceof MessageSubject) {
alert(renderTestMessageAsText(subject.message.message));
}
this.peek.value.setModel(subject);
this.currentPeekUri = uri;
}
public async openAndShow(uri: URI) {
const subject = this.retrieveTest(uri);
if (!subject) {
return;
}
if (!subject.revealLocation || subject.revealLocation.uri.toString() === this.editor.getModel()?.uri.toString()) {
return this.show(uri);
}
const otherEditor = await this.codeEditorService.openCodeEditor({
resource: subject.revealLocation.uri,
options: { pinned: false, revealIfOpened: true }
}, this.editor);
if (otherEditor) {
TestingOutputPeekController.get(otherEditor)?.removePeek();
return TestingOutputPeekController.get(otherEditor)?.show(uri);
}
}
/**
* Disposes the peek view, if any.
*/
public removePeek() {
this.peek.clear();
}
/**
* Shows the next message in the peek, if possible.
*/
public next() {
const subject = this.peek.value?.current;
if (!subject) {
return;
}
let found = false;
for (const { messageIndex, taskIndex, result, test } of allMessages(this.testResults.results)) {
if (subject instanceof TaskSubject && result.id === subject.result.id) {
found = true; // open the first message found in the current result
}
if (found) {
this.openAndShow(buildTestUri({
type: TestUriType.ResultMessage,
messageIndex,
taskIndex,
resultId: result.id,
testExtId: test.item.extId
}));
return;
}
if (subject instanceof TestOutputSubject && subject.test.item.extId === test.item.extId && subject.taskIndex === taskIndex && subject.result.id === result.id) {
found = true;
}
if (subject instanceof MessageSubject && subject.test.extId === test.item.extId && subject.messageIndex === messageIndex && subject.taskIndex === taskIndex && subject.result.id === result.id) {
found = true;
}
}
}
/**
* Shows the previous message in the peek, if possible.
*/
public previous() {
const subject = this.peek.value?.current;
if (!subject) {
return;
}
let previous: { messageIndex: number; taskIndex: number; result: ITestResult; test: TestResultItem } | undefined;
for (const m of allMessages(this.testResults.results)) {
if (subject instanceof TaskSubject) {
if (m.result.id === subject.result.id) {
break;
}
continue;
}
if (subject instanceof TestOutputSubject) {
if (m.test.item.extId === subject.test.item.extId && m.result.id === subject.result.id && m.taskIndex === subject.taskIndex) {
break;
}
continue;
}
if (subject.test.extId === m.test.item.extId && subject.messageIndex === m.messageIndex && subject.taskIndex === m.taskIndex && subject.result.id === m.result.id) {
break;
}
previous = m;
}
if (previous) {
this.openAndShow(buildTestUri({
type: TestUriType.ResultMessage,
messageIndex: previous.messageIndex,
taskIndex: previous.taskIndex,
resultId: previous.result.id,
testExtId: previous.test.item.extId
}));
}
}
/**
* Removes the peek view if it's being displayed on the given test ID.
*/
public removeIfPeekingForTest(testId: string) {
const c = this.peek.value?.current;
if (c && c instanceof MessageSubject && c.test.extId === testId) {
this.peek.clear();
}
}
/**
* If the test we're currently showing has its state change to something
* else, then clear the peek.
*/
private closePeekOnTestChange(evt: TestResultItemChange) {
if (evt.reason !== TestResultItemChangeReason.OwnStateChange || evt.previousState === evt.item.ownComputedState) {
return;
}
this.removeIfPeekingForTest(evt.item.item.extId);
}
private closePeekOnCertainResultEvents(evt: ResultChangeEvent) {
if ('started' in evt) {
this.peek.clear(); // close peek when runs start
}
if ('removed' in evt && this.testResults.results.length === 0) {
this.peek.clear(); // close the peek if results are cleared
}
}
private retrieveTest(uri: URI): InspectSubject | undefined {
const parts = parseTestUri(uri);
if (!parts) {
return undefined;
}
const result = this.testResults.results.find(r => r.id === parts.resultId);
if (!result) {
return;
}
if (parts.type === TestUriType.TaskOutput) {
return new TaskSubject(result, parts.taskIndex);
}
if (parts.type === TestUriType.TestOutput) {
const test = result.getStateById(parts.testExtId);
if (!test) { return; }
return new TestOutputSubject(result, parts.taskIndex, test);
}
const { testExtId, taskIndex, messageIndex } = parts;
const test = result?.getStateById(testExtId);
if (!test || !test.tasks[parts.taskIndex]) {
return;
}
return new MessageSubject(result, test, taskIndex, messageIndex);
}
}
const FOLLOWUP_ANIMATION_MIN_TIME = 500;
class FollowupActionWidget extends Disposable {
private readonly el = dom.h('div.testing-followup-action', []);
private readonly visibleStore = this._register(new DisposableStore());
constructor(
private readonly container: HTMLElement,
@ITestService private readonly testService: ITestService,
@IQuickInputService private readonly quickInput: IQuickInputService,
) {
super();
}
public show(subject: InspectSubject) {
this.visibleStore.clear();
if (subject instanceof MessageSubject) {
this.showMessage(subject);
}
}
private async showMessage(subject: MessageSubject) {
const cts = this.visibleStore.add(new CancellationTokenSource());
const start = Date.now();
// Wait for completion otherwise results will not be available to the ext host:
if (subject.result instanceof LiveTestResult && !subject.result.completedAt) {
await new Promise(r => Event.once((subject.result as LiveTestResult).onComplete)(r));
}
const followups = await this.testService.provideTestFollowups({
extId: subject.test.extId,
messageIndex: subject.messageIndex,
resultId: subject.result.id,
taskIndex: subject.taskIndex,
}, cts.token);
if (!followups.followups.length || cts.token.isCancellationRequested) {
followups.dispose();
return;
}
this.visibleStore.add(followups);
dom.clearNode(this.el.root);
this.el.root.classList.toggle('animated', Date.now() - start > FOLLOWUP_ANIMATION_MIN_TIME);
this.el.root.appendChild(this.makeFollowupLink(followups.followups[0]));
if (followups.followups.length > 1) {
this.el.root.appendChild(this.makeMoreLink(followups.followups));
}
this.container.appendChild(this.el.root);
this.visibleStore.add(toDisposable(() => {
this.el.root.parentElement?.removeChild(this.el.root);
}));
}
private makeFollowupLink(first: ITestFollowup) {
const link = this.makeLink(() => this.actionFollowup(link, first));
dom.reset(link, ...renderLabelWithIcons(first.message));
return link;
}
private makeMoreLink(followups: ITestFollowup[]) {
const link = this.makeLink(() =>
this.quickInput.pick(followups.map((f, i) => ({
label: f.message,
index: i
}))).then(picked => {
if (picked?.length) {
followups[picked[0].index].execute();
}
})
);
link.innerText = localize('testFollowup.more', '+{0} More...', followups.length - 1);
return link;
}
private makeLink(onClick: () => void) {
const link = document.createElement('a');
link.tabIndex = 0;
this.visibleStore.add(dom.addDisposableListener(link, 'click', onClick));
this.visibleStore.add(dom.addDisposableListener(link, 'keydown', e => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.Space) || event.equals(KeyCode.Enter)) {
onClick();
}
}));
return link;
}
private actionFollowup(link: HTMLAnchorElement, fu: ITestFollowup) {
if (link.ariaDisabled !== 'true') {
link.ariaDisabled = 'true';
fu.execute();
}
}
}
class TestResultsViewContent extends Disposable {
private static lastSplitWidth?: number;
private readonly didReveal = this._register(new Emitter<{ subject: InspectSubject; preserveFocus: boolean }>());
private readonly currentSubjectStore = this._register(new DisposableStore());
private followupWidget!: FollowupActionWidget;
private messageContextKeyService!: IContextKeyService;
private contextKeyTestMessage!: IContextKey<string>;
private contextKeyResultOutdated!: IContextKey<boolean>;
private dimension?: dom.Dimension;
private splitView!: SplitView;
private messageContainer!: HTMLElement;
private contentProviders!: IPeekOutputRenderer[];
private contentProvidersUpdateLimiter = this._register(new Limiter(1));
public current?: InspectSubject;
/** Fired when a tree item is selected. Populated only on .fillBody() */
public onDidRequestReveal!: Event<InspectSubject>;
constructor(
private readonly editor: ICodeEditor | undefined,
private readonly options: {
historyVisible: IObservableValue<boolean>;
showRevealLocationOnMessages: boolean;
locationForProgress: string;
},
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ITextModelService protected readonly modelService: ITextModelService,
@IContextKeyService private readonly contextKeyService: IContextKeyService,
) {
super();
}
public fillBody(containerElement: HTMLElement): void {
const initialSpitWidth = TestResultsViewContent.lastSplitWidth;
this.splitView = new SplitView(containerElement, { orientation: Orientation.HORIZONTAL });
const { historyVisible, showRevealLocationOnMessages } = this.options;
const isInPeekView = this.editor !== undefined;
const messageContainer = this.messageContainer = dom.append(containerElement, dom.$('.test-output-peek-message-container'));
this.followupWidget = this._register(this.instantiationService.createInstance(FollowupActionWidget, messageContainer));
this.contentProviders = [
this._register(this.instantiationService.createInstance(DiffContentProvider, this.editor, messageContainer)),
this._register(this.instantiationService.createInstance(MarkdownTestMessagePeek, messageContainer)),
this._register(this.instantiationService.createInstance(TerminalMessagePeek, messageContainer, isInPeekView)),
this._register(this.instantiationService.createInstance(PlainTextMessagePeek, this.editor, messageContainer)),
];
this.messageContextKeyService = this._register(this.contextKeyService.createScoped(containerElement));
this.contextKeyTestMessage = TestingContextKeys.testMessageContext.bindTo(this.messageContextKeyService);
this.contextKeyResultOutdated = TestingContextKeys.testResultOutdated.bindTo(this.messageContextKeyService);
const treeContainer = dom.append(containerElement, dom.$('.test-output-peek-tree'));
const tree = this._register(this.instantiationService.createInstance(
OutputPeekTree,
treeContainer,
this.didReveal.event,
{ showRevealLocationOnMessages, locationForProgress: this.options.locationForProgress },
));
this.onDidRequestReveal = tree.onDidRequestReview;
this.splitView.addView({
onDidChange: Event.None,
element: messageContainer,
minimumSize: 200,
maximumSize: Number.MAX_VALUE,
layout: width => {
TestResultsViewContent.lastSplitWidth = width;
if (this.dimension) {
for (const provider of this.contentProviders) {
provider.layout({ height: this.dimension.height, width });
}
}
},
}, Sizing.Distribute);
this.splitView.addView({
onDidChange: Event.None,
element: treeContainer,
minimumSize: 100,
maximumSize: Number.MAX_VALUE,
layout: width => {
if (this.dimension) {
tree.layout(this.dimension.height, width);
}
},
}, Sizing.Distribute);
const historyViewIndex = 1;
this.splitView.setViewVisible(historyViewIndex, historyVisible.value);
this._register(historyVisible.onDidChange(visible => {
this.splitView.setViewVisible(historyViewIndex, visible);
}));
if (initialSpitWidth) {
queueMicrotask(() => this.splitView.resizeView(0, initialSpitWidth));
}
}
/**
* Shows a message in-place without showing or changing the peek location.
* This is mostly used if peeking a message without a location.
*/
public reveal(opts: { subject: InspectSubject; preserveFocus: boolean }) {
this.didReveal.fire(opts);
if (this.current && equalsSubject(this.current, opts.subject)) {
return Promise.resolve();
}
this.current = opts.subject;
return this.contentProvidersUpdateLimiter.queue(async () => {
await Promise.all(this.contentProviders.map(p => p.update(opts.subject)));
this.followupWidget.show(opts.subject);
this.currentSubjectStore.clear();
this.populateFloatingClick(opts.subject);
});
}
private populateFloatingClick(subject: InspectSubject) {