Repository navigation
Expand file tree
/
Copy pathAnalyticsProcessorTest.java
More file actions
183 lines (159 loc) · 6.75 KB
/
Copy pathAnalyticsProcessorTest.java
File metadata and controls
183 lines (159 loc) · 6.75 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
package com.flagsmith.threads;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flagsmith.FlagsmithApiWrapper;
import com.flagsmith.FlagsmithException;
import com.flagsmith.FlagsmithLogger;
import com.flagsmith.MapperFactory;
import com.flagsmith.config.FlagsmithConfig;
import com.flagsmith.config.Retry;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.SneakyThrows;
import okhttp3.Protocol;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okhttp3.mock.MockInterceptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
public class AnalyticsProcessorTest {
private FlagsmithApiWrapper api;
private FlagsmithLogger flagsmithLogger;
private FlagsmithConfig defaultConfig;
private MockInterceptor interceptor;
private RequestProcessor requestProcessor;
private AnalyticsProcessor analytics;
@BeforeEach
public void init() {
flagsmithLogger = mock(FlagsmithLogger.class);
doThrow(new FlagsmithException("error Response")).when(flagsmithLogger)
.httpError(any(), any(Response.class), eq(true));
doThrow(new FlagsmithException("error IOException")).when(flagsmithLogger)
.httpError(any(), any(IOException.class), eq(true));
interceptor = new MockInterceptor();
defaultConfig = FlagsmithConfig.newBuilder().addHttpInterceptor(interceptor)
.retries(new Retry(1)).baseUri("http://base-uri/")
.build();
api = mock(FlagsmithApiWrapper.class);
requestProcessor = mock(RequestProcessor.class);
when(requestProcessor.submitForStatus(any()))
.thenReturn(CompletableFuture.completedFuture(true));
when(api.getConfig()).thenReturn(defaultConfig);
analytics = new AnalyticsProcessor(api, flagsmithLogger, requestProcessor);
}
@Test
public void AnalyticsProcessor_checkAnalyticsData() {
String featureName = "foo";
analytics.trackFeature(featureName);
Assertions.assertTrue(analytics.getAnalyticsData().containsKey(featureName));
Assertions.assertEquals(analytics.getAnalyticsData().size(), 1);
analytics.trackFeature(featureName);
Assertions.assertEquals(analytics.getAnalyticsData().size(), 1);
Assertions.assertEquals(analytics.getAnalyticsData().get(featureName).intValue(), 2);
}
@Test
public void AnalyticsProcessor_checkAnalyticsDataCheckFlushRuns() throws InterruptedException {
String featureName = "foo";
Long nextFlush = analytics.getNextFlush();
analytics.trackFeature(featureName);
Assertions.assertEquals(nextFlush, analytics.getNextFlush());
Thread.sleep(11000);
analytics.trackFeature(featureName);
Assertions.assertEquals(analytics.getAnalyticsData().size(), 0);
Assertions.assertNotEquals(nextFlush, analytics.getNextFlush());
verify(api, times(1)).newPostRequest(any(), any());
verify(requestProcessor, times(1)).submitForStatus(any());
}
@Test
public void AnalyticsProcessor_checkAnalyticsRequestCheckFlushRuns() {
String featureName = "foo";
Long nextFlush = analytics.getNextFlush();
analytics.trackFeature(featureName);
Assertions.assertEquals(nextFlush, analytics.getNextFlush());
analytics.flush();
verify(api, times(1)).newPostRequest(any(), any());
verify(requestProcessor, times(1)).submitForStatus(any());
}
@Test
public void testFlush_RestoresCountsAfterRetriesAreExhausted() throws Exception {
BlockingQueue<String> bodies = new LinkedBlockingQueue<>();
AtomicInteger attempts = new AtomicInteger();
FlagsmithConfig config = FlagsmithConfig.newBuilder().baseUri("http://base-uri/")
.addHttpInterceptor(chain -> {
Buffer body = new Buffer();
chain.request().body().writeTo(body);
bodies.add(body.readUtf8());
int status = attempts.incrementAndGet() <= 2 ? 503 : 200;
return new Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1)
.code(status).message("").body(ResponseBody.create("", null)).build();
}).build();
Retry retry = new Retry(2, 0, 0f, 15f, Collections.singleton(503), true);
RequestProcessor processor = new RequestProcessor(config.getHttpClient(), flagsmithLogger,
retry);
FlagsmithApiWrapper wrapper =
new FlagsmithApiWrapper(config, new HashMap<>(), flagsmithLogger, "test-key", processor);
AnalyticsProcessor tracker = new AnalyticsProcessor(wrapper, flagsmithLogger, processor);
try {
tracker.trackFeature("foo");
tracker.trackFeature("foo");
tracker.flush();
Assertions.assertEquals("{\"foo\":2}", bodies.poll(5, TimeUnit.SECONDS));
Assertions.assertEquals("{\"foo\":2}", bodies.poll(5, TimeUnit.SECONDS));
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2);
while (!tracker.getAnalyticsData().containsKey("foo") && System.nanoTime() < deadline) {
Thread.sleep(10);
}
tracker.trackFeature("foo");
tracker.flush();
Assertions.assertEquals("{\"foo\":3}", bodies.poll(5, TimeUnit.SECONDS));
} finally {
tracker.close();
}
}
@Test
public void testFlush_DoesNotResendSuccessfulCounts() throws IOException {
analytics.trackFeature("foo");
analytics.trackFeature("foo");
analytics.flush();
analytics.trackFeature("foo");
analytics.flush();
ArgumentCaptor<RequestBody> bodies = ArgumentCaptor.forClass(RequestBody.class);
verify(api, times(2)).newPostRequest(any(), bodies.capture());
Buffer body = new Buffer();
bodies.getAllValues().get(0).writeTo(body);
Assertions.assertEquals("{\"foo\":2}", body.readUtf8());
bodies.getAllValues().get(1).writeTo(body);
Assertions.assertEquals("{\"foo\":1}", body.readUtf8());
}
@Test
public void testClose_ShutsDownExecutor() {
// When
analytics.close();
// Then
verify(requestProcessor, times(1)).close();
}
@Test
@SneakyThrows
public void AnalyticsProcessor_longAdderGetsSerializedCorrectly() {
analytics.trackFeature("foo");
ObjectMapper mapper = MapperFactory.getMapper();
String response = mapper.writeValueAsString(analytics.getAnalyticsData());
Assertions.assertEquals("{\"foo\":1}", response);
}
}