forked from DonJayamanne/pythonVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexperiments.unit.test.ts
More file actions
755 lines (652 loc) · 34.7 KB
/
experiments.unit.test.ts
File metadata and controls
755 lines (652 loc) · 34.7 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
// tslint:disable:no-any
import { assert, expect } from 'chai';
import * as sinon from 'sinon';
import { anything, instance, mock, resetCalls, verify, when } from 'ts-mockito';
import * as TypeMoq from 'typemoq';
import { WorkspaceConfiguration } from 'vscode';
import { ApplicationEnvironment } from '../../client/common/application/applicationEnvironment';
import { IApplicationEnvironment, IWorkspaceService } from '../../client/common/application/types';
import { WorkspaceService } from '../../client/common/application/workspace';
import { CryptoUtils } from '../../client/common/crypto';
import { configUri, downloadedExperimentStorageKey, ExperimentsManager, experimentStorageKey, isDownloadedStorageValidKey } from '../../client/common/experiments';
import { HttpClient } from '../../client/common/net/httpClient';
import { PersistentStateFactory } from '../../client/common/persistentState';
import { FileSystem } from '../../client/common/platform/fileSystem';
import { IFileSystem } from '../../client/common/platform/types';
import { ICryptoUtils, IHttpClient, IOutputChannel, IPersistentState, IPersistentStateFactory } from '../../client/common/types';
import { createDeferred, createDeferredFromPromise } from '../../client/common/utils/async';
import { sleep } from '../common';
// tslint:disable-next-line: max-func-body-length
suite('xA/B experiments', () => {
let workspaceService: IWorkspaceService;
let httpClient: IHttpClient;
let crypto: ICryptoUtils;
let appEnvironment: IApplicationEnvironment;
let persistentStateFactory: IPersistentStateFactory;
let isDownloadedStorageValid: TypeMoq.IMock<IPersistentState<boolean>>;
let experimentStorage: TypeMoq.IMock<IPersistentState<any>>;
let downloadedExperimentsStorage: TypeMoq.IMock<IPersistentState<any>>;
let output: TypeMoq.IMock<IOutputChannel>;
let fs: IFileSystem;
let expManager: ExperimentsManager;
setup(() => {
workspaceService = mock(WorkspaceService);
httpClient = mock(HttpClient);
crypto = mock(CryptoUtils);
appEnvironment = mock(ApplicationEnvironment);
persistentStateFactory = mock(PersistentStateFactory);
isDownloadedStorageValid = TypeMoq.Mock.ofType<IPersistentState<boolean>>();
experimentStorage = TypeMoq.Mock.ofType<IPersistentState<any>>();
downloadedExperimentsStorage = TypeMoq.Mock.ofType<IPersistentState<any>>();
output = TypeMoq.Mock.ofType<IOutputChannel>();
fs = mock(FileSystem);
when(persistentStateFactory.createGlobalPersistentState(isDownloadedStorageValidKey, false, anything())).thenReturn(isDownloadedStorageValid.object);
when(persistentStateFactory.createGlobalPersistentState(experimentStorageKey, undefined as any)).thenReturn(experimentStorage.object);
when(persistentStateFactory.createGlobalPersistentState(downloadedExperimentStorageKey, undefined as any)).thenReturn(downloadedExperimentsStorage.object);
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
});
teardown(() => {
sinon.restore();
});
async function testInitialization(
downloadError: boolean = false,
experimentsDownloaded: any = [{ name: 'experiment1', salt: 'salt', min: 90, max: 100 }]
) {
if (downloadError) {
when(httpClient.getJSON(configUri, false)).thenReject(new Error('Kaboom'));
} else {
when(httpClient.getJSON(configUri, false)).thenResolve(experimentsDownloaded);
}
try {
await expManager.initializeInBackground();
// tslint:disable-next-line:no-empty
} catch { }
isDownloadedStorageValid.verifyAll();
}
test('Initializing experiments does not download experiments if storage is valid and contains experiments', async () => {
isDownloadedStorageValid.setup(n => n.value).returns(() => true).verifiable(TypeMoq.Times.once());
await testInitialization();
verify(httpClient.getJSON(configUri, false)).never();
});
test('If storage has expired, initializing experiments downloads the experiments, but does not store them if they are invalid or incomplete', async () => {
const experiments = [{ name: 'experiment1', salt: 'salt', max: 100 }];
isDownloadedStorageValid
.setup(n => n.value)
.returns(() => false)
.verifiable(TypeMoq.Times.once());
isDownloadedStorageValid
.setup(n => n.updateValue(true))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
downloadedExperimentsStorage
.setup(n => n.updateValue(experiments))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
// downloadError = false, experimentsDownloaded = experiments
await testInitialization(false, experiments);
verify(httpClient.getJSON(configUri, false)).once();
});
test('If storage has expired, initializing experiments downloads the experiments, and stores them if they are valid', async () => {
isDownloadedStorageValid.setup(n => n.value).returns(() => false).verifiable(TypeMoq.Times.once());
isDownloadedStorageValid.setup(n => n.updateValue(true)).returns(() => Promise.resolve(undefined)).verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage.setup(n => n.updateValue([{ name: 'experiment1', salt: 'salt', min: 90, max: 100 }])).returns(() => Promise.resolve(undefined)).verifiable(TypeMoq.Times.once());
await testInitialization();
verify(httpClient.getJSON(configUri, false)).once();
});
test('If downloading experiments fails with error, the storage is left as it is', async () => {
isDownloadedStorageValid.setup(n => n.value).returns(() => false).verifiable(TypeMoq.Times.once());
isDownloadedStorageValid.setup(n => n.updateValue(true)).returns(() => Promise.resolve(undefined)).verifiable(TypeMoq.Times.never());
downloadedExperimentsStorage.setup(n => n.updateValue(anything())).returns(() => Promise.resolve(undefined)).verifiable(TypeMoq.Times.never());
// downloadError = true
await testInitialization(true);
verify(httpClient.getJSON(configUri, false)).once();
});
test('If the users have opted out of telemetry, then they are opted out of AB testing ', async () => {
const workspaceConfig = TypeMoq.Mock.ofType<WorkspaceConfiguration>();
const settings = { globalValue: false };
when(
workspaceService.getConfiguration('telemetry')
).thenReturn(workspaceConfig.object);
workspaceConfig.setup(c => c.inspect<boolean>('enableTelemetry'))
.returns(() => settings as any)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.never());
await expManager.activate();
verify(workspaceService.getConfiguration('telemetry')).once();
workspaceConfig.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('Ensure experiments can only be activated once', async () => {
const updateExperimentStorage = sinon.stub(ExperimentsManager.prototype, 'updateExperimentStorage');
updateExperimentStorage.callsFake(() => Promise.resolve());
const populateUserExperiments = sinon.stub(ExperimentsManager.prototype, 'populateUserExperiments');
populateUserExperiments.callsFake(() => Promise.resolve());
const initializeInBackground = sinon.stub(ExperimentsManager.prototype, 'initializeInBackground');
initializeInBackground.callsFake(() => Promise.resolve());
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
// Activate it twice and check
const workspaceConfig = TypeMoq.Mock.ofType<WorkspaceConfiguration>();
const settings = {};
when(
workspaceService.getConfiguration('telemetry')
).thenReturn(workspaceConfig.object);
workspaceConfig.setup(c => c.inspect<boolean>('enableTelemetry'))
.returns(() => settings as any)
.verifiable(TypeMoq.Times.once());
// First activation
await expManager.activate();
resetCalls(workspaceService);
// Second activation
await expManager.activate();
verify(workspaceService.getConfiguration(anything())).never();
workspaceConfig.verifyAll();
});
test('Ensure experiments are reliably downloaded in the background', async () => {
const experimentsDeferred = createDeferred<void>();
const workspaceConfig = TypeMoq.Mock.ofType<WorkspaceConfiguration>();
const settings = {};
const updateExperimentStorage = sinon.stub(ExperimentsManager.prototype, 'updateExperimentStorage');
updateExperimentStorage.callsFake(() => Promise.resolve());
const populateUserExperiments = sinon.stub(ExperimentsManager.prototype, 'populateUserExperiments');
populateUserExperiments.callsFake(() => Promise.resolve());
const initializeInBackground = sinon.stub(ExperimentsManager.prototype, 'initializeInBackground');
initializeInBackground.callsFake(() => experimentsDeferred.promise);
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
when(
workspaceService.getConfiguration('telemetry')
)
.thenReturn(workspaceConfig.object);
workspaceConfig
.setup(c => c.inspect<boolean>('enableTelemetry'))
.returns(() => settings as any)
.verifiable(TypeMoq.Times.once());
const promise = expManager.activate();
const deferred = createDeferredFromPromise(promise);
await sleep(1);
// Ensure activate() function has completed while experiments are still being downloaded
assert.equal(deferred.completed, true);
experimentsDeferred.resolve();
await sleep(1);
verify(
workspaceService.getConfiguration('telemetry')
).once();
workspaceConfig.verifyAll();
assert.ok(initializeInBackground.calledOnce);
});
test('Ensure experiment storage is updated to contain the latest downloaded experiments', async () => {
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => [{ name: 'experiment1', salt: 'salt', min: 90, max: 100 }])
.verifiable(TypeMoq.Times.atLeastOnce());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue([{ name: 'experiment1', salt: 'salt', min: 90, max: 100 }]))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.once());
await expManager.updateExperimentStorage();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('When latest experiments are not available, but experiment storage contains experiments, then experiment storage is not updated', async () => {
const doBestEffortToPopulateExperiments = sinon.stub(ExperimentsManager.prototype, 'doBestEffortToPopulateExperiments');
doBestEffortToPopulateExperiments.callsFake(() => Promise.resolve(false));
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
experimentStorage
.setup(n => n.value)
.returns(() => [{ name: 'experiment1', salt: 'salt', min: 90, max: 100 }])
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
await expManager.updateExperimentStorage();
assert.ok(doBestEffortToPopulateExperiments.notCalled);
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('When best effort to populate experiments succeeds, function updateStorage() returns', async () => {
const doBestEffortToPopulateExperiments = sinon.stub(ExperimentsManager.prototype, 'doBestEffortToPopulateExperiments');
doBestEffortToPopulateExperiments.callsFake(() => Promise.resolve(true));
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
experimentStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
await expManager.updateExperimentStorage();
assert.ok(doBestEffortToPopulateExperiments.calledOnce);
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('When latest experiments are not available, experiment storage is empty, but if local experiments file is not valid, experiment storage is not updated', async () => {
const doBestEffortToPopulateExperiments = sinon.stub(ExperimentsManager.prototype, 'doBestEffortToPopulateExperiments');
doBestEffortToPopulateExperiments.callsFake(() => Promise.resolve(false));
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
// tslint:disable-next-line:no-multiline-string
const fileContent = `
// Yo! I am a JSON file with comments as well as trailing commas!
[{ "name": "experiment1", "salt": "salt", "min": 90, },]
`;
when(
fs.fileExists(anything())
).thenResolve(true);
when(
fs.readFile(anything())
).thenResolve(fileContent);
experimentStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined)).verifiable(TypeMoq.Times.never());
await expManager.updateExperimentStorage();
verify(fs.fileExists(anything())).once();
verify(fs.readFile(anything())).once();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('When latest experiments are not available, and experiment storage is empty, then experiment storage is updated using local experiments file given experiments are valid', async () => {
const doBestEffortToPopulateExperiments = sinon.stub(ExperimentsManager.prototype, 'doBestEffortToPopulateExperiments');
doBestEffortToPopulateExperiments.callsFake(() => Promise.resolve(false));
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
// tslint:disable-next-line:no-multiline-string
const fileContent = `
// Yo! I am a JSON file with comments as well as trailing commas!
[{ "name": "experiment1", "salt": "salt", "min": 90, "max": 100, },]
`;
when(
fs.fileExists(anything())
).thenResolve(true);
when(
fs.readFile(anything())
).thenResolve(fileContent);
experimentStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue([{ name: 'experiment1', salt: 'salt', min: 90, max: 100 }]))
.returns(() => Promise.resolve(undefined)).verifiable(TypeMoq.Times.once());
await expManager.updateExperimentStorage();
verify(fs.fileExists(anything())).once();
verify(fs.readFile(anything())).once();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
// tslint:disable-next-line:max-func-body-length
suite('When latest experiments are not available, and experiment storage is empty, then function updateExperimentStorage() stops execution and returns', () => {
setup(() => {
const doBestEffortToPopulateExperiments = sinon.stub(ExperimentsManager.prototype, 'doBestEffortToPopulateExperiments');
doBestEffortToPopulateExperiments.callsFake(() => Promise.resolve(false));
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
});
test('If checking the existence of config file fails', async () => {
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
const error = new Error('Kaboom');
when(
fs.fileExists(anything())
).thenThrow(error);
when(
fs.readFile(anything())
).thenResolve('fileContent');
experimentStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
await expManager.updateExperimentStorage();
verify(fs.fileExists(anything())).once();
verify(fs.readFile(anything())).never();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('If reading config file fails', async () => {
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
const error = new Error('Kaboom');
when(
fs.fileExists(anything())
).thenResolve(true);
when(
fs.readFile(anything())
).thenThrow(error);
experimentStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
await expManager.updateExperimentStorage();
verify(fs.fileExists(anything())).once();
verify(fs.readFile(anything())).once();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('If config file does not exist', async () => {
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
when(
fs.fileExists(anything())
).thenResolve(false);
when(
fs.readFile(anything())
).thenResolve('fileContent');
experimentStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
await expManager.updateExperimentStorage();
verify(fs.fileExists(anything())).once();
verify(fs.readFile(anything())).never();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
test('If parsing file or updating storage fails', async () => {
downloadedExperimentsStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
downloadedExperimentsStorage
.setup(n => n.updateValue(undefined))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
// tslint:disable-next-line:no-multiline-string
const fileContent = `
// Yo! I am a JSON file with comments as well as trailing commas!
[{ "name": "experiment1", "salt": "salt", "min": 90, "max": 100 },]
`;
const error = new Error('Kaboom');
when(
fs.fileExists(anything())
).thenResolve(true);
when(
fs.readFile(anything())
).thenResolve(fileContent);
experimentStorage
.setup(n => n.value)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
experimentStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.reject(error))
.verifiable(TypeMoq.Times.once());
await expManager.updateExperimentStorage();
verify(fs.fileExists(anything())).once();
verify(fs.readFile(anything())).once();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
});
const testsForInExperiment =
[
{
testName: 'If experiment\'s name is not in user experiment list, user is not in experiment',
experimentName: 'imaginary experiment',
userExperiments: [{ name: 'experiment1', salt: 'salt', min: 79, max: 94 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
expectedResult: false
},
{
testName: 'If experiment\'s name is in user experiment list and hash modulo output is in range, user is in experiment',
experimentName: 'experiment1',
userExperiments: [{ name: 'experiment1', salt: 'salt', min: 79, max: 94 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
expectedResult: true
}
];
testsForInExperiment.forEach(testParams => {
test(testParams.testName, async () => {
expManager.userExperiments = testParams.userExperiments;
expect(expManager.inExperiment(testParams.experimentName)).to.equal(testParams.expectedResult, 'Incorrectly identified');
});
});
const testsForIsUserInRange =
[
// Note min equals 79 and max equals 94
{
testName: 'Returns true if hash modulo output is in range',
hash: 1181,
expectedResult: true
},
{
testName: 'Returns false if hash modulo is less than min',
hash: 967,
expectedResult: false
},
{
testName: 'Returns false if hash modulo is more than max',
hash: 3297,
expectedResult: false
},
{
testName: 'If checking if user is in range fails with error, throw error',
hash: 3297,
error: true,
expectedResult: false
},
{
testName: 'If machine ID is bogus, throw error',
hash: 3297,
machineIdError: true,
expectedResult: false
}
];
suite('Function IsUserInRange()', () => {
testsForIsUserInRange.forEach(testParams => {
test(testParams.testName, async () => {
when(appEnvironment.machineId).thenReturn('101');
if (testParams.machineIdError) {
when(appEnvironment.machineId).thenReturn(undefined as any);
expect(() => expManager.isUserInRange(79, 94, 'salt')).to.throw();
} else if (testParams.error) {
const error = new Error('Kaboom');
when(crypto.createHash(anything(), 'number')).thenThrow(error);
expect(() => expManager.isUserInRange(79, 94, 'salt')).to.throw(error);
} else {
when(crypto.createHash(anything(), 'number')).thenReturn(testParams.hash);
expect(expManager.isUserInRange(79, 94, 'salt')).to.equal(testParams.expectedResult, 'Incorrectly identified');
}
});
});
});
const testsForPopulateUserExperiments =
[
{
testName: 'User experiments list is empty if experiment storage value is not an array',
experimentStorageValue: undefined,
expectedResult: []
},
{
testName: 'User experiments list is empty if experiment storage value is an empty array',
experimentStorageValue: [],
expectedResult: []
},
{
testName: 'User experiments list contains the experiment if and only if user is in experiment range',
experimentStorageValue: [{ name: 'experiment1', salt: 'salt', min: 79, max: 94 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
hash: 8187,
expectedResult: [{ name: 'experiment1', salt: 'salt', min: 79, max: 94 }]
}
];
testsForPopulateUserExperiments.forEach(testParams => {
test(testParams.testName, async () => {
experimentStorage
.setup(n => n.value)
.returns(() => testParams.experimentStorageValue);
when(appEnvironment.machineId).thenReturn('101');
if (testParams.hash) {
when(crypto.createHash(anything(), 'number')).thenReturn(testParams.hash);
}
expManager.populateUserExperiments();
assert.deepEqual(expManager.userExperiments, testParams.expectedResult);
});
});
const testsForAreExperimentsValid =
[
{
testName: 'If experiments are not an array, return false',
experiments: undefined,
expectedResult: false
},
{
testName: 'If any experiment have `min` field missing, return false',
experiments: [{ name: 'experiment1', salt: 'salt', max: 94 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
expectedResult: false
},
{
testName: 'If any experiment have `max` field missing, return false',
experiments: [{ name: 'experiment1', salt: 'salt', min: 79 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
expectedResult: false
},
{
testName: 'If any experiment have `salt` field missing, return false',
experiments: [{ name: 'experiment1', min: 79, max: 94 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
expectedResult: false
},
{
testName: 'If any experiment have `name` field missing, return false',
experiments: [{ salt: 'salt', min: 79, max: 94 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
expectedResult: false
},
{
testName: 'If all experiments contain all the fields in type `ABExperiment`, return true',
experiments: [{ name: 'experiment1', salt: 'salt', min: 79, max: 94 }, { name: 'experiment2', salt: 'salt', min: 19, max: 30 }],
expectedResult: true
}
];
suite('Function areExperimentsValid()', () => {
testsForAreExperimentsValid.forEach(testParams => {
test(testParams.testName, () => {
expect(expManager.areExperimentsValid(testParams.experiments as any)).to.equal(testParams.expectedResult);
});
});
});
suite('Function doBestEffortToPopulateExperiments()', async () => {
let downloadAndStoreExperiments: sinon.SinonStub<any>;
test('If attempt to download experiments within timeout suceeds, return true', async () => {
downloadAndStoreExperiments = sinon.stub(ExperimentsManager.prototype, 'downloadAndStoreExperiments');
const timeout = 150;
const downloadExperimentsDeferred = createDeferred<void>();
downloadAndStoreExperiments.callsFake(() => downloadExperimentsDeferred.promise);
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs), timeout);
// Download set to complete in 50 ms, timeout is of 150 ms, i.e download will complete within timeout
const timer = setTimeout(() => downloadExperimentsDeferred.resolve(), 50);
const result = await expManager.doBestEffortToPopulateExperiments();
expect(result).to.equal(true, 'Expected value is true');
assert.ok(downloadAndStoreExperiments.calledOnce);
clearTimeout(timer);
});
test('If downloading experiments fails to complete within timeout, return false', async () => {
downloadAndStoreExperiments = sinon.stub(ExperimentsManager.prototype, 'downloadAndStoreExperiments');
const timeout = 100;
const downloadExperimentsDeferred = createDeferred<void>();
downloadAndStoreExperiments.callsFake(() => downloadExperimentsDeferred.promise);
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs), timeout);
// Download set to complete in 200 ms, timeout is of 100 ms, i.e download will complete within timeout
const timer = setTimeout(() => downloadExperimentsDeferred.resolve(), 200);
const result = await expManager.doBestEffortToPopulateExperiments();
expect(result).to.equal(false, 'Expected value is false');
assert.ok(downloadAndStoreExperiments.calledOnce);
clearTimeout(timer);
});
test('If downloading experiments fails with error, return false', async () => {
downloadAndStoreExperiments = sinon.stub(ExperimentsManager.prototype, 'downloadAndStoreExperiments');
downloadAndStoreExperiments.callsFake(() => Promise.reject('Kaboom'));
expManager = new ExperimentsManager(instance(persistentStateFactory), instance(workspaceService), instance(httpClient), instance(crypto), instance(appEnvironment), output.object, instance(fs));
const result = await expManager.doBestEffortToPopulateExperiments();
expect(result).to.equal(false, 'Expected value is false');
assert.ok(downloadAndStoreExperiments.calledOnce);
});
});
test('If storage as parameter is passed in as argument to function downloadAndStoreExperiments(), download experiments into that storage', async () => {
downloadedExperimentsStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
experimentStorage
.setup(n => n.updateValue(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.once());
isDownloadedStorageValid
.setup(n => n.updateValue(true))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.once());
when(
httpClient.getJSON(configUri, false)
).thenResolve(
[{ name: 'experiment1', salt: 'salt', min: 90, max: 100 }]
);
await expManager.downloadAndStoreExperiments(experimentStorage.object);
verify(httpClient.getJSON(configUri, false)).once();
isDownloadedStorageValid.verifyAll();
experimentStorage.verifyAll();
downloadedExperimentsStorage.verifyAll();
});
});