[ONOS-7902] Add default implementation of k8s node with unit tests
Change-Id: I283967ae14dc7f38e749d7407e4bec698536c18b
diff --git a/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/codec/K8sNodeCodecTest.java b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/codec/K8sNodeCodecTest.java
new file mode 100644
index 0000000..7f156e8
--- /dev/null
+++ b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/codec/K8sNodeCodecTest.java
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * 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 org.onosproject.k8snode.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.packet.IpAddress;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snode.api.DefaultK8sNode;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNodeState;
+import org.onosproject.net.DeviceId;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+import static junit.framework.TestCase.assertEquals;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.onosproject.k8snode.codec.K8sNodeJsonMatcher.matchesK8sNode;
+import static org.onosproject.net.NetTestTools.APP_ID;
+
+/**
+ * Unit tests for Kubernetes Node codec.
+ */
+public class K8sNodeCodecTest {
+
+ MockCodecContext context;
+
+ JsonCodec<K8sNode> k8sNodeCodec;
+
+ final CoreService mockCoreService = createMock(CoreService.class);
+ private static final String REST_APP_ID = "org.onosproject.rest";
+
+ /**
+ * Initial setup for this unit test.
+ */
+ @Before
+ public void setUp() {
+ context = new MockCodecContext();
+ k8sNodeCodec = new K8sNodeCodec();
+
+ assertThat(k8sNodeCodec, notNullValue());
+
+ expect(mockCoreService.registerApplication(REST_APP_ID))
+ .andReturn(APP_ID).anyTimes();
+ replay(mockCoreService);
+ context.registerService(CoreService.class, mockCoreService);
+ }
+
+ /**
+ * Tests the kubernetes minion node encoding.
+ */
+ @Test
+ public void testK8sMinionNodeEncode() {
+ K8sNode node = DefaultK8sNode.builder()
+ .hostname("minion")
+ .type(K8sNode.Type.MINION)
+ .state(K8sNodeState.INIT)
+ .managementIp(IpAddress.valueOf("10.10.10.1"))
+ .dataIp(IpAddress.valueOf("20.20.20.2"))
+ .intgBridge(DeviceId.deviceId("kbr-int"))
+ .build();
+
+ ObjectNode nodeJson = k8sNodeCodec.encode(node, context);
+ assertThat(nodeJson, matchesK8sNode(node));
+ }
+
+ /**
+ * Tests the kubernetes minion node decoding.
+ *
+ * @throws IOException IO exception
+ */
+ @Test
+ public void testK8sMinionNodeDecode() throws IOException {
+ K8sNode node = getK8sNode("K8sMinionNode.json");
+
+ assertEquals("minion", node.hostname());
+ assertEquals("MINION", node.type().name());
+ assertEquals("172.16.130.4", node.managementIp().toString());
+ assertEquals("172.16.130.4", node.dataIp().toString());
+ assertEquals("of:00000000000000a1", node.intgBridge().toString());
+ }
+
+ private K8sNode getK8sNode(String resourceName) throws IOException {
+ InputStream jsonStream = K8sNodeCodecTest.class.getResourceAsStream(resourceName);
+ JsonNode json = context.mapper().readTree(jsonStream);
+ assertThat(json, notNullValue());
+ K8sNode node = k8sNodeCodec.decode((ObjectNode) json, context);
+ assertThat(node, notNullValue());
+ return node;
+ }
+
+ private class MockCodecContext implements CodecContext {
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final CodecManager manager = new CodecManager();
+ private final Map<Class<?>, Object> services = new HashMap<>();
+
+ /**
+ * Constructs a new mock codec context.
+ */
+ public MockCodecContext() {
+ manager.activate();
+ }
+
+ @Override
+ public ObjectMapper mapper() {
+ return mapper;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> JsonCodec<T> codec(Class<T> entityClass) {
+ if (entityClass == K8sNode.class) {
+ return (JsonCodec<T>) k8sNodeCodec;
+ }
+ return manager.getCodec(entityClass);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T getService(Class<T> serviceClass) {
+ return (T) services.get(serviceClass);
+ }
+
+ // for registering mock services
+ public <T> void registerService(Class<T> serviceClass, T impl) {
+ services.put(serviceClass, impl);
+ }
+ }
+}
diff --git a/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/codec/K8sNodeJsonMatcher.java b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/codec/K8sNodeJsonMatcher.java
new file mode 100644
index 0000000..58b15d2
--- /dev/null
+++ b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/codec/K8sNodeJsonMatcher.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * 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 org.onosproject.k8snode.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.onosproject.k8snode.api.K8sNode;
+
+/**
+ * Hamcrest matcher for kubernetes node.
+ */
+public final class K8sNodeJsonMatcher extends TypeSafeDiagnosingMatcher<JsonNode> {
+
+ private final K8sNode node;
+
+ private static final String HOSTNAME = "hostname";
+ private static final String TYPE = "type";
+ private static final String MANAGEMENT_IP = "managementIp";
+ private static final String DATA_IP = "dataIp";
+ private static final String INTEGRATION_BRIDGE = "integrationBridge";
+ private static final String STATE = "state";
+
+ private K8sNodeJsonMatcher(K8sNode node) {
+ this.node = node;
+ }
+
+ @Override
+ protected boolean matchesSafely(JsonNode jsonNode, Description description) {
+
+ // check hostname
+ String jsonHostname = jsonNode.get(HOSTNAME).asText();
+ String hostname = node.hostname();
+ if (!jsonHostname.equals(hostname)) {
+ description.appendText("hostname was " + jsonHostname);
+ return false;
+ }
+
+ // check type
+ String jsonType = jsonNode.get(TYPE).asText();
+ String type = node.type().name();
+ if (!jsonType.equals(type)) {
+ description.appendText("type was " + jsonType);
+ return false;
+ }
+
+ // check management IP
+ String jsonMgmtIp = jsonNode.get(MANAGEMENT_IP).asText();
+ String mgmtIp = node.managementIp().toString();
+ if (!jsonMgmtIp.equals(mgmtIp)) {
+ description.appendText("management IP was " + jsonMgmtIp);
+ return false;
+ }
+
+ // check integration bridge
+ JsonNode jsonIntgBridge = jsonNode.get(INTEGRATION_BRIDGE);
+ if (jsonIntgBridge != null) {
+ String intgBridge = node.intgBridge().toString();
+ if (!jsonIntgBridge.asText().equals(intgBridge)) {
+ description.appendText("integration bridge was " + jsonIntgBridge);
+ return false;
+ }
+ }
+
+ // check state
+ String jsonState = jsonNode.get(STATE).asText();
+ String state = node.state().name();
+ if (!jsonState.equals(state)) {
+ description.appendText("state was " + jsonState);
+ return false;
+ }
+
+ // check data IP
+ JsonNode jsonDataIp = jsonNode.get(DATA_IP);
+ if (jsonDataIp != null) {
+ String dataIp = node.dataIp().toString();
+ if (!jsonDataIp.asText().equals(dataIp)) {
+ description.appendText("Data IP was " + jsonDataIp.asText());
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText(node.toString());
+ }
+
+ /**
+ * Factory to allocate an kubernetes node matcher.
+ *
+ * @param node kubernetes node object we are looking for
+ * @return matcher
+ */
+ public static K8sNodeJsonMatcher matchesK8sNode(K8sNode node) {
+ return new K8sNodeJsonMatcher(node);
+ }
+}
diff --git a/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/impl/K8sNodeManagerTest.java b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/impl/K8sNodeManagerTest.java
new file mode 100644
index 0000000..066647b
--- /dev/null
+++ b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/impl/K8sNodeManagerTest.java
@@ -0,0 +1,334 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * 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 org.onosproject.k8snode.impl;
+
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.MoreExecutors;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onlab.packet.ChassisId;
+import org.onlab.packet.IpAddress;
+import org.onosproject.cluster.ClusterServiceAdapter;
+import org.onosproject.cluster.LeadershipServiceAdapter;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.event.Event;
+import org.onosproject.k8snode.api.DefaultK8sNode;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNodeEvent;
+import org.onosproject.k8snode.api.K8sNodeListener;
+import org.onosproject.k8snode.api.K8sNodeState;
+import org.onosproject.net.DefaultDevice;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.provider.ProviderId;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.onosproject.k8snode.api.K8sNode.Type.MINION;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_COMPLETE;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_CREATED;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_INCOMPLETE;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_REMOVED;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_UPDATED;
+import static org.onosproject.k8snode.api.K8sNodeState.COMPLETE;
+import static org.onosproject.k8snode.api.K8sNodeState.INCOMPLETE;
+import static org.onosproject.k8snode.api.K8sNodeState.INIT;
+import static org.onosproject.net.Device.Type.SWITCH;
+
+/**
+ * Unit tests for Kubernetes node manager.
+ */
+public class K8sNodeManagerTest {
+
+ private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+ private static final String ERR_SIZE = "Number of nodes did not match";
+ private static final String ERR_NOT_MATCH = "Node did not match";
+ private static final String ERR_NOT_FOUND = "Node did not exist";
+
+ private static final String MINION_1_HOSTNAME = "minion_1";
+ private static final String MINION_2_HOSTNAME = "minion_2";
+ private static final String MINION_3_HOSTNAME = "minion_3";
+
+ private static final Device MINION_1_INTG_DEVICE = createDevice(1);
+ private static final Device MINION_2_INTG_DEVICE = createDevice(2);
+ private static final Device MINION_3_INTG_DEVICE = createDevice(3);
+
+ private static final K8sNode MINION_1 = createNode(
+ MINION_1_HOSTNAME,
+ MINION,
+ MINION_1_INTG_DEVICE,
+ IpAddress.valueOf("10.100.0.1"),
+ INIT
+ );
+ private static final K8sNode MINION_2 = createNode(
+ MINION_2_HOSTNAME,
+ MINION,
+ MINION_2_INTG_DEVICE,
+ IpAddress.valueOf("10.100.0.2"),
+ INIT
+ );
+ private static final K8sNode MINION_3 = createNode(
+ MINION_3_HOSTNAME,
+ MINION,
+ MINION_3_INTG_DEVICE,
+ IpAddress.valueOf("10.100.0.3"),
+ COMPLETE
+ );
+
+ private final TestK8sNodeListener testListener = new TestK8sNodeListener();
+
+ private K8sNodeManager target;
+ private DistributedK8sNodeStore nodeStore;
+
+ /**
+ * Initial setup for this unit test.
+ */
+ @Before
+ public void setUp() {
+ nodeStore = new DistributedK8sNodeStore();
+ TestUtils.setField(nodeStore, "coreService", new TestCoreService());
+ TestUtils.setField(nodeStore, "storageService", new TestStorageService());
+ TestUtils.setField(nodeStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
+ nodeStore.activate();
+
+ nodeStore.createNode(MINION_2);
+ nodeStore.createNode(MINION_3);
+
+ target = new K8sNodeManager();
+ target.storageService = new TestStorageService();
+ target.coreService = new TestCoreService();
+ target.clusterService = new TestClusterService();
+ target.leadershipService = new TestLeadershipService();
+ target.nodeStore = nodeStore;
+ target.addListener(testListener);
+ target.activate();
+ testListener.events.clear();
+ }
+
+ /**
+ * Clean up unit test.
+ */
+ @After
+ public void tearDown() {
+ target.removeListener(testListener);
+ target.deactivate();
+ nodeStore.deactivate();
+ nodeStore = null;
+ target = null;
+ }
+
+ /**
+ * Checks if creating and removing a node work well with proper events.
+ */
+ @Test
+ public void testCreateAndRemoveNode() {
+ target.createNode(MINION_1);
+ assertEquals(ERR_SIZE, 3, target.nodes().size());
+ assertNotNull(target.node(MINION_1_HOSTNAME));
+
+ target.removeNode(MINION_1_HOSTNAME);
+ assertEquals(ERR_SIZE, 2, target.nodes().size());
+ assertNull(target.node(MINION_1_HOSTNAME));
+
+ validateEvents(K8S_NODE_CREATED, K8S_NODE_REMOVED);
+ }
+
+ /**
+ * Checks if creating null node fails with proper exception.
+ */
+ @Test(expected = NullPointerException.class)
+ public void testCreateNullNode() {
+ target.createNode(null);
+ }
+
+ /**
+ * Checks if creating a duplicated node fails with proper exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testCreateDuplicateNode() {
+ target.createNode(MINION_1);
+ target.createNode(MINION_1);
+ }
+
+ /**
+ * Checks if removing null node fails with proper exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testRemoveNullNode() {
+ target.removeNode(null);
+ }
+
+ /**
+ * Checks if updating a node works well with proper event.
+ */
+ @Test
+ public void testUpdateNode() {
+ K8sNode updated = DefaultK8sNode.from(MINION_2)
+ .dataIp(IpAddress.valueOf("10.200.0.100"))
+ .build();
+ target.updateNode(updated);
+ assertEquals(ERR_NOT_MATCH, updated, target.node(MINION_2_INTG_DEVICE.id()));
+ validateEvents(K8S_NODE_UPDATED);
+ }
+
+ /**
+ * Checks if updating a node state to complete generates proper events.
+ */
+ @Test
+ public void testUpdateNodeStateComplete() {
+ K8sNode updated = DefaultK8sNode.from(MINION_2)
+ .state(COMPLETE)
+ .build();
+ target.updateNode(updated);
+ assertEquals(ERR_NOT_MATCH, updated, target.node(MINION_2_HOSTNAME));
+ validateEvents(K8S_NODE_UPDATED, K8S_NODE_COMPLETE);
+ }
+
+ /**
+ * Checks if updating a node state to incomplete generates proper events.
+ */
+ @Test
+ public void testUpdateNodeStateIncomplete() {
+ K8sNode updated = DefaultK8sNode.from(MINION_3)
+ .state(INCOMPLETE)
+ .build();
+ target.updateNode(updated);
+ assertEquals(ERR_NOT_MATCH, updated, target.node(MINION_3_HOSTNAME));
+ validateEvents(K8S_NODE_UPDATED, K8S_NODE_INCOMPLETE);
+ }
+
+ /**
+ * Checks if updating a null node fails with proper exception.
+ */
+ @Test(expected = NullPointerException.class)
+ public void testUpdateNullNode() {
+ target.updateNode(null);
+ }
+
+ /**
+ * Checks if updating not existing node fails with proper exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testUpdateNotExistingNode() {
+ target.updateNode(MINION_1);
+ }
+
+ /**
+ * Checks if getting all nodes method returns correct set of nodes.
+ */
+ @Test
+ public void testGetAllNodes() {
+ assertEquals(ERR_SIZE, 2, target.nodes().size());
+ assertTrue(ERR_NOT_FOUND, target.nodes().contains(MINION_2));
+ assertTrue(ERR_NOT_FOUND, target.nodes().contains(MINION_3));
+ }
+
+ /**
+ * Checks if getting complete nodes method returns correct set of nodes.
+ */
+ @Test
+ public void testGetCompleteNodes() {
+ assertEquals(ERR_SIZE, 1, target.completeNodes().size());
+ assertTrue(ERR_NOT_FOUND, target.completeNodes().contains(MINION_3));
+ }
+
+ /**
+ * Checks if getting nodes by type method returns correct set of nodes.
+ */
+ @Test
+ public void testGetNodesByType() {
+ assertEquals(ERR_SIZE, 2, target.nodes(MINION).size());
+ assertTrue(ERR_NOT_FOUND, target.nodes(MINION).contains(MINION_2));
+ assertTrue(ERR_NOT_FOUND, target.nodes(MINION).contains(MINION_3));
+ }
+
+ /**
+ * Checks if getting a node by hostname returns correct node.
+ */
+ @Test
+ public void testGetNodeByHostname() {
+ assertEquals(ERR_NOT_FOUND, target.node(MINION_2_HOSTNAME), MINION_2);
+ assertEquals(ERR_NOT_FOUND, target.node(MINION_3_HOSTNAME), MINION_3);
+ }
+
+ private void validateEvents(Enum... types) {
+ int i = 0;
+ assertEquals("Number of events did not match", types.length, testListener.events.size());
+ for (Event event : testListener.events) {
+ assertEquals("Incorrect event received", types[i], event.type());
+ i++;
+ }
+ testListener.events.clear();
+ }
+
+ private static Device createDevice(long devIdNum) {
+ return new DefaultDevice(new ProviderId("of", "foo"),
+ DeviceId.deviceId(String.format("of:%016d", devIdNum)),
+ SWITCH,
+ "manufacturer",
+ "hwVersion",
+ "swVersion",
+ "serialNumber",
+ new ChassisId(1));
+ }
+
+ private static class TestK8sNodeListener implements K8sNodeListener {
+ private List<K8sNodeEvent> events = Lists.newArrayList();
+
+ @Override
+ public void event(K8sNodeEvent event) {
+ events.add(event);
+ }
+ }
+
+ private static class TestCoreService extends CoreServiceAdapter {
+ @Override
+ public ApplicationId registerApplication(String name) {
+ return TEST_APP_ID;
+ }
+ }
+
+ private class TestClusterService extends ClusterServiceAdapter {
+
+ }
+
+ private static class TestLeadershipService extends LeadershipServiceAdapter {
+
+ }
+
+ private static K8sNode createNode(String hostname, K8sNode.Type type,
+ Device intgBridge, IpAddress ipAddr,
+ K8sNodeState state) {
+ return DefaultK8sNode.builder()
+ .hostname(hostname)
+ .type(type)
+ .intgBridge(intgBridge.id())
+ .managementIp(ipAddr)
+ .dataIp(ipAddr)
+ .state(state)
+ .build();
+ }
+}
diff --git a/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/web/K8sNodeCodecRegisterTest.java b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/web/K8sNodeCodecRegisterTest.java
new file mode 100644
index 0000000..09958bd
--- /dev/null
+++ b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/web/K8sNodeCodecRegisterTest.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * 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 org.onosproject.k8snode.web;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onosproject.codec.CodecService;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.codec.K8sNodeCodec;
+
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+/**
+ * Unit tests for kubernetes node codec register.
+ */
+public final class K8sNodeCodecRegisterTest {
+
+ private K8sNodeCodecRegister register;
+
+ /**
+ * Tests codec register activation and deactivation.
+ */
+ @Test
+ public void testActivateDeactivate() {
+ register = new K8sNodeCodecRegister();
+ CodecService codecService = new TestCodecService();
+
+ TestUtils.setField(register, "codecService", codecService);
+ register.activate();
+
+ assertEquals(K8sNodeCodec.class.getName(),
+ codecService.getCodec(K8sNode.class).getClass().getName());
+
+ register.deactivate();
+
+ assertNull(codecService.getCodec(K8sNode.class));
+ }
+
+ private static class TestCodecService implements CodecService {
+
+ private Map<String, JsonCodec> codecMap = Maps.newConcurrentMap();
+
+ @Override
+ public Set<Class<?>> getCodecs() {
+ return ImmutableSet.of();
+ }
+
+ @Override
+ public <T> JsonCodec<T> getCodec(Class<T> entityClass) {
+ return codecMap.get(entityClass.getName());
+ }
+
+ @Override
+ public <T> void registerCodec(Class<T> entityClass, JsonCodec<T> codec) {
+ codecMap.put(entityClass.getName(), codec);
+ }
+
+ @Override
+ public void unregisterCodec(Class<?> entityClass) {
+ codecMap.remove(entityClass.getName());
+ }
+ }
+}
diff --git a/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/web/K8sNodeWebResourceTest.java b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/web/K8sNodeWebResourceTest.java
new file mode 100644
index 0000000..c52f398
--- /dev/null
+++ b/apps/k8s-node/app/src/test/java/org/onosproject/k8snode/web/K8sNodeWebResourceTest.java
@@ -0,0 +1,214 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * 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 org.onosproject.k8snode.web;
+
+import org.glassfish.jersey.server.ResourceConfig;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.osgi.TestServiceDirectory;
+import org.onlab.packet.IpAddress;
+import org.onosproject.codec.CodecService;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.k8snode.api.DefaultK8sNode;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNodeAdminService;
+import org.onosproject.k8snode.api.K8sNodeState;
+import org.onosproject.k8snode.codec.K8sNodeCodec;
+import org.onosproject.net.DeviceId;
+import org.onosproject.rest.resources.ResourceTest;
+
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.InputStream;
+
+import static org.easymock.EasyMock.anyObject;
+import static org.easymock.EasyMock.anyString;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Unit test for Kubernetes node REST API.
+ */
+public class K8sNodeWebResourceTest extends ResourceTest {
+
+ final K8sNodeAdminService mockK8sNodeAdminService = createMock(K8sNodeAdminService.class);
+ private static final String PATH = "configure";
+
+ private K8sNode k8sNode;
+
+ /**
+ * Constructs a kubernetes node resource test instance.
+ */
+ public K8sNodeWebResourceTest() {
+ super(ResourceConfig.forApplicationClass(K8sNodeWebApplication.class));
+ }
+
+ /**
+ * Sets up the global values for all the tests.
+ */
+ @Before
+ public void setUpTest() {
+ final CodecManager codecService = new CodecManager();
+ codecService.activate();
+ codecService.registerCodec(K8sNode.class, new K8sNodeCodec());
+ ServiceDirectory testDirectory =
+ new TestServiceDirectory()
+ .add(K8sNodeAdminService.class, mockK8sNodeAdminService)
+ .add(CodecService.class, codecService);
+ setServiceDirectory(testDirectory);
+
+ k8sNode = DefaultK8sNode.builder()
+ .hostname("minion-node")
+ .type(K8sNode.Type.MINION)
+ .dataIp(IpAddress.valueOf("10.134.34.222"))
+ .managementIp(IpAddress.valueOf("10.134.231.30"))
+ .intgBridge(DeviceId.deviceId("of:00000000000000a1"))
+ .state(K8sNodeState.INIT)
+ .build();
+ }
+
+ /**
+ * Tests the results of the REST API POST method with creating new nodes operation.
+ */
+ @Test
+ public void testCreateNodesWithCreateOperation() {
+ expect(mockK8sNodeAdminService.node(anyString())).andReturn(null).once();
+ mockK8sNodeAdminService.createNode(anyObject());
+ replay(mockK8sNodeAdminService);
+
+ final WebTarget wt = target();
+ InputStream jsonStream = K8sNodeWebResourceTest.class
+ .getResourceAsStream("k8s-node-minion-config.json");
+ Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.json(jsonStream));
+ final int status = response.getStatus();
+
+ assertThat(status, is(201));
+
+ verify(mockK8sNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API POST method without creating new nodes operation.
+ */
+ @Test
+ public void testCreateNodesWithoutCreateOperation() {
+ expect(mockK8sNodeAdminService.node(anyString())).andReturn(k8sNode).once();
+ replay(mockK8sNodeAdminService);
+
+ final WebTarget wt = target();
+ InputStream jsonStream = K8sNodeWebResourceTest.class
+ .getResourceAsStream("k8s-node-minion-config.json");
+ Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.json(jsonStream));
+ final int status = response.getStatus();
+
+ assertThat(status, is(201));
+
+ verify(mockK8sNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API PUT method with modifying the nodes.
+ */
+ @Test
+ public void testUpdateNodesWithoutModifyOperation() {
+ expect(mockK8sNodeAdminService.node(anyString())).andReturn(k8sNode).once();
+ mockK8sNodeAdminService.updateNode(anyObject());
+ replay(mockK8sNodeAdminService);
+
+ final WebTarget wt = target();
+ InputStream jsonStream = K8sNodeWebResourceTest.class
+ .getResourceAsStream("k8s-node-minion-config.json");
+ Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE)
+ .put(Entity.json(jsonStream));
+ final int status = response.getStatus();
+
+ assertThat(status, is(200));
+
+ verify(mockK8sNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API PUT method without modifying the nodes.
+ */
+ @Test
+ public void testUpdateNodesWithModifyOperation() {
+ expect(mockK8sNodeAdminService.node(anyString())).andReturn(null).once();
+ replay(mockK8sNodeAdminService);
+
+ final WebTarget wt = target();
+ InputStream jsonStream = K8sNodeWebResourceTest.class
+ .getResourceAsStream("k8s-node-minion-config.json");
+ Response response = wt.path(PATH).request(MediaType.APPLICATION_JSON_TYPE)
+ .put(Entity.json(jsonStream));
+ final int status = response.getStatus();
+
+ assertThat(status, is(304));
+
+ verify(mockK8sNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API DELETE method with deleting the nodes.
+ */
+ @Test
+ public void testDeleteNodesWithDeletionOperation() {
+ expect(mockK8sNodeAdminService.node(anyString())).andReturn(k8sNode).once();
+ expect(mockK8sNodeAdminService.removeNode(anyString())).andReturn(k8sNode).once();
+ replay(mockK8sNodeAdminService);
+
+ String location = PATH + "/minion-node";
+
+ final WebTarget wt = target();
+ Response response = wt.path(location).request(
+ MediaType.APPLICATION_JSON_TYPE).delete();
+
+ final int status = response.getStatus();
+
+ assertThat(status, is(204));
+
+ verify(mockK8sNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API DELETE method without deleting the nodes.
+ */
+ @Test
+ public void testDeleteNodesWithoutDeletionOperation() {
+ expect(mockK8sNodeAdminService.node(anyString())).andReturn(null).once();
+ replay(mockK8sNodeAdminService);
+
+ String location = PATH + "/minion-node";
+
+ final WebTarget wt = target();
+ Response response = wt.path(location).request(
+ MediaType.APPLICATION_JSON_TYPE).delete();
+
+ final int status = response.getStatus();
+
+ assertThat(status, is(304));
+
+ verify(mockK8sNodeAdminService);
+ }
+}