-
Notifications
You must be signed in to change notification settings - Fork 454
Expand file tree
/
Copy pathMockObjects.ts
More file actions
847 lines (736 loc) · 29.2 KB
/
Copy pathMockObjects.ts
File metadata and controls
847 lines (736 loc) · 29.2 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
/*---------------------------------------------------------------------------------------------
* Licensed to the .NET Foundation under one or more agreements.
* The .NET Foundation licenses this file to you under the MIT license.
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import * as path from 'path';
import { AcquisitionInvoker } from '../../Acquisition/AcquisitionInvoker';
import { DotnetCoreAcquisitionWorker } from '../../Acquisition/DotnetCoreAcquisitionWorker';
import { DotnetInstall, GetDotnetInstallInfo } from '../../Acquisition/DotnetInstall';
import { DotnetInstallMode } from '../../Acquisition/DotnetInstallMode';
import { GenericDistroSDKProvider } from '../../Acquisition/GenericDistroSDKProvider';
import { IAcquisitionInvoker } from '../../Acquisition/IAcquisitionInvoker';
import { IAcquisitionWorkerContext } from '../../Acquisition/IAcquisitionWorkerContext';
import { IDistroDotnetSDKProvider } from '../../Acquisition/IDistroDotnetSDKProvider';
import { IDotnetInstallationContext } from '../../Acquisition/IDotnetInstallationContext';
import { IInstallationValidator } from '../../Acquisition/IInstallationValidator';
import { InstallScriptAcquisitionWorker } from '../../Acquisition/InstallScriptAcquisitionWorker';
import { InstallTrackerSingleton } from '../../Acquisition/InstallTrackerSingleton';
import { DistroVersionPair, DotnetDistroSupportStatus } from '../../Acquisition/LinuxVersionResolver';
import { VersionResolver } from '../../Acquisition/VersionResolver';
import { IEventStream } from '../../EventStream/EventStream';
import { CommandExecutionEvent, DotnetAcquisitionCompleted, EventBasedError, TestAcquireCalled } from '../../EventStream/EventStreamEvents';
import { IEvent } from '../../EventStream/IEvent';
import { ILoggingObserver } from '../../EventStream/ILoggingObserver';
import { ITelemetryReporter } from '../../EventStream/TelemetryObserver';
import { IExtensionConfiguration, ILocalExistingPath } from '../../IExtensionContext';
import { IExtensionState } from '../../IExtensionState';
import { IVSCodeExtensionContext } from '../../IVSCodeExtensionContext';
import { CommandExecutor } from '../../Utils/CommandExecutor';
import { CommandExecutorCommand } from '../../Utils/CommandExecutorCommand';
import { CommandExecutorResult } from '../../Utils/CommandExecutorResult';
import { FileUtilities } from '../../Utils/FileUtilities';
import { ICommandExecutor } from '../../Utils/ICommandExecutor';
import { IFileUtilities } from '../../Utils/IFileUtilities';
import { IUtilityContext } from '../../Utils/IUtilityContext';
import { IVSCodeEnvironment } from '../../Utils/IVSCodeEnvironment';
import { INodeIPCMutexLogger, NodeIPCMutex } from '../../Utils/NodeIPCMutex';
import { getDotnetExecutable } from '../../Utils/TypescriptUtilities';
import { WebRequestWorkerSingleton } from '../../Utils/WebRequestWorkerSingleton';
import { getMockUtilityContext } from '../unit/TestUtility';
const testDefaultTimeoutTimeMs = 60000;
/**
* A NodeIPCMutex that lets tests override the IPC directory so they can use a directory they fully
* own and can chmod freely (or an unwritable one like "/") to produce REAL bind/listen errors from
* the kernel — no synthetic error injection.
*/
export class MockNodeIPCMutex extends NodeIPCMutex
{
private readonly customDirectory?: string;
constructor(lockId: string, logger: INodeIPCMutexLogger, customDirectory?: string, lockFailureErrorMessage?: string)
{
// Temporarily stash the directory so the parent ctor (which resolves the lock path before any
// subclass field is set) can read it via our overridden getIPCDirectory().
// We cannot set `this.customDirectory` before `super()` in TypeScript, so route through a module-level holder.
MockNodeIPCMutex.pendingDirectory = customDirectory;
super(lockId, logger, lockFailureErrorMessage);
this.customDirectory = customDirectory;
MockNodeIPCMutex.pendingDirectory = undefined;
}
private static pendingDirectory: string | undefined;
protected override getIPCDirectory(): string
{
const dir = this.customDirectory ?? MockNodeIPCMutex.pendingDirectory;
return dir ?? super.getIPCDirectory();
}
public getLockPathForTest(): string
{
return this.lockPath;
}
}
export class MockExtensionContext implements IExtensionState
{
private values: { [n: string]: any; } = {};
public syncedKeys: readonly string[] | undefined = undefined;
public get<T>(key: string): T | undefined;
public get<T>(key: string, defaultValue: T): T;
public get(key: any, defaultValue?: any)
{
let value = this.values![key];
if (typeof value === 'undefined')
{
value = defaultValue;
}
return value;
}
public update(key: string, value: any): Thenable<void>
{
return this.values[key] = value;
}
public setKeysForSync(keys: readonly string[]): void
{
this.syncedKeys = keys;
}
public clear()
{
this.values = {};
}
public keys(): readonly string[]
{
return Object.keys(this.values);
}
}
export class MockEventStream implements IEventStream
{
public events: IEvent[] = [];
public post(event: IEvent)
{
this.events = this.events.concat(event);
}
}
export class NoInstallAcquisitionInvoker extends IAcquisitionInvoker
{
constructor(eventStream: IEventStream, worker: MockDotnetCoreAcquisitionWorker, private readonly workerContext: IAcquisitionWorkerContext, private readonly path: string)
{
super(eventStream);
worker.enableNoInstallInvoker();
}
public installDotnet(install: DotnetInstall): Promise<void>
{
const testInstallContext = {
version: install.version,
installMode: install.installMode,
architecture: install.architecture ?? 'null',
dotnetPath: path.join(this.path, getDotnetExecutable()) ?? path.join(this.workerContext.installDirectoryProvider.getInstallDir(install.installId), getDotnetExecutable()),
installDir: this.path ?? this.workerContext.installDirectoryProvider.getInstallDir(install.installId),
installType: install.isGlobal ? 'global' : 'local',
timeoutSeconds: testDefaultTimeoutTimeMs,
} as IDotnetInstallationContext
return new Promise<void>((resolve, reject) =>
{
this.eventStream.post(new TestAcquireCalled(testInstallContext));
const install = GetDotnetInstallInfo(testInstallContext.version, testInstallContext.installMode, 'local', testInstallContext.architecture ?? 'null')
this.eventStream.post(new DotnetAcquisitionCompleted(
install, testInstallContext.dotnetPath, testInstallContext.version));
resolve();
});
}
}
export class MockDotnetCoreAcquisitionWorker extends DotnetCoreAcquisitionWorker
{
public constructor(utilityContext: IUtilityContext, extensionContext: IVSCodeExtensionContext)
{
super(utilityContext, extensionContext);
}
public enableNoInstallInvoker()
{
this.usingNoInstallInvoker = true;
}
}
export class RejectingAcquisitionInvoker extends IAcquisitionInvoker
{
public installDotnet(install: DotnetInstall): Promise<void>
{
return new Promise<void>((resolve, reject) =>
{
reject('Rejecting message');
});
}
}
export class ErrorAcquisitionInvoker extends IAcquisitionInvoker
{
public installDotnet(install: DotnetInstall): Promise<void>
{
throw new EventBasedError('MockErrorAcquisitionInvokerFailure', 'Command Failed');
}
}
// Major.Minor-> Major.Minor.Patch from mock releases.json
export const versionPairs = [['1.0', '1.0.16'], ['1.1', '1.1.13'], ['2.0', '2.0.9'], ['2.1', '2.1.14'], ['2.2', '2.2.8']];
export class FileWebRequestWorker extends WebRequestWorkerSingleton
{
constructor(private readonly mockFilePath: string)
{
super();
const _ = WebRequestWorkerSingleton.getInstance(); // cause super to exist
}
protected async makeWebRequest(uri: string, ctx: IAcquisitionWorkerContext): Promise<string | undefined>
{
const result = JSON.parse(fs.readFileSync(this.mockFilePath, 'utf8'));
return result;
}
}
export class FailingWebRequestWorker extends WebRequestWorkerSingleton
{
constructor()
{
// Use Empty strings as uri to cause failure. Uri is required to match the interface even though it's unused.
super();
const _ = WebRequestWorkerSingleton.getInstance(); // cause super to exist
}
public async getCachedData(uri: string, ctx: IAcquisitionWorkerContext): Promise<string | undefined>
{
throw new Error('Fail!');
}
public async makeWebRequest(uri: string, ctx: IAcquisitionWorkerContext): Promise<string | undefined>
{
return super.makeWebRequest('', ctx, true, 0);
}
public async downloadFile(url: string, dest: string, ctx: IAcquisitionWorkerContext): Promise<void>
{
return super.downloadFile('', dest, ctx);
}
}
export class MockTrackingWebRequestWorker extends WebRequestWorkerSingleton
{
private requestCount = 0;
public response = 'Mock Web Request Result';
constructor(protected readonly succeed = true)
{
super();
const _ = WebRequestWorkerSingleton.getInstance(); // cause super to exist
}
public getRequestCount()
{
return this.requestCount;
}
public incrementRequestCount()
{
this.requestCount++;
}
protected async makeWebRequest(url: string, ctx: IAcquisitionWorkerContext, shouldThrow = false, retries = 2, requestOptions?: object): Promise<string | undefined>
{
if (!(await this.isUrlCached(url, ctx)))
{
this.incrementRequestCount();
}
return super.makeWebRequest(url, ctx, shouldThrow, retries, requestOptions);
}
}
export class MockWebRequestWorker extends MockTrackingWebRequestWorker
{
public readonly errorMessage = 'Web Request Failed';
public response = 'Mock Web Request Result';
constructor()
{
super();
const _ = WebRequestWorkerSingleton.getInstance(); // cause super to exist
}
protected async makeWebRequest(): Promise<string | undefined>
{
this.incrementRequestCount()
if (this.succeed)
{
try // axios will return a json object instead of a string if the object is json. mimic this.
{
JSON.parse(this.response);
}
catch (e)
{
return this.response;
}
} else
{
throw new Error(this.errorMessage);
}
}
}
export class MockIndexWebRequestWorker extends WebRequestWorkerSingleton
{
public knownUrls = ['Mock Web Request Result'];
public matchingUrlResponses = [
``
];
constructor(protected readonly succeed = true)
{
super();
const _ = WebRequestWorkerSingleton.getInstance(); // cause super to exist
}
public async getCachedData(url: string, ctx: IAcquisitionWorkerContext, retriesCount = 2): Promise<string | undefined>
{
const urlResponseIndex = this.knownUrls.indexOf(url);
if (urlResponseIndex === -1)
{
throw Error(`The requested URL ${url} was not expected as the mock object did not have a set response for it.`)
}
return JSON.parse(this.matchingUrlResponses[urlResponseIndex]);
}
}
export class MockVSCodeExtensionContext extends IVSCodeExtensionContext
{
registerOnExtensionChange<A extends any[], R>(f: (...args: A) => R, ...args: A): void
{
f(...args);
}
getExtensions(): readonly any[]
{
return [{ extensionId: 'test' }];
}
executeCommand(command: string, ...args: any[]): Thenable<any>
{
return Promise.resolve({});
}
appendToEnvironmentVariable(variable: string, pathAdditionWithDelimiter: string): void
{
// Do nothing.
}
setVSCodeEnvironmentVariable(variable: string, value: string): void
{
// Do nothing.
}
}
export class MockVSCodeEnvironment extends IVSCodeEnvironment
{
isTelemetryEnabled(): boolean
{
return true;
}
}
export class MockVersionResolver extends VersionResolver
{
private readonly filePath = path.join(__dirname, '../../..', 'src', 'test', 'mocks', 'mock-releases.json');
constructor(ctx: IAcquisitionWorkerContext)
{
super(ctx);
this.webWorker = new FileWebRequestWorker(this.filePath);
}
}
export class MockInstallScriptWorker extends InstallScriptAcquisitionWorker
{
constructor(ctx: IAcquisitionWorkerContext, private failing: boolean, private fallback = false)
{
super(ctx);
this.webWorker = failing ?
new FailingWebRequestWorker() :
new MockWebRequestWorker();
}
protected getFallbackScriptPath(): string
{
if (this.fallback)
{
return path.join(__dirname, '..');
}
else
{
if (this.failing)
{
throw new Error('Failed to Acquire Dotnet Install Script');
}
return super.getFallbackScriptPath();
}
}
}
export class MockApostropheScriptAcquisitionWorker extends MockInstallScriptWorker
{
protected readonly scriptFilePath: string;
constructor(ctx: IAcquisitionWorkerContext, installFolder: string)
{
super(ctx, false);
const scriptFileEnding = 'win32';
const scriptFileName = 'dotnet-install';
this.scriptFilePath = path.join(installFolder, 'install scripts', `${scriptFileName}.${scriptFileEnding}`);
}
}
export class MockAcquisitionInvoker extends AcquisitionInvoker
{
protected readonly scriptWorker: MockApostropheScriptAcquisitionWorker
constructor(ctx: IAcquisitionWorkerContext, installFolder: string)
{
super(ctx, getMockUtilityContext());
this.scriptWorker = new MockApostropheScriptAcquisitionWorker(ctx, installFolder);
}
}
/**
* @remarks does NOT run the commands (if they have sudo), but records them to verify the correct command should've been run.
*/
export class MockCommandExecutor extends ICommandExecutor
{
private trueExecutor: CommandExecutor;
public fakeReturnValue = { status: '', stderr: '', stdout: '' };
public attemptedCommand = '';
private readonly acquisitionContext: IAcquisitionWorkerContext;
// If you expect several commands to be run and want to specify unique outputs for each, describe them in the same order using the below two arrays.
// We will check for an includes match and not an exact match!
public otherCommandPatternsToMock: string[] = [];
public otherCommandsReturnValues: CommandExecutorResult[] = [];
public workingCommandIndex: number | null = 0;
public capturedCommands: CommandExecutorCommand[] = [];
public capturedOptions: any;
constructor(acquisitionContext: IAcquisitionWorkerContext, utilContext: IUtilityContext)
{
super(acquisitionContext, utilContext);
this.acquisitionContext = acquisitionContext;
this.trueExecutor = new CommandExecutor(acquisitionContext, utilContext);
}
public async execute(command: CommandExecutorCommand, options: object | null = null, terminalFailure?: boolean): Promise<CommandExecutorResult>
{
this.attemptedCommand = CommandExecutor.prettifyCommandExecutorCommand(command);
this.acquisitionContext.eventStream.post(new CommandExecutionEvent(`Executing command: ${this.attemptedCommand}`));
for (let i = 0; i < this.otherCommandPatternsToMock.length; ++i)
{
const commandPatternToLookFor = this.otherCommandPatternsToMock[i];
if (command.commandRoot.includes(commandPatternToLookFor) ||
command.commandParts.some((arg) => commandPatternToLookFor.includes(arg)))
{
let indexOfExactMatch = this.otherCommandPatternsToMock.indexOf(this.attemptedCommand);
if (indexOfExactMatch === -1)
{
indexOfExactMatch = this.otherCommandPatternsToMock.indexOf(command.commandParts.join(' '));
}
if (indexOfExactMatch !== -1)
{
// If we have an exact match, return the value for that command.
return this.otherCommandsReturnValues[indexOfExactMatch];
}
return this.otherCommandsReturnValues[i];
}
}
if (this.shouldActuallyExecuteCommand(command))
{
return this.trueExecutor.execute(command, options, terminalFailure);
}
return this.fakeReturnValue;
}
public async executeMultipleCommands(commands: CommandExecutorCommand[], options?: any, terminalFailure?: boolean): Promise<CommandExecutorResult[]>
{
const result = [];
for (const command of commands)
{
result.push(await this.execute(command, options, terminalFailure));
}
return result;
}
public async tryFindWorkingCommand(commands: CommandExecutorCommand[], options?: any): Promise<CommandExecutorCommand | null>
{
this.capturedCommands = commands;
this.capturedOptions = options;
if (this.workingCommandIndex === null)
{
return null;
}
return commands[this.workingCommandIndex];
}
/**
* @remarks For commands which do not edit the global system state or we don't need to mock their data, we can just execute them
* with a real command executor to provide better code coverage.
*/
private shouldActuallyExecuteCommand(command: CommandExecutorCommand): boolean
{
return !command.runUnderSudo && this.fakeReturnValue.status === '' && this.fakeReturnValue.stderr === '' && this.fakeReturnValue.stdout === '';
}
public resetReturnValues()
{
this.fakeReturnValue = { status: '', stderr: '', stdout: '' };
this.attemptedCommand = '';
this.otherCommandPatternsToMock = [];
this.otherCommandsReturnValues = [];
this.workingCommandIndex = 0;
this.capturedCommands = [];
this.capturedOptions = undefined;
}
public async setEnvironmentVariable(variable: string, value: string, vscodeContext: IVSCodeExtensionContext, failureWarningMessage?: string, nonWinFailureMessage?: string)
{
return this.trueExecutor.setEnvironmentVariable(variable, value, vscodeContext, failureWarningMessage, nonWinFailureMessage);
}
}
export class MockFileUtilities extends IFileUtilities
{
private trueUtilities = new FileUtilities();
public filePathsAndExistValues: { [filePath: string]: boolean; } = {};
public filePathsAndReadValues: { [filePath: string]: string; } = {};
public writeFileOntoDisk(content: string, filePath: string)
{
return this.trueUtilities.writeFileOntoDisk(content, filePath, new MockEventStream());
}
public wipeDirectory(directoryToWipe: string, eventSteam: IEventStream, fileExtensionsToDelete?: string[], verifyDotnetNotInUse?: boolean)
{
return this.trueUtilities.wipeDirectory(directoryToWipe, eventSteam, fileExtensionsToDelete);
}
public isElevated(context: IAcquisitionWorkerContext, utilContext: IUtilityContext)
{
return this.trueUtilities.isElevated(context, utilContext);
}
public async getFileHash(filePath: string)
{
return '';
}
public async exists(filePath: string)
{
return this.filePathsAndExistValues[filePath] || new FileUtilities().exists(filePath);
}
public async read(filePath: string): Promise<string>
{
return this.filePathsAndReadValues[filePath] || '';
}
public async realpath(filePath: string): Promise<string | null>
{
return this.filePathsAndReadValues[filePath] || new FileUtilities().realpath(filePath);
}
}
/**
* @remarks does NOT run the commands (if they have sudo), but records them to verify the correct command should've been run.
*/
export class MockDistroProvider extends IDistroDotnetSDKProvider
{
public installReturnValue = '';
public installedSDKsReturnValue = [];
public installedRuntimesReturnValue: string[] = [];
public globalPathReturnValue: string | null = '';
public globalVersionReturnValue: string | null = '';
public distroFeedReturnValue = '';
public microsoftFeedReturnValue = '';
public packageExistsReturnValue = false;
public supportStatusReturnValue: DotnetDistroSupportStatus = DotnetDistroSupportStatus.Distro;
public recommendedVersionReturnValue = '';
public upgradeReturnValue = '';
public uninstallReturnValue = '';
public versionPackagesReturnValue = [];
public context: IAcquisitionWorkerContext;
constructor(version: DistroVersionPair, context: IAcquisitionWorkerContext, utilContext: IUtilityContext, commandRunner: ICommandExecutor)
{
super(version, context, utilContext, commandRunner);
this.context = context;
}
public installDotnet(fullySpecifiedVersion: string): Promise<string>
{
this.commandRunner.execute(CommandExecutor.makeCommand('install', [`dotnet`]));
return Promise.resolve(this.installReturnValue);
}
public getInstalledDotnetSDKVersions(): Promise<string[]>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`get`, [`sdk`, `versions`]));
return Promise.resolve(this.installedSDKsReturnValue);
}
public getInstalledDotnetRuntimeVersions(): Promise<string[]>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`get`, [`runtime`, `versions`]));
return Promise.resolve(this.installedRuntimesReturnValue);
}
public getInstalledGlobalDotnetPathIfExists(): Promise<string | null>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`global`, [`path`]));
return Promise.resolve(this.globalPathReturnValue);
}
public getInstalledGlobalDotnetVersionIfExists(): Promise<string | null>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`global`, [`version`]));
return Promise.resolve(this.globalVersionReturnValue);
}
public getExpectedDotnetDistroFeedInstallationDirectory(): string
{
this.commandRunner.execute(CommandExecutor.makeCommand(`distro`, [`feed`, `dir`]));
return this.distroFeedReturnValue;
}
public getExpectedDotnetMicrosoftFeedInstallationDirectory(): string
{
this.commandRunner.execute(CommandExecutor.makeCommand(`microsoft`, [`feed`, `dir`]));
return this.microsoftFeedReturnValue;
}
public dotnetPackageExistsOnSystem(fullySpecifiedVersion: string): Promise<boolean>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`package`, [`check`]));
return Promise.resolve(this.packageExistsReturnValue);
}
public getDotnetVersionSupportStatus(fullySpecifiedVersion: string): Promise<DotnetDistroSupportStatus>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`support`, [`status`]));
return Promise.resolve(this.supportStatusReturnValue);
}
public getRecommendedDotnetVersion(installType: DotnetInstallMode): Promise<string>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`recommended`, [`version`]));
return Promise.resolve(this.recommendedVersionReturnValue);
}
public upgradeDotnet(versionToUpgrade: string): Promise<string>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`upgrade`, [`update`, `dotnet`]));
return Promise.resolve(this.upgradeReturnValue);
}
public uninstallDotnet(versionToUninstall: string): Promise<string>
{
this.commandRunner.execute(CommandExecutor.makeCommand(`uninstall`, [`dotnet`]));
return Promise.resolve(this.uninstallReturnValue);
}
public JsonDotnetVersion(fullySpecifiedDotnetVersion: string): string
{
return new GenericDistroSDKProvider(this.distroVersion, this.context, getMockUtilityContext()).JsonDotnetVersion(fullySpecifiedDotnetVersion);
}
protected isPackageFoundInSearch(resultOfSearchCommand: any, searchCommandExitCode: string): boolean
{
return true;
}
}
export class FailingInstallScriptWorker extends InstallScriptAcquisitionWorker
{
constructor(ctx: IAcquisitionWorkerContext)
{
super(ctx);
this.webWorker = new MockWebRequestWorker();
}
public getDotnetInstallScriptPath(): Promise<string>
{
throw new Error('Failed to write file');
}
}
export interface ITelemetryEvent
{
eventName: string;
properties?: {
[key: string]: string;
} | undefined;
measures?: {
[key: string]: number;
} | undefined;
}
export type TelemetryEvents = ITelemetryEvent[];
export class MockTelemetryReporter implements ITelemetryReporter
{
public static telemetryEvents: TelemetryEvents = [];
public async dispose(): Promise<void>
{
// Nothing to dispose
}
public sendTelemetryEvent(eventName: string, properties?: { [key: string]: string; } | undefined, measures?: { [key: string]: number; } | undefined): void
{
MockTelemetryReporter.telemetryEvents = MockTelemetryReporter.telemetryEvents.concat({ eventName, properties, measures });
}
public sendTelemetryErrorEvent(eventName: string, properties?: { [key: string]: string }, measures?: { [key: string]: number }): void
{
eventName = `[ERROR]:${eventName}`;
MockTelemetryReporter.telemetryEvents = MockTelemetryReporter.telemetryEvents.concat({ eventName, properties, measures });
}
}
export class MockInstallationValidator extends IInstallationValidator
{
public validateDotnetInstall(version: DotnetInstall, dotnetPath: string, validateDirectory?: boolean, failOnErr?: boolean): boolean
{
return true;
}
}
export class MockLoggingObserver implements ILoggingObserver
{
public post(event: IEvent): void
{
// Nothing to post
}
public dispose(): void
{
// Nothing to dispose
}
public async flush(): Promise<void>
{
// Nothing to flush
}
public getFileLocation(): string
{
return 'Mock file location';
}
}
export class MockExtensionConfiguration implements IExtensionConfiguration
{
constructor(private readonly existingPaths: ILocalExistingPath[], private readonly enableTelemetry: boolean, private readonly existingSharedPath: string,
public allowInvalidPaths = false
) {}
public update<T>(section: string, value: T): Thenable<void>
{
// Not used, stubbed to implement interface
return new Promise<void>((resolve) => resolve());
}
public get<T>(name: string): T | undefined
{
if (name === 'existingDotnetPath')
{
return this.existingPaths as unknown as T;
}
else if (name === 'sharedExistingDotnetPath')
{
return this.existingSharedPath as unknown as T;
}
else if (name === 'enableTelemetry')
{
return this.enableTelemetry as unknown as T;
}
else if (name === 'allowInvalidPaths')
{
return this.allowInvalidPaths as unknown as T;
}
else if (name === 'showResetDataCommand')
{
return true as unknown as T;
}
else if (name === 'runtimeUpdateDelaySeconds')
{
return 99999999 as unknown as T;
}
else
{
return undefined;
}
}
}
export class MockInstallTracker extends InstallTrackerSingleton
{
constructor(eventStream: IEventStream, extensionState: IExtensionState)
{
super(eventStream, extensionState, false);
// Cause an instance to exist so that we can override the members.
const _ = InstallTrackerSingleton.getInstance(eventStream, extensionState);
this.overrideMembers(eventStream, extensionState);
}
public getExtensionState(): IExtensionState
{
return this.extensionState;
}
public setExtensionState(extensionState: IExtensionState): void
{
this.extensionState = extensionState;
}
public getSessionId(): string
{
return InstallTrackerSingleton.sessionId;
}
/**
* Marks an install as in use by a specific session
* @param sessionId - The session ID to mark as using the installation
* @param installExePath - The path to the dotnet executable of the install to mark
*/
public async markInstallAsInUseBySession(sessionId: string, installExePath: string): Promise<void>
{
return super.markInstallAsInUseWithInstallLock(installExePath, false, sessionId);
}
/**
* Exposes the protected endSession method for testing purposes
* @returns A promise that resolves when the mutex is released
*/
public async endAnySingletonTrackingSessions(): Promise<void>
{
return this.endSession();
}
/**
* Exposes the protected restartSessionMutex method for testing purposes
* @returns A promise that resolves when the mutex is acquired
*/
public async startNewSharedSingletonSession(): Promise<void>
{
return this.restartSessionMutex();
}
}