-
Notifications
You must be signed in to change notification settings - Fork 454
Expand file tree
/
Copy pathDotnetCoreAcquisitionExtension.test.ts
More file actions
1139 lines (992 loc) · 61 KB
/
Copy pathDotnetCoreAcquisitionExtension.test.ts
File metadata and controls
1139 lines (992 loc) · 61 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
/*---------------------------------------------------------------------------------------------
* Licensed to the .NET Foundation under one or more agreements.
* The .NET Foundation licenses this file to you under the MIT license.
*--------------------------------------------------------------------------------------------*/
import * as chai from 'chai';
import * as cp from 'child_process';
import { warn } from 'console';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import
{
DotnetCoreDependencyInstaller,
DotnetInstallMode,
DotnetInstallType,
DotnetVersionSpecRequirement,
EnvironmentVariableIsDefined,
FileUtilities,
getDistroInfo,
getDotnetExecutable,
getInstallIdCustomArchitecture,
getLinuxSupportedDotnetSDKVersion,
getMajorMinor,
getMockAcquisitionContext,
getMockAcquisitionWorkerContext,
getMockUtilityContext,
getPathSeparator,
IDotnetAcquireContext,
IDotnetAcquireResult,
IDotnetFindPathContext,
IDotnetListVersionsContext,
IDotnetListVersionsResult,
IDotnetLogResult,
IDotnetSearchContext,
IDotnetSearchResult,
IExistingPaths,
ITelemetryEvent,
LocalMemoryCacheSingleton,
MockEnvironmentVariableCollection,
MockExtensionConfiguration,
MockExtensionContext,
MockTelemetryReporter,
MockWebRequestWorker,
MockWindowDisplayWorker
} from 'vscode-dotnet-runtime-library';
import * as extension from '../../extension';
const assert: any = chai.assert;
const standardTimeoutTime = 40000;
const originalPATH = process.env.PATH;
suite('DotnetCoreAcquisitionExtension End to End', function ()
{
this.retries(1);
const storagePath = path.join(__dirname, 'tmp');
const mockState = new MockExtensionContext();
const extensionPath = path.join(__dirname, '/../../..');
const logPath = path.join(__dirname, 'logs');
const requestingExtensionId = 'fake.extension';
const mockDisplayWorker = new MockWindowDisplayWorker();
let extensionContext: vscode.ExtensionContext;
let skipInstallCleanupAfterTest = false;
const environmentVariableCollection = new MockEnvironmentVariableCollection();
const existingPathVersionToFake = '5.0.1~x64'
const pathWithIncorrectVersionForTest = path.join(__dirname, `/.dotnet/${existingPathVersionToFake}/${getDotnetExecutable()}`);
const mockExistingPathsWithGlobalConfig: IExistingPaths = {
individualizedExtensionPaths: [{ extensionId: 'alternative.extension', path: pathWithIncorrectVersionForTest }],
sharedExistingPath: undefined
}
const mockReleasesData = `{
"releases-index": [
{
"channel-version": "8.0",
"latest-release": "8.0.0-preview.2",
"latest-runtime": "8.0.0-preview.2.23128.3",
"latest-sdk": "8.0.100-preview.2.23157.25",
"release-type" : "lts",
"support-phase": "preview"
},
{
"channel-version": "7.0",
"latest-release": "7.0.4",
"latest-release-date": "2023-03-14",
"latest-runtime": "7.0.4",
"latest-sdk": "7.0.202",
"release-type" : "sts",
"support-phase": "active"
}
]
}`;
this.beforeAll(async () =>
{
extensionContext = {
subscriptions: [],
globalStoragePath: storagePath,
globalState: mockState,
extensionPath,
logPath,
environmentVariableCollection
} as any;
process.env.DOTNET_INSTALL_TOOL_UNDER_TEST = 'true';
extension.ReEnableActivationForManualActivation();
extension.activate(extensionContext, {
telemetryReporter: new MockTelemetryReporter(),
extensionConfiguration: new MockExtensionConfiguration(mockExistingPathsWithGlobalConfig.individualizedExtensionPaths!, true, mockExistingPathsWithGlobalConfig.sharedExistingPath!),
displayWorker: mockDisplayWorker,
});
});
this.afterEach(async () =>
{
// Tear down tmp storage for fresh run
process.env.PATH = originalPATH;
LocalMemoryCacheSingleton.getInstance().invalidate();
if (!skipInstallCleanupAfterTest)
{
await vscode.commands.executeCommand<string>('dotnet.uninstallAll');
}
skipInstallCleanupAfterTest = false;
mockState.clear();
MockTelemetryReporter.telemetryEvents = [];
await new FileUtilities().wipeDirectory(storagePath);
// Do not want cached results from prior tests to interfere
LocalMemoryCacheSingleton.getInstance().invalidate();
}).timeout(standardTimeoutTime);
test('Activate', async () =>
{
// Commands should now be registered
assert.exists(extensionContext);
assert.isAbove(extensionContext.subscriptions.length, 0);
}).timeout(standardTimeoutTime);
test('GlobalState keys are not synced across machines', async () =>
{
// setKeysForSync should have been called with an empty array during activation
// to prevent machine-specific install tracking state from leaking to dev containers
assert.deepEqual((mockState as any).syncedKeys, [], 'setKeysForSync should be called with empty array to prevent syncing install state');
}).timeout(standardTimeoutTime);
test('dotnet.getAcquisitionLog returns the path to the current log file', async () =>
{
const result = await vscode.commands.executeCommand<IDotnetLogResult>('dotnet.getAcquisitionLog');
assert.exists(result, 'dotnet.getAcquisitionLog returns a value');
assert.exists(result!.logPath, 'dotnet.getAcquisitionLog result contains logPath');
assert.isString(result!.logPath, 'dotnet.getAcquisitionLog returns a string logPath');
assert.isTrue(result!.logPath.length > 0, 'dotnet.getAcquisitionLog returns a non-empty path');
// The log file is named like `DotNetAcquisition-<extensionId>-<timestamp>.txt`
// (see EventStreamRegistration.ts). Validate the filename shape so callers know
// they are being handed the acquisition log rather than some other file.
assert.include(path.basename(result!.logPath), 'DotNetAcquisition', 'Returned path points at a DotNetAcquisition log file');
assert.isTrue(result!.logPath.endsWith('.txt'), 'Returned log file has a .txt extension');
// The directory containing the log should exist after activation even if no log
// lines have been flushed yet; ensureDirectory is invoked on flush.
assert.isTrue(fs.existsSync(path.dirname(result!.logPath)), 'Log directory exists');
// Activation performs JSON scanning which should always produce at least one
// log entry, so the file should exist and be non-empty after awaiting flush.
assert.isTrue(fs.existsSync(result!.logPath), 'Log file exists on disk');
const logContents = fs.readFileSync(result!.logPath, 'utf8');
assert.isTrue(logContents.length > 0, 'Log file is non-empty after activation');
}).timeout(standardTimeoutTime);
test('dotnet.ensureDotnetDependencies prompts when dotnet --info fails with a Linux dependency signal', async () =>
{
const originalPlatform = os.platform;
const originalSpawnSync = cp.spawnSync;
const originalSignalCheck = DotnetCoreDependencyInstaller.prototype.signalIndicatesMissingLinuxDependencies;
const originalPromptLinuxDependencyInstall = DotnetCoreDependencyInstaller.prototype.promptLinuxDependencyInstall;
let promptCount = 0;
try
{
skipInstallCleanupAfterTest = true;
Object.defineProperty(os, 'platform', { value: () => 'linux', configurable: true, writable: true });
// Stub the platform-gated signal check rather than mutating the read-only process.platform, so this runs on any OS.
DotnetCoreDependencyInstaller.prototype.signalIndicatesMissingLinuxDependencies = (signal: string) => signal === 'SIGABRT';
Object.defineProperty(cp, 'spawnSync', {
configurable: true,
writable: true,
value: (command: string, args?: string[]) =>
{
assert.equal(command, 'dotnet');
assert.deepEqual(args, ['--info']);
return { signal: 'SIGABRT', stderr: Buffer.from('Couldn\'t find a valid ICU package installed on the system.') };
}
});
DotnetCoreDependencyInstaller.prototype.promptLinuxDependencyInstall = async (message: string) =>
{
assert.equal(message, 'Failed to run .NET runtime.');
promptCount++;
return false;
};
await vscode.commands.executeCommand('dotnet.ensureDotnetDependencies', { command: 'dotnet', arguments: ['--info'] });
assert.equal(promptCount, 1, 'Missing Linux dependency prompt should be shown when dotnet --info aborts.');
}
finally
{
Object.defineProperty(os, 'platform', { value: originalPlatform, configurable: true, writable: true });
Object.defineProperty(cp, 'spawnSync', { value: originalSpawnSync, configurable: true, writable: true });
DotnetCoreDependencyInstaller.prototype.signalIndicatesMissingLinuxDependencies = originalSignalCheck;
DotnetCoreDependencyInstaller.prototype.promptLinuxDependencyInstall = originalPromptLinuxDependencyInstall;
}
}).timeout(standardTimeoutTime);
test('dotnet.ensureDotnetDependencies does not prompt when a dotnet dll payload starts successfully', async () =>
{
const originalPlatform = os.platform;
const originalSpawnSync = cp.spawnSync;
const originalSignalCheck = DotnetCoreDependencyInstaller.prototype.signalIndicatesMissingLinuxDependencies;
const originalPromptLinuxDependencyInstall = DotnetCoreDependencyInstaller.prototype.promptLinuxDependencyInstall;
let promptCount = 0;
try
{
skipInstallCleanupAfterTest = true;
Object.defineProperty(os, 'platform', { value: () => 'linux', configurable: true, writable: true });
// Stub the platform-gated signal check rather than mutating the read-only process.platform, so this runs on any OS.
DotnetCoreDependencyInstaller.prototype.signalIndicatesMissingLinuxDependencies = (signal: string) => signal === 'SIGABRT';
Object.defineProperty(cp, 'spawnSync', {
configurable: true,
writable: true,
value: (command: string, args?: string[]) =>
{
assert.equal(command, 'dotnet');
assert.deepEqual(args, [path.join('server', 'Microsoft.CodeAnalysis.LanguageServer.dll')]);
return { signal: null };
}
});
DotnetCoreDependencyInstaller.prototype.promptLinuxDependencyInstall = async () =>
{
promptCount++;
return false;
};
await vscode.commands.executeCommand('dotnet.ensureDotnetDependencies', {
command: 'dotnet',
arguments: [path.join('server', 'Microsoft.CodeAnalysis.LanguageServer.dll')]
});
assert.equal(promptCount, 0, 'Missing Linux dependency prompt should not be shown when the dotnet dll payload starts.');
}
finally
{
Object.defineProperty(os, 'platform', { value: originalPlatform, configurable: true, writable: true });
Object.defineProperty(cp, 'spawnSync', { value: originalSpawnSync, configurable: true, writable: true });
DotnetCoreDependencyInstaller.prototype.signalIndicatesMissingLinuxDependencies = originalSignalCheck;
DotnetCoreDependencyInstaller.prototype.promptLinuxDependencyInstall = originalPromptLinuxDependencyInstall;
}
}).timeout(standardTimeoutTime);
async function installRuntime(dotnetVersion: string, installMode: DotnetInstallMode, arch?: string)
{
let context: IDotnetAcquireContext = { version: dotnetVersion, requestingExtensionId, mode: installMode };
if (arch)
{
context.architecture = arch;
}
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.exists(result, 'Command results a result');
assert.exists(result!.dotnetPath, 'The return type of the local runtime install command has a .dotnetPath property');
assert.isTrue(fs.existsSync(result!.dotnetPath), 'The returned path of .net does exist');
assert.include(result!.dotnetPath, '.dotnet', '.dotnet is in the path of the local runtime install');
assert.include(result!.dotnetPath, context.version, 'the path of the local runtime install includes the version of the runtime requested');
return result.dotnetPath ?? 'runtimePathNotFound';
}
async function installMultipleVersions(versions: string[], installMode: DotnetInstallMode)
{
let dotnetPaths: string[] = [];
for (const version of versions)
{
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', { version, requestingExtensionId, mode: installMode });
assert.exists(result, 'acquire command returned a result/success');
assert.exists(result!.dotnetPath, 'the result has a path');
assert.include(result!.dotnetPath, version, 'the path includes the version');
if (result!.dotnetPath)
{
dotnetPaths = dotnetPaths.concat(result!.dotnetPath);
}
}
// All versions are still there after all installs are completed
for (const dotnetPath of dotnetPaths)
{
assert.isTrue(fs.existsSync(dotnetPath));
}
}
async function installUninstallOne(dotnetVersion: string, versionToKeep: string, installMode: DotnetInstallMode, type: DotnetInstallType)
{
const context: IDotnetAcquireContext = { version: dotnetVersion, requestingExtensionId, mode: installMode, installType: type };
const contextToKeep: IDotnetAcquireContext = { version: versionToKeep, requestingExtensionId, mode: installMode, installType: type };
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
const resultToKeep = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', contextToKeep);
assert.exists(result?.dotnetPath, 'The install succeeds and returns a path');
assert.exists(resultToKeep?.dotnetPath, 'The 2nd install succeeds and returns a path');
const uninstallResult = await vscode.commands.executeCommand<string>('dotnet.uninstall', context);
assert.equal(uninstallResult, '0', 'Uninstall returns 0');
assert.isFalse(fs.existsSync(result!.dotnetPath), 'the dotnet path result does not exist after uninstall');
assert.isTrue(fs.existsSync(resultToKeep!.dotnetPath), 'Only one thing is uninstalled.');
}
async function installUninstallAll(dotnetVersion: string, installMode: DotnetInstallMode)
{
const context: IDotnetAcquireContext = { version: dotnetVersion, requestingExtensionId, mode: installMode };
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.exists(result);
assert.exists(result!.dotnetPath);
assert.isTrue(fs.existsSync(result!.dotnetPath!));
assert.include(result!.dotnetPath, context.version);
await vscode.commands.executeCommand<string>('dotnet.uninstallAll', context.version);
assert.isFalse(fs.existsSync(result!.dotnetPath), 'the dotnet path result does not exist after uninstall');
}
async function uninstallWithMultipleOwners(dotnetVersion: string, installMode: DotnetInstallMode, type: DotnetInstallType)
{
const context: IDotnetAcquireContext = { version: dotnetVersion, requestingExtensionId, mode: installMode, installType: type };
const contextFromOtherId: IDotnetAcquireContext = { version: dotnetVersion, requestingExtensionId: 'fake.extension.two', mode: installMode, installType: type };
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
const resultToKeep = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', contextFromOtherId);
assert.exists(result?.dotnetPath, 'The install succeeds and returns a path');
assert.equal(result?.dotnetPath, resultToKeep?.dotnetPath, 'The two dupe installs use the same path');
const uninstallResult = await vscode.commands.executeCommand<string>('dotnet.uninstall', context);
assert.equal(uninstallResult, '0', '1st owner Uninstall returns 0');
assert.isTrue(fs.existsSync(resultToKeep!.dotnetPath), 'Nothing is uninstalled without FORCE if theres multiple owners.');
const finalUninstallResult = await vscode.commands.executeCommand<string>('dotnet.uninstall', contextFromOtherId);
assert.equal(finalUninstallResult, '0', '2nd owner Uninstall returns 0');
assert.isFalse(fs.existsSync(result!.dotnetPath), 'the dotnet path result does not exist after uninstalling from all owners');
}
function includesPathWithLikelyDotnet(pathToCheck: string): boolean
{
const lowerPath = pathToCheck.toLowerCase();
return lowerPath.includes('dotnet') || lowerPath.includes('program') || lowerPath.includes('share') || lowerPath.includes('bin') || lowerPath.includes('snap') || lowerPath.includes('homebrew');
}
async function findPathWithRequirementAndInstall(version: string, iMode: DotnetInstallMode, arch: string, condition: DotnetVersionSpecRequirement, shouldFind: boolean, contextToLookFor?: IDotnetAcquireContext, setPath = true,
blockNoArch = false, dontCheckNonPaths = true)
{
const installPath = await installRuntime(version, iMode, arch);
// use path.dirname : the dotnet.exe cant be on the PATH
if (setPath)
{
process.env.PATH = `${path.dirname(installPath)}${getPathSeparator()}${process.env.PATH?.split(getPathSeparator()).filter((x: string) => !(includesPathWithLikelyDotnet(x))).join(getPathSeparator())}`;
}
else
{
// remove dotnet so the test will work on machines with dotnet installed
process.env.PATH = `${process.env.PATH?.split(getPathSeparator()).filter((x: string) => !(includesPathWithLikelyDotnet(x))).join(getPathSeparator())}`;
process.env.DOTNET_ROOT = path.dirname(installPath);
}
extensionContext.environmentVariableCollection.replace('PATH', process.env.PATH ?? '');
if (blockNoArch)
{
extensionContext.environmentVariableCollection.replace('DOTNET_INSTALL_TOOL_DONT_ACCEPT_UNKNOWN_ARCH', '1');
process.env.DOTNET_INSTALL_TOOL_DONT_ACCEPT_UNKNOWN_ARCH = '1';
}
if (dontCheckNonPaths)
{
process.env.DOTNET_INSTALL_TOOL_SKIP_HOSTFXR = 'true';
}
const result: IDotnetAcquireResult = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.findPath',
{
acquireContext: contextToLookFor ?? { version, requestingExtensionId: requestingExtensionId, mode: iMode, architecture: arch } as IDotnetAcquireContext,
versionSpecRequirement: condition
} as IDotnetFindPathContext
);
extensionContext.environmentVariableCollection.replace('DOTNET_INSTALL_TOOL_DONT_ACCEPT_UNKNOWN_ARCH', '0');
process.env.DOTNET_INSTALL_TOOL_DONT_ACCEPT_UNKNOWN_ARCH = '0';
process.env.DOTNET_INSTALL_TOOL_SKIP_HOSTFXR = '0';
if (shouldFind)
{
assert.exists(result.dotnetPath, 'find path command returned a result');
assert.equal(result.dotnetPath.toLowerCase(), installPath.toLowerCase(), 'The path returned by findPath is correct');
}
else
{
assert.equal(result?.dotnetPath, undefined, 'find path command returned no undefined if no path matches condition');
}
}
test('Install Local Runtime Command', async () =>
{
await installRuntime('2.2', 'runtime');
}).timeout(standardTimeoutTime);
test('Install Local ASP.NET Runtime Command', async () =>
{
await installRuntime('7.0', 'aspnetcore');
}).timeout(standardTimeoutTime);
test('Uninstall One Local Runtime Command', async () =>
{
await installUninstallOne('2.2', '7.0', 'runtime', 'local');
}).timeout(standardTimeoutTime);
test('Uninstall One Local ASP.NET Runtime Command', async () =>
{
await installUninstallOne('2.2', '6.0', 'aspnetcore', 'local');
}).timeout(standardTimeoutTime);
test('Uninstall All Local Runtime Command', async () =>
{
await installUninstallAll('2.2', 'runtime')
}).timeout(standardTimeoutTime);
test('Uninstall All Local ASP.NET Runtime Command', async () =>
{
await installUninstallAll('2.2', 'aspnetcore')
}).timeout(standardTimeoutTime);
test('Uninstall Runtime Only Once No Owners Exist', async () =>
{
await uninstallWithMultipleOwners('8.0', 'runtime', 'local');
}).timeout(standardTimeoutTime);
test('Uninstall ASP.NET Runtime Only Once No Owners Exist', async () =>
{
await uninstallWithMultipleOwners('8.0', 'aspnetcore', 'local');
}).timeout(standardTimeoutTime);
test('Install and Uninstall Multiple Local Runtime Versions', async () =>
{
await installMultipleVersions(['2.2', '3.0', '3.1'], 'runtime');
}).timeout(standardTimeoutTime * 2);
test('Install and Uninstall Multiple Local ASP.NET Runtime Versions', async () =>
{
await installMultipleVersions(['2.2', '3.0', '3.1'], 'aspnetcore');
}).timeout(standardTimeoutTime * 2);
test('Works With Prior Incomplete or Corrupted Install', async () =>
{
const installPath = await installRuntime('9.0', 'runtime');
assert.isTrue(fs.existsSync(installPath), 'The path exists after install');
// remove the install executable but not the folder to simulate a corrupt install
fs.rmSync(installPath, { recursive: true, force: true });
assert.isFalse(fs.existsSync(installPath), 'The path does not exist after uninstall');
// try to acquire again, and it should succeed
const _ = await installRuntime('9.0', 'runtime');
}).timeout(standardTimeoutTime);
test('It works if the install exists', async () =>
{
const installPath = await installRuntime('9.0', 'runtime');
const samePath = await installRuntime('9.0', 'runtime');
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Met Condition', async () =>
{
// install 5.0 then look for 5.0 path
await findPathWithRequirementAndInstall('5.0', 'runtime', os.arch(), 'greater_than_or_equal', true);
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Met ROOT Condition', async () =>
{
// install 7.0, set dotnet_root and not path, then look for root
const oldROOT = process.env.DOTNET_ROOT;
await findPathWithRequirementAndInstall('7.0', 'runtime', os.arch(), 'equal', true,
{ version: '7.0', mode: 'runtime', architecture: os.arch(), requestingExtensionId: requestingExtensionId }, false
);
if (EnvironmentVariableIsDefined(oldROOT))
{
process.env.DOTNET_ROOT = oldROOT;
}
else
{
delete process.env.DOTNET_ROOT;
}
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Met Version Condition', async () =>
{
// Install 8.0, look for 3.1 with accepting dotnet gr than or eq to 3.1
await findPathWithRequirementAndInstall('8.0', 'runtime', os.arch(), 'greater_than_or_equal', true,
{ version: '3.1', mode: 'runtime', architecture: os.arch(), requestingExtensionId: requestingExtensionId }
);
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Met Version Condition with Double Digit Major', async () =>
{
await findPathWithRequirementAndInstall('9.0', 'runtime', os.arch(), 'less_than_or_equal', true,
{ version: '11.0', mode: 'runtime', architecture: os.arch(), requestingExtensionId: requestingExtensionId }
);
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Unmet Version Condition', async () =>
{
// Install 9.0, look for 90.0 which is not equal to 9.0
await findPathWithRequirementAndInstall('9.0', 'runtime', os.arch(), 'equal', false,
{ version: '90.0', mode: 'runtime', architecture: os.arch(), requestingExtensionId: requestingExtensionId }
);
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Unmet Mode Condition', async () =>
{
// look for 3.1 runtime but install 3.1 aspnetcore
await findPathWithRequirementAndInstall('3.1', 'runtime', os.arch(), 'equal', false,
{ version: '3.1', mode: 'aspnetcore', architecture: os.arch(), requestingExtensionId: requestingExtensionId }
);
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Unmet Arch Condition', async () =>
{
// look for a different architecture of 3.1
if (os.platform() !== 'darwin')
{
// The CI Machines are running on ARM64 for OS X.
// They also have an x64 HOST. We can't set DOTNET_MULTILEVEL_LOOKUP to 0 because it will break the ability to find the host on --info
// As a 3.1 runtime host does not provide the architecture, but we try to use 3.1 because CI machines won't have it.
//
await findPathWithRequirementAndInstall('3.1', 'runtime', os.arch() == 'arm64' ? 'x64' : os.arch(), 'greater_than_or_equal', false,
{ version: '3.1', mode: 'runtime', architecture: 'arm64', requestingExtensionId: requestingExtensionId }, true, true
);
}
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Unmet Arch Condition With Host that prints Arch', async () =>
{
if (os.platform() !== 'darwin')
{
await findPathWithRequirementAndInstall('9.0', 'runtime', os.arch() == 'arm64' ? 'x64' : os.arch(), 'greater_than_or_equal', false,
{ version: '9.0', mode: 'runtime', architecture: 'arm64', requestingExtensionId: requestingExtensionId }
);
}
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command No Arch Available But Arch Found From File', async () =>
{
// look for a different architecture of 3.1
if (os.platform() !== 'darwin')
{
await findPathWithRequirementAndInstall('3.1', 'runtime', os.arch() == 'arm64' ? 'x64' : os.arch(), 'greater_than_or_equal', false,
{ version: '3.1', mode: 'runtime', architecture: 'arm64', requestingExtensionId: requestingExtensionId }
);
}
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command Unmet Runtime Patch Condition', async () =>
{
// Install 8.0.{LATEST, which will be < 99}, look for 8.0.99 with accepting dotnet gr than or eq to 8.0.99
// No tests for SDK since that's harder to replicate with a global install and different machine states
if (os.platform() !== 'darwin')
{
await findPathWithRequirementAndInstall('8.0', 'runtime', os.arch(), 'greater_than_or_equal', false,
{ version: '8.0.99', mode: 'runtime', architecture: os.arch(), requestingExtensionId: requestingExtensionId }
);
}
}).timeout(standardTimeoutTime);
test('Find dotnet PATH Command does work with extension-managed runtime installations', async () =>
{
// First install a runtime that we'll try to find
const version = '7.0';
const runtimePath = await installRuntime(version, 'runtime', os.arch());
assert.exists(runtimePath, 'Runtime should be installed successfully');
const originalPath = process.env.PATH;
try
{
// Filter PATH to remove any existing dotnet installations
process.env.PATH = process.env.PATH?.split(getPathSeparator())
.filter((x: string) => !(includesPathWithLikelyDotnet(x)))
.join(getPathSeparator());
const findPathContext: IDotnetFindPathContext = {
acquireContext: {
version,
requestingExtensionId,
mode: 'runtime',
architecture: os.arch()
},
versionSpecRequirement: 'latestPatch'
};
// Then verify we can find the extension-managed runtime
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.findPath', findPathContext);
assert.exists(result, 'Should find a runtime');
assert.exists(result!.dotnetPath, 'Should find a runtime path');
assert.equal(result!.dotnetPath.toLowerCase(), runtimePath.toLowerCase(), 'Should find the correct runtime path');
const findPathWithoutLocalLookup = { ...findPathContext, disableLocalLookup: true };
const resultWithoutLocalLookup = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.findPath', findPathWithoutLocalLookup);
assert.notEqual(resultWithoutLocalLookup?.dotnetPath?.toLowerCase(), runtimePath.toLowerCase(), 'Should not find the extension-managed runtime when local lookup is disabled');
}
finally
{
process.env.PATH = originalPath;
}
}).timeout(standardTimeoutTime);
async function runGlobalSdkInstallTest(version: string)
{
const context: IDotnetAcquireContext = { version, requestingExtensionId: 'sample-extension', installType: 'global' };
if (await new FileUtilities().isElevated(getMockAcquisitionWorkerContext(context), getMockUtilityContext()))
{
const originalPath = process.env.PATH;
let result: IDotnetAcquireResult | undefined;
let error: any;
let pathAfterInstall: string | undefined;
process.env.VSCODE_DOTNET_GLOBAL_INSTALL_FAKE_PATH = 'true';
try
{
result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquireGlobalSDK', context);
}
catch (err)
{
error = err;
}
finally
{
pathAfterInstall = process.env.PATH;
process.env.VSCODE_DOTNET_GLOBAL_INSTALL_FAKE_PATH = undefined;
process.env.PATH = originalPath;
}
if (error)
{
throw new Error(`The test failed to run the acquire command successfully for version ${version}. Error: ${error}`);
}
assert.exists(result, `The global acquisition command did not provide a result for version ${version}`);
assert.exists(result!.dotnetPath);
assert.equal(result!.dotnetPath, path.join('fake-sdk', getDotnetExecutable()));
assert.exists(pathAfterInstall, 'The environment variable PATH for DOTNET was not found?');
assert.include(pathAfterInstall!, path.dirname(result!.dotnetPath), 'Is the install directory correctly added to the PATH by the global installer?');
assert.notInclude(pathAfterInstall!, result!.dotnetPath, 'The PATH should contain the install directory, not the dotnet executable file path itself.');
}
else
{
warn('The Global SDK E2E Install test cannot run as the machine is unprivileged.');
}
}
test('Install SDK Globally E2E (Requires Admin)', async () =>
{
await runGlobalSdkInstallTest('7.0.103');
}).timeout(standardTimeoutTime * 1000);
test('Install SDK Globally with major version format', async () =>
{
await runGlobalSdkInstallTest('9');
}).timeout(standardTimeoutTime * 1000);
test('Install SDK Globally with major minor format', async () =>
{
await runGlobalSdkInstallTest('10.0');
}).timeout(standardTimeoutTime * 1000);
test('Install SDK Globally with feature band format', async () =>
{
await runGlobalSdkInstallTest('10.0.1xx');
}).timeout(standardTimeoutTime * 1000);
test('Telemetry Sent During Install and Uninstall', async () =>
{
if (!vscode.env.isTelemetryEnabled)
{
console.warn('The telemetry test cannot run as VS Code Telemetry is disabled in user settings.');
return;
}
const rntVersion = '2.2';
const fullyResolvedVersion = '2.2.8'; // 2.2 is very much out of support, so we don't expect this to change to a newer version
const installId = getInstallIdCustomArchitecture(fullyResolvedVersion, os.arch(), 'runtime', 'local');
const context: IDotnetAcquireContext = { version: rntVersion, requestingExtensionId };
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.exists(result);
assert.exists(result!.dotnetPath);
assert.include(result!.dotnetPath, context.version);
// Check that we got the expected telemetry
const requestedEvent = MockTelemetryReporter.telemetryEvents.find((event: ITelemetryEvent) => event.eventName === 'DotnetAcquisitionRequested');
assert.exists(requestedEvent, 'The acquisition requested event is found');
assert.include(requestedEvent!.properties!.AcquisitionStartVersion, rntVersion, 'The acquisition requested event contains the version');
// assert that the extension id is hashed by checking that it DNE
assert.notInclude(requestedEvent!.properties!.RequestingExtensionId, requestingExtensionId, 'The extension id is hashed in telemetry');
const startedEvent = MockTelemetryReporter.telemetryEvents.find((event: ITelemetryEvent) => event.eventName === 'DotnetAcquisitionStarted');
assert.exists(startedEvent, 'Acquisition started event gets published');
assert.include(startedEvent!.properties!.AcquisitionStartVersion, rntVersion, 'Acquisition started event has a starting version');
assert.include(startedEvent!.properties!.AcquisitionInstallId, installId, 'Acquisition started event has a install key');
const completedEvent = MockTelemetryReporter.telemetryEvents.find((event: ITelemetryEvent) => event.eventName === 'DotnetAcquisitionCompleted');
assert.exists(completedEvent, 'Acquisition completed events exist');
assert.include(completedEvent!.properties!.AcquisitionCompletedVersion, rntVersion, 'Acquisition completed events have a version');
await vscode.commands.executeCommand<string>('dotnet.uninstallAll');
assert.isFalse(fs.existsSync(result!.dotnetPath), 'Dotnet is uninstalled correctly.');
const uninstallStartedEvent = MockTelemetryReporter.telemetryEvents.find((event: ITelemetryEvent) => event.eventName === 'DotnetUninstallAllStarted');
assert.exists(uninstallStartedEvent, 'Uninstall All is reported in telemetry');
const uninstallCompletedEvent = MockTelemetryReporter.telemetryEvents.find((event: ITelemetryEvent) => event.eventName === 'DotnetUninstallAllCompleted');
assert.exists(uninstallCompletedEvent, 'Uninstall All success is reported in telemetry');
// Check that no errors were reported
const errors = MockTelemetryReporter.telemetryEvents.filter((event: ITelemetryEvent) => event.eventName.includes('Error') && event.eventName !== 'CommandExecutionStdError');
assert.isEmpty(errors, `No error events were reported in telemetry reporting. ${JSON.stringify(errors)}`);
}).timeout(standardTimeoutTime);
test('Telemetry Sent on Error', async () =>
{
if (!vscode.env.isTelemetryEnabled)
{
console.warn('The telemetry test cannot run as VS Code Telemetry is disabled in user settings.');
return;
}
const context: IDotnetAcquireContext = { version: 'foo', requestingExtensionId };
try
{
await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.isTrue(false); // An error should have been thrown
} catch (error)
{
const versionError = MockTelemetryReporter.telemetryEvents.find((event: ITelemetryEvent) => event.eventName === '[ERROR]:DotnetVersionResolutionError');
assert.exists(versionError, 'The version resolution error appears in telemetry');
}
}).timeout(standardTimeoutTime / 2);
test('Install Local Runtime Command Passes With Warning With No RequestingExtensionId', async () =>
{
const context: IDotnetAcquireContext = { version: '3.1' };
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.exists(result, 'A result from the API exists');
assert.exists(result!.dotnetPath, 'The result has a dotnet path');
assert.include(result!.dotnetPath, context.version, 'The version is included in the path');
assert.include(mockDisplayWorker.warningMessage, 'Ignoring existing .NET paths');
}).timeout(standardTimeoutTime);
test('Install Local Runtime Command With Path Settings', async () =>
{
let clearedFolder = false;
if (fs.existsSync(path.dirname(pathWithIncorrectVersionForTest)))
{
// Delete the test folder so it doesn't exist from any old test run
fs.rmSync(path.dirname(pathWithIncorrectVersionForTest), { recursive: true, force: true });
clearedFolder = true;
}
assert.isEmpty(fs.existsSync(path.dirname(pathWithIncorrectVersionForTest)) ? fs.readdirSync(path.dirname(pathWithIncorrectVersionForTest)) : [], `Test setup: cleared folder ${clearedFolder}?
the fake dotnet path setting is an empty dir -- if it is not empty, test cleanup must not work properly.`);
// acquire with the alternative extension id which has a path setting set to the fake path
// If the setting is bad then it should also acquire somewhere else.
const context: IDotnetAcquireContext = { version: '5.0', requestingExtensionId: 'alternative.extension', architecture: os.arch() };
const resultForAcquiringPathSettingRuntime = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.exists(resultForAcquiringPathSettingRuntime!.dotnetPath, 'Basic acquire works');
// The runtime setting on the path needs to be a match for a runtime but also a different folder name
// so that we can tell the setting was used. We cant tell it to install an older besides latest,
// but we can rename the folder then re-acquire for latest and see that it uses the existing 'older' runtime path
assert.notEqual(path.dirname(resultForAcquiringPathSettingRuntime.dotnetPath), path.dirname(pathWithIncorrectVersionForTest), `Test setup: path setting is different from the path acquire chose when the setting is enabled but nothing exists there.
File system at ${pathWithIncorrectVersionForTest}: ${fs.existsSync(path.dirname(pathWithIncorrectVersionForTest)) ?
fs.readdirSync(path.dirname(pathWithIncorrectVersionForTest)) : 'empty'}.
Paths: 'acquire returned: ${resultForAcquiringPathSettingRuntime.dotnetPath} while the fake setting is ${pathWithIncorrectVersionForTest}`);
// Copy the real install to the fake install directory with a differnt version
fs.cpSync(path.dirname(resultForAcquiringPathSettingRuntime.dotnetPath), path.dirname(pathWithIncorrectVersionForTest), { recursive: true });
assert.isTrue(fs.existsSync(path.dirname(pathWithIncorrectVersionForTest)), 'The copy of the real dotnet to the new wrong-versioned path succeeded');
// Delete the actual install that was done so it looks like it was correctly installed to the fake location
fs.rmSync(resultForAcquiringPathSettingRuntime.dotnetPath, { recursive: true, force: true });
assert.isTrue(!fs.existsSync(resultForAcquiringPathSettingRuntime.dotnetPath), 'The deletion of the acquired install path succeeded');
assert.isTrue(fs.existsSync(path.dirname(pathWithIncorrectVersionForTest)), 'The copy of the real dotnet to the new wrong-versioned path was not deleted');
// Call Acquire on the alternative extension to cause it to return the path setting
LocalMemoryCacheSingleton.getInstance().invalidate();
const result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.exists(result, 'returns a result with path setting');
assert.exists(result!.dotnetPath, 'path setting has a path in its object');
assert.equal(result!.dotnetPath, pathWithIncorrectVersionForTest, 'path setting is used'); // this is set for the alternative.extension in the settings
// check that find path uses the setting
LocalMemoryCacheSingleton.getInstance().invalidate();
const findPath = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.findPath', { acquireContext: Object.assign({}, context, { mode: 'runtime' }), versionSpecRequirement: 'equal' });
assert.equal(findPath!.dotnetPath, pathWithIncorrectVersionForTest, 'findPath uses vscode setting for runtime'); // this is set for the alternative.extension in the settings
// check that find path does not use the setting even if its set because it should not use the wrong thing that does not meet the condition
const findSDKPath = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.findPath', { acquireContext: Object.assign({}, context, { mode: 'sdk' }), versionSpecRequirement: 'equal' });
assert.equal(findSDKPath?.dotnetPath ?? undefined, undefined, 'findPath does not find path setting for the SDK');
}).timeout(standardTimeoutTime * 3);
test('List Sdks & Runtimes', async () =>
{
const mockAcquisitionContext = getMockAcquisitionContext('sdk', '');
const webWorker = new MockWebRequestWorker();
webWorker.response = JSON.parse(mockReleasesData);
// The API can find the available SDKs and list their versions.
const apiContext: IDotnetListVersionsContext = { listRuntimes: false };
const result = await vscode.commands.executeCommand<IDotnetListVersionsResult>('dotnet.listVersions', apiContext, webWorker);
assert.exists(result);
assert.equal(result?.length, 2, `It can find both versions of the SDKs. Found: ${result}`);
assert.equal(result?.filter((sdk: any) => sdk.version === '7.0.202').length, 1, 'The mock SDK with the expected version {7.0.200} was not found by the API parsing service.');
assert.equal(result?.filter((sdk: any) => sdk.channelVersion === '7.0').length, 1, 'The mock SDK with the expected channel version {7.0} was not found by the API parsing service.');
assert.equal(result?.filter((sdk: any) => sdk.supportPhase === 'active').length, 1, 'The mock SDK with the expected support phase of {active} was not found by the API parsing service.');
// The API can find the available runtimes and their versions.
apiContext.listRuntimes = true;
const runtimeResult = await vscode.commands.executeCommand<IDotnetListVersionsResult>('dotnet.listVersions', apiContext, webWorker);
assert.exists(runtimeResult);
assert.equal(runtimeResult?.length, 2, `It can find both versions of the runtime. Found: ${result}`);
assert.equal(runtimeResult?.filter((runtime: any) => runtime.version === '7.0.4').length, 1, 'The mock Runtime with the expected version was not found by the API parsing service.');
}).timeout(standardTimeoutTime);
test('Get Recommended SDK Version', async () =>
{
const mockAcquisitionContext = getMockAcquisitionContext('sdk', '');
const webWorker = new MockWebRequestWorker();
webWorker.response = JSON.parse(mockReleasesData);
const result = await vscode.commands.executeCommand<IDotnetListVersionsResult>('dotnet.recommendedVersion', { listRuntimes: false } as IDotnetListVersionsContext, webWorker);
assert.exists(result);
assert.exists(result[0]);
if (os.platform() !== 'linux')
{
assert.equal(result[0].version, '7.0.202', 'The SDK did not recommend the version it was supposed to, which should be {7.0.200} from the mock data.');
}
else
{
const recLinuxVersionFull = getMajorMinor(await getLinuxSupportedDotnetSDKVersion(mockAcquisitionContext), mockAcquisitionContext.eventStream, mockAcquisitionContext)
assert.equal(result[0].version, `${recLinuxVersionFull}.1xx`, `The SDK did not recommend the version (it said ${result[0].version}) it was supposed to, which should be N.0.1xx based on surface level distro knowledge, version ${JSON.stringify(await getDistroInfo(mockAcquisitionContext))}. If a new version is available, this test may need to be updated to the newest version.`);
}
}).timeout(standardTimeoutTime);
test('dotnet.availableInstalls API works after acquiring a runtime', async () =>
{
// Acquire a runtime
const runtimeContext: IDotnetAcquireContext = { version: '6.0', requestingExtensionId, mode: 'runtime' };
const acquireResult = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', runtimeContext);
assert.exists(acquireResult, 'The acquire command should return a result');
assert.exists(acquireResult!.dotnetPath, 'The acquire command should return a valid dotnet path');
// Call dotnet.availableInstalls API
const availableInstalls = await vscode.commands.executeCommand<IDotnetSearchResult[]>('dotnet.availableInstalls',
{
dotnetExecutablePath: acquireResult!.dotnetPath,
mode: 'runtime',
requestingExtensionId,
architecture: os.arch()
} as IDotnetSearchContext
);
assert.exists(availableInstalls, 'The availableInstalls API should return a result');
assert.isArray(availableInstalls, 'The availableInstalls API should return an array');
assert.isTrue(availableInstalls!.some(install => install.version.includes('6')), 'The acquired runtime should be listed in available installs');
}).timeout(standardTimeoutTime);
test('dotnet.availableInstalls API checks system dotnet if no path is provided', async () =>
{
// Call dotnet.availableInstalls API without providing a dotnet path
const availableInstalls = await vscode.commands.executeCommand<IDotnetSearchResult[]>('dotnet.availableInstalls', {
mode: 'runtime',
requestingExtensionId
});
assert.exists(availableInstalls, 'The availableInstalls API should return a result');
assert.isArray(availableInstalls, 'The availableInstalls API should return an array');
// Validate the output (system may or may not have installs)
if (availableInstalls!.length > 0)
{
assert.exists(availableInstalls![0].version, 'The first install should have a version');
assert.exists(availableInstalls![0].directory, 'The first install should have a directory');
} else
{
assert.isTrue(availableInstalls!.length === 0, 'No installs found on the system');
}
}).timeout(standardTimeoutTime);
test('dotnet.availableInstalls only falls back to findPath when fallbackToFindPathInstalls is set', async () =>
{
// Install a runtime so there is a real host to discover, then arrange for that host to be off the PATH
// (as happens on macOS GUI launches) while still being discoverable via DOTNET_ROOT. This lets us prove
// that the findPath fallback is what recovers the install, and that it only runs when opted in.
const installPath = await installRuntime('6.0', 'runtime', os.arch());
const originalPath = process.env.PATH;
const originalDotnetRoot = process.env.DOTNET_ROOT;
const originalSkipHostfxr = process.env.DOTNET_INSTALL_TOOL_SKIP_HOSTFXR;
try
{
// Remove dotnet from the PATH so the default (PATH-based) search finds nothing on the first try.
process.env.PATH = process.env.PATH?.split(getPathSeparator())
.filter((x: string) => !(includesPathWithLikelyDotnet(x)))
.join(getPathSeparator());
extensionContext.environmentVariableCollection.replace('PATH', process.env.PATH ?? '');
// findPath can still locate the host independently of the PATH via DOTNET_ROOT.
process.env.DOTNET_ROOT = path.dirname(installPath);
// Avoid depending on machine-wide hostfxr records so the result is deterministic across environments.
process.env.DOTNET_INSTALL_TOOL_SKIP_HOSTFXR = 'true';
// Without opting in, the API must not fall back and therefore finds nothing (host is not on the PATH).
const withoutFallback = await vscode.commands.executeCommand<IDotnetSearchResult[]>('dotnet.availableInstalls', {
mode: 'runtime',
requestingExtensionId,
fallbackToFindPathInstalls: false
} as IDotnetSearchContext);
assert.isArray(withoutFallback, 'The availableInstalls API should return an array');
assert.equal(withoutFallback!.length, 0, 'Without the fallback, no installs should be found when the host is not on the PATH');
// With the opt-in, the API falls back to findPath (which locates the host via DOTNET_ROOT) and finds installs.
const withFallback = await vscode.commands.executeCommand<IDotnetSearchResult[]>('dotnet.availableInstalls', {
mode: 'runtime',
requestingExtensionId,
fallbackToFindPathInstalls: true
} as IDotnetSearchContext);
assert.isArray(withFallback, 'The availableInstalls API should return an array');
assert.isTrue(withFallback!.length > 0, 'With the fallback enabled, the findPath logic should recover the install');
assert.isTrue(withFallback!.some(install => install.version.includes('6')), 'The acquired 6.0 runtime should be listed via the fallback');
}
finally
{
process.env.PATH = originalPath;
extensionContext.environmentVariableCollection.replace('PATH', originalPath ?? '');
process.env.DOTNET_ROOT = originalDotnetRoot;
process.env.DOTNET_INSTALL_TOOL_SKIP_HOSTFXR = originalSkipHostfxr;
}
}).timeout(standardTimeoutTime);
async function testAcquire(installMode: DotnetInstallMode)
{
// Runtime is not yet installed
const context: IDotnetAcquireContext = { version: '3.1', requestingExtensionId, mode: installMode };
let result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquireStatus', context);
assert.notExists(result);
// Install runtime
result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquire', context);
assert.exists(result);
assert.exists(result!.dotnetPath);
assert.isTrue(fs.existsSync(result!.dotnetPath!));
// Runtime has been installed
result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquireStatus', context);
assert.exists(result);
assert.exists(result!.dotnetPath);
assert.isTrue(fs.existsSync(result!.dotnetPath!));
await fs.promises.rm(result!.dotnetPath!, { force: true });
}
test('Install Runtime Status Command', async () =>
{
await testAcquire('runtime');
}).timeout(standardTimeoutTime);
test('acquireStatus can work Offline', async () =>
{
const availableVersion = '8.0';
try
{
await installRuntime(availableVersion, 'runtime');
// Simulate offline mode by not allowing network requests
process.env.DOTNET_INSTALL_TOOL_OFFLINE = '1';
const context: IDotnetAcquireContext = { version: availableVersion, requestingExtensionId, mode: 'runtime' };
let result = await vscode.commands.executeCommand<IDotnetAcquireResult>('dotnet.acquireStatus', context);
assert.isDefined(result, 'acquireStatusResult should be defined');
assert.include(result!.dotnetPath, availableVersion, 'acquireStatusResult should contain the expected version in the path');
}
finally
{
process.env.DOTNET_INSTALL_TOOL_OFFLINE = undefined
}
}).timeout(standardTimeoutTime);
test('Install Aspnet runtime Status Command', async () =>
{
await testAcquire('aspnetcore');
}).timeout(standardTimeoutTime);