Implement security group manager, codec and watcher with unit tests

Change-Id: Ib2201d140b9dcb2eff453f13447113bdba66babd
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupCodecTest.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupCodecTest.java
new file mode 100644
index 0000000..51bdeb5
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupCodecTest.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright 2021-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.kubevirtnetworking.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.ImmutableSet;
+import org.hamcrest.MatcherAssert;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.core.CoreService;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtSecurityGroup;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtSecurityGroupRule;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroup;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupRule;
+
+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.kubevirtnetworking.codec.KubevirtSecurityGroupJsonMatcher.matchesKubevirtSecurityGroup;
+import static org.onosproject.net.NetTestTools.APP_ID;
+
+/**
+ * Unit tests for KubevirtSecurityGroup codec.
+ */
+public final class KubevirtSecurityGroupCodecTest {
+
+    MockCodecContext context;
+
+    JsonCodec<KubevirtSecurityGroup> kubevirtSecurityGroupCodec;
+    JsonCodec<KubevirtSecurityGroupRule> kubevirtSecurityGroupRuleCodec;
+
+    final CoreService mockCoreService = createMock(CoreService.class);
+    private static final String REST_APP_ID = "org.onosproject.rest";
+
+    @Before
+    public void setUp() {
+        context = new MockCodecContext();
+        kubevirtSecurityGroupCodec = new KubevirtSecurityGroupCodec();
+        kubevirtSecurityGroupRuleCodec = new KubevirtSecurityGroupRuleCodec();
+
+        assertThat(kubevirtSecurityGroupCodec, notNullValue());
+        assertThat(kubevirtSecurityGroupRuleCodec, notNullValue());
+        expect(mockCoreService.registerApplication(REST_APP_ID))
+                .andReturn(APP_ID).anyTimes();
+        replay(mockCoreService);
+        context.registerService(CoreService.class, mockCoreService);
+    }
+
+    /**
+     * Tests the kubevirt security group encoding.
+     */
+    @Test
+    public void testKubevirtSecurityGroupEncode() {
+        KubevirtSecurityGroupRule rule = DefaultKubevirtSecurityGroupRule.builder()
+                .id("sgr-1")
+                .securityGroupId("sg-1")
+                .direction("ingress")
+                .etherType("IPv4")
+                .portRangeMin(0)
+                .portRangeMax(80)
+                .protocol("tcp")
+                .remoteIpPrefix(IpPrefix.valueOf("0.0.0.0/0"))
+                .remoteGroupId("g-1")
+                .build();
+
+        KubevirtSecurityGroup sg = DefaultKubevirtSecurityGroup.builder()
+                .id("sg-1")
+                .name("sg")
+                .description("example-sg")
+                .rules(ImmutableSet.of(rule))
+                .build();
+
+        ObjectNode sgJson = kubevirtSecurityGroupCodec.encode(sg, context);
+        assertThat(sgJson, matchesKubevirtSecurityGroup(sg));
+    }
+
+    /**
+     * Tests the kubevirt security group decoding.
+     */
+    @Test
+    public void testKubevirtSecurityGroupDecode() throws IOException {
+        KubevirtSecurityGroup sg = getKubevirtSecurityGroup("KubevirtSecurityGroup.json");
+        KubevirtSecurityGroupRule rule = sg.rules().stream().findAny().orElse(null);
+
+        assertEquals("sg-1", sg.id());
+        assertEquals("sg", sg.name());
+        assertEquals("example-sg", sg.description());
+
+        assertEquals("sgr-1", rule.id());
+        assertEquals("sg-1", rule.securityGroupId());
+        assertEquals("ingress", rule.direction());
+        assertEquals("IPv4", rule.etherType());
+        assertEquals((Integer) 80, rule.portRangeMax());
+        assertEquals((Integer) 0, rule.portRangeMin());
+        assertEquals("tcp", rule.protocol());
+        assertEquals("0.0.0.0/0", rule.remoteIpPrefix().toString());
+        assertEquals("g-1", rule.remoteGroupId());
+    }
+
+    private KubevirtSecurityGroup getKubevirtSecurityGroup(String resourceName) throws IOException {
+        InputStream jsonStream = KubevirtSecurityGroupCodecTest.class.getResourceAsStream(resourceName);
+        JsonNode json = context.mapper().readTree(jsonStream);
+        MatcherAssert.assertThat(json, notNullValue());
+        KubevirtSecurityGroup sg = kubevirtSecurityGroupCodec.decode((ObjectNode) json, context);
+        assertThat(sg, notNullValue());
+        return sg;
+    }
+
+    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
+        public <T> JsonCodec<T> codec(Class<T> entityClass) {
+            if (entityClass == KubevirtSecurityGroupRule.class) {
+                return (JsonCodec<T>) kubevirtSecurityGroupRuleCodec;
+            }
+
+            return manager.getCodec(entityClass);
+        }
+
+        @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/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupJsonMatcher.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupJsonMatcher.java
new file mode 100644
index 0000000..ea04c60
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupJsonMatcher.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2021-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.kubevirtnetworking.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroup;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupRule;
+
+/**
+ * Hamcrest matcher for security group.
+ */
+public final class KubevirtSecurityGroupJsonMatcher extends TypeSafeDiagnosingMatcher<JsonNode> {
+
+    private static final String ID = "id";
+    private static final String NAME = "name";
+    private static final String DESCRIPTION = "description";
+    private static final String RULES = "rules";
+
+    private final KubevirtSecurityGroup sg;
+
+    private KubevirtSecurityGroupJsonMatcher(KubevirtSecurityGroup sg) {
+        this.sg = sg;
+    }
+
+    @Override
+    protected boolean matchesSafely(JsonNode jsonNode, Description description) {
+        // check sg ID
+        String jsonId = jsonNode.get(ID).asText();
+        String id = sg.id();
+        if (!jsonId.equals(id)) {
+            description.appendText("ID was " + jsonId);
+            return false;
+        }
+
+        // check sg name
+        String jsonName = jsonNode.get(NAME).asText();
+        String name = sg.name();
+        if (!jsonName.equals(name)) {
+            description.appendText("Name was " + jsonName);
+            return false;
+        }
+
+        // check description
+        JsonNode jsonDescription = jsonNode.get(DESCRIPTION);
+        if (jsonDescription != null) {
+            String myDescription = sg.description();
+            if (!jsonDescription.asText().equals(myDescription)) {
+                description.appendText("Description was " + jsonDescription);
+                return false;
+            }
+        }
+
+        JsonNode jsonSgr = jsonNode.get(RULES);
+        if (jsonSgr != null) {
+            // check size of rule array
+            if (jsonSgr.size() != sg.rules().size()) {
+                description.appendText("Rules was " + jsonSgr.size());
+                return false;
+            }
+
+            // check rules
+            for (KubevirtSecurityGroupRule sgr : sg.rules()) {
+                boolean ruleFound = false;
+                for (int ruleIndex = 0; ruleIndex < jsonSgr.size(); ruleIndex++) {
+                    KubevirtSecurityGroupRuleJsonMatcher ruleMatcher =
+                            KubevirtSecurityGroupRuleJsonMatcher
+                                    .matchesKubevirtSecurityGroupRule(sgr);
+                    if (ruleMatcher.matches(jsonSgr.get(ruleIndex))) {
+                        ruleFound = true;
+                        break;
+                    }
+                }
+
+                if (!ruleFound) {
+                    description.appendText("Rule not found " + sgr.toString());
+                    return false;
+                }
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public void describeTo(Description description) {
+        description.appendText(sg.toString());
+    }
+
+    /**
+     * Factory to allocate a kubevirt security group matcher.
+     *
+     * @param sg kubevirt security group object we are looking for
+     * @return matcher
+     */
+    public static KubevirtSecurityGroupJsonMatcher
+    matchesKubevirtSecurityGroup(KubevirtSecurityGroup sg) {
+        return new KubevirtSecurityGroupJsonMatcher(sg);
+    }
+}
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupRuleJsonMatcher.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupRuleJsonMatcher.java
new file mode 100644
index 0000000..81ba374
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/codec/KubevirtSecurityGroupRuleJsonMatcher.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2021-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.kubevirtnetworking.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import org.hamcrest.Description;
+import org.hamcrest.TypeSafeDiagnosingMatcher;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupRule;
+
+/**
+ * Hamcrest matcher for kubevirt port.
+ */
+public final class KubevirtSecurityGroupRuleJsonMatcher extends TypeSafeDiagnosingMatcher<JsonNode> {
+
+    private final KubevirtSecurityGroupRule rule;
+
+    private static final String ID = "id";
+    private static final String SECURITY_GROUP_ID = "securityGroupId";
+    private static final String DIRECTION = "direction";
+    private static final String ETHER_TYPE = "etherType";
+    private static final String PORT_RANGE_MAX = "portRangeMax";
+    private static final String PORT_RANGE_MIN = "portRangeMin";
+    private static final String PROTOCOL = "protocol";
+    private static final String REMOTE_IP_PREFIX = "remoteIpPrefix";
+    private static final String REMOTE_GROUP_ID = "remoteGroupId";
+
+    private KubevirtSecurityGroupRuleJsonMatcher(KubevirtSecurityGroupRule rule) {
+        this.rule = rule;
+    }
+
+    @Override
+    protected boolean matchesSafely(JsonNode jsonNode, Description description) {
+        // check rule ID
+        String jsonId = jsonNode.get(ID).asText();
+        String id = rule.id();
+        if (!jsonId.equals(id)) {
+            description.appendText("Rule ID was " + jsonId);
+            return false;
+        }
+
+        // check security group ID
+        String jsonSecurityGroupId = jsonNode.get(SECURITY_GROUP_ID).asText();
+        String securityGroupId = rule.securityGroupId();
+        if (!jsonSecurityGroupId.equals(securityGroupId)) {
+            description.appendText("Security group ID was " + jsonSecurityGroupId);
+            return false;
+        }
+
+        // check direction
+        String jsonDirection = jsonNode.get(DIRECTION).asText();
+        String direction = rule.direction();
+        if (!jsonDirection.equals(direction)) {
+            description.appendText("Direction was " + jsonDirection);
+            return false;
+        }
+
+        // check ether type
+        JsonNode jsonEtherType = jsonNode.get(ETHER_TYPE);
+        if (jsonEtherType != null) {
+            String etherType = rule.etherType();
+            if (!jsonEtherType.asText().equals(etherType)) {
+                description.appendText("EtherType was " + jsonEtherType);
+                return false;
+            }
+        }
+
+        // check port range max
+        JsonNode jsonPortRangeMax = jsonNode.get(PORT_RANGE_MAX);
+        if (jsonPortRangeMax != null) {
+            int portRangeMax = rule.portRangeMax();
+            if (portRangeMax != jsonPortRangeMax.asInt()) {
+                description.appendText("PortRangeMax was " + jsonPortRangeMax);
+                return false;
+            }
+        }
+
+        // check port range min
+        JsonNode jsonPortRangeMin = jsonNode.get(PORT_RANGE_MIN);
+        if (jsonPortRangeMin != null) {
+            int portRangeMin = rule.portRangeMin();
+            if (portRangeMin != jsonPortRangeMin.asInt()) {
+                description.appendText("PortRangeMin was " + jsonPortRangeMin);
+                return false;
+            }
+        }
+
+        // check protocol
+        JsonNode jsonProtocol = jsonNode.get(PROTOCOL);
+        if (jsonProtocol != null) {
+            String protocol = rule.protocol();
+            if (!jsonProtocol.asText().equals(protocol)) {
+                description.appendText("Protocol was " + jsonProtocol);
+                return false;
+            }
+        }
+
+        // check remote IP prefix
+        JsonNode jsonRemoteIpPrefix = jsonNode.get(REMOTE_IP_PREFIX);
+        if (jsonRemoteIpPrefix != null) {
+            IpPrefix remoteIpPrefix = rule.remoteIpPrefix();
+            if (!jsonRemoteIpPrefix.asText().equals(remoteIpPrefix.toString())) {
+                description.appendText("Remote IP prefix was " + jsonRemoteIpPrefix);
+                return false;
+            }
+        }
+
+        // check remote group ID
+        JsonNode jsonRemoteGroupId = jsonNode.get(REMOTE_GROUP_ID);
+        if (jsonRemoteGroupId != null) {
+            String remoteGroupId = rule.remoteGroupId();
+            if (!jsonRemoteGroupId.asText().equals(remoteGroupId)) {
+                description.appendText("Remote group ID was " + jsonRemoteGroupId);
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    @Override
+    public void describeTo(Description description) {
+        description.appendText(rule.toString());
+    }
+
+    /**
+     * Factory to allocate an kubevirt security group rule matcher.
+     *
+     * @param rule kubevirt security group rule object we are looking for
+     * @return matcher
+     */
+    public static KubevirtSecurityGroupRuleJsonMatcher
+        matchesKubevirtSecurityGroupRule(KubevirtSecurityGroupRule rule) {
+        return new KubevirtSecurityGroupRuleJsonMatcher(rule);
+    }
+}
diff --git a/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtSecurityGroupManagerTest.java b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtSecurityGroupManagerTest.java
new file mode 100644
index 0000000..b7d8d64
--- /dev/null
+++ b/apps/kubevirt-networking/app/src/test/java/org/onosproject/kubevirtnetworking/impl/KubevirtSecurityGroupManagerTest.java
@@ -0,0 +1,299 @@
+/*
+ * Copyright 2021-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.kubevirtnetworking.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.IpPrefix;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.event.Event;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtSecurityGroup;
+import org.onosproject.kubevirtnetworking.api.DefaultKubevirtSecurityGroupRule;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroup;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupEvent;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupListener;
+import org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupRule;
+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.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupEvent.Type.KUBEVIRT_SECURITY_GROUP_CREATED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupEvent.Type.KUBEVIRT_SECURITY_GROUP_REMOVED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupEvent.Type.KUBEVIRT_SECURITY_GROUP_RULE_CREATED;
+import static org.onosproject.kubevirtnetworking.api.KubevirtSecurityGroupEvent.Type.KUBEVIRT_SECURITY_GROUP_RULE_REMOVED;
+
+/**
+ * Unit tests for kubevirt security group manager.
+ */
+public class KubevirtSecurityGroupManagerTest {
+
+    private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+    private static final String SECURITY_GROUP_ID_1 = "sg-id-1";
+    private static final String SECURITY_GROUP_ID_2 = "sg-id-2";
+    private static final String UNKNOWN_ID = "sg-id-x";
+
+
+    private static final String SECURITY_GROUP_NAME_1 = "sg-name-1";
+    private static final String SECURITY_GROUP_NAME_2 = "sg-name-2";
+
+    private static final String SECURITY_GROUP_DESCRIPTION_1 = "description-1";
+    private static final String SECURITY_GROUP_DESCRIPTION_2 = "description-2";
+
+    private static final String SECURITY_GROUP_RULE_ID_1_1 = "sgr-id-1-1";
+    private static final String SECURITY_GROUP_RULE_ID_1_2 = "sgr-id-1-2";
+
+    private static final String SECURITY_GROUP_ETH_TYPE = "IP";
+    private static final String SECURITY_GROUP_DIRECTION = "EGRESS";
+    private static final String SECURITY_GROUP_PROTOCOL_1 = "TCP";
+    private static final String SECURITY_GROUP_PROTOCOL_2 = "UDP";
+
+    private static final int SECURITY_GROUP_PORT_RANGE_MIN_1 = 1;
+    private static final int SECURITY_GROUP_PORT_RANGE_MIN_2 = 101;
+    private static final int SECURITY_GROUP_PORT_RANGE_MAX_1 = 100;
+    private static final int SECURITY_GROUP_PORT_RANGE_MAX_2 = 200;
+
+    private static final IpPrefix SECURITY_GROUP_REMOTE_IP_PREFIX_1 = IpPrefix.valueOf("1.1.1.0/24");
+    private static final IpPrefix SECURITY_GROUP_REMOTE_IP_PREFIX_2 = IpPrefix.valueOf("2.2.2.0/24");
+
+    private KubevirtSecurityGroup sg1;
+    private KubevirtSecurityGroup sg2;
+
+    private KubevirtSecurityGroupRule sgRule11;
+    private KubevirtSecurityGroupRule sgRule12;
+
+    private KubevirtSecurityGroupManager target;
+    private DistributedKubevirtSecurityGroupStore store;
+
+    private final TestKubevirtSecurityGroupListener testListener =
+            new TestKubevirtSecurityGroupListener();
+
+    /**
+     * Initial setup for this unit test.
+     */
+    @Before
+    public void setUp() throws Exception {
+        store = new DistributedKubevirtSecurityGroupStore();
+        TestUtils.setField(store, "coreService", new TestCoreService());
+        TestUtils.setField(store, "storageService", new TestStorageService());
+        TestUtils.setField(store, "eventExecutor", MoreExecutors.newDirectExecutorService());
+        store.activate();
+
+        target = new KubevirtSecurityGroupManager();
+        TestUtils.setField(target, "coreService", new TestCoreService());
+        target.sgStore = store;
+        target.addListener(testListener);
+        target.activate();
+
+        sgRule11 = DefaultKubevirtSecurityGroupRule.builder()
+                .id(SECURITY_GROUP_RULE_ID_1_1)
+                .securityGroupId(SECURITY_GROUP_ID_1)
+                .remoteGroupId(SECURITY_GROUP_ID_1)
+                .direction(SECURITY_GROUP_DIRECTION)
+                .etherType(SECURITY_GROUP_ETH_TYPE)
+                .portRangeMax(SECURITY_GROUP_PORT_RANGE_MAX_1)
+                .portRangeMin(SECURITY_GROUP_PORT_RANGE_MIN_1)
+                .protocol(SECURITY_GROUP_PROTOCOL_1)
+                .remoteIpPrefix(SECURITY_GROUP_REMOTE_IP_PREFIX_1)
+                .build();
+
+        sgRule12 = DefaultKubevirtSecurityGroupRule.builder()
+                .id(SECURITY_GROUP_RULE_ID_1_2)
+                .securityGroupId(SECURITY_GROUP_ID_1)
+                .remoteGroupId(SECURITY_GROUP_ID_2)
+                .direction(SECURITY_GROUP_DIRECTION)
+                .etherType(SECURITY_GROUP_ETH_TYPE)
+                .portRangeMax(SECURITY_GROUP_PORT_RANGE_MAX_2)
+                .portRangeMin(SECURITY_GROUP_PORT_RANGE_MIN_2)
+                .protocol(SECURITY_GROUP_PROTOCOL_2)
+                .remoteIpPrefix(SECURITY_GROUP_REMOTE_IP_PREFIX_2)
+                .build();
+
+        sg1 = DefaultKubevirtSecurityGroup.builder()
+                .id(SECURITY_GROUP_ID_1)
+                .name(SECURITY_GROUP_NAME_1)
+                .description(SECURITY_GROUP_DESCRIPTION_1)
+                .build();
+
+        sg2 = DefaultKubevirtSecurityGroup.builder()
+                .id(SECURITY_GROUP_ID_2)
+                .name(SECURITY_GROUP_NAME_2)
+                .description(SECURITY_GROUP_DESCRIPTION_2)
+                .build();
+    }
+
+    /**
+     * Tears down all of this unit test.
+     */
+    @After
+    public void tearDown() {
+        target.removeListener(testListener);
+        store.deactivate();
+        target.deactivate();
+        store = null;
+        target = null;
+    }
+
+    /**
+     * Tests if getting all security groups returns the correct set of groups.
+     */
+    @Test
+    public void testGetSecurityGroups() {
+        createBasicSecurityGroups();
+        assertEquals("Number of security group did not match",
+                2, target.securityGroups().size());
+    }
+
+    /**
+     * Tests if getting a security group with group ID returns the correct group.
+     */
+    @Test
+    public void testGetSecurityGroupById() {
+        createBasicSecurityGroups();
+        assertNotNull("Security group did not match", target.securityGroup(SECURITY_GROUP_ID_1));
+        assertNotNull("Security group  did not match", target.securityGroup(SECURITY_GROUP_ID_2));
+        assertNull("Security group  did not match", target.securityGroup(UNKNOWN_ID));
+    }
+
+    /**
+     * Tests creating and removing a security group, and checks if it triggers proper events.
+     */
+    @Test
+    public void testCreateAndRemoveSecurityGroup() {
+        target.createSecurityGroup(sg1);
+        assertEquals("Number of security group did not match",
+                1, target.securityGroups().size());
+        assertNotNull("Security group did not match",
+                target.securityGroup(SECURITY_GROUP_ID_1));
+
+        target.removeSecurityGroup(SECURITY_GROUP_ID_1);
+        assertEquals("Number of security group did not match",
+                0, target.securityGroups().size());
+        assertNull("Security group did not match",
+                target.securityGroup(SECURITY_GROUP_ID_1));
+
+        validateEvents(KUBEVIRT_SECURITY_GROUP_CREATED, KUBEVIRT_SECURITY_GROUP_REMOVED);
+    }
+
+    /**
+     * Tests creating and removing a security group rule, and checks if it triggers proper events.
+     */
+    @Test
+    public void testCreateAndRemoveSecurityGroupRule() {
+        target.createSecurityGroup(sg1);
+        assertEquals("Number of security group rule did not match",
+                0, target.securityGroup(sg1.id()).rules().size());
+
+        target.createSecurityGroupRule(sgRule11);
+        assertEquals("Number of security group rule did not match",
+                1, target.securityGroup(sg1.id()).rules().size());
+
+        target.createSecurityGroupRule(sgRule12);
+        assertEquals("Number of security group rule did not match",
+                2, target.securityGroup(sg1.id()).rules().size());
+
+        target.removeSecurityGroupRule(sgRule11.id());
+        assertEquals("Number of security group rule did not match",
+                1, target.securityGroup(sg1.id()).rules().size());
+
+        target.removeSecurityGroupRule(sgRule12.id());
+        assertEquals("Number of security group rule did not match",
+                0, target.securityGroup(sg1.id()).rules().size());
+
+        validateEvents(KUBEVIRT_SECURITY_GROUP_CREATED,
+                KUBEVIRT_SECURITY_GROUP_RULE_CREATED,
+                KUBEVIRT_SECURITY_GROUP_RULE_CREATED,
+                KUBEVIRT_SECURITY_GROUP_RULE_REMOVED,
+                KUBEVIRT_SECURITY_GROUP_RULE_REMOVED);
+    }
+
+    /**
+     * Tests if creating a null security group fails with an exception.
+     */
+    @Test(expected = NullPointerException.class)
+    public void testCreateNullSecurityGroup() {
+        target.createSecurityGroup(null);
+    }
+
+    /**
+     * Tests if creating a duplicated security group fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testCreateDuplicateSecurityGroup() {
+        target.createSecurityGroup(sg1);
+        target.createSecurityGroup(sg1);
+    }
+
+    /**
+     * Tests if removing security group with null ID fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testRemoveSecurityGroupWithNull() {
+        target.removeSecurityGroup(null);
+    }
+
+    /**
+     * Tests if updating an unregistered security group fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testUpdateUnregisteredSecurityGroup() {
+        target.updateSecurityGroup(sg1);
+    }
+
+    private void createBasicSecurityGroups() {
+        target.createSecurityGroup(sg1);
+        target.createSecurityGroup(sg2);
+    }
+
+    private static class TestCoreService extends CoreServiceAdapter {
+
+        @Override
+        public ApplicationId registerApplication(String name) {
+            return TEST_APP_ID;
+        }
+    }
+
+    private static class TestKubevirtSecurityGroupListener
+            implements KubevirtSecurityGroupListener {
+
+        private List<KubevirtSecurityGroupEvent> events = Lists.newArrayList();
+
+        @Override
+        public void event(KubevirtSecurityGroupEvent event) {
+            events.add(event);
+        }
+    }
+
+    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();
+    }
+}