This repository has been archived by the owner on Sep 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 212
/
ServiceHelperTest.java
341 lines (269 loc) · 10 KB
/
ServiceHelperTest.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
/*
* -\-\-
* Spotify Apollo Testing Helpers
* --
* Copyright (C) 2013 - 2015 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.apollo.test.helper;
import com.google.common.base.Stopwatch;
import com.spotify.apollo.Environment;
import com.spotify.apollo.Request;
import com.spotify.apollo.Response;
import com.spotify.apollo.module.AbstractApolloModule;
import com.spotify.apollo.test.ServiceHelper;
import com.spotify.apollo.test.StubClient;
import com.spotify.metrics.core.SemanticMetricRegistry;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import okio.ByteString;
import static okio.ByteString.encodeUtf8;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ServiceHelperTest {
private static final Logger LOG = LoggerFactory.getLogger(ServiceHelperTest.class);
private static final String TEST_THING = "a test string";
private static final String TEST_CONFIG_THING = "a-test-string-in-the-config";
private static final String SERVICE_NAME = "test-service";
@Rule
public ServiceHelper serviceHelper = ServiceHelper.create(this::appInit, SERVICE_NAME)
.startTimeoutSeconds(10)
.domain("xyz99.spotify.net")
.conf("some.key", TEST_CONFIG_THING)
.args("-v");
@Rule
public ExpectedException thrown = ExpectedException.none();
private StubClient stubClient = serviceHelper.stubClient();
@Mock
SomeApplication.SomeService someService;
@Mock
static SomeApplication.CloseCall closeCall;
private void appInit(Environment environment) {
SomeApplication someApplication =
SomeApplication.create(environment, someService, closeCall);
environment.routingEngine()
.registerAutoRoutes(someApplication);
}
@AfterClass
public static void tearDown() throws Exception {
verify(closeCall).didClose();
}
@Test
public void smokeTest() throws Exception {
when(someService.thatDoesThings()).thenReturn(TEST_THING);
String response = doGet();
assertThat(response, is(TEST_THING));
}
@Test
public void smokeTest2() throws Exception {
when(someService.thatDoesThings()).thenReturn(TEST_THING + " and more");
String response = doGet();
assertThat(response, is(TEST_THING + " and more"));
}
@Test
public void testDomain() throws Exception {
String response = doGet("/domain");
assertThat(response, is("xyz99.spotify.net"));
}
@Test
public void shouldSeeConfigValues() throws Exception {
String response = doGet("/conf-key");
assertThat(response, is(TEST_CONFIG_THING));
}
@Test
public void shouldOverrideConfig() throws Exception {
serviceHelper = ServiceHelper.create(this::appInit, SERVICE_NAME)
.conf("some.key", TEST_CONFIG_THING)
.conf("some.key", "different config")
.args("-v");
serviceHelper.start();
String response = doGet("/conf-key");
assertThat(response, is("different config"));
}
@Test
public void shouldResetConfig() throws Exception {
serviceHelper = ServiceHelper.create(this::appInit, SERVICE_NAME)
.conf("some.key", TEST_CONFIG_THING)
.resetConf("some.key")
.args("-v");
serviceHelper.start();
String response = doGet("/conf-key");
assertThat(response, is("no value found for some.key"));
}
@Test
public void callTest() throws Exception {
stubClient.respond(Response.forPayload(encodeUtf8("hello from something")))
.in(300, TimeUnit.MILLISECONDS)
.to("http://something/foo");
String response = doGet("/call/something/foo");
assertThat(response, is("hello from something"));
}
@Test
public void testPayload() throws Exception {
Response<ByteString> thing = serviceHelper.request("POST", "/post", encodeUtf8("bytes"))
.toCompletableFuture().get();
assertThat(thing.payload().get().utf8(), is("bytes"));
}
@Test
public void testCallServiceClient() throws Exception {
stubClient.respond(Response.forPayload(encodeUtf8("hello from something")))
.to("http://something/foo");
Request request = Request.forUri("http://" + SERVICE_NAME + "/call/something/foo");
Response<ByteString> response = serviceHelper.serviceClient().send(request)
.toCompletableFuture().get();
assertThat(response.payload().get().utf8(), is("hello from something"));
}
@Test
public void shouldDisallowRequestsBeforeStarted() throws Exception {
ServiceHelper notStarted = ServiceHelper.create(this::appInit, "test-service")
.conf("some.key", TEST_CONFIG_THING)
.args("-v");
thrown.expect(IllegalStateException.class);
thrown.expectMessage("ServiceHelper not started");
notStarted.request("GET", "/");
}
@Test
public void shouldTimeoutIfStartupIsSlow() throws Exception {
ServiceHelper timeout = ServiceHelper.create(ServiceHelperTest::tooSlow, "test-service")
.conf("some.key", TEST_CONFIG_THING)
.args("-v")
.startTimeoutSeconds(1);
Stopwatch stopwatch = Stopwatch.createStarted();
try {
timeout.start();
}
catch (RuntimeException e) {
if (!e.getMessage().contains("a reasonable time")) {
throw e;
}
}
assertThat(stopwatch.elapsed(TimeUnit.SECONDS), lessThan(3L));
}
@Test
public void shouldCatchExceptionBeforeTimeout() throws Exception {
ServiceHelper timeout = ServiceHelper.create(ServiceHelperTest::throwsException, "test-service")
.conf("some.key", TEST_CONFIG_THING)
.args("-v")
.startTimeoutSeconds(2);
Stopwatch stopwatch = Stopwatch.createStarted();
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Service failed during startup");
timeout.start();
assertThat(stopwatch.elapsed(TimeUnit.SECONDS), lessThan(1L));
}
@Test
public void shouldCatchErrorBeforeTimeout() throws Exception {
ServiceHelper timeout = ServiceHelper.create(ServiceHelperTest::throwsError, "test-service")
.conf("some.key", TEST_CONFIG_THING)
.args("-v")
.startTimeoutSeconds(2);
Stopwatch stopwatch = Stopwatch.createStarted();
thrown.expect(IllegalStateException.class);
thrown.expectMessage("Service failed during startup");
timeout.start();
assertThat(stopwatch.elapsed(TimeUnit.SECONDS), lessThan(1L));
}
@Test
public void shouldSupportRegisteringAdditionalModules() throws Exception {
stubClient.respond(Response.forPayload(encodeUtf8("hello from something")))
.to("http://something/foo");
ServiceHelper withModule = ServiceHelper.create(environment -> {
assertThat(environment.resolve(TestModule.class), is(notNullValue()));
}, SERVICE_NAME)
.domain("xyz99.spotify.net")
.conf("some.key", TEST_CONFIG_THING)
.withModule(new TestModule())
.args("-v");
withModule.start();
}
@Test
public void shouldUseScheme() throws Exception {
ServiceHelper scheme = ServiceHelper.create(this::appInit, "test-service")
.scheme("gopher+my-go.pher");
scheme.start();
Response<ByteString> response = scheme.request("GET", "/uri")
.toCompletableFuture().get();
scheme.close();
assertThat(response.payload().get().utf8(), is("gopher+my-go.pher://test-service/uri"));
}
@Test
public void shouldValidateScheme() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Illegal scheme format");
ServiceHelper.create(this::appInit, "test-service").scheme("http://"); // invalid
}
@Test
public void shouldAllowSemanticMetricRegistryResolution() throws Exception {
ServiceHelper serviceHelper = ServiceHelper.create(this::resolveRegistry, "resolve-registry");
serviceHelper.start();
}
@Test
public void shouldWorkAfterRestart() throws Exception {
when(someService.thatDoesThings()).thenReturn(TEST_THING);
serviceHelper.close();
serviceHelper.start();
String response = doGet();
assertThat(response, is(TEST_THING));
}
private void resolveRegistry(Environment environment) {
assertThat(environment.resolve(SemanticMetricRegistry.class), is(notNullValue()));
}
private static void tooSlow(Environment environment) {
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
LOG.info("interrupted because I was too slow, terminating!");
}
}
private static void throwsException(Environment environment) {
throw new RuntimeException("I fail!");
}
private static void throwsError(Environment environment) {
throw new NoClassDefFoundError("I fail!");
}
private String doGet() throws Exception {
return doGet("/");
}
private String doGet(String url) throws Exception {
final URI uri = URI.create(url);
final Response<ByteString> response =
serviceHelper.request("GET", uri).toCompletableFuture().get();
return response.payload().get().utf8();
}
private static class TestModule extends AbstractApolloModule {
@Override
protected void configure() {
bind(TestModule.class).toInstance(this);
}
@Override
public String getId() {
return "addheaderdecorator";
}
}
}