-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathDefaultUnleashTest.java
More file actions
321 lines (283 loc) · 13.6 KB
/
DefaultUnleashTest.java
File metadata and controls
321 lines (283 loc) · 13.6 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
package io.getunleash;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.verify;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import io.getunleash.event.ClientFeaturesResponse;
import io.getunleash.event.EventDispatcher;
import io.getunleash.event.UnleashReady;
import io.getunleash.event.UnleashSubscriber;
import io.getunleash.repository.FeatureFetcher;
import io.getunleash.repository.ToggleBootstrapProvider;
import io.getunleash.strategy.Strategy;
import io.getunleash.util.ResourceReader;
import io.getunleash.util.UnleashConfig;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.slf4j.LoggerFactory;
class DefaultUnleashTest {
private DefaultUnleash sut;
private EngineProxy engineProxy;
private UnleashContextProvider contextProvider;
private EventDispatcher eventDispatcher;
private String loadMockFeatures(String path) {
return ResourceReader.readResourceAsString(path);
}
@RegisterExtension
static WireMockExtension serverMock =
WireMockExtension.newInstance()
.configureStaticDsl(true)
.options(wireMockConfig().dynamicPort().dynamicHttpsPort())
.build();
@BeforeEach
public void setup() {
UnleashConfig unleashConfig =
UnleashConfig.builder().unleashAPI("http://fakeAPI").appName("fakeApp").build();
engineProxy = mock(EngineProxy.class);
contextProvider = mock(UnleashContextProvider.class);
eventDispatcher = mock(EventDispatcher.class);
sut = new DefaultUnleash(unleashConfig, engineProxy, contextProvider, eventDispatcher);
}
@Test
public void should_evaluate_all_toggle_with_context() {
ToggleBootstrapProvider bootstrapper =
new ToggleBootstrapProvider() {
@Override
public Optional<String> read() {
return Optional.of(loadMockFeatures("unleash-repo-v2.json"));
}
};
UnleashConfig unleashConfig =
UnleashConfig.builder()
.unleashAPI("http://fakeAPI")
.appName("fakeApp")
.toggleBootstrapProvider(bootstrapper)
.build();
Unleash unleash = new DefaultUnleash(unleashConfig);
List<EvaluatedToggle> toggles = unleash.more().evaluateAllToggles();
assertThat(toggles).hasSize(5);
// rather than getting the first toggle, we need to find the toggle with the
// correct name since this now comes from Yggdrasil and the feature set is
// backed by
// hashmap, we can't guarantee a stable ordering
EvaluatedToggle t1 =
toggles.stream().filter(t -> t.getName().equals("featureX")).findFirst().get();
assertThat(t1.getName()).isEqualTo("featureX");
assertThat(t1.isEnabled()).isTrue();
}
@Test
public void should_allow_fallback_strategy() {
Strategy fallback = mock(Strategy.class);
when(fallback.getName()).thenReturn("custom strategy");
when(fallback.isEnabled(any(), any(UnleashContext.class))).thenReturn(true);
ToggleBootstrapProvider bootstrapper =
() ->
Optional.of(
"{\"version\":1,\"features\":[{\"name\":\"toggle1\",\"enabled\":true,\"strategies\":[{\"name\":\"nonexistent\"}]}]}");
UnleashConfig unleashConfigWithFallback =
UnleashConfig.builder()
.unleashAPI("http://fakeAPI")
.appName("fakeApp")
.toggleBootstrapProvider(bootstrapper)
.fallbackStrategy(fallback)
.build();
sut = new DefaultUnleash(unleashConfigWithFallback);
when(contextProvider.getContext()).thenReturn(UnleashContext.builder().build());
sut.isEnabled("toggle1");
verify(fallback).isEnabled(any(), any());
}
@Test
public void not_setting_current_time_falls_back_to_correct_now_instant() {
ToggleBootstrapProvider bootstrapper =
() -> Optional.of(loadMockFeatures("unleash-repo-v2-advanced.json"));
UnleashConfig unleashConfigWithFallback =
UnleashConfig.builder()
.unleashAPI("http://fakeAPI")
.appName("fakeApp")
.toggleBootstrapProvider(bootstrapper)
.synchronousFetchOnInitialisation(false)
.build();
sut = new DefaultUnleash(unleashConfigWithFallback);
boolean enabled = sut.isEnabled("Test.currentTime");
assertThat(enabled).isTrue();
}
@Test
public void multiple_instantiations_of_the_same_config_gives_errors() {
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
Logger unleashLogger = (Logger) LoggerFactory.getLogger(DefaultUnleash.class);
unleashLogger.addAppender(appender);
String appName = "multiple_connection_logging";
String instanceId = "multiple_connection_instance_id";
UnleashConfig config =
UnleashConfig.builder()
.unleashAPI("http://test:4242")
.appName(appName)
.apiKey("default:development:1234567890123456")
.instanceId(instanceId)
.build();
new DefaultUnleash(config);
// We've only instantiated the client once, so no errors should've been logged
assertThat(appender.list).isEmpty();
new DefaultUnleash(config);
// We've now instantiated the client twice, so we expect an error log line.
assertThat(appender.list).hasSize(1);
config.getClientIdentifier();
assertThat(appender.list)
.extracting(ILoggingEvent::getFormattedMessage)
.containsExactly(
"You already have 1 clients for AppName ["
+ appName
+ "] with instanceId: ["
+ instanceId
+ "] running. Please double check your code where you are instantiating the Unleash SDK");
appender.list.clear();
new DefaultUnleash(config);
// We've now instantiated the client twice, so we expect an error log line.
assertThat(appender.list).hasSize(1);
assertThat(appender.list)
.extracting(ILoggingEvent::getFormattedMessage)
.containsExactly(
"You already have 2 clients for AppName ["
+ appName
+ "] with instanceId: ["
+ instanceId
+ "] running. Please double check your code where you are instantiating the Unleash SDK");
}
@Test
public void supports_failing_hard_on_multiple_instantiations() {
UnleashConfig config =
UnleashConfig.builder()
.unleashAPI("http://test:4242")
.appName("multiple_connection_exception")
.apiKey("default:development:1234567890123456")
.instanceId("multiple_connection_exception")
.build();
String id = config.getClientIdentifier();
new DefaultUnleash(config);
assertThatThrownBy(
() -> {
new DefaultUnleash(config, null, null, null, true);
})
.isInstanceOf(RuntimeException.class)
.withFailMessage(
"You already have 1 clients for Unleash Configuration ["
+ id
+ "] running. Please double check your code where you are instantiating the Unleash SDK");
}
@Test
public void synchronous_fetch_on_initialisation_fails_on_initialization() {
IsReadyTestSubscriber readySubscriber = new IsReadyTestSubscriber();
UnleashConfig config =
UnleashConfig.builder()
.unleashAPI("http://wrong:4242")
.appName("wrong_upstream")
.apiKey("default:development:1234567890123456")
.instanceId("multiple_connection_exception")
.synchronousFetchOnInitialisation(true)
.subscriber(readySubscriber)
.build();
assertThatThrownBy(() -> new DefaultUnleash(config)).isInstanceOf(UnleashException.class);
assertThat(readySubscriber.ready).isFalse();
}
@ParameterizedTest
@ValueSource(ints = {401, 403, 404, 500})
public void synchronous_fetch_on_initialisation_fails_on_non_200_response(int code)
throws URISyntaxException {
mockUnleashAPI(code);
IsReadyTestSubscriber readySubscriber = new IsReadyTestSubscriber();
UnleashConfig config =
UnleashConfig.builder()
.unleashAPI(new URI("http://localhost:" + serverMock.getPort() + "/api/"))
.appName("wrong_upstream")
.apiKey("default:development:1234567890123456")
.instanceId("non-200")
.synchronousFetchOnInitialisation(true)
.subscriber(readySubscriber)
.build();
assertThatThrownBy(() -> new DefaultUnleash(config)).isInstanceOf(UnleashException.class);
assertThat(readySubscriber.ready).isFalse();
}
@Test
public void synchronous_fetch_on_initialisation_switches_to_ready_on_200()
throws URISyntaxException {
mockUnleashAPI(200);
IsReadyTestSubscriber readySubscriber = new IsReadyTestSubscriber();
UnleashConfig config =
UnleashConfig.builder()
.unleashAPI(new URI("http://localhost:" + serverMock.getPort() + "/api/"))
.appName("wrong_upstream")
.apiKey("default:development:1234567890123456")
.instanceId("with-success-response")
.synchronousFetchOnInitialisation(true)
.subscriber(readySubscriber)
.build();
new DefaultUnleash(config);
assertThat(readySubscriber.ready).isTrue();
}
private void mockUnleashAPI(int featuresStatusCode) {
stubFor(
get(urlEqualTo("/api/client/features"))
.withHeader("Accept", equalTo("application/json"))
.willReturn(
aResponse()
.withStatus(featuresStatusCode)
.withHeader("Content-Type", "application/json")
.withBody(loadMockFeatures("unleash-repo-v2.json"))));
stubFor(post(urlEqualTo("/api/client/register")).willReturn(aResponse().withStatus(200)));
}
@Test
public void asynchronous_fetch_on_initialisation_fails_silently_and_retries()
throws InterruptedException {
FeatureFetcher fetcher = mock(FeatureFetcher.class);
when(fetcher.fetchFeatures())
.thenThrow(UnleashException.class)
.thenReturn(ClientFeaturesResponse.updated("doesn't matter for this test"));
UnleashConfig config =
UnleashConfig.builder()
.unleashAPI("http://wrong:4242")
.appName("wrong_upstream")
.apiKey("default:development:1234567890123456")
.instanceId("multiple_connection_exception")
.fetchTogglesInterval(1)
.unleashFeatureFetcherFactory((UnleashConfig c) -> fetcher)
.build();
new DefaultUnleash(config);
Thread.sleep(1);
verify(fetcher, times(1)).fetchFeatures();
Thread.sleep(1200);
verify(fetcher, times(2)).fetchFeatures();
}
@Test
public void client_identifier_handles_api_key_being_null() {
UnleashConfig config =
UnleashConfig.builder()
.unleashAPI("http://test:4242")
.appName("multiple_connection")
.instanceId("testing_multiple")
.build();
String id = config.getClientIdentifier();
assertThat(id)
.isEqualTo("f83eb743f4c8dc41294aafb96f454763e5a90b96db8b7040ddc505d636bdb243");
}
private static class IsReadyTestSubscriber implements UnleashSubscriber {
public boolean ready = false;
public void onReady(UnleashReady unleashReady) {
this.ready = true;
}
}
}