forked from spotify/docker-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDefaultDockerClientUnitTest.java
384 lines (319 loc) · 13.8 KB
/
DefaultDockerClientUnitTest.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
/*-
* -\-\-
* docker-client
* --
* Copyright (C) 2016 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.docker.client;
import static com.spotify.docker.FixtureUtil.fixture;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.BaseEncoding;
import com.google.common.io.Resources;
import com.spotify.docker.client.auth.RegistryAuthSupplier;
import com.spotify.docker.client.exceptions.DockerCertificateException;
import com.spotify.docker.client.exceptions.NodeNotFoundException;
import com.spotify.docker.client.exceptions.NonSwarmNodeException;
import com.spotify.docker.client.messages.ContainerConfig;
import com.spotify.docker.client.messages.HostConfig;
import com.spotify.docker.client.messages.RegistryAuth;
import com.spotify.docker.client.messages.RegistryConfigs;
import com.spotify.docker.client.messages.swarm.NodeInfo;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okio.Buffer;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Tests DefaultDockerClient against a {@link okhttp3.mockwebserver.MockWebServer} instance, so
* we can assert what the HTTP requests look like that DefaultDockerClient sends and test how
* DefaltDockerClient behaves given certain responses from the Docker Remote API.
* <p>
* This test may not be a true "unit test", but using a MockWebServer where we can control the HTTP
* responses sent by the server and capture the HTTP requests sent by the class-under-test is far
* simpler that attempting to mock the {@link javax.ws.rs.client.Client} instance used by
* DefaultDockerClient, since the Client has such a rich/fluent interface and many methods/classes
* that would need to be mocked. Ultimately for testing DefaultDockerClient all we care about is
* the HTTP requests it sends, rather than what HTTP client library it uses.</p>
* <p>
* When adding new functionality to DefaultDockerClient, please consider and prioritize adding unit
* tests to cover the new functionality in this file rather than integration tests that require a
* real docker daemon in {@link DefaultDockerClientTest}. While integration tests are valuable,
* they are more brittle and harder to run than a simple unit test that captures/asserts HTTP
* requests and responses.</p>
*
* @see <a href="https://github.com/square/okhttp/tree/master/mockwebserver">
* https://github.com/square/okhttp/tree/master/mockwebserver</a>
*/
public class DefaultDockerClientUnitTest {
private final MockWebServer server = new MockWebServer();
private DefaultDockerClient.Builder builder;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setup() throws Exception {
server.start();
builder = DefaultDockerClient.builder();
builder.uri(server.url("/").uri());
}
@After
public void tearDown() throws Exception {
server.shutdown();
}
@Test
public void testHostForUnixSocket() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("unix:///var/run/docker.sock").build();
assertThat(client.getHost(), equalTo("localhost"));
}
@Test
public void testHostForLocalHttps() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://localhost:2375").build();
assertThat(client.getHost(), equalTo("localhost"));
}
@Test
public void testHostForFqdnHttps() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://perdu.com:2375").build();
assertThat(client.getHost(), equalTo("perdu.com"));
}
@Test
public void testHostForIpHttps() {
final DefaultDockerClient client = DefaultDockerClient.builder()
.uri("https://192.168.53.103:2375").build();
assertThat(client.getHost(), equalTo("192.168.53.103"));
}
private RecordedRequest takeRequestImmediately() throws InterruptedException {
return server.takeRequest(1, TimeUnit.MILLISECONDS);
}
@Test
public void testCustomHeaders() throws Exception {
builder.header("int", 1);
builder.header("string", "2");
builder.header("list", Lists.newArrayList("a", "b", "c"));
server.enqueue(new MockResponse());
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
dockerClient.info();
final RecordedRequest recordedRequest = takeRequestImmediately();
assertThat(recordedRequest.getMethod(), is("GET"));
assertThat(recordedRequest.getPath(), is("/info"));
assertThat(recordedRequest.getHeader("int"), is("1"));
assertThat(recordedRequest.getHeader("string"), is("2"));
// TODO (mbrown): this seems like incorrect behavior - the client should send 3 headers with
// name "list", not one header with a value of "[a, b, c]"
assertThat(recordedRequest.getHeaders().values("list"), contains("[a, b, c]"));
}
private static JsonNode toJson(Buffer buffer) throws IOException {
return ObjectMapperProvider.objectMapper().readTree(buffer.inputStream());
}
private static JsonNode toJson(byte[] bytes) throws IOException {
return ObjectMapperProvider.objectMapper().readTree(bytes);
}
private static JsonNode toJson(Object object) throws IOException {
return ObjectMapperProvider.objectMapper().valueToTree(object);
}
private static ObjectNode createObjectNode() {
return ObjectMapperProvider.objectMapper().createObjectNode();
}
@Test
@SuppressWarnings("unchecked")
public void testCapAddAndDrop() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
final HostConfig hostConfig = HostConfig.builder()
.capAdd(ImmutableList.of("foo", "bar"))
.capAdd(ImmutableList.of("baz", "qux"))
.build();
final ContainerConfig containerConfig = ContainerConfig.builder()
.hostConfig(hostConfig)
.build();
server.enqueue(new MockResponse());
dockerClient.createContainer(containerConfig);
final RecordedRequest recordedRequest = takeRequestImmediately();
assertThat(recordedRequest.getMethod(), is("POST"));
assertThat(recordedRequest.getPath(), is("/containers/create"));
assertThat(recordedRequest.getHeader("Content-Type"), is("application/json"));
// TODO (mbrown): use hamcrest-jackson for this, once we upgrade to Java 8
final JsonNode requestJson = toJson(recordedRequest.getBody());
final JsonNode capAddNode = requestJson.get("HostConfig").get("CapAdd");
assertThat(capAddNode.isArray(), is(true));
assertThat(childrenTextNodes((ArrayNode) capAddNode), containsInAnyOrder("baz", "qux"));
}
private static Set<String> childrenTextNodes(ArrayNode arrayNode) {
final Set<String> texts = new HashSet<>();
for (JsonNode child : arrayNode) {
Preconditions.checkState(child.isTextual(),
"ArrayNode must only contain text nodes, but found %s in %s",
child.getNodeType(),
arrayNode);
texts.add(child.textValue());
}
return texts;
}
@Test
@SuppressWarnings("deprecated")
public void buildThrowsIfRegistryAuthandRegistryAuthSupplierAreBothSpecified()
throws DockerCertificateException {
thrown.expect(IllegalStateException.class);
thrown.expectMessage("LOGIC ERROR");
final RegistryAuthSupplier authSupplier = mock(RegistryAuthSupplier.class);
DefaultDockerClient.builder()
.registryAuth(RegistryAuth.builder().identityToken("hello").build())
.registryAuthSupplier(authSupplier)
.build();
}
@Test
public void testBuildPassesMultipleRegistryConfigs() throws Exception {
final RegistryConfigs registryConfigs = RegistryConfigs.create(ImmutableMap.of(
"server1", RegistryAuth.builder()
.serverAddress("server1")
.username("u1")
.password("p1")
.email("e1")
.build(),
"server2", RegistryAuth.builder()
.serverAddress("server2")
.username("u2")
.password("p2")
.email("e2")
.build()
));
final RegistryAuthSupplier authSupplier = mock(RegistryAuthSupplier.class);
when(authSupplier.authForBuild()).thenReturn(registryConfigs);
final DefaultDockerClient client = builder.registryAuthSupplier(authSupplier)
.build();
// build() calls /version to check what format of header to send
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
createObjectNode()
.put("ApiVersion", "1.20")
.put("Arch", "foobar")
.put("GitCommit", "foobar")
.put("GoVersion", "foobar")
.put("KernelVersion", "foobar")
.put("Os", "foobar")
.put("Version", "1.20")
.toString()
)
);
// TODO (mbrown): what to return for build response?
server.enqueue(new MockResponse()
.setResponseCode(200)
);
final Path path = Paths.get(Resources.getResource("dockerDirectory").toURI());
client.build(path);
final RecordedRequest versionRequest = takeRequestImmediately();
assertThat(versionRequest.getMethod(), is("GET"));
assertThat(versionRequest.getPath(), is("/version"));
final RecordedRequest buildRequest = takeRequestImmediately();
assertThat(buildRequest.getMethod(), is("POST"));
assertThat(buildRequest.getPath(), is("/build"));
final String registryConfigHeader = buildRequest.getHeader("X-Registry-Config");
assertThat(registryConfigHeader, is(not(nullValue())));
// check that the JSON in the header is equivalent to what we mocked out above from
// the registryAuthSupplier
final JsonNode headerJsonNode = toJson(BaseEncoding.base64().decode(registryConfigHeader));
assertThat(headerJsonNode, is(toJson(registryConfigs.configs())));
}
@Test
public void testInspectNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.28");
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
fixture("fixtures/1.28/nodeInfo.json")
)
);
NodeInfo nodeInfo = dockerClient.inspectNode("24ifsmvkjbyhk");
assertThat(nodeInfo, notNullValue());
assertThat(nodeInfo.id(), is("24ifsmvkjbyhk"));
assertThat(nodeInfo.status(), notNullValue());
assertThat(nodeInfo.status().addr(), is("172.17.0.2"));
assertThat(nodeInfo.managerStatus(), notNullValue());
assertThat(nodeInfo.managerStatus().addr(), is("172.17.0.2:2377"));
assertThat(nodeInfo.managerStatus().leader(), is(true));
assertThat(nodeInfo.managerStatus().reachability(), is("reachable"));
}
@Test(expected = NodeNotFoundException.class)
public void testInspectMissingNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.28");
server.enqueue(new MockResponse()
.setResponseCode(404)
.addHeader("Content-Type", "application/json")
);
dockerClient.inspectNode("24ifsmvkjbyhk");
}
@Test(expected = NonSwarmNodeException.class)
public void testInspectNonSwarmNode() throws Exception {
final DefaultDockerClient dockerClient = new DefaultDockerClient(builder);
// build() calls /version to check what format of header to send
enqueueServerApiVersion("1.28");
server.enqueue(new MockResponse()
.setResponseCode(503)
.addHeader("Content-Type", "application/json")
);
dockerClient.inspectNode("24ifsmvkjbyhk");
}
private void enqueueServerApiVersion(final String apiVersion) {
server.enqueue(new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json")
.setBody(
createObjectNode()
.put("ApiVersion", apiVersion)
.put("Arch", "foobar")
.put("GitCommit", "foobar")
.put("GoVersion", "foobar")
.put("KernelVersion", "foobar")
.put("Os", "foobar")
.put("Version", "1.20")
.toString()
)
);
}
}