-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathFlagsmithClientTest.java
More file actions
1001 lines (846 loc) · 39.5 KB
/
FlagsmithClientTest.java
File metadata and controls
1001 lines (846 loc) · 39.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.flagsmith;
import static okhttp3.mock.MediaTypes.MEDIATYPE_JSON;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.flagsmith.config.FlagsmithCacheConfig;
import com.flagsmith.config.FlagsmithConfig;
import com.flagsmith.exceptions.FlagsmithApiError;
import com.flagsmith.exceptions.FlagsmithClientError;
import com.flagsmith.exceptions.FlagsmithRuntimeError;
import com.flagsmith.flagengine.EvaluationContext;
import com.flagsmith.flagengine.EvaluationResult;
import com.flagsmith.interfaces.FlagsmithCache;
import com.flagsmith.models.BaseFlag;
import com.flagsmith.models.DefaultFlag;
import com.flagsmith.models.environments.EnvironmentModel;
import com.flagsmith.models.features.FeatureStateModel;
import com.flagsmith.models.Flags;
import com.flagsmith.models.SdkTraitModel;
import com.flagsmith.models.Segment;
import com.flagsmith.models.TraitConfig;
import com.flagsmith.models.TraitModel;
import com.flagsmith.responses.FlagsAndTraitsResponse;
import com.flagsmith.threads.PollingManager;
import com.flagsmith.threads.RequestProcessor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okhttp3.mock.MockInterceptor;
import okio.Buffer;
import com.flagsmith.flagengine.Engine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.invocation.Invocation;
import org.slf4j.Logger;
/**
* Unit tests are env specific and will probably will need to adjust keys,
* identities and features
* ids etc as required.
*/
public class FlagsmithClientTest {
private static String DEFAULT_FLAG_VALUE = "foobar";
private static boolean DEFAULT_FLAG_STATE = true;
private static BaseFlag defaultHandler(String featureName) {
DefaultFlag defaultFlag = new DefaultFlag();
defaultFlag.setEnabled(DEFAULT_FLAG_STATE);
defaultFlag.setValue(DEFAULT_FLAG_VALUE);
defaultFlag.setFeatureName(featureName);
return defaultFlag;
}
@Test
public void testClient_When_Cache_Disabled_Return_Null() {
FlagsmithClient client = FlagsmithClient.newBuilder()
.setApiKey("api-key")
.build();
FlagsmithCache cache = client.getCache();
assertNull(cache);
}
@Test
public void testClient_validateObjectCreation() throws InterruptedException {
PollingManager manager = mock(PollingManager.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withPollingManager(manager)
.withConfiguration(
FlagsmithConfig.newBuilder().withLocalEvaluation(Boolean.TRUE).build())
.setApiKey("ser.abcdefg")
.build();
Thread.sleep(10);
verify(manager, times(1)).startPolling();
}
@Test
public void testLocalEvaluationRequiresServerKey() throws InterruptedException {
assertThrows(RuntimeException.class, () -> FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder().withLocalEvaluation(Boolean.TRUE).build())
.setApiKey("not-a-server-key")
.build());
}
@Test
public void testClient_errorEnvironmentApi() {
Logger logger = mock(Logger.class);
String baseUrl = "http://bad-url";
MockInterceptor interceptor = new MockInterceptor();
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.enableLogging(logger)
.setApiKey("api-key")
.build();
interceptor.addRule()
.get(baseUrl + "/environment-document/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.respond(
500,
ResponseBody.create("error", MEDIATYPE_JSON));
client.updateEnvironment();
// Verify that an error was written to the log by mocking the logger and checking that a call was made
// with the expected log message. Note that the logger will also have other invocations so we need to
// iterate over them to check that the one we expect has been made.
boolean found = false;
String expectedMsg = "Unable to update environment from API. No environment configured - using defaultHandler if configured.";
for (Invocation invocation : Mockito.mockingDetails(logger).getInvocations().stream().collect(Collectors.toList())) {
if (invocation.getArgument(0).toString().contains(expectedMsg)) {
found = true;
}
}
assertTrue(found);
}
@Test
public void testClient_validateEnvironment()
throws JsonProcessingException {
String baseUrl = "http://bad-url";
MockInterceptor interceptor = new MockInterceptor();
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
interceptor.addRule()
.get(baseUrl + "/environment-document/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.anyTimes()
.respond(
FlagsmithTestHelper.environmentString(),
MEDIATYPE_JSON);
client.updateEnvironment();
assertNotNull(client.getEvaluationContext());
assertEquals(client.getEvaluationContext(), evaluationContext);
}
@Test
public void testClient_flagsApiException()
throws FlagsmithApiError {
String baseUrl = "http://bad-url";
MockInterceptor interceptor = new MockInterceptor();
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
interceptor.addRule()
.get(baseUrl + "/flags/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.respond(
500,
ResponseBody.create("error", MEDIATYPE_JSON));
assertThrows(FlagsmithApiError.class, () -> client.getEnvironmentFlags());
}
@Test
public void testClient_flagsApiEmpty()
throws FlagsmithClientError {
String baseUrl = "http://bad-url";
MockInterceptor interceptor = new MockInterceptor();
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
interceptor.addRule()
.get(baseUrl + "/flags/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.respond(
"[]",
MEDIATYPE_JSON);
assertNotNull(client);
List<BaseFlag> flags = client.getEnvironmentFlags().getAllFlags();
assertTrue(flags.isEmpty());
}
@Test
public void testClient_flagsApi()
throws JsonProcessingException, FlagsmithClientError {
String baseUrl = "http://bad-url";
MockInterceptor interceptor = new MockInterceptor();
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
List<FeatureStateModel> featureStateModel = FlagsmithTestHelper.getFlags();
interceptor.addRule()
.get(baseUrl + "/flags/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.respond(
MapperFactory.getMapper().writeValueAsString(featureStateModel),
MEDIATYPE_JSON);
List<BaseFlag> flags = client.getEnvironmentFlags().getAllFlags();
assertEquals(flags.get(0).getEnabled(), Boolean.TRUE);
assertEquals(flags.get(0).getValue(), "some-value");
assertEquals(flags.get(0).getFeatureName(), "some_feature");
}
@Test
public void testClient_identityFlagsApiNoTraitsException() throws FlagsmithClientError {
String baseUrl = "http://bad-url";
String identifier = "identifier";
MockInterceptor interceptor = new MockInterceptor();
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
interceptor.addRule()
.post(baseUrl + "/identities/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.respond(
500,
ResponseBody.create("error", MEDIATYPE_JSON));
assertThrows(FlagsmithApiError.class, () -> client.getIdentityFlags(identifier));
}
@Test
public void testClient_identityFlagsApiNoTraits() throws FlagsmithClientError {
String baseUrl = "http://bad-url";
String identifier = "identifier";
MockInterceptor interceptor = new MockInterceptor();
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
String json = FlagsmithTestHelper.getIdentitiesFlags();
interceptor.addRule()
.post(baseUrl + "/identities/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.respond(
json,
MEDIATYPE_JSON);
List<BaseFlag> flags = client.getIdentityFlags(identifier).getAllFlags();
assertEquals(flags.get(0).getEnabled(), Boolean.TRUE);
assertEquals(flags.get(0).getValue(), "some-value");
assertEquals(flags.get(0).getFeatureName(), "some_feature");
}
private static Stream<Arguments> dataProviderForIdentityFlagsApiWithTraitsTest() {
return Stream.of(
Arguments.of(
"identifier",
false,
new HashMap<String, Object>() {
{
put("some_trait", "some_value");
put("transient_trait", new TraitConfig("transient_value", true));
}
}, FlagsmithTestHelper.getIdentityRequest("identifier", new ArrayList<SdkTraitModel>() {
{
add(
SdkTraitModel.builder()
.traitKey("some_trait")
.traitValue("some_value")
.build()
);
add(
SdkTraitModel.builder()
.traitKey("transient_trait")
.traitValue("transient_value")
.isTransient(true)
.build()
);
}
})),
Arguments.of(
"transient-identifier",
true,
new HashMap<String, Object>() {
{
put("some_trait", "some_value");
}
}, FlagsmithTestHelper.getIdentityRequest("transient-identifier", new ArrayList<TraitModel>() {
{
add(
TraitModel.builder()
.traitKey("some_trait")
.traitValue("some_value")
.build()
);
}
}, true))
);
}
@ParameterizedTest
@MethodSource("dataProviderForIdentityFlagsApiWithTraitsTest")
public void testClient_identityFlagsApiWithTraits(
String identifier, boolean isTransient, Map<String, Object> traits, JsonNode expectedRequest)
throws FlagsmithClientError, IOException {
String baseUrl = "http://bad-url";
MockInterceptor interceptor = new MockInterceptor();
RequestProcessor requestProcessor = mock(RequestProcessor.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
// mocking the requestor
((FlagsmithApiWrapper) client.getFlagsmithSdk()).setRequestor(requestProcessor);
String json = FlagsmithTestHelper.getIdentitiesFlags();
TypeReference<FlagsAndTraitsResponse> tr = new TypeReference<FlagsAndTraitsResponse>() {
};
when(requestProcessor.executeAsync(any(), any(), any()))
.thenReturn(
FlagsmithTestHelper.futurableReturn(MapperFactory.getMapper().readValue(json, tr)));
List<BaseFlag> flags = client.getIdentityFlags(identifier, traits, isTransient).getAllFlags();
ArgumentCaptor<Request> argument = ArgumentCaptor.forClass(Request.class);
verify(requestProcessor, times(1)).executeAsync(argument.capture(), any(), any());
Buffer buffer = new Buffer();
argument.getValue().body().writeTo(buffer);
assertEquals(expectedRequest.toString(), buffer.readUtf8());
assertEquals(flags.get(0).getEnabled(), Boolean.TRUE);
assertEquals(flags.get(0).getValue(), "some-value");
assertEquals(flags.get(0).getFeatureName(), "some_feature");
}
@Test
public void testClient_identityFlagsApiWithTraitsWithLocalEnvironment() {
String baseUrl = "http://bad-url";
String identifier = "identifier";
Map<String, Object> traits = new HashMap<String, Object>() {
{
put("some_trait", "some_value");
}
};
MockInterceptor interceptor = new MockInterceptor();
RequestProcessor requestProcessor = mock(RequestProcessor.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.build();
interceptor.addRule()
.get(baseUrl + "/flags/")
.anyTimes()
.respond(500, ResponseBody.create("error", MEDIATYPE_JSON));
assertThrows(FlagsmithApiError.class,
() -> client.getEnvironmentFlags());
}
@Test
public void testClient_defaultFlagWithNoEnvironment() throws FlagsmithClientError {
String baseUrl = "http://bad-url";
String identifier = "identifier";
Map<String, Object> traits = new HashMap<String, Object>() {
{
put("some_trait", "some_value");
}
};
MockInterceptor interceptor = new MockInterceptor();
RequestProcessor requestProcessor = mock(RequestProcessor.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.build())
.setApiKey("api-key")
.setDefaultFlagValueFunction((name) -> {
DefaultFlag flag = new DefaultFlag();
flag.setValue("some-value");
flag.setEnabled(true);
return flag;
})
.build();
interceptor.addRule()
.get(baseUrl + "/flags/")
.headerMatches("X-Environment-Key", Pattern.compile("api-key"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.respond(
"[]",
MEDIATYPE_JSON);
Flags flags = client.getEnvironmentFlags();
DefaultFlag flag = (DefaultFlag) flags.getFlag("some_feature");
assertEquals(flag.getIsDefault(), Boolean.TRUE);
assertEquals(flag.getEnabled(), Boolean.TRUE);
assertEquals(flag.getValue(), "some-value");
}
@Test
public void testClient_When_Cache_Enabled_Return_Cache_Obj() {
FlagsmithClient client = FlagsmithClient.newBuilder()
.setApiKey("api-key")
.withCache(FlagsmithCacheConfig
.newBuilder()
.enableEnvLevelCaching("newkey-random-name")
.maxSize(2)
.build())
.build();
FlagsmithCache cache = client.getCache();
assertNotNull(cache);
}
@Test
public void testGetIdentitySegmentsNoTraits() throws JsonProcessingException,
FlagsmithClientError {
String baseUrl = "http://bad-url";
EnvironmentModel environmentModel = FlagsmithTestHelper.environmentModel();
MockInterceptor interceptor = new MockInterceptor();
interceptor.addRule()
.get(baseUrl + "/environment-document/")
.headerMatches("X-Environment-Key", Pattern.compile("ser.abcdefg"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.anyTimes()
.respond(
MapperFactory.getMapper().writeValueAsString(environmentModel),
MEDIATYPE_JSON);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.withLocalEvaluation(true)
.build())
.setApiKey("ser.abcdefg")
.build();
client.updateEnvironment();
String identifier = "identifier";
List<Segment> segments = client.getIdentitySegments(identifier);
assertTrue(segments.isEmpty());
}
@Test
public void testGetIdentitySegmentsWithValidTrait() throws JsonProcessingException,
FlagsmithClientError {
String baseUrl = "http://bad-url";
EnvironmentModel environmentModel = FlagsmithTestHelper.environmentModel();
MockInterceptor interceptor = new MockInterceptor();
interceptor.addRule()
.get(baseUrl + "/environment-document/")
.headerMatches("X-Environment-Key", Pattern.compile("ser.abcdefg"))
.headerMatches("User-Agent", Pattern.compile("flagsmith-java-sdk/.*"))
.anyTimes()
.respond(
MapperFactory.getMapper().writeValueAsString(environmentModel),
MEDIATYPE_JSON);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withConfiguration(
FlagsmithConfig.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.withLocalEvaluation(true)
.build())
.setApiKey("ser.abcdefg")
.build();
client.updateEnvironment();
String identifier = "identifier";
Map<String, Object> traits = new HashMap<String, Object>() {
{
put("foo", "bar");
}
};
List<Segment> segments = client.getIdentitySegments(identifier, traits);
assertEquals(segments.size(), 1);
assertEquals(segments.get(0).getName(), "Test segment");
}
@Test
public void testUpdateEnvironment_DoesNothing_WhenGetEnvironmentThrowsExceptionAndEnvironmentExists() {
// Given
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
FlagsmithApiWrapper mockApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockApiWrapper.getEvaluationContext())
.thenReturn(evaluationContext)
.thenThrow(RuntimeException.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockApiWrapper)
.withConfiguration(FlagsmithConfig.newBuilder().withLocalEvaluation(true).build())
.setApiKey("ser.dummy-key")
.build();
// When
// we call the update environment method twice (1st should be successful, 2nd
// will do nothing because of error)
client.updateEnvironment();
client.updateEnvironment();
// Then
// No exception is thrown and the client environment remains what was first
// retrieved from the ApiWrapper
assertEquals(client.getEvaluationContext(), evaluationContext);
}
@Test
public void testUpdateEnvironment_DoesNothing_WhenGetEnvironmentReturnsNullAndEnvironmentExists() {
// Given
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
FlagsmithApiWrapper mockApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockApiWrapper.getEvaluationContext())
.thenReturn(evaluationContext)
.thenReturn(null);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockApiWrapper)
.withConfiguration(FlagsmithConfig.newBuilder().withLocalEvaluation(true).build())
.setApiKey("ser.dummy-key")
.build();
// When
// we call the update environment method twice
// (1st should be successful, 2nd will do nothing because of null return)
client.updateEnvironment();
client.updateEnvironment();
// Then
// The client environment is not overwritten with null
assertEquals(client.getEvaluationContext(), evaluationContext);
}
@Test
public void testUpdateEnvironment_DoesNothing_WhenGetEnvironmentReturnsNullAndEnvironmentNotExists() {
// Given
FlagsmithApiWrapper mockApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockApiWrapper.getEvaluationContext()).thenThrow(RuntimeException.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockApiWrapper)
.withConfiguration(FlagsmithConfig.newBuilder().withLocalEvaluation(true).build())
.setApiKey("ser.dummy-key")
.build();
// When
client.updateEnvironment();
// Then
// The environment remains null
assertEquals(client.getEvaluationContext(), null);
}
@Test
public void testUpdateEnvironment_StoresIdentityOverrides_WhenGetEnvironmentReturnsEnvironmentWithOverrides()
throws FlagsmithClientError {
// Given
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
FlagsmithConfig config = FlagsmithConfig.newBuilder()
.withLocalEvaluation(true)
.build();
FlagsmithApiWrapper mockApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockApiWrapper.getEvaluationContext()).thenReturn(evaluationContext);
when(mockApiWrapper.getConfig()).thenReturn(config);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockApiWrapper)
.withConfiguration(config)
.setApiKey("ser.dummy-key")
.build();
// When
client.updateEnvironment();
// Then
// Identity overrides are correctly stored
assertEquals(
client.getIdentityFlags("overridden-identity")
.getFlag("some_feature").getValue(),
"overridden-value");
}
@Test
public void testClose_StopsPollingManager() {
// Given
PollingManager mockedPollingManager = mock(PollingManager.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withPollingManager(mockedPollingManager)
.withConfiguration(FlagsmithConfig.newBuilder().withLocalEvaluation(true).build())
.setApiKey("ser.dummy-key")
.build();
// When
client.close();
// Then
verify(mockedPollingManager, times(1)).stopPolling();
}
@Test
public void testClose_ClosesFlagsmithSdk() {
// Given
FlagsmithApiWrapper mockedApiWrapper = mock(FlagsmithApiWrapper.class);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockedApiWrapper)
.withConfiguration(FlagsmithConfig.newBuilder().withLocalEvaluation(true).build())
.setApiKey("ser.dummy-key")
.build();
// When
client.close();
// Then
verify(mockedApiWrapper, times(1)).close();
}
@Test
public void testLocalEvaluation_ReturnsConsistentResults() throws FlagsmithClientError {
// Specific test to ensure that results are consistent when making multiple
// calls to
// evaluate flags soon after the client is instantiated.
// Given
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
FlagsmithConfig config = FlagsmithConfig.newBuilder().withLocalEvaluation(true).build();
FlagsmithApiWrapper mockedApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockedApiWrapper.getEvaluationContext())
.thenReturn(evaluationContext)
.thenReturn(null);
when(mockedApiWrapper.getConfig()).thenReturn(config);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockedApiWrapper)
.withConfiguration(config)
.setApiKey("ser.dummy-key")
.build();
// When
// make 3 calls to get identity flags
List<Flags> results = new ArrayList<>();
for (int i = 0; i < 3; ++i) {
results.add(client.getIdentityFlags("some-identity"));
}
// Then
// iterate over the results list and verify that the results are all the same
boolean expectedState = true;
String expectedValue = "some-value";
for (Flags flags : results) {
assertEquals(flags.isFeatureEnabled("some_feature"), expectedState);
assertEquals(flags.getFeatureValue("some_feature"), expectedValue);
}
}
@Test
public void testLocalEvaluation_ReturnsIdentityOverrides() throws FlagsmithClientError {
// Given
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
FlagsmithConfig config = FlagsmithConfig.newBuilder().withLocalEvaluation(true).build();
FlagsmithApiWrapper mockedApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockedApiWrapper.getEvaluationContext())
.thenReturn(evaluationContext)
.thenReturn(null);
when(mockedApiWrapper.getConfig()).thenReturn(config);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockedApiWrapper)
.withConfiguration(config)
.setApiKey("ser.dummy-key")
.build();
Flags flagsWithoutOverride = client.getIdentityFlags("test");
// When
Flags flagsWithOverride = client.getIdentityFlags("overridden-identity");
// Then
assertEquals(flagsWithoutOverride.getFeatureValue("some_feature"), "some-value");
assertEquals(flagsWithOverride.getFeatureValue("some_feature"), "overridden-value");
}
@Test
public void testLocalEvaluation_getEnvironmentFlags_NoTargeting() throws FlagsmithClientError {
// Given
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
EvaluationResult evaluationResult = Engine.getEvaluationResult(
new EvaluationContext(evaluationContext)
.withSegments(null)
);
FlagsmithConfig config = FlagsmithConfig.newBuilder().withLocalEvaluation(true).build();
FlagsmithApiWrapper mockedApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockedApiWrapper.getEvaluationContext())
.thenReturn(evaluationContext);
when(mockedApiWrapper.getConfig()).thenReturn(config);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockedApiWrapper)
.withConfiguration(config)
.setApiKey("ser.dummy-key")
.build();
// When
try (MockedStatic<Engine> mockedEngine = mockStatic(Engine.class)) {
mockedEngine.when(
() -> Engine.getEvaluationResult(
new EvaluationContext(evaluationContext)
.withSegments(null)
)
).thenReturn(evaluationResult);
client.getEnvironmentFlags();
// Then
mockedEngine.verify(
() -> Engine.getEvaluationResult(
new EvaluationContext(evaluationContext)
.withSegments(null)
)
);
}
}
@Test
public void testGetEnvironmentFlags_UsesDefaultFlags_IfLocalEvaluationEnvironmentNull()
throws FlagsmithClientError {
// Given
FlagsmithConfig config = FlagsmithConfig.newBuilder().withLocalEvaluation(true).build();
FlagsmithApiWrapper mockedApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockedApiWrapper.getEvaluationContext()).thenThrow(RuntimeException.class);
when(mockedApiWrapper.getConfig()).thenReturn(config);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockedApiWrapper)
.withConfiguration(config)
.setApiKey("ser.dummy-key")
.setDefaultFlagValueFunction(FlagsmithClientTest::defaultHandler)
.build();
// When
Flags environmentFlags = client.getEnvironmentFlags();
// Then
assertEquals(environmentFlags.getFeatureValue("foo"), DEFAULT_FLAG_VALUE);
assertEquals(environmentFlags.isFeatureEnabled("foo"), DEFAULT_FLAG_STATE);
}
@Test
public void testGetIdentityFlags_UsesDefaultFlags_IfLocalEvaluationEnvironmentNull() throws FlagsmithClientError {
// Given
FlagsmithConfig config = FlagsmithConfig.newBuilder().withLocalEvaluation(true).build();
FlagsmithApiWrapper mockedApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockedApiWrapper.getEvaluationContext()).thenThrow(RuntimeException.class);
when(mockedApiWrapper.getConfig()).thenReturn(config);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockedApiWrapper)
.withConfiguration(config)
.setApiKey("ser.dummy-key")
.setDefaultFlagValueFunction(FlagsmithClientTest::defaultHandler)
.build();
// When
Flags identityFlags = client.getIdentityFlags("some-identity");
// Then
assertEquals(identityFlags.getFeatureValue("foo"), DEFAULT_FLAG_VALUE);
assertEquals(identityFlags.isFeatureEnabled("foo"), DEFAULT_FLAG_STATE);
}
@Test
public void testClose() throws FlagsmithApiError, InterruptedException {
// Given
int pollingIntervalSeconds = 1;
FlagsmithConfig config = FlagsmithConfig
.newBuilder()
.withLocalEvaluation(true)
.withEnvironmentRefreshIntervalSeconds(pollingIntervalSeconds)
.build();
FlagsmithApiWrapper mockedApiWrapper = mock(FlagsmithApiWrapper.class);
when(mockedApiWrapper.getEvaluationContext()).thenReturn(FlagsmithTestHelper.evaluationContext());
when(mockedApiWrapper.getConfig()).thenReturn(config);
FlagsmithClient client = FlagsmithClient.newBuilder()
.withFlagsmithApiWrapper(mockedApiWrapper)
.withConfiguration(config)
.setApiKey("ser.dummy-key")
.build();
// When
client.close();
// Then
// Since the thread will only stop once it reads the interrupt signal correctly
// on its next polling interval, we need to wait for the polling interval
// to complete before checking the thread has been killed correctly.
Thread.sleep((pollingIntervalSeconds * 1000) + 100);
assertFalse(client.getPollingManager().getIsThreadAlive());
}
@Test
public void testOfflineMode() throws FlagsmithClientError {
// Given
EvaluationContext evaluationContext = FlagsmithTestHelper.evaluationContext();
FlagsmithConfig config = FlagsmithConfig
.newBuilder()
.withOfflineMode(true)
.withOfflineHandler(new DummyOfflineHandler())
.build();
// When
FlagsmithClient client = FlagsmithClient.newBuilder().withConfiguration(config).build();
// Then
assertEquals(evaluationContext, client.getEvaluationContext());
Flags environmentFlags = client.getEnvironmentFlags();
assertTrue(environmentFlags.isFeatureEnabled("some_feature"));
Flags identityFlags = client.getIdentityFlags("my-identity");
assertTrue(identityFlags.isFeatureEnabled("some_feature"));
}
@Test
public void testCannotUserOfflineModeWithoutOfflineHandler() throws FlagsmithRuntimeError {
FlagsmithConfig config = FlagsmithConfig.newBuilder().withOfflineMode(true).build();
FlagsmithRuntimeError ex = assertThrows(
FlagsmithRuntimeError.class,
() -> FlagsmithClient.newBuilder().withConfiguration(config).build());
assertEquals("Offline handler must be provided to use offline mode.", ex.getMessage());
}
@Test
public void testCannotUserOfflineHandlerWithLocalEvaluationMode() throws FlagsmithRuntimeError {
FlagsmithConfig config = FlagsmithConfig
.newBuilder()
.withOfflineHandler(new DummyOfflineHandler())
.withLocalEvaluation(true)
.build();
FlagsmithRuntimeError ex = assertThrows(
FlagsmithRuntimeError.class,
() -> FlagsmithClient.newBuilder().withConfiguration(config).build());
assertEquals("Local evaluation and offline handler cannot be used together.", ex.getMessage());
}
@Test
public void testCannotUseDefaultHandlerAndOfflineHandler() throws FlagsmithClientError {
FlagsmithConfig config = FlagsmithConfig
.newBuilder()
.withOfflineHandler(new DummyOfflineHandler())
.build();
FlagsmithClient.Builder clientBuilder = FlagsmithClient
.newBuilder()
.withConfiguration(config)
.setDefaultFlagValueFunction(FlagsmithClientTest::defaultHandler);
FlagsmithRuntimeError ex = assertThrows(
FlagsmithRuntimeError.class,
() -> clientBuilder.build());
assertEquals("Cannot use both default flag handler and offline handler.", ex.getMessage());
}
@Test
public void testFlagsmithUsesOfflineHandlerIfSetAndNoAPIResponse() throws FlagsmithClientError {
// Given
MockInterceptor interceptor = new MockInterceptor();
String baseUrl = "http://bad-url";
FlagsmithConfig config = FlagsmithConfig
.newBuilder()
.baseUri(baseUrl)
.addHttpInterceptor(interceptor)
.withOfflineHandler(new DummyOfflineHandler())
.build();
FlagsmithClient client = FlagsmithClient
.newBuilder()
.withConfiguration(config)
.setApiKey("some-key")
.build();
interceptor.addRule().get(baseUrl + "/flags/").respond(500);
interceptor.addRule().post(baseUrl + "/identities/").respond(500);
// When
Flags environmentFlags = client.getEnvironmentFlags();
Flags identityFlags = client.getIdentityFlags("some-identity");
// Then
assertTrue(environmentFlags.isFeatureEnabled("some_feature"));
assertTrue(identityFlags.isFeatureEnabled("some_feature"));
}