forked from fabric8io/kubernetes-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerializationTest.java
500 lines (437 loc) · 17.4 KB
/
SerializationTest.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* 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 io.fabric8.kubernetes.client.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonTypeResolver;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.fabric8.kubernetes.api.model.AnyType;
import io.fabric8.kubernetes.api.model.Config;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.GenericKubernetesResource;
import io.fabric8.kubernetes.api.model.KubernetesList;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceDefinition;
import io.fabric8.kubernetes.api.model.apiextensions.v1beta1.JSONSchemaProps;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.coordination.v1.Lease;
import io.fabric8.kubernetes.api.model.coordination.v1.LeaseSpec;
import io.fabric8.kubernetes.api.model.runtime.RawExtension;
import io.fabric8.kubernetes.client.CustomResource;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.model.annotation.Group;
import io.fabric8.kubernetes.model.annotation.Version;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.assertj.core.groups.Tuple;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class SerializationTest {
@Test
void unmarshalCRDWithSchema() throws Exception {
// Given
final String input = readYamlToString("/serialization/test-crd-schema.yml");
final CustomResourceDefinition crd = Serialization.unmarshal(input, CustomResourceDefinition.class);
// When
JSONSchemaProps spec = crd.getSpec()
.getValidation()
.getOpenAPIV3Schema()
.getProperties()
.get("spec");
// Then
assertThat(spec)
.hasFieldOrPropertyWithValue("properties.builderName.example", new TextNode("builder-example"))
.hasFieldOrPropertyWithValue("properties.hollow.default", BooleanNode.FALSE)
.hasFieldOrPropertyWithValue("properties.dimensions.properties.x.default", new IntNode(10))
.extracting(JSONSchemaProps::getRequired).asList()
.containsExactly("builderName", "edges", "dimensions");
}
@Test
void asYamlWithDeserializedCRD() throws Exception {
// Given
final String input = readYamlToString("/serialization/test-crd-schema.yml");
final CustomResourceDefinition crd = Serialization.unmarshal(input, CustomResourceDefinition.class);
// When
final String result = Serialization.asYaml(crd);
// Then
assertThat(result.trim()).isEqualTo(input.trim());
}
@Test
@DisplayName("unmarshal, String containing List with windows like line-ends (CRLF), all list items should be available")
void unmarshalListWithWindowsLineSeparatorsString() throws Exception {
// Given
final String crlfFile = readYamlToString("/serialization/test-list.yml");
// When
final KubernetesResource result = Serialization.unmarshal(crlfFile, KubernetesResource.class);
// Then
assertThat(result)
.asInstanceOf(InstanceOfAssertFactories.type(KubernetesList.class))
.extracting(KubernetesList::getItems).asList()
.hasSize(2)
.hasAtLeastOneElementOfType(Service.class)
.hasAtLeastOneElementOfType(Deployment.class);
}
private String readYamlToString(String path) throws IOException {
return Files.readAllLines(
new File(SerializationTest.class.getResource(path).getFile()).toPath(), StandardCharsets.UTF_8)
.stream()
.filter(line -> !line.startsWith("#"))
.collect(Collectors.joining("\n"));
}
@Test
@DisplayName("containsMultipleDocuments, multiple documents with windows line ends, should return true")
void containsMultipleDocumentsWithMultipleDocumentsAndWindowsLineEnds() {
// Given
final String multiDocument = "---\r\napiVersion: v1\r\nKind: Something\r\n\r\n---\r\napiVersion: v2\r\nKind: Other";
// When
final boolean result = Serialization.containsMultipleDocuments(multiDocument);
// Then
assertThat(result).isTrue();
}
@Test
@DisplayName("containsMultipleDocuments, single document with windows line ends, should return false")
void containsMultipleDocumentsWithSingleDocumentAndWindowsLineEnds() {
// Given
final String multiDocument = "---\r\napiVersion: v1\r\nKind: Something\r\n\r\n";
// When
final boolean result = Serialization.containsMultipleDocuments(multiDocument);
// Then
assertThat(result).isFalse();
}
@Test
@DisplayName("containsMultipleDocuments, multiple documents with linux line ends, should return true")
void containsMultipleDocumentsWithMultipleDocumentsAndLinuxLineEnds() {
// Given
final String multiDocument = "---\napiVersion: v1\nKind: Something\n\n---\napiVersion: v2\nKind: Other";
// When
final boolean result = Serialization.containsMultipleDocuments(multiDocument);
// Then
assertThat(result).isTrue();
}
@Test
@DisplayName("containsMultipleDocuments, single document with linux line ends, should return false")
void containsMultipleDocumentsWithSingleDocumentAndLinuxLineEnds() {
// Given
final String multiDocument = "---\napiVersion: v1\nKind: Something\n\n";
// When
final boolean result = Serialization.containsMultipleDocuments(multiDocument);
// Then
assertThat(result).isFalse();
}
@Test
void testSerializeYamlWithAlias() {
// Given
InputStream fileInputStream = getClass().getResourceAsStream("/serialization/test-pod-manifest-with-aliases.yml");
// When
Pod pod = Serialization.unmarshal(fileInputStream);
// Then
assertThat(pod)
.isNotNull()
.hasFieldOrPropertyWithValue("metadata.name", "test-pod-with-alias")
.hasFieldOrPropertyWithValue("spec.nodeSelector.workload", "build")
.hasFieldOrPropertyWithValue("spec.tolerations.size", 1)
.hasFieldOrPropertyWithValue("spec.securityContext.runAsGroup", 1000L)
.hasFieldOrPropertyWithValue("spec.securityContext.runAsUser", 1000L)
.extracting(Pod::getSpec).extracting(PodSpec::getContainers).asList()
.hasSize(2)
.extracting("name", "image", "resources.requests.cpu")
.containsExactly(
new Tuple("ubuntu", "ubuntu:bionic", new Quantity("100m")),
new Tuple("python3", "python:3.7", new Quantity("100m")));
}
@Test
void testClone() {
// Given
Pod pod = new PodBuilder().withNewMetadata().withName("pod").endMetadata().build();
// When
Pod clonePod = Serialization.clone(pod);
// Then
assertThat(clonePod)
.isEqualTo(pod)
.isNotSameAs(pod)
.hasFieldOrPropertyWithValue("metadata.name", "pod");
}
@Test
void testCloneNonResource() {
// Given
Map<String, String> value = Collections.singletonMap("key", "value");
// When
Map<String, String> cloneValue = Serialization.clone(value);
// Then
assertThat(cloneValue)
.isEqualTo(value)
.isNotSameAs(value);
}
@Test
@DisplayName("unmarshal, with valid YAML custom resource, should return GenericKubernetesResource instance")
void unmarshalWithValidCustomResourceShouldReturnGenericCustomResource() {
// When
final KubernetesResource result = Serialization.unmarshal(
SerializationTest.class.getResourceAsStream("/serialization/custom-resource.yml"));
// Then
assertThat(result)
.isNotNull()
.isInstanceOf(GenericKubernetesResource.class)
.hasFieldOrPropertyWithValue("apiVersion", "the-cr.example.com/v1")
.hasFieldOrPropertyWithValue("Kind", "SomeCustomResource")
.hasFieldOrPropertyWithValue("metadata.name", "custom-resource-example")
.hasFieldOrPropertyWithValue("additionalProperties.spec.field", "value")
.hasFieldOrPropertyWithValue("additionalProperties.status.reconciled", true);
}
@Test
void unmarshalWithInvalidYamlShouldThrowException() {
// Given
final InputStream is = SerializationTest.class.getResourceAsStream("/serialization/invalid-yaml.yml");
// When
RawExtension result = Serialization.unmarshal(is);
// Then
assertEquals("This\nis not\nYAML", result.getValue());
}
@Test
void unmarshalArrays() {
// not valid as KubernetesResource - we'd have to look ahead to know if the array values
// were not hasmetadata
assertThrows(KubernetesClientException.class, () -> Serialization.unmarshal("[1, 2]"));
assertThrows(IllegalArgumentException.class, () -> Serialization.unmarshal("- 1\n- 2"));
assertEquals(Arrays.asList(1, 2), Serialization.unmarshal("[1, 2]", List.class));
assertEquals(Arrays.asList(1, 2), Serialization.unmarshal("- 1\n- 2", List.class));
}
@Test
void unmarshalPrimitives() {
// as json
RawExtension raw = Serialization.unmarshal("\"a\"");
assertEquals("a", raw.getValue());
// as yaml
raw = Serialization.unmarshal("a");
assertEquals("a", raw.getValue());
assertEquals("a", Serialization.unmarshal("\"a\"", String.class));
assertEquals("a", Serialization.unmarshal("a", String.class));
}
@Test
void unmarshalRawResource() {
InputStream is = SerializationTest.class.getResourceAsStream("/serialization/invalid-resource.yml");
RawExtension raw = Serialization.unmarshal(is);
((Map) raw.getValue()).get("not-a").equals("resource");
}
@Test
@DisplayName("unmarshal, with valid YAML list, should return KubernetesList")
void unmarshalWithValidListShouldReturnKubernetesList() {
// When
final KubernetesResource result = Serialization.unmarshal(
SerializationTest.class.getResourceAsStream("/serialization/kubernetes-list.yml"));
// Then
assertThat(result)
.asInstanceOf(InstanceOfAssertFactories.type(KubernetesList.class))
.extracting(KubernetesList::getItems).asList()
.hasSize(3)
.extracting("class", "apiVersion", "kind", "metadata.name")
.containsExactlyInAnyOrder(
new Tuple(GenericKubernetesResource.class, "custom.resource.example.com/v1", "Example", "a-custom-resource"),
new Tuple(Namespace.class, "v1", "Namespace", "a-namespace"),
new Tuple(Pod.class, "v1", "Pod", "a-pod"));
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes(@JsonSubTypes.Type(value = Typed.class, name = "x"))
public interface Typeable {
String getType();
}
public static class Typed implements Typeable {
@Override
public String getType() {
return "x";
}
}
public static class Root {
private Typeable typeable;
public Typeable getTypeable() {
return typeable;
}
public void setTypeable(Typeable typeable) {
this.typeable = typeable;
}
}
@Test
void testSerializeYamlWithJsonSubTypes() {
Root root = new Root();
root.setTypeable(new Typed());
final String result = Serialization.asYaml(root);
assertThat(result)
.isEqualTo("---\n"
+ "typeable:\n"
+ " type: \"x\"\n", Serialization.asYaml(root));
}
@Group("serialization.fabric8.io")
@Version("v1")
private static class MyCR extends CustomResource<String, Void> {
public MyCR() {
setSpec("foo");
}
}
@Test
void nullValueShouldNotBeOutput() {
MyCR cr = new MyCR();
final String s = Serialization.asYaml(cr);
assertThat(s)
.doesNotContain("status")
.contains("spec: \"foo\"");
}
@Test
void quantityQuoting() {
Quantity quantity = Serialization.unmarshal("amount: \"2\"\nformat: \"Gi\"", Quantity.class);
assertThat(Serialization.asYaml(quantity)).isEqualTo("--- \"2Gi\"\n");
}
@Test
void parseConfigWithRaw() {
Config config = Serialization.unmarshal("extensions: \n"
+ "- name: foo\n"
+ " extension:\n"
+ " not: kubernetesresource", Config.class);
// ensure that the extenion is preserved
assertThat(Serialization.asYaml(config)).isEqualTo("---\n"
+ "clusters: []\n"
+ "contexts: []\n"
+ "extensions:\n"
+ "- extension:\n"
+ " not: \"kubernetesresource\"\n"
+ " name: \"foo\"\n"
+ "users: []\n");
}
@JsonTypeResolver(io.fabric8.kubernetes.model.jackson.UnwrappedTypeResolverBuilder.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonSubTypes({
@JsonSubTypes.Type(Named.class),
@JsonSubTypes.Type(Counted.class)
})
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION)
interface Poly {
}
@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
static class Named implements Poly {
public String name;
}
@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
static class Counted implements Poly {
public int count;
}
@JsonDeserialize(using = io.fabric8.kubernetes.model.jackson.JsonUnwrappedDeserializer.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
static class PolyParent {
@JsonUnwrapped
public Poly poly;
public int other;
}
@Test
void polymorphicUnwrap() {
PolyParent parent = Serialization.unmarshal("other: 1\nname: x", PolyParent.class);
assertEquals("x", ((Named) parent.poly).name);
// should be null if it can't be deduced
parent = Serialization.unmarshal("other: 1", PolyParent.class);
assertThat(parent.poly).isNull();
}
@Test
void unmarshal_podWithYYYYMMDDAnnotation_shouldNotConvertToDate() {
// Given
InputStream inputStream = getClass().getResourceAsStream("/serialization/test-pod-manifest-dateformat-annotation.yml");
// When
Pod pod = Serialization.unmarshal(inputStream);
// Then
assertThat(pod)
.isNotNull()
.hasFieldOrPropertyWithValue("spec.shareProcessNamespace", false)
.hasFieldOrPropertyWithValue("spec.terminationGracePeriodSeconds", 2L)
.extracting(Pod::getMetadata)
.extracting(ObjectMeta::getAnnotations)
.isEqualTo(Collections.singletonMap("report_date", "2020-01-01"));
}
@Test
void unmarshal_leaseWithTypedValues_ShouldConvertToTypedFields() {
// Given
InputStream inputStream = getClass().getResourceAsStream("/serialization/test-lease-manifest-typed-fields.yml");
// When
Lease lease = Serialization.unmarshal(inputStream);
// Then
assertThat(lease)
.isNotNull()
.hasFieldOrPropertyWithValue("metadata.annotations",
Collections.singletonMap("creationTimestamp", "2022-07-22T10:42:02Z"))
.hasFieldOrPropertyWithValue("spec.leaseDurationSeconds", 2)
.hasFieldOrPropertyWithValue("spec.leaseTransitions", 3)
.extracting(Lease::getSpec)
.extracting(LeaseSpec::getAcquireTime)
.isInstanceOf(ZonedDateTime.class);
}
@Test
void unmarshal_configMapWithBoolAndDateData_shouldBeDeserializedAsString() {
// Given
InputStream inputStream = getClass().getResourceAsStream("/serialization/test-configmap-manifest-bool-dateformat.yml");
// When
ConfigMap configMap = Serialization.unmarshal(inputStream);
// Then
assertThat(configMap)
.isNotNull()
.extracting(ConfigMap::getData)
.asInstanceOf(InstanceOfAssertFactories.MAP)
.containsEntry("bool", "NO")
.containsEntry("date", "2022-07-22");
}
@Test
void testAnyTypeSerialization() {
// Given
AnyType value = new AnyType("x");
// When
String yaml = Serialization.asYaml(value);
// Then
assertThat(yaml).isEqualTo("--- \"x\"\n");
}
@Test
void testAnyTypeDeserialization() {
// Given
String yaml = "x: 1";
HashMap<String, Object> map = new HashMap<>();
map.put("x", 1);
// When
AnyType type = Serialization.unmarshal(yaml, AnyType.class);
// Then
assertThat(type.getValue()).isEqualTo(map);
}
}