-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathHookSpecTest.java
804 lines (703 loc) · 31.6 KB
/
HookSpecTest.java
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
package dev.openfeature.sdk;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import dev.openfeature.sdk.exceptions.FlagNotFoundError;
import dev.openfeature.sdk.fixtures.HookFixtures;
import dev.openfeature.sdk.testutils.TestEventsProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.SneakyThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
class HookSpecTest implements HookFixtures {
private OpenFeatureAPI api;
@BeforeEach
void setUp() {
this.api = new OpenFeatureAPI();
}
@Specification(
number = "4.1.3",
text =
"The flag key, flag type, and default value properties MUST be immutable. If the language does not support immutability, the hook MUST NOT modify these properties.")
@Test
void immutableValues() {
try {
HookContext.class.getMethod("setFlagKey");
fail("Shouldn't be able to find this method");
} catch (NoSuchMethodException e) {
// expected
}
try {
HookContext.class.getMethod("setType");
fail("Shouldn't be able to find this method");
} catch (NoSuchMethodException e) {
// expected
}
try {
HookContext.class.getMethod("setDefaultValue");
fail("Shouldn't be able to find this method");
} catch (NoSuchMethodException e) {
// expected
}
}
@Specification(
number = "4.1.1",
text =
"Hook context MUST provide: the flag key, flag value type, evaluation context, and the default value.")
@Test
void nullish_properties_on_hookcontext() {
// missing ctx
try {
HookContext.<Integer>builder()
.flagKey("key")
.type(FlagValueType.INTEGER)
.defaultValue(1)
.build();
fail("Missing context shouldn't be valid");
} catch (NullPointerException e) {
// expected
}
// missing type
try {
HookContext.<Integer>builder()
.flagKey("key")
.ctx(null)
.defaultValue(1)
.build();
fail("Missing type shouldn't be valid");
} catch (NullPointerException e) {
// expected
}
// missing key
try {
HookContext.<Integer>builder()
.type(FlagValueType.INTEGER)
.ctx(null)
.defaultValue(1)
.build();
fail("Missing key shouldn't be valid");
} catch (NullPointerException e) {
// expected
}
// missing default value
try {
HookContext.<Integer>builder()
.flagKey("key")
.type(FlagValueType.INTEGER)
.ctx(new ImmutableContext())
.build();
fail("Missing default value shouldn't be valid");
} catch (NullPointerException e) {
// expected
}
// normal
try {
HookContext.<Integer>builder()
.flagKey("key")
.type(FlagValueType.INTEGER)
.ctx(new ImmutableContext())
.defaultValue(1)
.build();
} catch (NullPointerException e) {
fail("NPE after we provided all relevant info");
}
}
@Specification(
number = "4.1.2",
text = "The hook context SHOULD provide: access to the client metadata and the provider metadata fields.")
@Test
void optional_properties() {
// don't specify
HookContext.<Integer>builder()
.flagKey("key")
.type(FlagValueType.INTEGER)
.ctx(new ImmutableContext())
.defaultValue(1)
.build();
// add optional provider
HookContext.<Integer>builder()
.flagKey("key")
.type(FlagValueType.INTEGER)
.ctx(new ImmutableContext())
.providerMetadata(new NoOpProvider().getMetadata())
.defaultValue(1)
.build();
// add optional client
HookContext.<Integer>builder()
.flagKey("key")
.type(FlagValueType.INTEGER)
.ctx(new ImmutableContext())
.defaultValue(1)
.clientMetadata(api.getClient().getMetadata())
.build();
}
@Specification(
number = "4.3.2.1",
text =
"The before stage MUST run before flag resolution occurs. It accepts a hook context (required) and hook hints (optional) as parameters and returns either an evaluation context or nothing.")
@Test
void before_runs_ahead_of_evaluation() {
api.setProviderAndWait(new AlwaysBrokenWithExceptionProvider());
Client client = api.getClient();
Hook<Boolean> evalHook = mockBooleanHook();
client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(evalHook).build());
verify(evalHook, times(1)).before(any(), any());
}
@Test
void feo_has_hook_list() {
FlagEvaluationOptions feo = FlagEvaluationOptions.builder().build();
assertNotNull(feo.getHooks());
}
@Test
void error_hook_run_during_non_finally_stage() {
final boolean[] error_called = {false};
Hook h = mockBooleanHook();
doThrow(RuntimeException.class).when(h).finallyAfter(any(), any(), any());
verify(h, times(0)).error(any(), any(), any());
}
@Test
void error_hook_must_run_if_resolution_details_returns_an_error_code() {
String errorMessage = "not found...";
EvaluationContext invocationCtx = new ImmutableContext();
Hook<Boolean> hook = mockBooleanHook();
FeatureProvider provider = mock(FeatureProvider.class);
when(provider.getBooleanEvaluation(any(), any(), any()))
.thenReturn(ProviderEvaluation.<Boolean>builder()
.errorCode(ErrorCode.FLAG_NOT_FOUND)
.errorMessage(errorMessage)
.build());
api.setProviderAndWait("errorHookMustRun", provider);
Client client = api.getClient("errorHookMustRun");
client.getBooleanValue(
"key",
false,
invocationCtx,
FlagEvaluationOptions.builder().hook(hook).build());
ArgumentCaptor<Exception> captor = ArgumentCaptor.forClass(Exception.class);
verify(hook, times(1)).before(any(), any());
verify(hook, times(1)).error(any(), captor.capture(), any());
verify(hook, times(1)).finallyAfter(any(), any(), any());
verify(hook, never()).after(any(), any(), any());
Exception exception = captor.getValue();
assertEquals(errorMessage, exception.getMessage());
assertInstanceOf(FlagNotFoundError.class, exception);
}
@Specification(
number = "4.3.6",
text =
"The after stage MUST run after flag resolution occurs. It accepts a hook context (required), flag evaluation details (required) and hook hints (optional). It has no return value.")
@Specification(
number = "4.3.7",
text =
"The error hook MUST run when errors are encountered in the before stage, the after stage or during flag resolution. It accepts hook context (required), exception representing what went wrong (required), and hook hints (optional). It has no return value.")
@Specification(
number = "4.3.8",
text =
"The finally hook MUST run after the before, after, and error stages. It accepts a hook context (required) and hook hints (optional). There is no return value.")
@Specification(
number = "4.4.1",
text = "The API, Client, Provider, and invocation MUST have a method for registering hooks.")
@Specification(
number = "4.4.2",
text =
"Hooks MUST be evaluated in the following order: - before: API, Client, Invocation, Provider - after: Provider, Invocation, Client, API - error (if applicable): Provider, Invocation, Client, API - finally: Provider, Invocation, Client, API")
@Test
void hook_eval_order() {
List<String> evalOrder = new ArrayList<>();
api.setProviderAndWait("evalOrder", new TestEventsProvider() {
public List<Hook> getProviderHooks() {
return Collections.singletonList(new BooleanHook() {
@Override
public Optional<EvaluationContext> before(HookContext<Boolean> ctx, Map<String, Object> hints) {
evalOrder.add("provider before");
return null;
}
@Override
public void after(
HookContext<Boolean> ctx,
FlagEvaluationDetails<Boolean> details,
Map<String, Object> hints) {
evalOrder.add("provider after");
}
@Override
public void error(HookContext<Boolean> ctx, Exception error, Map<String, Object> hints) {
evalOrder.add("provider error");
}
@Override
public void finallyAfter(
HookContext<Boolean> ctx,
FlagEvaluationDetails<Boolean> details,
Map<String, Object> hints) {
evalOrder.add("provider finally");
}
});
}
});
api.addHooks(new BooleanHook() {
@Override
public Optional<EvaluationContext> before(HookContext<Boolean> ctx, Map<String, Object> hints) {
evalOrder.add("api before");
return null;
}
@Override
public void after(
HookContext<Boolean> ctx, FlagEvaluationDetails<Boolean> details, Map<String, Object> hints) {
evalOrder.add("api after");
throw new RuntimeException(); // trigger error flows.
}
@Override
public void error(HookContext<Boolean> ctx, Exception error, Map<String, Object> hints) {
evalOrder.add("api error");
}
@Override
public void finallyAfter(
HookContext<Boolean> ctx, FlagEvaluationDetails<Boolean> details, Map<String, Object> hints) {
evalOrder.add("api finally");
}
});
Client c = api.getClient("evalOrder");
c.addHooks(new BooleanHook() {
@Override
public Optional<EvaluationContext> before(HookContext<Boolean> ctx, Map<String, Object> hints) {
evalOrder.add("client before");
return null;
}
@Override
public void after(
HookContext<Boolean> ctx, FlagEvaluationDetails<Boolean> details, Map<String, Object> hints) {
evalOrder.add("client after");
}
@Override
public void error(HookContext<Boolean> ctx, Exception error, Map<String, Object> hints) {
evalOrder.add("client error");
}
@Override
public void finallyAfter(
HookContext<Boolean> ctx, FlagEvaluationDetails<Boolean> details, Map<String, Object> hints) {
evalOrder.add("client finally");
}
});
c.getBooleanValue(
"key",
false,
null,
FlagEvaluationOptions.builder()
.hook(new BooleanHook() {
@Override
public Optional<EvaluationContext> before(
HookContext<Boolean> ctx, Map<String, Object> hints) {
evalOrder.add("invocation before");
return null;
}
@Override
public void after(
HookContext<Boolean> ctx,
FlagEvaluationDetails<Boolean> details,
Map<String, Object> hints) {
evalOrder.add("invocation after");
}
@Override
public void error(HookContext<Boolean> ctx, Exception error, Map<String, Object> hints) {
evalOrder.add("invocation error");
}
@Override
public void finallyAfter(
HookContext<Boolean> ctx,
FlagEvaluationDetails<Boolean> details,
Map<String, Object> hints) {
evalOrder.add("invocation finally");
}
})
.build());
List<String> expectedOrder = Arrays.asList(
"api before",
"client before",
"invocation before",
"provider before",
"provider after",
"invocation after",
"client after",
"api after",
"provider error",
"invocation error",
"client error",
"api error",
"provider finally",
"invocation finally",
"client finally",
"api finally");
assertEquals(expectedOrder, evalOrder);
}
@Specification(
number = "4.4.6",
text =
"If an error occurs during the evaluation of before or after hooks, any remaining hooks in the before or after stages MUST NOT be invoked.")
@Test
void error_stops_before() {
Hook<Boolean> h = mockBooleanHook();
doThrow(RuntimeException.class).when(h).before(any(), any());
Hook<Boolean> h2 = mockBooleanHook();
api.setProviderAndWait(new AlwaysBrokenWithExceptionProvider());
Client c = api.getClient();
c.getBooleanDetails(
"key",
false,
null,
FlagEvaluationOptions.builder().hook(h2).hook(h).build());
verify(h, times(1)).before(any(), any());
verify(h2, times(0)).before(any(), any());
}
@Specification(
number = "4.4.6",
text =
"If an error occurs during the evaluation of before or after hooks, any remaining hooks in the before or after stages MUST NOT be invoked.")
@SneakyThrows
@Test
void error_stops_after() {
Hook<Boolean> h = mockBooleanHook();
doThrow(RuntimeException.class).when(h).after(any(), any(), any());
Hook<Boolean> h2 = mockBooleanHook();
Client c = getClient(TestEventsProvider.newInitializedTestEventsProvider());
c.getBooleanDetails(
"key",
false,
null,
FlagEvaluationOptions.builder().hook(h).hook(h2).build());
verify(h, times(1)).after(any(), any(), any());
verify(h2, times(0)).after(any(), any(), any());
}
@Specification(
number = "4.2.1",
text =
"hook hints MUST be a structure supports definition of arbitrary properties, with keys of type string, and values of type boolean | string | number | datetime | structure..")
@Specification(number = "4.5.2", text = "hook hints MUST be passed to each hook.")
@Specification(number = "4.2.2.1", text = "Condition: Hook hints MUST be immutable.")
@Specification(number = "4.5.3", text = "The hook MUST NOT alter the hook hints structure.")
@SneakyThrows
@Test
void hook_hints() {
String hintKey = "My hint key";
Client client = getClient(null);
Hook<Boolean> mutatingHook = new BooleanHook() {
@Override
public Optional<EvaluationContext> before(HookContext<Boolean> ctx, Map<String, Object> hints) {
assertThatCode(() -> hints.put(hintKey, "changed value"))
.isInstanceOf(UnsupportedOperationException.class);
return Optional.empty();
}
@Override
public void after(
HookContext<Boolean> ctx, FlagEvaluationDetails<Boolean> details, Map<String, Object> hints) {
assertThatCode(() -> hints.put(hintKey, "changed value"))
.isInstanceOf(UnsupportedOperationException.class);
}
@Override
public void error(HookContext<Boolean> ctx, Exception error, Map<String, Object> hints) {
assertThatCode(() -> hints.put(hintKey, "changed value"))
.isInstanceOf(UnsupportedOperationException.class);
}
@Override
public void finallyAfter(
HookContext<Boolean> ctx, FlagEvaluationDetails<Boolean> details, Map<String, Object> hints) {
assertThatCode(() -> hints.put(hintKey, "changed value"))
.isInstanceOf(UnsupportedOperationException.class);
}
};
Map<String, Object> hh = new HashMap<>();
hh.put(hintKey, "My hint value");
hh = Collections.unmodifiableMap(hh);
client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(mutatingHook).hookHints(hh).build());
}
@Specification(
number = "4.5.1",
text = "Flag evaluation options MAY contain hook hints, a map of data to be provided to hook invocations.")
@Test
void missing_hook_hints() {
FlagEvaluationOptions feo = FlagEvaluationOptions.builder().build();
assertNotNull(feo.getHookHints());
assertTrue(feo.getHookHints().isEmpty());
}
@Test
void flag_eval_hook_order() {
Hook hook = mockBooleanHook();
FeatureProvider provider = mock(FeatureProvider.class);
when(provider.getBooleanEvaluation(any(), any(), any()))
.thenReturn(ProviderEvaluation.<Boolean>builder().value(true).build());
InOrder order = inOrder(hook, provider);
api.setProviderAndWait(provider);
Client client = api.getClient();
client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook).build());
order.verify(hook).before(any(), any());
order.verify(provider).getBooleanEvaluation(any(), any(), any());
order.verify(hook).after(any(), any(), any());
order.verify(hook).finallyAfter(any(), any(), any());
}
@Specification(
number = "4.4.5",
text = "If an error occurs in the before or after hooks, the error hooks MUST be invoked.")
@Specification(
number = "4.4.7",
text = "If an error occurs in the before hooks, the default value MUST be returned.")
@Test
void error_hooks__before() {
Hook hook = mockBooleanHook();
doThrow(RuntimeException.class).when(hook).before(any(), any());
Client client = getClient(TestEventsProvider.newInitializedTestEventsProvider());
Boolean value = client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook).build());
verify(hook, times(1)).before(any(), any());
verify(hook, times(1)).error(any(), any(), any());
assertEquals(false, value, "Falls through to the default.");
}
@Specification(
number = "4.4.5",
text = "If an error occurs in the before or after hooks, the error hooks MUST be invoked.")
@Test
void error_hooks__after() {
Hook hook = mockBooleanHook();
doThrow(RuntimeException.class).when(hook).after(any(), any(), any());
Client client = getClient(TestEventsProvider.newInitializedTestEventsProvider());
client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook).build());
verify(hook, times(1)).after(any(), any(), any());
verify(hook, times(1)).error(any(), any(), any());
}
@Test
void erroneous_flagResolution_setsAppropriateFieldsInFlagEvaluationDetails() {
Hook hook = mockBooleanHook();
doThrow(RuntimeException.class).when(hook).after(any(), any(), any());
String flagKey = "test-flag-key";
Client client = getClient(TestEventsProvider.newInitializedTestEventsProvider());
client.getBooleanValue(
flagKey,
true,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook).build());
ArgumentCaptor<FlagEvaluationDetails<Boolean>> captor = ArgumentCaptor.forClass(FlagEvaluationDetails.class);
verify(hook).finallyAfter(any(), captor.capture(), any());
FlagEvaluationDetails<Boolean> evaluationDetails = captor.getValue();
assertThat(evaluationDetails).isNotNull();
assertThat(evaluationDetails.getErrorCode()).isEqualTo(ErrorCode.GENERAL);
assertThat(evaluationDetails.getReason()).isEqualTo("ERROR");
assertThat(evaluationDetails.getVariant()).isEqualTo("Passed in default");
assertThat(evaluationDetails.getFlagKey()).isEqualTo(flagKey);
assertThat(evaluationDetails.getFlagMetadata())
.isEqualTo(ImmutableMetadata.builder().build());
assertThat(evaluationDetails.getValue()).isTrue();
}
@Test
void shortCircuit_flagResolution_runsHooksWithAllFields() {
String domain = "shortCircuit_flagResolution_setsAppropriateFieldsInFlagEvaluationDetails";
api.setProvider(domain, new FatalErrorProvider());
Hook hook = mockBooleanHook();
String flagKey = "test-flag-key";
Client client = api.getClient(domain);
client.getBooleanValue(
flagKey,
true,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook).build());
verify(hook).before(any(), any());
verify(hook).error(any(HookContext.class), any(Exception.class), any(Map.class));
verify(hook).finallyAfter(any(HookContext.class), any(FlagEvaluationDetails.class), any(Map.class));
}
@Test
void successful_flagResolution_setsAppropriateFieldsInFlagEvaluationDetails() {
Hook hook = mockBooleanHook();
String flagKey = "test-flag-key";
Client client = getClient(TestEventsProvider.newInitializedTestEventsProvider());
client.getBooleanValue(
flagKey,
true,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook).build());
ArgumentCaptor<FlagEvaluationDetails<Boolean>> captor = ArgumentCaptor.forClass(FlagEvaluationDetails.class);
verify(hook).finallyAfter(any(), captor.capture(), any());
FlagEvaluationDetails<Boolean> evaluationDetails = captor.getValue();
assertThat(evaluationDetails).isNotNull();
assertThat(evaluationDetails.getErrorCode()).isNull();
assertThat(evaluationDetails.getReason()).isEqualTo("DEFAULT");
assertThat(evaluationDetails.getVariant()).isEqualTo("Passed in default");
assertThat(evaluationDetails.getFlagKey()).isEqualTo(flagKey);
assertThat(evaluationDetails.getFlagMetadata())
.isEqualTo(ImmutableMetadata.builder().build());
assertThat(evaluationDetails.getValue()).isTrue();
}
@Test
void multi_hooks_early_out__before() {
Hook<Boolean> hook = mockBooleanHook();
Hook<Boolean> hook2 = mockBooleanHook();
doThrow(RuntimeException.class).when(hook).before(any(), any());
Client client = getClient(null);
client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook2).hook(hook).build());
verify(hook, times(1)).before(any(), any());
verify(hook2, times(0)).before(any(), any());
verify(hook, times(1)).error(any(), any(), any());
verify(hook2, times(1)).error(any(), any(), any());
}
@Specification(number = "4.1.4", text = "The evaluation context MUST be mutable only within the before hook.")
@Specification(
number = "4.3.4",
text =
"Any `evaluation context` returned from a `before` hook MUST be passed to subsequent `before` hooks (via `HookContext`).")
@Test
void beforeContextUpdated() {
String targetingKey = "test-key";
EvaluationContext ctx = new ImmutableContext(targetingKey);
Hook<Boolean> hook = mockBooleanHook();
when(hook.before(any(), any())).thenReturn(Optional.of(ctx));
Hook<Boolean> hook2 = mockBooleanHook();
when(hook.before(any(), any())).thenReturn(Optional.empty());
InOrder order = inOrder(hook, hook2);
Client client = getClient(null);
client.getBooleanValue(
"key",
false,
ctx,
FlagEvaluationOptions.builder().hook(hook2).hook(hook).build());
order.verify(hook).before(any(), any());
ArgumentCaptor<HookContext<Boolean>> captor = ArgumentCaptor.forClass(HookContext.class);
order.verify(hook2).before(captor.capture(), any());
HookContext<Boolean> hc = captor.getValue();
assertEquals(hc.getCtx().getTargetingKey(), targetingKey);
}
@Specification(
number = "4.3.5",
text =
"When before hooks have finished executing, any resulting evaluation context MUST be merged with the existing evaluation context.")
@Test
void mergeHappensCorrectly() {
Map<String, Value> attributes = new HashMap<>();
attributes.put("test", new Value("works"));
attributes.put("another", new Value("exists"));
EvaluationContext hookCtx = new ImmutableContext(attributes);
Map<String, Value> attributes1 = new HashMap<>();
attributes1.put("something", new Value("here"));
attributes1.put("test", new Value("broken"));
EvaluationContext invocationCtx = new ImmutableContext(attributes1);
Hook<Boolean> hook = mockBooleanHook();
when(hook.before(any(), any())).thenReturn(Optional.of(hookCtx));
FeatureProvider provider = mock(FeatureProvider.class);
when(provider.getBooleanEvaluation(any(), any(), any()))
.thenReturn(ProviderEvaluation.<Boolean>builder().value(true).build());
api.setProviderAndWait(provider);
Client client = api.getClient();
client.getBooleanValue(
"key",
false,
invocationCtx,
FlagEvaluationOptions.builder().hook(hook).build());
ArgumentCaptor<ImmutableContext> captor = ArgumentCaptor.forClass(ImmutableContext.class);
verify(provider).getBooleanEvaluation(any(), any(), captor.capture());
EvaluationContext ec = captor.getValue();
assertEquals("works", ec.getValue("test").asString());
assertEquals("exists", ec.getValue("another").asString());
assertEquals("here", ec.getValue("something").asString());
}
@Specification(
number = "4.4.3",
text =
"If a finally hook abnormally terminates, evaluation MUST proceed, including the execution of any remaining finally hooks.")
@Test
void first_finally_broken() {
Hook hook = mockBooleanHook();
doThrow(RuntimeException.class).when(hook).before(any(), any());
doThrow(RuntimeException.class).when(hook).finallyAfter(any(), any(), any());
Hook hook2 = mockBooleanHook();
InOrder order = inOrder(hook, hook2);
Client client = getClient(null);
client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook2).hook(hook).build());
order.verify(hook).before(any(), any());
order.verify(hook2).finallyAfter(any(), any(), any());
order.verify(hook).finallyAfter(any(), any(), any());
}
@Specification(
number = "4.4.4",
text =
"If an error hook abnormally terminates, evaluation MUST proceed, including the execution of any remaining error hooks.")
@Test
void first_error_broken() {
Hook hook = mockBooleanHook();
doThrow(RuntimeException.class).when(hook).before(any(), any());
doThrow(RuntimeException.class).when(hook).error(any(), any(), any());
Hook hook2 = mockBooleanHook();
InOrder order = inOrder(hook, hook2);
Client client = getClient(null);
client.getBooleanValue(
"key",
false,
new ImmutableContext(),
FlagEvaluationOptions.builder().hook(hook2).hook(hook).build());
order.verify(hook).before(any(), any());
order.verify(hook2).error(any(), any(), any());
order.verify(hook).error(any(), any(), any());
}
private Client getClient(FeatureProvider provider) {
if (provider == null) {
api.setProviderAndWait(TestEventsProvider.newInitializedTestEventsProvider());
} else {
api.setProviderAndWait(provider);
}
return api.getClient();
}
@Specification(number = "4.3.1", text = "Hooks MUST specify at least one stage.")
@Test
void default_methods_so_impossible() {}
@Specification(number = "4.3.9.1", text = "Instead of finally, finallyAfter SHOULD be used.")
@SneakyThrows
@Test
void doesnt_use_finally() {
assertThatCode(() -> Hook.class.getMethod("finally", HookContext.class, Map.class))
.as("Not possible. Finally is a reserved word.")
.isInstanceOf(NoSuchMethodException.class);
assertThatCode(() ->
Hook.class.getMethod("finallyAfter", HookContext.class, FlagEvaluationDetails.class, Map.class))
.doesNotThrowAnyException();
}
}