-
Notifications
You must be signed in to change notification settings - Fork 0
/
EppoClientTest.java
372 lines (312 loc) · 15.5 KB
/
EppoClientTest.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
package cloud.eppo.android;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static cloud.eppo.android.ConfigCacheFile.CACHE_FILE_NAME;
import android.content.res.AssetManager;
import androidx.test.core.app.ApplicationProvider;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import cloud.eppo.android.dto.EppoValue;
import cloud.eppo.android.dto.SubjectAttributes;
import cloud.eppo.android.dto.adapters.EppoValueAdapter;
public class EppoClientTest {
private static final String TEST_HOST = "https://us-central1-eppo-qa.cloudfunctions.net/serveGitHubRacTestFile";
private static final String INVALID_HOST = "https://thisisabaddomainforthistest.com";
private Gson gson = new GsonBuilder()
.registerTypeAdapter(EppoValue.class, new EppoValueAdapter())
.registerTypeAdapter(AssignmentValueType.class, new AssignmentValueTypeAdapter(AssignmentValueType.STRING))
.create();
private CountDownLatch lock = new CountDownLatch(1);
static class SubjectWithAttributes {
String subjectKey;
SubjectAttributes subjectAttributes;
}
static enum AssignmentValueType {
STRING("string"),
BOOLEAN("boolean"),
JSON("json"),
NUMERIC("numeric");
private String strValue;
AssignmentValueType(String value) {
this.strValue = value;
}
String value() {
return this.strValue;
}
static AssignmentValueType getByString(String str) {
for (AssignmentValueType valueType : AssignmentValueType.values()) {
if (valueType.value().compareTo(str) == 0) {
return valueType;
}
}
return null;
}
}
static class AssignmentValueTypeAdapter implements JsonDeserializer<AssignmentValueType> {
private AssignmentValueType defaultValue = null;
AssignmentValueTypeAdapter(AssignmentValueType defaultValue) {
this.defaultValue = defaultValue;
}
AssignmentValueTypeAdapter() {
}
@Override
public AssignmentValueType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
if (json.isJsonNull()) {
return this.defaultValue;
}
AssignmentValueType value = AssignmentValueType.getByString(json.getAsString());
if (value == null) {
throw new RuntimeException("Invalid assignment value type");
}
return value;
}
}
static class AssignmentTestCase {
String experiment;
AssignmentValueType valueType = AssignmentValueType.STRING;
List<SubjectWithAttributes> subjectsWithAttributes;
List<String> subjects;
List<String> expectedAssignments;
}
private void deleteFileIfExists(String fileName) {
File file = new File(ApplicationProvider.getApplicationContext().getFilesDir(), fileName);
if (file.exists()) {
file.delete();
}
}
private void deleteCacheFiles() {
deleteFileIfExists(CACHE_FILE_NAME);
}
private void initClient(String host, boolean throwOnCallackError, boolean shouldDeleteCacheFiles, boolean isGracefulMode)
throws InterruptedException {
if (shouldDeleteCacheFiles) {
deleteCacheFiles();
}
new EppoClient.Builder()
.application(ApplicationProvider.getApplicationContext())
.apiKey("mock-api-key")
.isGracefulMode(isGracefulMode)
.host(host)
.callback(new InitializationCallback() {
@Override
public void onCompleted() {
lock.countDown();
}
@Override
public void onError(String errorMessage) {
if (throwOnCallackError) {
throw new RuntimeException("Unable to initialize: "+errorMessage);
}
lock.countDown();
}
})
.buildAndInit();
if(!lock.await(10000, TimeUnit.MILLISECONDS)) {
throw new RuntimeException("Request for RAC did not complete within timeout");
}
}
@After
public void teardown() {
deleteCacheFiles();
}
@Test
public void testAssignments() {
try {
initClient(TEST_HOST, true, true, false);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
runTestCases();
}
@Test
public void testErrorGracefulModeOn() {
try {
initClient(TEST_HOST, false, true, true);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
EppoClient realClient = EppoClient.getInstance();
EppoClient spyClient = spy(realClient);
doThrow(new RuntimeException("Exception thrown by mock"))
.when(spyClient)
.getTypedAssignment(anyString(), anyString(), any(SubjectAttributes.class));
assertNull(spyClient.getAssignment("subject1", "experiment1"));
assertNull(spyClient.getAssignment("subject1", "experiment1", new SubjectAttributes()));
assertNull(spyClient.getBooleanAssignment("subject1", "experiment1"));
assertNull(spyClient.getBooleanAssignment("subject1", "experiment1", new SubjectAttributes()));
assertNull(spyClient.getDoubleAssignment("subject1", "experiment1"));
assertNull(spyClient.getDoubleAssignment("subject1", "experiment1", new SubjectAttributes()));
assertNull(spyClient.getStringAssignment("subject1", "experiment1"));
assertNull(spyClient.getStringAssignment("subject1", "experiment1", new SubjectAttributes()));
assertNull(spyClient.getParsedJSONAssignment("subject1", "experiment1"));
assertNull(spyClient.getParsedJSONAssignment("subject1", "experiment1", new SubjectAttributes()));
assertNull(spyClient.getJSONStringAssignment("subject1", "experiment1"));
assertNull(spyClient.getJSONStringAssignment("subject1", "experiment1", new SubjectAttributes()));
}
@Test
public void testErrorGracefulModeOff() {
try {
initClient(TEST_HOST, false, true, false);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
EppoClient realClient = EppoClient.getInstance();
EppoClient spyClient = spy(realClient);
doThrow(new RuntimeException("Exception thrown by mock"))
.when(spyClient)
.getTypedAssignment(anyString(), anyString(), any(SubjectAttributes.class));
assertThrows(RuntimeException.class, () -> spyClient.getAssignment("subject1", "experiment1"));
assertThrows(RuntimeException.class, () -> spyClient.getAssignment("subject1", "experiment1", new SubjectAttributes()));
assertThrows(RuntimeException.class, () -> spyClient.getBooleanAssignment("subject1", "experiment1"));
assertThrows(RuntimeException.class, () -> spyClient.getBooleanAssignment("subject1", "experiment1", new SubjectAttributes()));
assertThrows(RuntimeException.class, () -> spyClient.getDoubleAssignment("subject1", "experiment1"));
assertThrows(RuntimeException.class, () -> spyClient.getDoubleAssignment("subject1", "experiment1", new SubjectAttributes()));
assertThrows(RuntimeException.class, () -> spyClient.getStringAssignment("subject1", "experiment1"));
assertThrows(RuntimeException.class, () -> spyClient.getStringAssignment("subject1", "experiment1", new SubjectAttributes()));
assertThrows(RuntimeException.class, () -> spyClient.getParsedJSONAssignment("subject1", "experiment1"));
assertThrows(RuntimeException.class, () -> spyClient.getParsedJSONAssignment("subject1", "experiment1", new SubjectAttributes()));
assertThrows(RuntimeException.class, () -> spyClient.getJSONStringAssignment("subject1", "experiment1"));
assertThrows(RuntimeException.class, () -> spyClient.getJSONStringAssignment("subject1", "experiment1", new SubjectAttributes()));
}
private void runTestCases() {
try {
int testsRan = 0;
AssetManager assets = ApplicationProvider.getApplicationContext().getAssets();
for (String path : assets.list("assignment-v2")) {
testsRan += runTestCaseFileStream(assets.open("assignment-v2/" + path));
}
System.out.println("We ran this many tests: " + testsRan);
assertTrue("Did not run any test cases", testsRan > 0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testCachedAssignments() {
try {
// First initialize successfully
initClient(TEST_HOST, false, true, false); // ensure cache is populated
// wait for a bit since cache file is loaded asynchronously
System.out.println("Sleeping for a bit to wait for cache population to complete");
Thread.sleep(10000);
// Then reinitialize with a bad host so we know it's using the cached RAC built from the first initialization
initClient(INVALID_HOST, false, false, false); // invalid port to force to use cache
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
runTestCases();
}
private int runTestCaseFileStream(InputStream testCaseStream) throws IOException {
String json = IOUtils.toString(testCaseStream, Charsets.toCharset("UTF8"));
AssignmentTestCase testCase = gson.fromJson(json, AssignmentTestCase.class);
switch (testCase.valueType) {
case NUMERIC:
List<Double> expectedDoubleAssignments = Converter.convertToDouble(testCase.expectedAssignments);
List<Double> actualDoubleAssignments = this.getDoubleAssignments(testCase);
assertEquals(expectedDoubleAssignments, actualDoubleAssignments);
return actualDoubleAssignments.size();
case BOOLEAN:
List<Boolean> expectedBooleanAssignments = Converter.convertToBoolean(testCase.expectedAssignments);
List<Boolean> actualBooleanAssignments = this.getBooleanAssignments(testCase);
assertEquals(expectedBooleanAssignments, actualBooleanAssignments);
return actualBooleanAssignments.size();
case JSON:
// test parsed json
List<JsonElement> actualParsedJSONAssignments = this.getJSONAssignments(testCase);
List<String> actualJSONStringAssignments = actualParsedJSONAssignments.stream().map(x -> x.toString()).collect(Collectors.toList());
assertEquals(testCase.expectedAssignments, actualJSONStringAssignments);
return actualParsedJSONAssignments.size();
default:
List<String> actualStringAssignments = this.getStringAssignments(testCase);
assertEquals(testCase.expectedAssignments, actualStringAssignments);
return actualStringAssignments.size();
}
}
private List<?> getAssignments(AssignmentTestCase testCase, AssignmentValueType valueType) {
EppoClient client = EppoClient.getInstance();
if (testCase.subjectsWithAttributes != null) {
return testCase.subjectsWithAttributes.stream()
.map(subject -> {
try {
switch (valueType) {
case NUMERIC:
return client.getDoubleAssignment(subject.subjectKey, testCase.experiment,
subject.subjectAttributes);
case BOOLEAN:
return client.getBooleanAssignment(subject.subjectKey, testCase.experiment,
subject.subjectAttributes);
case JSON:
return client.getParsedJSONAssignment(subject.subjectKey, testCase.experiment,
subject.subjectAttributes);
default:
return client.getStringAssignment(subject.subjectKey, testCase.experiment,
subject.subjectAttributes);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
}
return testCase.subjects.stream()
.map(subject -> {
try {
switch (valueType) {
case NUMERIC:
return client.getDoubleAssignment(subject, testCase.experiment);
case BOOLEAN:
return client.getBooleanAssignment(subject, testCase.experiment);
case JSON:
return client.getParsedJSONAssignment(subject, testCase.experiment);
default:
return client.getStringAssignment(subject, testCase.experiment);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toList());
}
private List<String> getStringAssignments(AssignmentTestCase testCase) {
return (List<String>) this.getAssignments(testCase, AssignmentValueType.STRING);
}
private List<Double> getDoubleAssignments(AssignmentTestCase testCase) {
return (List<Double>) this.getAssignments(testCase, AssignmentValueType.NUMERIC);
}
private List<Boolean> getBooleanAssignments(AssignmentTestCase testCase) {
return (List<Boolean>) this.getAssignments(testCase, AssignmentValueType.BOOLEAN);
}
private List<JsonElement> getJSONAssignments(AssignmentTestCase testCase) {
return (List<JsonElement>) this.getAssignments(testCase, AssignmentValueType.JSON);
}
private static String getMockRandomizedAssignmentResponse() {
try {
InputStream in = ApplicationProvider.getApplicationContext().getAssets()
.open("rac-experiments-v3-hashed-keys.json");
return IOUtils.toString(in, Charsets.toCharset("UTF8"));
} catch (IOException e) {
throw new RuntimeException("Error reading mock RAC data", e);
}
}
}