-
Notifications
You must be signed in to change notification settings - Fork 415
Expand file tree
/
Copy pathremote-config.spec.ts
More file actions
1856 lines (1689 loc) · 69.9 KB
/
remote-config.spec.ts
File metadata and controls
1856 lines (1689 loc) · 69.9 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
/*!
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
import * as _ from 'lodash';
import * as chai from 'chai';
import * as sinon from 'sinon';
import {
ParameterValueType,
RemoteConfig,
RemoteConfigTemplate,
RemoteConfigCondition,
TagColor,
ListVersionsResult,
RemoteConfigFetchResponse,
RolloutParameterValue,
PersonalizationParameterValue,
ExperimentParameterValue,
} from '../../../src/remote-config/index';
import { FirebaseApp } from '../../../src/app/firebase-app';
import * as mocks from '../../resources/mocks';
import {
FirebaseRemoteConfigError,
RemoteConfigApiClient
} from '../../../src/remote-config/remote-config-api-client-internal';
import { deepCopy } from '../../../src/utils/deep-copy';
import {
NamedCondition, ServerTemplate, ServerTemplateData, Version
} from '../../../src/remote-config/remote-config-api';
const expect = chai.expect;
describe('RemoteConfig', () => {
const INTERNAL_ERROR = new FirebaseRemoteConfigError('internal-error', 'message');
const PARAMETER_GROUPS = {
new_menu: {
description: 'Description of the group.',
parameters: {
pumpkin_spice_season: {
defaultValue: { value: 'A Gryffindor must love a pumpkin spice latte.' },
conditionalValues: {
'android_en': { value: 'A Droid must love a pumpkin spice latte.' },
},
description: 'Description of the parameter.',
valueType: 'STRING' as ParameterValueType,
},
},
},
};
const VERSION_INFO = {
versionNumber: '86',
updateOrigin: 'ADMIN_SDK_NODE',
updateType: 'INCREMENTAL_UPDATE',
updateUser: {
email: 'firebase-adminsdk@gserviceaccount.com'
},
description: 'production version',
updateTime: '2020-06-15T16:45:03.541527Z'
};
const REMOTE_CONFIG_RESPONSE: {
// This type is effectively a RemoteConfigTemplate, but with non-readonly fields
// to allow easier use from within the tests. An improvement would be to
// alter this into a helper that creates customized RemoteConfigTemplateContent based
// on the needs of the test, as that would ensure type-safety.
conditions?: Array<{ name: string; expression: string; tagColor: TagColor }>;
parameters?: object | null;
parameterGroups?: object | null;
etag: string;
version?: object;
} = {
conditions: [
{
name: 'ios',
expression: 'device.os == \'ios\'',
tagColor: 'BLUE',
},
],
parameters: {
holiday_promo_enabled: {
defaultValue: { value: 'true' },
conditionalValues: { ios: { useInAppDefault: true } },
description: 'this is a promo',
valueType: 'BOOLEAN',
},
new_ui_enabled: {
defaultValue: { value: 'false' },
conditionalValues: {
ios: {
rolloutValue: {
rolloutId: 'rollout_1',
value: 'true',
percent: 50,
}
}
},
description: 'New UI Rollout',
valueType: 'BOOLEAN',
},
personalized_welcome_message: {
defaultValue: { value: 'Welcome!' },
conditionalValues: {
ios: {
personalizationValue: {
personalizationId: 'personalization_1',
}
}
},
description: 'Personalized Welcome Message',
valueType: 'STRING',
},
experiment_enabled: {
defaultValue: { value: 'false' },
conditionalValues: {
ios: {
experimentValue: {
experimentId: 'experiment_1',
variantValue: [
{ variantId: 'variant_A', value: 'true' },
{ variantId: 'variant_B', noChange: true }
],
exposurePercent: 25,
}
}
},
description: 'Experiment Enabled',
valueType: 'BOOLEAN',
}
},
parameterGroups: PARAMETER_GROUPS,
etag: 'etag-123456789012-5',
version: VERSION_INFO,
};
const SERVER_REMOTE_CONFIG_RESPONSE: {
// This type is effectively a RemoteConfigServerTemplate, but with mutable fields
// to allow easier use from within the tests. An improvement would be to
// alter this into a helper that creates customized RemoteConfigTemplateContent based
// on the needs of the test, as that would ensure type-safety.
conditions?: Array<NamedCondition>;
parameters?: object | null;
etag: string;
version?: object;
} = {
conditions: [
{
name: 'ios',
condition: {
orCondition: {
conditions: [
{
andCondition: {
conditions: [
{ true: {} }
]
}
}
]
}
}
},
],
parameters: {
holiday_promo_enabled: {
defaultValue: { value: 'true' },
conditionalValues: { ios: { useInAppDefault: true } }
},
},
etag: 'etag-123456789012-5',
version: VERSION_INFO,
};
const REMOTE_CONFIG_TEMPLATE: RemoteConfigTemplate = {
conditions: [{
name: 'ios',
expression: 'device.os == \'ios\'',
tagColor: 'PINK',
}],
parameters: {
holiday_promo_enabled: {
defaultValue: { value: 'true' },
conditionalValues: { ios: { useInAppDefault: true } },
description: 'this is a promo',
valueType: 'BOOLEAN',
},
new_ui_enabled: {
defaultValue: { value: 'false' },
conditionalValues: {
ios: {
rolloutValue: {
rolloutId: 'rollout_1',
value: 'true',
percent: 50,
}
}
},
description: 'New UI Rollout',
valueType: 'BOOLEAN',
},
personalized_welcome_message: {
defaultValue: { value: 'Welcome!' },
conditionalValues: {
ios: {
personalizationValue: {
personalizationId: 'personalization_1',
}
}
},
description: 'Personalized Welcome Message',
valueType: 'STRING',
},
experiment_enabled: {
defaultValue: { value: 'false' },
conditionalValues: {
ios: {
experimentValue: {
experimentId: 'experiment_1',
variantValue: [
{ variantId: 'variant_A', value: 'true' },
{ variantId: 'variant_B', noChange: true }
],
exposurePercent: 25,
}
}
},
description: 'Experiment Enabled',
valueType: 'BOOLEAN',
}
},
parameterGroups: PARAMETER_GROUPS,
etag: 'etag-123456789012-6',
version: {
description: 'production version',
}
};
const REMOTE_CONFIG_LIST_VERSIONS_RESULT: ListVersionsResult = {
versions: [
{
versionNumber: '78',
updateTime: '2020-05-07T18:46:09.495234Z',
updateUser: {
email: 'user@gmail.com',
imageUrl: 'https://photo.jpg'
},
description: 'Rollback to version 76',
updateOrigin: 'REST_API',
updateType: 'ROLLBACK',
rollbackSource: '76'
},
{
versionNumber: '77',
updateTime: '2020-05-07T18:44:41.555Z',
updateUser: {
email: 'user@gmail.com',
imageUrl: 'https://photo.jpg'
},
updateOrigin: 'REST_API',
updateType: 'INCREMENTAL_UPDATE',
},
],
nextPageToken: '76'
}
let remoteConfig: RemoteConfig;
let mockApp: FirebaseApp;
let mockCredentialApp: FirebaseApp;
// Stubs used to simulate underlying api calls.
let stubs: sinon.SinonStub[] = [];
before(() => {
mockApp = mocks.app();
mockCredentialApp = mocks.mockCredentialApp();
remoteConfig = new RemoteConfig(mockApp);
});
after(() => {
return mockApp.delete();
});
afterEach(() => {
_.forEach(stubs, (stub) => stub.restore());
stubs = [];
});
describe('Constructor', () => {
const invalidApps = [null, NaN, 0, 1, true, false, '', 'a', [], [1, 'a'], {}, { a: 1 }, _.noop];
invalidApps.forEach((invalidApp) => {
it('should throw given invalid app: ' + JSON.stringify(invalidApp), () => {
expect(() => {
const remoteConfigAny: any = RemoteConfig;
return new remoteConfigAny(invalidApp);
}).to.throw(
'First argument passed to admin.remoteConfig() must be a valid Firebase app '
+ 'instance.');
});
});
it('should throw given no app', () => {
expect(() => {
const remoteConfigAny: any = RemoteConfig;
return new remoteConfigAny();
}).to.throw(
'First argument passed to admin.remoteConfig() must be a valid Firebase app '
+ 'instance.');
});
it('should reject when initialized without project ID', () => {
// Project ID not set in the environment.
delete process.env.GOOGLE_CLOUD_PROJECT;
delete process.env.GCLOUD_PROJECT;
const noProjectId = 'Failed to determine project ID. Initialize the SDK with service '
+ 'account credentials, or set project ID as an app option. Alternatively, set the '
+ 'GOOGLE_CLOUD_PROJECT environment variable.';
const remoteConfigWithoutProjectId = new RemoteConfig(mockCredentialApp);
return remoteConfigWithoutProjectId.getTemplate()
.should.eventually.rejectedWith(noProjectId);
});
it('should not throw given a valid app', () => {
expect(() => {
return new RemoteConfig(mockApp);
}).not.to.throw();
});
});
describe('app', () => {
it('returns the app from the constructor', () => {
// We expect referential equality here
expect(remoteConfig.app).to.equal(mockApp);
});
});
describe('getTemplate', () => {
runInvalidResponseTests(() => remoteConfig.getTemplate(), 'getTemplate');
runValidResponseTests(() => remoteConfig.getTemplate(), 'getTemplate');
});
describe('getTemplateAtVersion', () => {
runInvalidResponseTests(() => remoteConfig.getTemplateAtVersion(65), 'getTemplateAtVersion');
runValidResponseTests(() => remoteConfig.getTemplateAtVersion(65), 'getTemplateAtVersion');
});
describe('validateTemplate', () => {
runInvalidResponseTests(() => remoteConfig.validateTemplate(REMOTE_CONFIG_TEMPLATE),
'validateTemplate');
runValidResponseTests(() => remoteConfig.validateTemplate(REMOTE_CONFIG_TEMPLATE),
'validateTemplate');
});
describe('publishTemplate', () => {
runInvalidResponseTests(() => remoteConfig.publishTemplate(REMOTE_CONFIG_TEMPLATE),
'publishTemplate');
runValidResponseTests(() => remoteConfig.publishTemplate(REMOTE_CONFIG_TEMPLATE),
'publishTemplate');
});
describe('rollback', () => {
runInvalidResponseTests(() => remoteConfig.rollback('5'), 'rollback');
runValidResponseTests(() => remoteConfig.rollback('5'), 'rollback');
});
describe('listVersions', () => {
it('should propagate API errors', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.rejects(INTERNAL_ERROR);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.deep.equal(INTERNAL_ERROR);
});
['', null, NaN, true, [], {}].forEach((invalidVersion) => {
it(`should reject if the versionNumber is: ${invalidVersion}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].versionNumber = invalidVersion as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected
.and.to.match(/^Error: Version number must be a non-empty string in int64 format or a number$/);
});
});
['abc', 'a123b', 'a123', '123a', 1.2, '70.2'].forEach((invalidVersion) => {
it(`should reject if the versionNumber is: ${invalidVersion}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].versionNumber = invalidVersion as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected
.and.to.match(/^Error: Version number must be an integer or a string in int64 format$/);
});
});
['', 123, 1.2, null, NaN, true, [], {}].forEach((invalidUpdateOrigin) => {
it(`should reject if the updateOrigin is: ${invalidUpdateOrigin}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].updateOrigin = invalidUpdateOrigin as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.have.property('message',
'Version update origin must be a non-empty string');
});
});
['', 123, 1.2, null, NaN, true, [], {}].forEach((invalidUpdateType) => {
it(`should reject if the updateType is: ${invalidUpdateType}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].updateType = invalidUpdateType as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.have.property('message',
'Version update type must be a non-empty string');
});
});
['', 'abc', 1.2, 123, null, NaN, true, []].forEach((invalidUpdateUser) => {
it(`should reject if the updateUser is: ${invalidUpdateUser}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].updateUser = invalidUpdateUser as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.have.property('message',
'Version update user must be a non-null object');
});
});
['', 123, 1.2, null, NaN, true, [], {}].forEach((invalidDescription) => {
it(`should reject if the description is: ${invalidDescription}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].description = invalidDescription as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.have.property('message',
'Version description must be a non-empty string');
});
});
['', 123, 1.2, null, NaN, true, [], {}].forEach((invalidRollbackSource) => {
it(`should reject if the rollbackSource is: ${invalidRollbackSource}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].rollbackSource = invalidRollbackSource as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.have.property('message',
'Version rollback source must be a non-empty string');
});
});
['', 'abc', 123, 1.2, null, NaN, [], {}].forEach((invalidIsLegacy) => {
it(`should reject if the isLegacy is: ${invalidIsLegacy}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].isLegacy = invalidIsLegacy as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.have.property('message',
'Version.isLegacy must be a boolean');
});
});
['', 'abc', 123, 1.2, null, NaN, [], {}].forEach((invalidUpdateTime) => {
it(`should reject if the updateTime is: ${invalidUpdateTime}`, () => {
const response = deepCopy(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
response.versions[0].updateTime = invalidUpdateTime as any;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(response);
stubs.push(stub);
return remoteConfig.listVersions()
.should.eventually.be.rejected.and.have.property('message',
'Version update time must be a valid date string');
});
});
it('should resolve with an empty versions list if no results are available for requested list options', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves({} as any);
stubs.push(stub);
return remoteConfig.listVersions({
pageSize: 2,
endVersionNumber: 10,
})
.then((response) => {
expect(response.versions.length).to.equal(0);
expect(response.nextPageToken).to.be.undefined;
});
});
it('should resolve with template versions list on success', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, 'listVersions')
.resolves(REMOTE_CONFIG_LIST_VERSIONS_RESULT);
stubs.push(stub);
return remoteConfig.listVersions({
pageSize: 2
})
.then((response) => {
expect(response.versions.length).to.equal(2);
expect(response.versions[0].updateTime).equals('Thu, 07 May 2020 18:46:09 GMT');
expect(response.versions[1].updateTime).equals('Thu, 07 May 2020 18:44:41 GMT');
expect(response.nextPageToken).to.equal('76');
});
});
});
const INVALID_PARAMETERS: any[] = [null, '', 'abc', 1, true, []];
const INVALID_PARAMETER_GROUPS: any[] = [null, '', 'abc', 1, true, []];
const INVALID_CONDITIONS: any[] = [null, '', 'abc', 1, true, {}];
describe('createTemplateFromJSON', () => {
const INVALID_STRINGS: any[] = [null, undefined, '', 1, true, {}, []];
const INVALID_JSON_STRINGS: any[] = ['abc', 'foo', 'a:a', '1:1'];
INVALID_STRINGS.forEach((invalidJson) => {
it(`should throw if the json string is ${JSON.stringify(invalidJson)}`, () => {
expect(() => remoteConfig.createTemplateFromJSON(invalidJson))
.to.throw('JSON string must be a valid non-empty string');
});
});
INVALID_JSON_STRINGS.forEach((invalidJson) => {
it(`should throw if the json string is ${JSON.stringify(invalidJson)}`, () => {
expect(() => remoteConfig.createTemplateFromJSON(invalidJson))
.to.throw(/Failed to parse the JSON string: ([\D\w]*)\./);
});
});
let sourceTemplate = deepCopy(REMOTE_CONFIG_RESPONSE);
INVALID_STRINGS.forEach((invalidEtag) => {
sourceTemplate.etag = invalidEtag;
const jsonString = JSON.stringify(sourceTemplate);
it(`should throw if the ETag is ${JSON.stringify(invalidEtag)}`, () => {
expect(() => remoteConfig.createTemplateFromJSON(jsonString))
.to.throw(`Invalid Remote Config template: ${jsonString}`);
});
});
sourceTemplate = deepCopy(REMOTE_CONFIG_RESPONSE);
INVALID_PARAMETERS.forEach((invalidParameter) => {
sourceTemplate.parameters = invalidParameter;
const jsonString = JSON.stringify(sourceTemplate);
it(`should throw if the parameters is ${JSON.stringify(invalidParameter)}`, () => {
expect(() => remoteConfig.createTemplateFromJSON(jsonString))
.to.throw('Remote Config parameters must be a non-null object');
});
});
sourceTemplate = deepCopy(REMOTE_CONFIG_RESPONSE);
INVALID_PARAMETER_GROUPS.forEach((invalidParameterGroup) => {
sourceTemplate.parameterGroups = invalidParameterGroup;
const jsonString = JSON.stringify(sourceTemplate);
it(`should throw if the parameter groups are ${JSON.stringify(invalidParameterGroup)}`,
() => {
expect(() => remoteConfig.createTemplateFromJSON(jsonString))
.to.throw('Remote Config parameter groups must be a non-null object');
});
});
sourceTemplate = deepCopy(REMOTE_CONFIG_RESPONSE);
INVALID_CONDITIONS.forEach((invalidConditions) => {
sourceTemplate.conditions = invalidConditions;
const jsonString = JSON.stringify(sourceTemplate);
it(`should throw if the conditions is ${JSON.stringify(invalidConditions)}`, () => {
expect(() => remoteConfig.createTemplateFromJSON(jsonString))
.to.throw('Remote Config conditions must be an array');
});
});
it('should succeed when a valid json string is provided', () => {
const jsonString = JSON.stringify(REMOTE_CONFIG_RESPONSE);
const newTemplate = remoteConfig.createTemplateFromJSON(jsonString);
expect(newTemplate.conditions.length).to.equal(1);
expect(newTemplate.conditions[0].name).to.equal('ios');
expect(newTemplate.conditions[0].expression).to.equal('device.os == \'ios\'');
expect(newTemplate.conditions[0].tagColor).to.equal('BLUE');
// verify that the etag is unchanged
expect(newTemplate.etag).to.equal('etag-123456789012-5');
// verify that the etag is read-only
expect(() => {
(newTemplate as any).etag = 'new-etag';
}).to.throw(
'Cannot set property etag of #<RemoteConfigTemplateImpl> which has only a getter');
const key = 'holiday_promo_enabled';
const p1 = newTemplate.parameters[key];
expect(p1.defaultValue).deep.equals({ value: 'true' });
expect(p1.conditionalValues).deep.equals({ ios: { useInAppDefault: true } });
expect(p1.description).equals('this is a promo');
expect(p1.valueType).equals('BOOLEAN');
const p2 = newTemplate.parameters['new_ui_enabled'];
expect(p2.defaultValue).deep.equals({ value: 'false' });
expect(p2.conditionalValues).to.not.be.undefined;
const rolloutParam = p2.conditionalValues!['ios'] as RolloutParameterValue;
expect(rolloutParam.rolloutValue.rolloutId).to.equal('rollout_1');
expect(rolloutParam.rolloutValue.value).to.equal('true');
expect(rolloutParam.rolloutValue.percent).to.equal(50);
expect(p2.description).equals('New UI Rollout');
expect(p2.valueType).equals('BOOLEAN');
const p3 = newTemplate.parameters['personalized_welcome_message'];
expect(p3.defaultValue).deep.equals({ value: 'Welcome!' });
expect(p3.conditionalValues).to.not.be.undefined;
const personalizationParam = p3.conditionalValues!['ios'] as PersonalizationParameterValue;
expect(personalizationParam.personalizationValue.personalizationId).to.equal('personalization_1');
expect(p3.description).equals('Personalized Welcome Message');
expect(p3.valueType).equals('STRING');
const p4 = newTemplate.parameters['experiment_enabled'];
expect(p4.defaultValue).deep.equals({ value: 'false' });
expect(p4.conditionalValues).to.not.be.undefined;
const experimentParam = p4.conditionalValues!['ios'] as ExperimentParameterValue;
expect(experimentParam.experimentValue.experimentId).to.equal('experiment_1');
expect(experimentParam.experimentValue.exposurePercent).to.equal(25);
expect(experimentParam.experimentValue.variantValue.length).to.equal(2);
expect(experimentParam.experimentValue.variantValue[0]).to.deep.equal({ variantId: 'variant_A', value: 'true' });
expect(experimentParam.experimentValue.variantValue[1]).to.deep.equal({ variantId: 'variant_B', noChange: true });
expect(p4.description).equals('Experiment Enabled');
expect(p4.valueType).equals('BOOLEAN');
expect(newTemplate.parameterGroups).deep.equals(PARAMETER_GROUPS);
const c = newTemplate.conditions.find((c) => c.name === 'ios');
expect(c).to.be.not.undefined;
const cond = c as RemoteConfigCondition;
expect(cond.name).to.equal('ios');
expect(cond.expression).to.equal('device.os == \'ios\'');
expect(cond.tagColor).to.equal('BLUE');
});
});
describe('getServerTemplate', () => {
const operationName = 'getServerTemplate';
it('should propagate API errors', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.rejects(INTERNAL_ERROR);
stubs.push(stub);
return remoteConfig.getServerTemplate().should.eventually.be.rejected.and.deep.equal(INTERNAL_ERROR);
});
it('should resolve a server template on success', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(SERVER_REMOTE_CONFIG_RESPONSE as ServerTemplateData);
stubs.push(stub);
return remoteConfig.getServerTemplate()
.then((template) => {
expect(template.toJSON().conditions.length).to.equal(1);
expect(template.toJSON().conditions[0].name).to.equal('ios');
expect(template.toJSON().etag).to.equal('etag-123456789012-5');
const version = template.toJSON().version!;
expect(version.versionNumber).to.equal('86');
expect(version.updateOrigin).to.equal('ADMIN_SDK_NODE');
expect(version.updateType).to.equal('INCREMENTAL_UPDATE');
expect(version.updateUser).to.deep.equal({
email: 'firebase-adminsdk@gserviceaccount.com'
});
expect(version.description).to.equal('production version');
expect(version.updateTime).to.equal('Mon, 15 Jun 2020 16:45:03 GMT');
const key = 'holiday_promo_enabled';
const p1 = template.toJSON().parameters[key];
expect(p1.defaultValue).deep.equals({ value: 'true' });
expect(p1.conditionalValues).deep.equals({ ios: { useInAppDefault: true } });
const c = template.toJSON().conditions.find((c) => c.name === 'ios');
expect(c).to.be.not.undefined;
const cond = c as NamedCondition;
expect(cond.name).to.equal('ios');
const parsed = template.toJSON();
const expectedTemplate = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
const expectedVersion = deepCopy(VERSION_INFO);
expectedVersion.updateTime = new Date(expectedVersion.updateTime).toUTCString();
expectedTemplate.version = expectedVersion;
expect(parsed).deep.equals(expectedTemplate);
});
});
it('should set defaultConfig when passed', () => {
// Defines template with no parameters to demonstrate
// default config will be used instead,
const template = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE) as ServerTemplateData;
template.parameters = {};
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(template);
stubs.push(stub);
const defaultConfig = {
holiday_promo_enabled: false,
holiday_promo_discount: 20,
};
return remoteConfig.getServerTemplate({ defaultConfig })
.then((template) => {
const config = template.evaluate();
expect(config.getBoolean('holiday_promo_enabled')).to.equal(
defaultConfig.holiday_promo_enabled);
expect(config.getNumber('holiday_promo_discount')).to.equal(
defaultConfig.holiday_promo_discount);
});
});
});
describe('initServerTemplate', () => {
it('should set and instantiates template when passed', () => {
const template = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE) as ServerTemplateData;
template.parameters = {
dog_type: {
defaultValue: {
value: 'shiba'
}
}
};
const initializedTemplate = remoteConfig.initServerTemplate({ template });
const parsed = initializedTemplate.toJSON();
const expectedVersion = deepCopy(VERSION_INFO);
expectedVersion.updateTime = new Date(expectedVersion.updateTime).toUTCString();
template.version = expectedVersion as Version;
expect(parsed).deep.equals(deepCopy(template));
});
it('should set and instantiates template when json string is passed', () => {
const template = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE) as ServerTemplateData;
template.parameters = {
dog_type: {
defaultValue: {
value: 'shiba'
},
description: 'Type of dog breed',
valueType: 'STRING'
}
};
const templateJson = JSON.stringify(template);
const initializedTemplate = remoteConfig.initServerTemplate({ template: templateJson });
const parsed = initializedTemplate.toJSON();
const expectedVersion = deepCopy(VERSION_INFO);
expectedVersion.updateTime = new Date(expectedVersion.updateTime).toUTCString();
template.version = expectedVersion as Version;
expect(parsed).deep.equals(deepCopy(template));
});
describe('should throw error if invalid template JSON is passed', () => {
const INVALID_PARAMETERS: any[] = [null, '', 'abc', 1, true, []];
const INVALID_CONDITIONS: any[] = [null, '', 'abc', 1, true, {}];
let sourceTemplate = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
const jsonString = '{invalidJson: null}';
it('should throw if template is an invalid JSON', () => {
expect(() => remoteConfig.initServerTemplate({ template: jsonString }))
.to.throw(/Failed to parse the JSON string: ([\D\w]*)\./);
});
INVALID_PARAMETERS.forEach((invalidParameter) => {
sourceTemplate.parameters = invalidParameter;
const jsonString = JSON.stringify(sourceTemplate);
it(`should throw if the parameters is ${JSON.stringify(invalidParameter)}`, () => {
expect(() => remoteConfig.initServerTemplate({ template: jsonString }))
.to.throw('Remote Config parameters must be a non-null object');
});
});
sourceTemplate = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
INVALID_CONDITIONS.forEach((invalidConditions) => {
sourceTemplate.conditions = invalidConditions;
const jsonString = JSON.stringify(sourceTemplate);
it(`should throw if the conditions is ${JSON.stringify(invalidConditions)}`, () => {
expect(() => remoteConfig.initServerTemplate({ template: jsonString }))
.to.throw('Remote Config conditions must be an array');
});
});
});
});
describe('RemoteConfigServerTemplate', () => {
const SERVER_REMOTE_CONFIG_RESPONSE_2 = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
SERVER_REMOTE_CONFIG_RESPONSE_2.parameters = {
dog_type: {
defaultValue: {
value: 'corgi'
}
},
dog_type_enabled: {
defaultValue: {
value: 'true'
}
},
dog_age: {
defaultValue: {
value: '22'
}
},
dog_jsonified: {
defaultValue: {
value: '{"name":"Taro","breed":"Corgi","age":1,"fluffiness":100}'
}
},
dog_use_inapp_default: {
defaultValue: {
useInAppDefault: true
}
},
dog_no_remote_default_value: {
}
};
describe('load', () => {
const operationName = 'getServerTemplate';
it('should propagate API errors', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.rejects(INTERNAL_ERROR);
stubs.push(stub);
return remoteConfig.getServerTemplate().should.eventually.be.rejected.and.deep.equal(INTERNAL_ERROR);
});
it('should reject when API response is invalid', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(undefined);
stubs.push(stub);
return remoteConfig.getServerTemplate().should.eventually.be.rejected.and.have.property(
'message', 'Invalid Remote Config template: undefined');
});
it('should reject when API response does not contain an ETag', () => {
const response = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
response.etag = '';
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(response as ServerTemplateData);
stubs.push(stub);
return remoteConfig.getServerTemplate()
.should.eventually.be.rejected.and.have.property(
'message', `Invalid Remote Config template: ${JSON.stringify(response)}`);
});
it('should reject when API response does not contain valid parameters', () => {
const response = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
response.parameters = null;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(response as ServerTemplateData);
stubs.push(stub);
return remoteConfig.getServerTemplate()
.should.eventually.be.rejected.and.have.property(
'message', 'Remote Config parameters must be a non-null object');
});
it('should reject when API response does not contain valid conditions', () => {
const response = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
response.conditions = Object();
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(response as ServerTemplateData);
stubs.push(stub);
return remoteConfig.getServerTemplate()
.should.eventually.be.rejected.and.have.property(
'message', 'Remote Config conditions must be an array');
});
it('should resolve with parameters:{} when no parameters present in the response', () => {
const response = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
response.parameters = undefined;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(response as ServerTemplateData);
stubs.push(stub);
return remoteConfig.getServerTemplate()
.then((template) => {
// If parameters are not present in the response, we set it to an empty object.
expect(template.toJSON().parameters).deep.equals({});
});
});
it('should resolve with conditions:[] when no conditions present in the response', () => {
const response = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
response.conditions = undefined;
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(response as ServerTemplateData);
stubs.push(stub);
return remoteConfig.getServerTemplate()
.then((template) => {
// If conditions are not present in the response, we set it to an empty array.
expect(template.toJSON().conditions).deep.equals([]);
});
});
it('should resolve a server template on success', () => {
const stub = sinon
.stub(RemoteConfigApiClient.prototype, operationName)
.resolves(SERVER_REMOTE_CONFIG_RESPONSE as ServerTemplateData);
stubs.push(stub);
return remoteConfig.getServerTemplate()
.then((template) => {
expect(template.toJSON().conditions.length).to.equal(1);
expect(template.toJSON().conditions[0].name).to.equal('ios');
expect(template.toJSON().etag).to.equal('etag-123456789012-5');
const version = template.toJSON().version!;
expect(version.versionNumber).to.equal('86');
expect(version.updateOrigin).to.equal('ADMIN_SDK_NODE');
expect(version.updateType).to.equal('INCREMENTAL_UPDATE');
expect(version.updateUser).to.deep.equal({
email: 'firebase-adminsdk@gserviceaccount.com'
});
expect(version.description).to.equal('production version');
expect(version.updateTime).to.equal('Mon, 15 Jun 2020 16:45:03 GMT');
const key = 'holiday_promo_enabled';
const p1 = template.toJSON().parameters[key];
expect(p1.defaultValue).deep.equals({ value: 'true' });
expect(p1.conditionalValues).deep.equals({ ios: { useInAppDefault: true } });
const c = template.toJSON().conditions.find((c) => c.name === 'ios');
expect(c).to.be.not.undefined;
const cond = c as NamedCondition;
expect(cond.name).to.equal('ios');
expect(cond.condition).deep.equals({
'orCondition': {
'conditions': [
{
'andCondition': {
'conditions': [
{
'true': {}
}
]
}
}
]
}
});
const parsed = template.toJSON();
const expectedTemplate = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
const expectedVersion = deepCopy(VERSION_INFO);
expectedVersion.updateTime = new Date(expectedVersion.updateTime).toUTCString();
expectedTemplate.version = expectedVersion;
expect(parsed).deep.equals(expectedTemplate);
});
});
it('should resolve with template when Version updateTime contains 3 digits in fractional seconds', () => {
const response = deepCopy(SERVER_REMOTE_CONFIG_RESPONSE);
const versionInfo = deepCopy(VERSION_INFO);