blob: 4a0cf73ad349e2acd03ea2c67a4d053b2f52cae6 [file] [log] [blame]
Jian Lie2a04ce2020-07-01 19:07:02 +09001/*
2 * Copyright 2020-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.k8snode.codec;
17
18
19import com.fasterxml.jackson.databind.JsonNode;
20import org.hamcrest.Description;
21import org.hamcrest.TypeSafeDiagnosingMatcher;
22import org.onosproject.k8snode.api.K8sHost;
23
24/**
25 * Hamcrest matcher for kubernetes host.
26 */
27public final class K8sHostJsonMatcher extends TypeSafeDiagnosingMatcher<JsonNode> {
28
29 private final K8sHost host;
30
31 private static final String HOST_IP = "hostIp";
32 private static final String NODE_NAMES = "nodeNames";
33 private static final String STATE = "state";
34
35 private K8sHostJsonMatcher(K8sHost host) {
36 this.host = host;
37 }
38
39 @Override
40 protected boolean matchesSafely(JsonNode jsonNode, Description description) {
41
42 // check host IP
43 String jsonHostIp = jsonNode.get(HOST_IP).asText();
44 String hostIp = host.hostIp().toString();
45 if (!jsonHostIp.equals(hostIp)) {
46 description.appendText("host IP was " + jsonHostIp);
47 return false;
48 }
49
50 // check state
51 String jsonState = jsonNode.get(STATE).asText();
52 String state = host.state().name();
53 if (!jsonState.equals(state)) {
54 description.appendText("state was " + jsonState);
55 return false;
56 }
57
58 // check node names size
59 JsonNode jsonNames = jsonNode.get(NODE_NAMES);
60 if (jsonNames.size() != host.nodeNames().size()) {
61 description.appendText("Node names size was " + jsonNames.size());
62 return false;
63 }
64
65 // check node names
66 for (String name : host.nodeNames()) {
67 boolean nameFound = false;
68 for (int nameIndex = 0; nameIndex < jsonNames.size(); nameIndex++) {
69 if (name.equals(jsonNames.get(nameIndex).asText())) {
70 nameFound = true;
71 break;
72 }
73 }
74
75 if (!nameFound) {
76 description.appendText("Name not found " + name);
77 return false;
78 }
79 }
80
81 return true;
82 }
83
84 @Override
85 public void describeTo(Description description) {
86 description.appendText(host.toString());
87 }
88
89 /**
90 * Factory to allocate an k8s host matcher.
91 *
92 * @param host k8s host object we are looking for
93 * @return matcher
94 */
95 public static K8sHostJsonMatcher matchesK8sHost(K8sHost host) {
96 return new K8sHostJsonMatcher(host);
97 }
98}