Skip to content

Commit

Permalink
mock: generation is an Integer field
Browse files Browse the repository at this point in the history
  • Loading branch information
petitlapin committed Mar 5, 2022
1 parent 8e453ab commit 67ccc66
Showing 1 changed file with 47 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ public KubernetesCrudDispatcher(List<CustomResourceDefinitionContext> crdContext
this(new KubernetesAttributesExtractor(crdContexts), new KubernetesResponseComposer());
}

public KubernetesCrudDispatcher(KubernetesAttributesExtractor attributeExtractor, KubernetesResponseComposer responseComposer) {
public KubernetesCrudDispatcher(KubernetesAttributesExtractor attributeExtractor,
KubernetesResponseComposer responseComposer) {
super(new Context(Serialization.jsonMapper()), attributeExtractor, responseComposer);
this.kubernetesAttributesExtractor = attributeExtractor;
this.kubernetesResponseComposer = responseComposer;
Expand All @@ -111,6 +112,7 @@ public MockResponse handleCreate(String path, String s) {

/**
* Replace the object on `path` endpoint with the object represented by `s`
*
* @param path String
* @param s String
* @return The {@link MockResponse}
Expand All @@ -137,11 +139,11 @@ public MockResponse handleGet(String path) {

synchronized (map) {
map.entrySet().stream()
.filter(entry -> entry.getKey().matches(query))
.forEach(entry -> {
LOGGER.debug("Entry found for query {} : {}", query, entry);
items.add(entry.getValue());
});
.filter(entry -> entry.getKey().matches(query))
.forEach(entry -> {
LOGGER.debug("Entry found for query {} : {}", query, entry);
items.add(entry.getValue());
});
}

if (query.containsKey(KubernetesAttributesExtractor.NAME)) {
Expand Down Expand Up @@ -175,8 +177,8 @@ public MockResponse handlePatch(RecordedRequest request) {
Optional<Map.Entry<AttributeSet, String>> bodyEntry;
synchronized (map) {
bodyEntry = map.entrySet().stream()
.filter(entry -> entry.getKey().matches(query))
.findFirst();
.filter(entry -> entry.getKey().matches(query))
.findFirst();
}

if (!bodyEntry.isPresent()) {
Expand All @@ -189,8 +191,7 @@ public MockResponse handlePatch(RecordedRequest request) {
JsonNode status = null;

Map<String, String> pathValues = kubernetesAttributesExtractor.fromKubernetesPath(path);
boolean statusSubresource =
crdProcessor.isStatusSubresource(pathValues);
boolean statusSubresource = crdProcessor.isStatusSubresource(pathValues);

if (statusSubresource && !isStatusPath(path)) {
status = removeStatus(source);
Expand All @@ -214,7 +215,7 @@ public MockResponse handlePatch(RecordedRequest request) {
}

JsonNode updated;
if (mergeType == PatchType.JSON) {
if (mergeType == PatchType.JSON) {
updated = JsonPatch.apply(patch, source);
} else {
ObjectReader objectReader = context.getMapper().readerForUpdating(source);
Expand All @@ -229,9 +230,9 @@ public MockResponse handlePatch(RecordedRequest request) {
// restore the status
if (statusSubresource || isStatusPath(path)) {
if (status == null) {
removeStatus(updated);
removeStatus(updated);
} else {
((ObjectNode)updated).set(STATUS, status);
((ObjectNode) updated).set(STATUS, status);
}
}

Expand Down Expand Up @@ -278,14 +279,13 @@ public MockResponse handleWatch(String path) {
query = query.add(new Attribute("name", resourceName));
}
WatchEventsListener watchEventListener = new WatchEventsListener(context, query, watchEventListeners, LOGGER,
watch -> {
synchronized (map) {
map.entrySet().stream()
.filter(entry -> watch.attributeMatches(entry.getKey()))
.forEach(entry -> watch.sendWebSocketResponse(entry.getValue(), Action.ADDED));
}
}
);
watch -> {
synchronized (map) {
map.entrySet().stream()
.filter(entry -> watch.attributeMatches(entry.getKey()))
.forEach(entry -> watch.sendWebSocketResponse(entry.getValue(), Action.ADDED));
}
});
watchEventListeners.add(watchEventListener);
mockResponse.setSocketPolicy(SocketPolicy.KEEP_OPEN);
return mockResponse.withWebSocketUpgrade(watchEventListener);
Expand Down Expand Up @@ -319,20 +319,21 @@ private String fetchResourceNameFromWatchRequestPath(String path) {
}

String name = "";
for (String q: queryString.split("&")) {
for (String q : queryString.split("&")) {
if (q.contains("fieldSelector") && q.contains("metadata.name")) {
String[] s = q.split("=");
name = s[s.length - 1];
}
}
return name.isEmpty()? null: name;
return name.isEmpty() ? null : name;
}

private int doDelete(String path) {
AttributeSet fromPath = attributeExtractor.fromPath(path);
List<AttributeSet> items = findItems(fromPath);

if (items.isEmpty()) return HttpURLConnection.HTTP_NOT_FOUND;
if (items.isEmpty())
return HttpURLConnection.HTTP_NOT_FOUND;

items.forEach(item -> processEvent(path, fromPath, item, null));
return HttpURLConnection.HTTP_OK;
Expand Down Expand Up @@ -370,8 +371,8 @@ private void processEvent(String path, AttributeSet pathAttributes, AttributeSet
private List<AttributeSet> findItems(AttributeSet query) {
synchronized (map) {
return map.keySet().stream()
.filter(entry -> entry.matches(query))
.collect(Collectors.toList());
.filter(entry -> entry.matches(query))
.collect(Collectors.toList());
}
}

Expand Down Expand Up @@ -442,24 +443,24 @@ private static boolean isStatusPath(String path) {
// Visible for testing
static boolean shouldIncreaseGeneration(JsonNode existing, JsonNode source) {
final JsonNode differences = Optional.ofNullable(existing).map(e -> JsonDiff.asJson(e, source))
.orElse(null);
.orElse(null);
return shouldIncreaseGeneration(differences);
}

static boolean shouldIncreaseGeneration(JsonNode differences) {
if (differences != null && !differences.isEmpty()) {
return StreamSupport.stream(differences.spliterator(), false)
.filter(n -> !n.get("path").asText().startsWith("/metadata/"))
.anyMatch(n -> !n.get("path").asText().startsWith("/status/"));
.filter(n -> !n.get("path").asText().startsWith("/metadata/"))
.anyMatch(n -> !n.get("path").asText().startsWith("/status/"));
}
return false;
}

private void setDefaultMetadata(JsonNode source, Map<String, String> pathValues, JsonNode existing) {
ObjectNode metadata = (ObjectNode)source.findValue("metadata");
ObjectNode metadata = (ObjectNode) source.findValue("metadata");
ObjectNode existingMetadata = null;
if (existing != null) {
existingMetadata = (ObjectNode)existing.findValue("metadata");
existingMetadata = (ObjectNode) existing.findValue("metadata");
}
UUID uuid = UUID.randomUUID();
if (metadata.get("name") == null) {
Expand All @@ -469,8 +470,9 @@ private void setDefaultMetadata(JsonNode source, Map<String, String> pathValues,
metadata.put("namespace", pathValues.get(KubernetesAttributesExtractor.NAMESPACE));
}
metadata.put("uid", getOrDefault(existingMetadata, "uid", uuid.toString()));
metadata.put(GENERATION, getOrDefault(existingMetadata, GENERATION, "1"));
metadata.put("creationTimestamp", getOrDefault(existingMetadata, "creationTimestamp", ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)));
metadata.put(GENERATION, Integer.parseInt(getOrDefault(existingMetadata, GENERATION, "1")));
metadata.put("creationTimestamp", getOrDefault(existingMetadata, "creationTimestamp",
ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)));

if (existing == null) {
metadata.put(RESOURCE_VERSION, String.valueOf(resourceVersion.incrementAndGet()));
Expand All @@ -497,7 +499,7 @@ private String getOrDefault(JsonNode node, String name, String defaultValue) {
}

private JsonNode removeStatus(JsonNode source) {
return ((ObjectNode)source).remove(STATUS);
return ((ObjectNode) source).remove(STATUS);
}

private void setStatus(JsonNode source, JsonNode status) {
Expand Down Expand Up @@ -534,14 +536,14 @@ private String getStatusBody(HasMetadata h, int code, Exception ex) {
kind = h.getKind();
}
Status status = new StatusBuilder().withStatus("Failure")
.withReason("Invalid")
.withMessage(kind + " is invalid")
.withNewDetails()
.withKind(kind)
.withCauses(getFailureStatusCause(ex))
.endDetails()
.withCode(code)
.build();
.withReason("Invalid")
.withMessage(kind + " is invalid")
.withNewDetails()
.withKind(kind)
.withCauses(getFailureStatusCause(ex))
.endDetails()
.withCode(code)
.build();
try {
return Serialization.jsonMapper().writeValueAsString(status);
} catch (IOException ioException) {
Expand All @@ -551,9 +553,9 @@ private String getStatusBody(HasMetadata h, int code, Exception ex) {

private StatusCause getFailureStatusCause(Exception ex) {
return new StatusCauseBuilder()
.withMessage(ex.getMessage())
.withReason("ValueRequired")
.build();
.withMessage(ex.getMessage())
.withReason("ValueRequired")
.build();
}

private void validateResource(HasMetadata item) {
Expand Down

0 comments on commit 67ccc66

Please sign in to comment.