-
Notifications
You must be signed in to change notification settings - Fork 253
Expand file tree
/
Copy pathtestController.ts
More file actions
1379 lines (1134 loc) · 45.5 KB
/
testController.ts
File metadata and controls
1379 lines (1134 loc) · 45.5 KB
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
import { exec } from "child_process";
import { promisify } from "util";
import path from "path";
import * as vscode from "vscode";
import { CodeLens } from "vscode-languageclient/node";
import { Workspace } from "./workspace";
import { featureEnabled } from "./common";
import { LspTestItem, ResolvedCommands, ServerTestItem } from "./client";
import { LinkedCancellationSource } from "./linkedCancellationSource";
import { Mode, StreamingRunner } from "./streamingRunner";
const asyncExec = promisify(exec);
const NESTED_TEST_DIR_PATTERN = "**/{test,spec,features}/**/";
const TEST_FILE_PATTERN = `${NESTED_TEST_DIR_PATTERN}{*_test.rb,test_*.rb,*_spec.rb,*.feature}`;
const IGNORED_FOLDERS = [".bundle", "vendor/bundle", "node_modules", "tmp", "log"];
const IGNORED_FOLDERS_EXCLUDE_PATTERN = `{${IGNORED_FOLDERS.map((folder) => `**/${folder}/**`).join(",")}}`;
// Build a regex to match paths containing any of the ignored folders
const IGNORED_FOLDERS_PATH_REGEX = new RegExp(
IGNORED_FOLDERS.map((folder) => `/${folder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`).join("|"),
);
interface CodeLensData {
type: string;
group_id: number;
id?: number;
kind: string;
}
const WORKSPACE_TAG = new vscode.TestTag("workspace");
const TEST_DIR_TAG = new vscode.TestTag("test_dir");
const TEST_GROUP_TAG = new vscode.TestTag("test_group");
const DEBUG_TAG = new vscode.TestTag("debug");
const TEST_FILE_TAG = new vscode.TestTag("test_file");
const RUN_PROFILE_LABEL = "Run";
const RUN_IN_TERMINAL_PROFILE_LABEL = "Run in terminal";
const DEBUG_PROFILE_LABEL = "Debug";
const COVERAGE_PROFILE_LABEL = "Coverage";
export class TestController {
// Only public for testing
readonly testController: vscode.TestController;
readonly testRunProfile: vscode.TestRunProfile;
readonly runInTerminalProfile: vscode.TestRunProfile;
readonly coverageProfile: vscode.TestRunProfile;
readonly testDebugProfile: vscode.TestRunProfile;
private readonly testCommands: WeakMap<vscode.TestItem, string>;
private terminal: vscode.Terminal | undefined;
private readonly telemetry: vscode.TelemetryLogger;
// We allow the timeout to be configured in seconds, but exec expects it in milliseconds
private readonly testTimeout = vscode.workspace.getConfiguration("rubyLsp").get("testTimeout") as number;
private readonly currentWorkspace: () => Workspace | undefined;
private readonly getOrActivateWorkspace: (workspaceFolder: vscode.WorkspaceFolder) => Promise<Workspace>;
private readonly fullDiscovery = featureEnabled("fullTestDiscovery");
private readonly coverageData = new WeakMap<vscode.FileCoverage, vscode.FileCoverageDetail[]>();
private readonly runner: StreamingRunner;
constructor(
context: vscode.ExtensionContext,
telemetry: vscode.TelemetryLogger,
currentWorkspace: () => Workspace | undefined,
getOrActivateWorkspace: (workspaceFolder: vscode.WorkspaceFolder) => Promise<Workspace>,
) {
this.telemetry = telemetry;
this.currentWorkspace = currentWorkspace;
this.getOrActivateWorkspace = getOrActivateWorkspace;
this.testController = vscode.tests.createTestController("rubyTests", "Ruby Tests");
this.runner = new StreamingRunner(
context,
this.findTestItem.bind(this),
this.testController.createTestRun.bind(this.testController),
);
if (this.fullDiscovery) {
this.testController.resolveHandler = this.resolveHandler.bind(this);
this.testController.refreshHandler = this.refreshHandler.bind(this);
}
this.testCommands = new WeakMap<vscode.TestItem, string>();
this.testRunProfile = this.testController.createRunProfile(
RUN_PROFILE_LABEL,
vscode.TestRunProfileKind.Run,
this.fullDiscovery ? this.runTest.bind(this) : this.runHandler.bind(this),
true,
undefined,
true,
);
this.testDebugProfile = this.testController.createRunProfile(
DEBUG_PROFILE_LABEL,
vscode.TestRunProfileKind.Debug,
this.fullDiscovery ? this.runTest.bind(this) : this.debugHandler.bind(this),
false,
DEBUG_TAG,
);
this.coverageProfile = this.testController.createRunProfile(
COVERAGE_PROFILE_LABEL,
vscode.TestRunProfileKind.Coverage,
this.fullDiscovery
? this.runTest.bind(this)
: async () => {
await vscode.window.showInformationMessage(
`Running tests with coverage requires the new explorer implementation,
which is currently under development.
If you wish to enable it, set the "fullTestDiscovery" feature flag to "true"`,
);
},
false,
);
// This method is invoked when a document is opened in the UI to gather any additional details about coverage for
// inline decorations. We save all of the available details in the `coverageData` map ahead of time, so we just need
// to return the existing data
// eslint-disable-next-line @typescript-eslint/require-await
this.coverageProfile.loadDetailedCoverage = async (_testRun, fileCoverage, _token) => {
return this.coverageData.get(fileCoverage)!;
};
this.runInTerminalProfile = this.testController.createRunProfile(
RUN_IN_TERMINAL_PROFILE_LABEL,
vscode.TestRunProfileKind.Run,
this.runTest.bind(this),
false,
);
const testFileWatcher = vscode.workspace.createFileSystemWatcher(TEST_FILE_PATTERN);
const nestedTestDirWatcher = vscode.workspace.createFileSystemWatcher(NESTED_TEST_DIR_PATTERN, true, true, false);
context.subscriptions.push(
this.testController,
this.testDebugProfile,
this.testRunProfile,
this.coverageProfile,
this.runner,
this.runInTerminalProfile,
vscode.window.onDidCloseTerminal((terminal: vscode.Terminal): void => {
if (terminal === this.terminal) this.terminal = undefined;
}),
testFileWatcher,
nestedTestDirWatcher,
testFileWatcher.onDidCreate(async (uri) => {
if (this.isInIgnoredFolder(uri)) {
return;
}
const workspace = vscode.workspace.getWorkspaceFolder(uri);
if (!workspace || !vscode.workspace.workspaceFolders) {
return;
}
const initialCollection =
vscode.workspace.workspaceFolders.length === 1
? this.testController.items
: this.testController.items.get(workspace.uri.toString())?.children;
if (!initialCollection) {
return;
}
await this.addTestItemsForFile(uri, workspace, initialCollection);
}),
testFileWatcher.onDidChange(async (uri) => {
if (this.isInIgnoredFolder(uri)) {
return;
}
const item = await this.getParentTestItem(uri);
if (item) {
const testFile = item.children.get(uri.toString());
if (testFile) {
testFile.children.replace([]);
await this.resolveHandler(testFile);
}
}
}),
nestedTestDirWatcher.onDidDelete(async (uri) => {
if (this.isInIgnoredFolder(uri)) {
return;
}
const pathParts = uri.fsPath.split(path.sep);
if (pathParts.includes(".git")) {
return;
}
const parentItem = await this.getParentTestItem(uri);
if (parentItem) {
parentItem.children.delete(uri.toString());
}
}),
testFileWatcher.onDidDelete(async (uri) => {
if (this.isInIgnoredFolder(uri)) {
return;
}
const item = await this.getParentTestItem(uri);
if (item) {
item.children.delete(uri.toString());
}
}),
);
}
/**
* @deprecated To be removed once the new test explorer is fully rolled out
*/
createTestItems(response: CodeLens[]) {
// In the new experience, we will no longer overload code lens
if (this.fullDiscovery) {
return;
}
this.testController.items.forEach((test) => {
this.testController.items.delete(test.id);
this.testCommands.delete(test);
});
const groupIdMap: Map<number, vscode.TestItem> = new Map();
const uri = vscode.Uri.from({
scheme: "file",
path: response[0].command!.arguments![0],
});
response.forEach((res) => {
const [_, name, command, location, label] = res.command!.arguments!;
const testItem: vscode.TestItem = this.testController.createTestItem(name, label || name, uri);
const data: CodeLensData = res.data;
testItem.tags = [new vscode.TestTag(data.kind)];
this.testCommands.set(testItem, command);
testItem.range = new vscode.Range(
new vscode.Position(location.start_line, location.start_column),
new vscode.Position(location.end_line, location.end_column),
);
// If it has an id, it's a group. Otherwise, it's a test example
if (data.id) {
// Add group to the map
groupIdMap.set(data.id, testItem);
testItem.canResolveChildren = true;
} else {
// Set example tags
testItem.tags = [...testItem.tags, DEBUG_TAG];
}
// Examples always have a `group_id`. Groups may or may not have it
if (data.group_id) {
// Add nested group to its parent group
const group = groupIdMap.get(data.group_id);
// If there's a mistake on the server or in an add-on, a code lens may be produced for a non-existing group
if (group) {
group.children.add(testItem);
} else {
this.currentWorkspace()?.outputChannel.error(
`Test example "${name}" is attached to group_id ${data.group_id}, but that group does not exist`,
);
}
} else {
// Or add it to the top-level
this.testController.items.add(testItem);
}
});
}
/**
* @deprecated by {@link runViaCommand}. To be removed once the new test explorer is fully rolled out
*/
runTestInTerminal(_path: string, _name: string, command?: string) {
command ??= this.testCommands.get(this.findTestByActiveLine()!) || "";
if (this.terminal === undefined) {
this.terminal = this.getTerminal();
}
this.terminal.show(true);
this.terminal.sendText(command);
this.telemetry.logUsage("ruby_lsp.code_lens", {
type: "counter",
attributes: {
label: "test_in_terminal",
vscodemachineid: vscode.env.machineId,
},
});
}
/**
* @deprecated by {@link runViaCommand}. To be removed once the new test explorer is fully rolled out
*/
async runOnClick(testId: string) {
const test = this.findTestById(testId);
if (!test) return;
await vscode.commands.executeCommand("vscode.revealTestInExplorer", test);
let tokenSource: vscode.CancellationTokenSource | null = new vscode.CancellationTokenSource();
tokenSource.token.onCancellationRequested(async () => {
tokenSource?.dispose();
tokenSource = null;
await vscode.window.showInformationMessage("Cancelled the progress");
});
const testRun = new vscode.TestRunRequest([test], [], this.testRunProfile);
return this.testRunProfile.runHandler(testRun, tokenSource.token);
}
/**
* @deprecated by {@link runViaCommand}. To be removed once the new test explorer is fully rolled out
*/
debugTest(_path: string, _name: string, command?: string) {
command ??= this.testCommands.get(this.findTestByActiveLine()!) || "";
const workspace = this.currentWorkspace();
if (!workspace) {
throw new Error("No workspace found. Debugging requires a workspace to be opened");
}
return vscode.debug.startDebugging(workspace.workspaceFolder, {
type: "ruby_lsp",
name: "Debug",
request: "launch",
program: command,
env: { ...workspace.ruby.env, DISABLE_SPRING: "1" },
});
}
// Public for testing purposes. Receives the controller's inclusions and exclusions and builds request test items for
// the server to resolve the command
buildRequestTestItems(
inclusions: vscode.TestItem[],
exclusions: ReadonlyArray<vscode.TestItem> | undefined,
): LspTestItem[] {
if (!exclusions) {
return inclusions.map((item) => this.testItemToServerItem(item));
}
const filtered: LspTestItem[] = [];
inclusions.forEach((item) => {
const includedItem = this.recursivelyFilter(item, exclusions);
if (includedItem) {
filtered.push(includedItem);
}
});
return filtered;
}
// Method to run tests in any profile through code lens buttons
async runViaCommand(path: string, name: string, mode: Mode) {
const uri = vscode.Uri.file(path);
const testItem = await this.findTestItem(name, uri);
if (!testItem) {
await vscode.window.showErrorMessage(
`Attempted to run "${name}" defined in "${path}", but that test has not been discovered.
Does the file path match the expected glob pattern?
[Read more](https://shopify.github.io/ruby-lsp/test_explorer.html)
Expected pattern: "**/{test,spec,features}/**/{*_test.rb,test_*.rb,*_spec.rb,*.feature}"
Excluded paths: ${IGNORED_FOLDERS.map((p) => `"${p}"`).join(", ")}`,
);
return;
}
if (mode === Mode.Run) {
await vscode.commands.executeCommand("vscode.revealTestInExplorer", testItem);
}
const tokenSource = new vscode.CancellationTokenSource();
tokenSource.token.onCancellationRequested(async () => {
tokenSource.dispose();
await vscode.window.showInformationMessage("Cancelled the progress");
});
let profile;
switch (mode) {
case Mode.Debug:
profile = this.testDebugProfile;
break;
case Mode.RunInTerminal:
profile = this.runInTerminalProfile;
break;
default:
profile = this.testRunProfile;
break;
}
const request = new vscode.TestRunRequest([testItem], [], profile);
return this.runTest(request, tokenSource.token);
}
async runTest(request: vscode.TestRunRequest, token: vscode.CancellationToken) {
this.telemetry.logUsage("ruby_lsp.test_explorer", {
type: "counter",
attributes: {
label: request.profile?.label || RUN_PROFILE_LABEL,
vscodemachineid: vscode.env.machineId,
continuousMode: request.continuous ?? false,
},
});
if (request.continuous) {
const disposables: vscode.Disposable[] = [];
const testFileWatcher = vscode.workspace.createFileSystemWatcher(TEST_FILE_PATTERN, true, false, true);
disposables.push(
testFileWatcher,
testFileWatcher.onDidChange(async () => {
const continuousRequest = new vscode.TestRunRequest(
request.include,
request.exclude,
request.profile,
false,
request.preserveFocus,
);
await this.handleTests(continuousRequest, token);
}),
);
disposables.push(
token.onCancellationRequested(() => {
disposables.forEach((disposable) => disposable.dispose());
}),
);
} else {
await this.handleTests(request, token);
}
}
// Public for testing purposes. Finds a test item based on its ID and URI
async findTestItem(id: string, uri: vscode.Uri, line?: number) {
if (this.testController.items.size === 0) {
// Discover and test items immediately if the test explorer hasn't been expanded
await vscode.window.withProgress(
{
title: "Discovering tests",
location: vscode.ProgressLocation.Notification,
},
async (progress) => {
await this.resolveHandler(undefined, progress);
},
);
}
const parentItem = await this.getParentTestItem(uri);
if (!parentItem) {
return;
}
if (parentItem.id === id) {
return parentItem;
}
const testFileItem = parentItem.children.get(uri.toString());
if (!testFileItem) {
return;
}
if (testFileItem.id === id) {
return testFileItem;
}
// If we're trying to find a test item inside a file that has never been expanded, then we never discovered its
// children and need to do so before trying to access them
if (testFileItem.children.size === 0) {
await this.resolveHandler(testFileItem);
}
// If we find an exact match for this ID, then return it right away
const groupOrItem = testFileItem.children.get(id);
if (groupOrItem) {
return groupOrItem;
}
// If not, the ID might be nested under groups
return this.findTestInGroup(id, testFileItem, line);
}
async activate() {
await this.runner.activate();
}
get streamingPort() {
return this.runner.tcpPort;
}
private async refreshHandler(_token: vscode.CancellationToken) {
this.testController.items.replace([]);
this.testController.invalidateTestResults();
await this.testController.resolveHandler!(undefined);
}
private async handleTests(request: vscode.TestRunRequest, token: vscode.CancellationToken) {
const run = this.testController.createTestRun(request);
// Gather all included test items
const items: vscode.TestItem[] = [];
if (request.include) {
request.include.forEach((test) => items.push(test));
} else {
this.testController.items.forEach((test) => items.push(test));
}
await this.discoverFrameworkTag(items);
const workspaceToTestItems = new Map<vscode.WorkspaceFolder, vscode.TestItem[]>();
// Organize the tests based on their workspace folder. Each workspace has their own LSP server running and may be
// using a different test framework, so we need to use the workspace associated with each item
items.forEach((item) => {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(item.uri!)!;
const existingEntry = workspaceToTestItems.get(workspaceFolder);
if (existingEntry) {
existingEntry.push(item);
} else {
workspaceToTestItems.set(workspaceFolder, [item]);
}
});
const linkedCancellationSource = new LinkedCancellationSource(token, run.token);
for (const [workspaceFolder, testItems] of workspaceToTestItems) {
if (linkedCancellationSource.isCancellationRequested()) {
break;
}
// Build the test item parameters that we send to the server, filtering out exclusions. Then ask the server for
// the resolved test commands
const requestTestItems = this.buildRequestTestItems(testItems, request.exclude);
const workspace = await this.getOrActivateWorkspace(workspaceFolder);
if (!workspace.lspClient?.initializeResult?.capabilities.experimental?.full_test_discovery) {
run.appendOutput(
`The version of the Ruby LSP server being used by ${workspaceFolder.name} does not support the new
test explorer functionality. Please make sure you are using the latest version of the server.
See https://shopify.github.io/ruby-lsp/troubleshooting.html#outdated-version for more information.`,
);
break;
}
const response = await workspace.lspClient?.resolveTestCommands(requestTestItems);
if (!response) {
testItems.forEach((test) =>
run.errored(test, new vscode.TestMessage("Could not resolve test command to run selected tests")),
);
continue;
}
// Enqueue all of the test we're about to run
testItems.forEach((test) => run.enqueued(test));
const profile = request.profile;
if (
!profile ||
profile.label === RUN_PROFILE_LABEL ||
profile.label === RUN_IN_TERMINAL_PROFILE_LABEL ||
profile.label === COVERAGE_PROFILE_LABEL
) {
await this.executeTestCommands(response, workspace, run, profile, linkedCancellationSource);
} else if (profile.label === DEBUG_PROFILE_LABEL) {
await this.debugTestCommands(response, workspace, run, linkedCancellationSource);
}
}
run.end();
linkedCancellationSource.dispose();
}
// When trying to a test file or directory, we need to know which framework is used by tests inside of it to resolve
// the command correctly. This method will resolve the first test file with children inside to determine the framework
// and then set that to all parents
private async discoverFrameworkTag(items: vscode.TestItem[]) {
const missingFramework = items.filter((item) => {
return !item.tags.some((tag) => tag.id.startsWith("framework"));
});
if (missingFramework.length === 0) {
return;
}
for (const item of missingFramework) {
let testFileItem = item;
while (!testFileItem.tags.some((tag) => tag === TEST_FILE_TAG)) {
let firstChild: vscode.TestItem | undefined;
testFileItem.children.forEach((child) => {
if (firstChild === undefined) firstChild = child;
});
testFileItem = firstChild!;
}
// Handle the case where the test file is empty and has no children
await this.resolveHandler(testFileItem);
this.setFrameworkTagInAllParents(testFileItem);
}
}
private setFrameworkTagInAllParents(item: vscode.TestItem) {
const tag = item.tags.find((tag) => tag.id.startsWith("framework"))!;
let parent = item.parent;
while (parent) {
if (!parent.tags.some((tag) => tag.id.startsWith("framework"))) {
parent.tags = [...parent.tags, tag];
}
parent = parent.parent;
}
}
// Execute all of the test commands reported by the server in the background using JSON RPC to receive streaming
// updates
private async executeTestCommands(
response: ResolvedCommands,
workspace: Workspace,
run: vscode.TestRun,
profile: vscode.TestRunProfile | undefined,
linkedCancellationSource: LinkedCancellationSource,
) {
let rubyOpt;
// Support for the old mechanism of requiring reporters not through test command, but through RUBYOPT. Remove
// after a few months of running new releases of server v0.26
if (response.reporterPaths) {
const commonOpts = `-rbundler/setup ${response.reporterPaths.map((path) => `-r${path}`).join(" ")}`;
rubyOpt = workspace.ruby.env.RUBYOPT ? `${workspace.ruby.env.RUBYOPT} ${commonOpts}` : commonOpts;
}
const runnerMode = profile === this.coverageProfile ? "coverage" : "run";
const mode = profile === this.runInTerminalProfile ? Mode.RunInTerminal : Mode.Run;
for (const command of response.commands) {
run.appendOutput(`Running tests with command:\r\n"${command}"\r\n\r\n`);
try {
await this.runner.execute(
run,
command,
{
...workspace.ruby.env,
RUBY_LSP_TEST_RUNNER: runnerMode,
RUBYOPT: rubyOpt,
},
workspace,
mode,
linkedCancellationSource,
);
} catch (error: any) {
await vscode.window.showErrorMessage(`Running ${command} failed: ${error.message}`);
}
}
if (profile === this.coverageProfile) {
run.appendOutput("\r\n\r\nProcessing test coverage results...\r\n\r\n");
await this.processTestCoverageResults(run, workspace.workspaceFolder);
}
}
// Launches the debugger for the test commands reported by the server. This mode of execution does not support the
// JSON RPC streaming updates as the debugger uses the stdio pipes to communicate with the editor
private async debugTestCommands(
response: ResolvedCommands,
workspace: Workspace,
run: vscode.TestRun,
linkedCancellationSource: LinkedCancellationSource,
) {
for (const command of response.commands) {
if (linkedCancellationSource.isCancellationRequested()) {
break;
}
let rubyOpt;
// Support for the old mechanism of requiring reporters not through test command, but through RUBYOPT. Remove
// after a few months of running new releases of server v0.26
if (response.reporterPaths) {
const commonOpts = `-rbundler/setup ${response.reporterPaths.map((path) => `-r${path}`).join(" ")}`;
rubyOpt = workspace.ruby.env.RUBYOPT ? `${workspace.ruby.env.RUBYOPT} ${commonOpts}` : commonOpts;
}
await this.runner.execute(
run,
command,
{
...workspace.ruby.env,
RUBY_LSP_TEST_RUNNER: "debug",
RUBYOPT: rubyOpt,
},
workspace,
Mode.Debug,
linkedCancellationSource,
);
}
}
private findTestInGroup(id: string, group: vscode.TestItem, line: number | undefined): vscode.TestItem | undefined {
let found: vscode.TestItem | undefined;
group.children.forEach((item) => {
if (id.startsWith(`${item.id}#`) || id.startsWith(`${item.id}::`)) {
found = item;
}
});
if (!found) {
return;
}
// If we found the exact item, return it
const target = found.children.get(id);
if (target) {
return target;
}
// If the ID we're looking for starts with the found item's ID suffixed by a `::`, it means that there are more
// groups nested inside and we can continue searching
if (id.startsWith(`${found.id}::`)) {
return this.findTestInGroup(id, found, line);
}
if (!line) {
return;
}
// If neither of the previous are true, then this test is dynamically defined and we need to create the items for it
// automatically
const label = id.split("#")[1];
const testItem = this.testController.createTestItem(id, `★ ${label}`, found.uri);
testItem.description = "dynamic test";
testItem.range = new vscode.Range(new vscode.Position(line, 0), new vscode.Position(line, 1));
const frameworkTag = found.tags.find((tag) => tag.id.startsWith("framework"));
testItem.tags = frameworkTag ? [DEBUG_TAG, frameworkTag] : [DEBUG_TAG];
found.children.add(testItem);
return testItem;
}
// Get an existing terminal or create a new one. For multiple workspaces, it's important to create a new terminal for
// each workspace because they might be using different Ruby versions. If there's no workspace, we fallback to a
// generic name
private getTerminal() {
const workspace = this.currentWorkspace();
const name = workspace ? `${workspace.workspaceFolder.name}: test` : "Ruby LSP: test";
const previousTerminal = vscode.window.terminals.find((terminal) => terminal.name === name);
return previousTerminal
? previousTerminal
: vscode.window.createTerminal({
name,
});
}
private async debugHandler(request: vscode.TestRunRequest, _token: vscode.CancellationToken) {
const run = this.testController.createTestRun(request, undefined, true);
const test = request.include![0];
const start = Date.now();
await this.debugTest("", "", this.testCommands.get(test));
run.passed(test, Date.now() - start);
run.end();
this.telemetry.logUsage("ruby_lsp.code_lens", {
type: "counter",
attributes: { label: "debug", vscodemachineid: vscode.env.machineId },
});
}
private async runHandler(request: vscode.TestRunRequest, token: vscode.CancellationToken) {
const run = this.testController.createTestRun(request, undefined, true);
const queue: vscode.TestItem[] = [];
const enqueue = (test: vscode.TestItem) => {
queue.push(test);
run.enqueued(test);
};
if (request.include) {
request.include.forEach(enqueue);
} else {
this.testController.items.forEach(enqueue);
}
const workspace = this.currentWorkspace();
while (queue.length > 0 && !token.isCancellationRequested) {
const test = queue.pop()!;
if (request.exclude?.includes(test)) {
run.skipped(test);
continue;
}
run.started(test);
if (test.tags.find((tag) => tag.id === "example")) {
const start = Date.now();
try {
if (!workspace) {
run.errored(test, new vscode.TestMessage("No workspace found"));
continue;
}
const output: string = await this.assertTestPasses(
test,
workspace.workspaceFolder.uri.fsPath,
workspace.ruby.env,
);
run.appendOutput(output.replace(/\r?\n/g, "\r\n"), undefined, test);
run.passed(test, Date.now() - start);
} catch (error: any) {
const err = error as { message: string; killed: boolean };
run.appendOutput(err.message.replace(/\r?\n/g, "\r\n"), undefined, test);
const duration = Date.now() - start;
if (err.killed) {
run.errored(test, new vscode.TestMessage(`Test timed out after ${this.testTimeout} seconds`), duration);
continue;
}
const messageArr = err.message.split("\n");
// Minitest and test/unit outputs are formatted differently so we need to slice the message
// differently to get an output format that only contains essential information
// If the first element of the message array is "", we know the output is a Minitest output
const summary =
messageArr[0] === ""
? messageArr.slice(10, messageArr.length - 2).join("\n")
: messageArr.slice(4, messageArr.length - 9).join("\n");
const messages = [new vscode.TestMessage(err.message), new vscode.TestMessage(summary)];
if (messageArr.find((elem: string) => elem === "F")) {
run.failed(test, messages, duration);
} else {
run.errored(test, messages, duration);
}
}
}
test.children.forEach(enqueue);
}
// Make sure to end the run after all tests have been executed
run.end();
this.telemetry.logUsage("ruby_lsp.code_lens", {
type: "counter",
attributes: { label: "test", vscodemachineid: vscode.env.machineId },
});
}
private async assertTestPasses(test: vscode.TestItem, cwd: string, env: NodeJS.ProcessEnv) {
try {
const result = await asyncExec(this.testCommands.get(test)!, {
cwd,
env,
timeout: this.testTimeout * 1000,
});
return result.stdout;
} catch (error: any) {
if (error.killed) {
throw error;
} else {
throw new Error(error.stdout);
}
}
}
private findTestById(testId: string, testItems: vscode.TestItemCollection = this.testController.items) {
if (!testId) {
return this.findTestByActiveLine();
}
let testItem = testItems.get(testId);
if (testItem) return testItem;
testItems.forEach((test) => {
const childTestItem = this.findTestById(testId, test.children);
if (childTestItem) testItem = childTestItem;
});
return testItem;
}
private findTestByActiveLine(
editor: vscode.TextEditor | undefined = vscode.window.activeTextEditor,
testItems: vscode.TestItemCollection = this.testController.items,
): vscode.TestItem | undefined {
if (!editor) {
return;
}
const line = editor.selection.active.line;
let testItem: vscode.TestItem | undefined;
testItems.forEach((test) => {
if (testItem) return;
const range = test.range;
if (
test.uri?.toString() === editor.document.uri.toString() &&
range &&
range.start.line <= line &&
range.end.line >= line
) {
testItem = test;
}
if (test.children.size > 0) {
const childInRange = this.findTestByActiveLine(editor, test.children);
if (childInRange) {
testItem = childInRange;
}
}
});
return testItem;
}
private async resolveHandler(
item: vscode.TestItem | undefined,
progress?: vscode.Progress<{ message?: string; increment?: number }>,
): Promise<void> {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
return;
}
// If we receive another initial resolve request, but the explorer is already populated, skip
if (item === undefined && this.testController.items.size > 0) {
return;
}
if (item) {
const workspaceFolder = vscode.workspace.getWorkspaceFolder(item.uri!)!;
// If the item is a workspace, then we need to gather all test files inside of it
if (item.tags.some((tag) => tag === WORKSPACE_TAG)) {
await this.gatherWorkspaceTests(workspaceFolder, item);
} else if (!item.tags.some((tag) => tag === TEST_GROUP_TAG)) {
const workspace = await this.getOrActivateWorkspace(workspaceFolder);
if (!workspace.lspClient?.initializeResult?.capabilities.experimental?.full_test_discovery) {
await vscode.window.showWarningMessage(
`The version of the Ruby LSP server being used by ${workspaceFolder.name} does not support the new
test explorer functionality. Please make sure you are using the latest version of the server.
See https://shopify.github.io/ruby-lsp/troubleshooting.html#outdated-version for more information.`,
);
return;
}
const lspClient = workspace.lspClient;
if (lspClient) {
await lspClient.waitForIndexing();
const testItems = await lspClient.discoverTests(item.uri!);
if (testItems) {
this.addDiscoveredItems(testItems, item);
}
}
}
} else if (workspaceFolders.length === 1) {
// If there's only one workspace, there's no point in nesting the tests under the workspace name
await vscode.commands.executeCommand("testing.clearTestResults");