Unit tests for ofoverlay 48/39748/2
authorKonstantin Blagov <kblagov@cisco.com>
Thu, 2 Jun 2016 07:48:01 +0000 (09:48 +0200)
committerKonstantin Blagov <kblagov@cisco.com>
Thu, 2 Jun 2016 11:29:00 +0000 (13:29 +0200)
Change-Id: I1b3773ac70a0ce2d00ed4bf0e97d3eb0462eaa0b
Signed-off-by: Konstantin Blagov <kblagov@cisco.com>
25 files changed:
renderers/ofoverlay/pom.xml
renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManager.java
renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTask.java
renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListener.java
renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnection.java
renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/util/SFlowQueryParams.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpTaskerTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpUtilsTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerListenerTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayAugTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayContextListenerTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3ContextListenerTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3NatAugTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/BucketsEquivalenceTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/GroupEquivalenceTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientResponseTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManagerTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ProcessDataTaskTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTaskTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListenerTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnectionTest.java [new file with mode: 0644]
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SflowClientSettingsListenerTest.java
renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/test/TransactionMockUtils.java [new file with mode: 0644]

index 5729d4b2baa610a8910604ee5e7aa4ba401ed7ef..8cf90c06cb3c8afe7b83293a0ac7c851039548fd 100755 (executable)
       <version>1.5.2</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>com.sun.jersey.jersey-test-framework</groupId>
+      <artifactId>jersey-test-framework-grizzly2</artifactId>
+      <scope>test</scope>
+    </dependency>
 
   </dependencies>
 
index a17c3159f9aa5daab7dbafdbfd3eda77f4c58e68..e28d119b8e8db5e36af84853a9758dc8bda61e13 100755 (executable)
@@ -49,6 +49,8 @@ public class OFStatisticsManager implements AutoCloseable {
     // key is String (not a full IpAddress) because
     // we will get String from REST query to sFlow
     private static ConcurrentMap<String, EndpointL3> endpointL3ByIpMap = new ConcurrentHashMap<>();
+    private static final int CONNECT_TIMEOUT_MILLISEC = 20000;
+    private static final int READ_TIMEOUT_MILLISEC = 30000;
 
     private static final Logger LOG = LoggerFactory.getLogger(OFStatisticsManager.class);
 
@@ -94,7 +96,8 @@ public class OFStatisticsManager implements AutoCloseable {
         epgsByContractId.put(contractId, Pair.of(consEpgKey, provEpgKey));
         boolean isFlowCacheNew = flowCacheNames.add(flowCacheName);
         if (isFlowCacheNew) {
-            SFlowRTConnection sFlowRTConnection = new SFlowRTConnection(executor, sflowCollectorUri, flowCache);
+            SFlowRTConnection sFlowRTConnection = new SFlowRTConnection(executor, sflowCollectorUri, flowCache, new JsonRestClient(sflowCollectorUri, CONNECT_TIMEOUT_MILLISEC,
+                    READ_TIMEOUT_MILLISEC));
             ScheduledFuture<?> collectStatsTask = this.executor.scheduleWithFixedDelay(new ReadGbpFlowCacheTask(flowCacheName, sFlowRTConnection,
                     statisticsManager, MAX_FLOWS, MIN_VALUE_IN_FLOW, AGG_MODE), 0, delay, TimeUnit.SECONDS);
             collectStatsTasks.add(collectStatsTask);
index bd476cf561ce25301494ad3d8ba20701ea818b87..85db48d242bec9484b9f28fc7d6c846aa620d38b 100755 (executable)
@@ -18,6 +18,7 @@ import javax.ws.rs.core.MultivaluedMap;
 
 import org.opendaylight.groupbasedpolicy.api.StatisticsManager;
 import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache.FlowCacheData;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util.SFlowQueryParams;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -31,9 +32,6 @@ public class ReadGbpFlowCacheTask implements Runnable {
 
     private static final Type LIST_OF_FLOW_CACHE_DATA = new TypeToken<List<FlowCacheData>>() {}.getType();
     private static final Gson GSON = new Gson();
-    private static final String MAX_FLOWS_PARAM = "maxFlows";
-    private static final String MIN_VALUE_PARAM = "minValue";
-    private static final String AGG_MODE_PARAM = "aggMode";
 
     private final SFlowRTConnection sFlowRTConnection;
     private final StatisticsManager statisticsManager;
@@ -55,9 +53,9 @@ public class ReadGbpFlowCacheTask implements Runnable {
     @Override
     public void run() {
         MultivaluedMap<String, String> params = new MultivaluedMapImpl();
-        params.add(MAX_FLOWS_PARAM, maxFlows);
-        params.add(MIN_VALUE_PARAM, minValue);
-        params.add(AGG_MODE_PARAM, aggMode);
+        params.add(SFlowQueryParams.MAX_FLOWS, maxFlows);
+        params.add(SFlowQueryParams.MIN_VALUE, minValue);
+        params.add(SFlowQueryParams.AGG_MODE, aggMode);
         JsonRestClientResponse result = sFlowRTConnection.get(path, params);
 
         if (result != null && result.getJsonResponse() != null) {
index 51ccc0f9122bf6b17f0edacd87bf9801c4baebe3..af9bec18044552c2edba32e7ab7e2dc0f9535d4f 100755 (executable)
@@ -51,9 +51,11 @@ public class ResolvedPolicyClassifierListener extends DataTreeChangeHandler<Reso
         ResolvedPolicy resolvedPolicy = rootNode.getDataAfter();
         Map<InstanceIdentifier<Classifier>, Classifier> classifierByIid =
                 resolveClassifiers(resolvedPolicy, rootIdentifier);
-        for (Entry<InstanceIdentifier<Classifier>, Classifier> classfierEntry : classifierByIid.entrySet()) {
-            LOG.trace("New classifier created: {}\n{}", classfierEntry.getKey(), classfierEntry.getValue());
-            ofStatsManager.pullStatsForClassifier(classfierEntry.getKey(), classfierEntry.getValue());
+        for (Entry<InstanceIdentifier<Classifier>, Classifier> classifierEntry : classifierByIid.entrySet()) {
+            LOG.trace("New classifier created: {}\n{}", classifierEntry.getKey(),
+                    classifierEntry.getValue());
+            ofStatsManager.pullStatsForClassifier(classifierEntry.getKey(),
+                    classifierEntry.getValue());
         }
     }
 
index 9a390fec785292fa77410b6f838107fefb51cd45..7189982c856d72c31d0057ef9a8707f5c5878583 100755 (executable)
@@ -21,25 +21,23 @@ public class SFlowRTConnection {
 
     private static final Logger LOG = LoggerFactory.getLogger(SFlowRTConnection.class);
 
-    private static final int CONNECT_TIMEOUT_MILLISEC = 20000;
-    private static final int READ_TIMEOUT_MILLISEC = 30000;
     private static final String GET = "GET";
     private static final String PUT = "PUT";
     private static final String DELETE = "DELETE";
 
+    static final String EX_MSG_NOT_INITIALIZED = "SFlowRTConnection is not initialized.";
+
     private final FlowCache flowCache;
     private JsonRestClient client;
     private boolean isInitialized = false;
     private final ScheduledExecutorService executor;
     private final String collectorUri;
 
-    public SFlowRTConnection(ScheduledExecutorService executor, String collectorUri, FlowCache flowCache) {
+    public SFlowRTConnection(ScheduledExecutorService executor, String collectorUri, FlowCache flowCache, JsonRestClient client) {
         this.executor = Preconditions.checkNotNull(executor);
         this.collectorUri = Preconditions.checkNotNull(collectorUri);
         this.flowCache = Preconditions.checkNotNull(flowCache);
-
-        this.client = new JsonRestClient(collectorUri, CONNECT_TIMEOUT_MILLISEC,
-                READ_TIMEOUT_MILLISEC);
+        this.client = client;
         initialize();
     }
 
@@ -60,7 +58,7 @@ public class SFlowRTConnection {
     public JsonRestClientResponse get(String path,
             MultivaluedMap<String, String> params) {
         if (!isInitialized()) {
-            throw new IllegalStateException("SFlowRTConnection is not initialized.");
+            throw new IllegalStateException(EX_MSG_NOT_INITIALIZED);
         }
         try {
             JsonRestClientResponse responce = client.get(path, params);
@@ -75,7 +73,7 @@ public class SFlowRTConnection {
     @Nullable
     public JsonRestClientResponse put(String path, String someJson) {
         if (!isInitialized()) {
-            throw new IllegalStateException("SFlowRTConnection is not initialized.");
+            throw new IllegalStateException(EX_MSG_NOT_INITIALIZED);
         }
         return putWithoutInitCheck(path, someJson);
     }
@@ -95,7 +93,7 @@ public class SFlowRTConnection {
 
     public JsonRestClientResponse delete(String path) {
         if (!isInitialized()) {
-            throw new IllegalStateException("SFlowRTConnection is not initialized.");
+            throw new IllegalStateException(EX_MSG_NOT_INITIALIZED);
         }
         try {
             JsonRestClientResponse responce = client.delete(path);
diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/util/SFlowQueryParams.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/util/SFlowQueryParams.java
new file mode 100644 (file)
index 0000000..8e1b9cf
--- /dev/null
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util;
+
+public class SFlowQueryParams {
+
+    public static final String MAX_FLOWS = "maxFlows";
+    public static final String MIN_VALUE = "minValue";
+    public static final String AGG_MODE = "aggMode";
+
+}
index 6d6b1eb7eeda39e25331493b8a937be3864c5fda..15453a0750bb5d2b02710fd95566eb4fafd9babc 100644 (file)
@@ -8,11 +8,21 @@
 
 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.arp;
 
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeNoException;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import java.net.InetAddress;
 import java.util.Collections;
 import java.util.concurrent.Future;
 
-import org.junit.Assert;
+import com.google.common.util.concurrent.UncheckedExecutionException;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.ArgumentCaptor;
@@ -102,11 +112,11 @@ public class ArpTaskerTest extends OfOverlayDataBrokerTest {
     @Before
     public void init() {
 
-        PacketProcessingService packetService = Mockito.mock(PacketProcessingService.class);
-        flowService = Mockito.mock(SalFlowService.class);
-        rpcRegistry = Mockito.mock(RpcProviderRegistry.class);
-        Mockito.when(rpcRegistry.getRpcService(PacketProcessingService.class)).thenReturn(packetService);
-        Mockito.when(rpcRegistry.getRpcService(SalFlowService.class)).thenReturn(flowService);
+        PacketProcessingService packetService = mock(PacketProcessingService.class);
+        flowService = mock(SalFlowService.class);
+        rpcRegistry = mock(RpcProviderRegistry.class);
+        when(rpcRegistry.getRpcService(PacketProcessingService.class)).thenReturn(packetService);
+        when(rpcRegistry.getRpcService(SalFlowService.class)).thenReturn(flowService);
     }
 
     @SuppressWarnings("unchecked")
@@ -147,24 +157,25 @@ public class ArpTaskerTest extends OfOverlayDataBrokerTest {
                     .build()));
 
         // test without key
-        ReadOnlyTransaction rtx = Mockito.mock(ReadOnlyTransaction.class);
-        broker = Mockito.mock(DataBroker.class);
+        ReadOnlyTransaction rtx = mock(ReadOnlyTransaction.class);
+        broker = mock(DataBroker.class);
         arpTasker = new ArpTasker(rpcRegistry, broker);
 
-        epL3.setKey(new EndpointL3Key(Mockito.mock(IpAddress.class), null));
+        epL3.setKey(new EndpointL3Key(mock(IpAddress.class), null));
         arpTasker.addMacForL3EpAndCreateEp(epL3.build());
-        Mockito.verify(broker, Mockito.never()).newReadOnlyTransaction();
+        verify(broker, never()).newReadOnlyTransaction();
 
         // test without node with external interface
         epL3.setKey(key);
-        Mockito.when(broker.newReadOnlyTransaction()).thenReturn(rtx);
+        when(broker.newReadOnlyTransaction()).thenReturn(rtx);
         CheckedFuture<Optional<DataObject>, ReadFailedException> future =
                 Futures.immediateCheckedFuture(Optional.<DataObject>absent());
-        Mockito.when(rtx.read(Matchers.eq(LogicalDatastoreType.CONFIGURATION), Matchers.any(InstanceIdentifier.class)))
+        when(rtx.read(Matchers.eq(LogicalDatastoreType.CONFIGURATION),
+                any(InstanceIdentifier.class)))
             .thenReturn(future);
         arpTasker.addMacForL3EpAndCreateEp(epL3.build());
-        Mockito.verify(broker).newReadOnlyTransaction();
-        Mockito.verify(rtx).close();
+        verify(broker).newReadOnlyTransaction();
+        verify(rtx).close();
 
         // test correct
         broker = getDataBroker();
@@ -177,27 +188,37 @@ public class ArpTaskerTest extends OfOverlayDataBrokerTest {
                 .child(NodeConnector.class, new NodeConnectorKey(connectorId))
                 .build(),
                 connector.build(), true);
-        wtx.put(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.builder(Tenants.class).build(), tenants.build(),
-                true);
+        // ignoring a Windows-specific bug
+        try {
+            wtx.put(LogicalDatastoreType.CONFIGURATION,
+                    InstanceIdentifier.builder(Tenants.class).build(), tenants.build(), true);
+        } catch (UncheckedExecutionException e) {
+            assumeNoException(e);
+        }
         wtx.submit().get();
 
-        Future<RpcResult<AddFlowOutput>> flowFuture = Mockito.mock(Future.class);
-        Mockito.when(flowService.addFlow(Mockito.any(AddFlowInput.class))).thenReturn(flowFuture);
+        Future<RpcResult<AddFlowOutput>> flowFuture = mock(Future.class);
+        when(flowService.addFlow(any(AddFlowInput.class))).thenReturn(flowFuture);
 
         epL3.setNetworkContainment(domainId).setTenant(tenantId);
         arpTasker.addMacForL3EpAndCreateEp(epL3.build());
         ArgumentCaptor<AddFlowInput> argument = ArgumentCaptor.forClass(AddFlowInput.class);
-        Mockito.verify(flowService).addFlow(argument.capture());
+        verify(flowService).addFlow(argument.capture());
         AddFlowInput result = argument.getValue();
-        Assert.assertEquals(EtherTypes.ARP.intValue(),
-                result.getMatch().getEthernetMatch().getEthernetType().getType().getValue().intValue());
+        assertEquals(EtherTypes.ARP.intValue(), result.getMatch()
+                .getEthernetMatch()
+                .getEthernetType()
+                .getType()
+                .getValue()
+                .intValue());
         ArpMatch match = (ArpMatch)result.getMatch().getLayer3Match();
-        Assert.assertEquals(ArpOperation.REPLY.intValue(),match.getArpOp().intValue());
-        Assert.assertEquals("192.168.0.254/32",match.getArpTargetTransportAddress().getValue());
-        Assert.assertEquals("192.168.0.1/32", match.getArpSourceTransportAddress().getValue());
-        Assert.assertEquals(connectorId, result.getMatch().getInPort());
-        Assert.assertEquals(new NodeRef(InstanceIdentifier.builder(Nodes.class)
-                .child(Node.class, node.getKey()).build()), result.getNode());
+        assertEquals(ArpOperation.REPLY.intValue(), match.getArpOp().intValue());
+        assertEquals("192.168.0.254/32", match.getArpTargetTransportAddress().getValue());
+        assertEquals("192.168.0.1/32", match.getArpSourceTransportAddress().getValue());
+        assertEquals(connectorId, result.getMatch().getInPort());
+        assertEquals(new NodeRef(
+                InstanceIdentifier.builder(Nodes.class).child(Node.class, node.getKey()).build()),
+                result.getNode());
 
         // onPacketReceived
         Arp arp = new Arp();
@@ -255,13 +276,14 @@ public class ArpTaskerTest extends OfOverlayDataBrokerTest {
         arpTasker.onPacketReceived(packet);
         rtx = broker.newReadOnlyTransaction();
         Optional<EndpointL3> optional = rtx.read(LogicalDatastoreType.OPERATIONAL, epL3Iid).get();
-        Assert.assertTrue(optional.isPresent());
+        assertTrue(optional.isPresent());
         EndpointL3 epl3 = optional.get();
-        Assert.assertArrayEquals(sha, HexEncode.bytesFromHexString(epl3.getMacAddress().getValue()));
-        Assert.assertEquals(l2domain.getId(), epl3.getL2Context());
+        assertArrayEquals(sha, HexEncode.bytesFromHexString(epl3.getMacAddress().getValue()));
+        assertEquals(l2domain.getId(), epl3.getL2Context());
         Optional<Endpoint> optionalEp = rtx.read(LogicalDatastoreType.OPERATIONAL,
                 IidFactory.endpointIid(l2domainId, new MacAddress("00:00:00:00:00:01"))).get();
-        Assert.assertTrue(optionalEp.isPresent());
-        Assert.assertEquals(new OfOverlayContextBuilder(augment).build(), optionalEp.get().getAugmentation(OfOverlayContext.class));
+        assertTrue(optionalEp.isPresent());
+        assertEquals(new OfOverlayContextBuilder(augment).build(),
+                optionalEp.get().getAugmentation(OfOverlayContext.class));
     }
 }
index 7e46d96217ada5ac18525bfa54187f554e774948..3586f03bbfd68554930e44254ed2b9f786561c28 100644 (file)
@@ -8,6 +8,9 @@
 
 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.arp;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
 import java.net.InetAddress;
 
 import org.junit.Assert;
@@ -67,4 +70,11 @@ public class ArpUtilsTest {
         Assert.assertTrue(
                 result.contains("getTargetProtocolAddress()=" + InetAddress.getByAddress(tpa).getHostAddress()));
     }
+
+    @Test
+    public void testBytesToMac(){
+        byte[] macBytes = {0,1,0,1,0,1};
+        assertEquals(new MacAddress("00:01:00:01:00:01"), ArpUtils.bytesToMac(macBytes));
+        assertNull(ArpUtils.bytesToMac(null));
+    }
 }
index 0f92fac41fc2e1cbaed00225f9bb06f4c7b4b84c..c7dc70c39fff521ed0352f26ff47c53ba993f5b0 100755 (executable)
@@ -31,8 +31,7 @@ public class EndpointManagerListenerTest {
         endpointManager = mock(EndpointManager.class);
         DataBroker dataProvider = mock(DataBroker.class);
 
-        EndpointManagerListener endpointManagerListener =
-                new EndpointManagerListener(dataProvider, endpointManager);
+        EndpointManagerListener endpointManagerListener = new EndpointManagerListener(dataProvider, endpointManager);
         tester = new DataChangeListenerTester(endpointManagerListener);
         tester.setRemovedPath(endpointId);
     }
@@ -45,8 +44,7 @@ public class EndpointManagerListenerTest {
         tester.callOnDataChanged();
 
         verify(endpointManager, times(3)).processEndpoint(any(Endpoint.class), any(Endpoint.class));
-        verify(endpointManager, never()).processL3Endpoint(any(EndpointL3.class),
-                any(EndpointL3.class));
+        verify(endpointManager, never()).processL3Endpoint(any(EndpointL3.class), any(EndpointL3.class));
     }
 
     @Test
@@ -57,8 +55,7 @@ public class EndpointManagerListenerTest {
         tester.callOnDataChanged();
 
         verify(endpointManager, never()).processEndpoint(any(Endpoint.class), any(Endpoint.class));
-        verify(endpointManager, times(3)).processL3Endpoint(any(EndpointL3.class),
-                any(EndpointL3.class));
+        verify(endpointManager, times(3)).processL3Endpoint(any(EndpointL3.class), any(EndpointL3.class));
     }
 
     @Test
@@ -69,8 +66,7 @@ public class EndpointManagerListenerTest {
         tester.callOnDataChanged();
 
         verify(endpointManager, never()).processEndpoint(any(Endpoint.class), any(Endpoint.class));
-        verify(endpointManager, never()).processL3Endpoint(any(EndpointL3.class),
-                any(EndpointL3.class));
+        verify(endpointManager, never()).processL3Endpoint(any(EndpointL3.class), any(EndpointL3.class));
     }
 
 }
index 2b59de46991216dc2bef107c0c4a0252d0836fd0..aa54188d21262eb3b68be8562fd8abc78f73eb84 100644 (file)
@@ -8,6 +8,11 @@
 
 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
@@ -16,17 +21,16 @@ import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import java.lang.reflect.Method;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.UUID;
 import java.util.concurrent.ScheduledExecutorService;
 
-import org.junit.Assert;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
@@ -35,7 +39,6 @@ import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
@@ -67,18 +70,12 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.r
 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddress;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContext;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayL3Context;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.Tenant;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.ForwardingContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
 public class EndpointManagerTest {
 
     private EndpointManager manager;
@@ -102,6 +99,8 @@ public class EndpointManagerTest {
     private EndpointL3 newL3Ep;
     private Optional<Endpoints> optionalRead;
 
+    // TODO get rid of unnecessary mocks (endpoint1, endpoint2, their parameters)
+
     @SuppressWarnings("unchecked")
     @Before
     public void initialisation() throws Exception {
@@ -114,7 +113,8 @@ public class EndpointManagerTest {
         when(dataProvider.newWriteOnlyTransaction()).thenReturn(writeTransaction);
         CheckedFuture<Void, TransactionCommitFailedException> checkedFutureWrite = mock(CheckedFuture.class);
         when(writeTransaction.submit()).thenReturn(checkedFutureWrite);
-        BindingAwareBroker.RpcRegistration<EndpointService> rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class);
+        BindingAwareBroker.RpcRegistration<EndpointService> rpcRegistration =
+                mock(BindingAwareBroker.RpcRegistration.class);
         listenerReg = mock(ListenerRegistration.class);
         when(dataProvider.registerDataChangeListener(any(LogicalDatastoreType.class), any(InstanceIdentifier.class),
                 any(DataChangeListener.class), any(DataChangeScope.class))).thenReturn(listenerReg);
@@ -167,8 +167,8 @@ public class EndpointManagerTest {
         ReadOnlyTransaction readTransaction = mock(ReadOnlyTransaction.class);
         when(dataProvider.newReadOnlyTransaction()).thenReturn(readTransaction);
         CheckedFuture<Optional<Endpoints>, ReadFailedException> checkedFutureRead = mock(CheckedFuture.class);
-        when(readTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(
-                checkedFutureRead);
+        when(readTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class)))
+            .thenReturn(checkedFutureRead);
         optionalRead = mock(Optional.class);
         when(checkedFutureRead.checkedGet()).thenReturn(optionalRead);
         when(optionalRead.isPresent()).thenReturn(false);
@@ -181,39 +181,39 @@ public class EndpointManagerTest {
 
     @Test
     public void getGroupsForNodeTest() {
-        Assert.assertTrue(manager.getGroupsForNode(nodeId1).isEmpty());
+        assertTrue(manager.getGroupsForNode(nodeId1).isEmpty());
         manager.processEndpoint(null, endpoint1);
-        Assert.assertFalse(manager.getGroupsForNode(nodeId1).isEmpty());
+        assertFalse(manager.getGroupsForNode(nodeId1).isEmpty());
     }
 
     @Test
     public void getNodesForGroupTest() {
         EgKey egKey = mock(EgKey.class);
         Set<NodeId> nodesForGroup = manager.getNodesForGroup(egKey);
-        Assert.assertNotNull(nodesForGroup);
-        Assert.assertTrue(nodesForGroup.isEmpty());
+        assertNotNull(nodesForGroup);
+        assertTrue(nodesForGroup.isEmpty());
     }
 
     @Test
     public void getEndpointsForNodeTestNodeIdEgKey() {
         EgKey egKey = new EgKey(tenantId, endpointGroupId);
-        Assert.assertTrue(manager.getEndpointsForNode(nodeId1, egKey).isEmpty());
+        assertTrue(manager.getEndpointsForNode(nodeId1, egKey).isEmpty());
         manager.processEndpoint(null, endpoint1);
-        Assert.assertFalse(manager.getEndpointsForNode(nodeId1, egKey).isEmpty());
+        assertFalse(manager.getEndpointsForNode(nodeId1, egKey).isEmpty());
     }
 
     @Test
     public void getEndpointsForNodeTestNodeId() {
-        Assert.assertTrue(manager.getEndpointsForNode(nodeId1).isEmpty());
+        assertTrue(manager.getEndpointsForNode(nodeId1).isEmpty());
         manager.processEndpoint(null, endpoint1);
-        Assert.assertFalse(manager.getEndpointsForNode(nodeId1).isEmpty());
+        assertFalse(manager.getEndpointsForNode(nodeId1).isEmpty());
     }
 
     @Test
     public void getEndpoint() {
         EpKey epKey = new EpKey(endpoint1.getL2Context(), endpoint1.getMacAddress());
         manager.processEndpoint(null, endpoint1);
-        Assert.assertEquals(endpoint1, manager.getEndpoint(epKey));
+        assertEquals(endpoint1, manager.getEndpoint(epKey));
     }
 
     @SuppressWarnings("unchecked")
@@ -222,8 +222,8 @@ public class EndpointManagerTest {
         ReadOnlyTransaction readTransaction = mock(ReadOnlyTransaction.class);
         when(dataProvider.newReadOnlyTransaction()).thenReturn(readTransaction);
         CheckedFuture<Optional<Endpoints>, ReadFailedException> resultFuture = mock(CheckedFuture.class);
-        when(readTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(
-                resultFuture);
+        when(readTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class)))
+            .thenReturn(resultFuture);
         Optional<Endpoints> optional = mock(Optional.class);
         when(resultFuture.checkedGet()).thenReturn(optional);
         when(optional.isPresent()).thenReturn(true);
@@ -234,7 +234,7 @@ public class EndpointManagerTest {
         when(endpointL3Prefix.getTenant()).thenReturn(tenantId);
 
         Collection<EndpointL3Prefix> result = manager.getEndpointsL3PrefixForTenant(tenantId);
-        Assert.assertTrue(result.contains(endpointL3Prefix));
+        assertTrue(result.contains(endpointL3Prefix));
     }
 
     @SuppressWarnings("unchecked")
@@ -243,24 +243,25 @@ public class EndpointManagerTest {
         ReadOnlyTransaction transaction = mock(ReadOnlyTransaction.class);
         when(dataProvider.newReadOnlyTransaction()).thenReturn(transaction);
         CheckedFuture<Optional<Endpoints>, ReadFailedException> checkedFuture = mock(CheckedFuture.class);
-        when(transaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(checkedFuture);
+        when(transaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class)))
+            .thenReturn(checkedFuture);
         Optional<Endpoints> optional = mock(Optional.class);
         when(checkedFuture.checkedGet()).thenReturn(optional);
         when(optional.isPresent()).thenReturn(false);
-        Assert.assertNull(manager.getEndpointsFromDataStore());
+        assertNull(manager.getEndpointsFromDataStore());
 
         when(optional.isPresent()).thenReturn(true);
         Endpoints endpoints = mock(Endpoints.class);
         when(optional.get()).thenReturn(endpoints);
-        Assert.assertEquals(endpoints, manager.getEndpointsFromDataStore());
+        assertEquals(endpoints, manager.getEndpointsFromDataStore());
 
         manager = new EndpointManager(null, rpcRegistry, notificationService, executor, switchManager);
-        Assert.assertNull(manager.getEndpointsFromDataStore());
+        assertNull(manager.getEndpointsFromDataStore());
     }
 
     @Test
     public void getL3EndpointsTestEndpointsNull() throws Exception {
-        Assert.assertNull(manager.getL3Endpoints());
+        assertNull(manager.getL3Endpoints());
     }
 
     @Test
@@ -270,7 +271,7 @@ public class EndpointManagerTest {
         when(optionalRead.get()).thenReturn(endpoints);
         when(endpoints.getEndpointL3()).thenReturn(null);
 
-        Assert.assertNull(manager.getL3Endpoints());
+        assertNull(manager.getL3Endpoints());
     }
 
     @Test
@@ -281,7 +282,7 @@ public class EndpointManagerTest {
         List<EndpointL3> endpointL3List = Collections.singletonList(mock(EndpointL3.class));
         when(endpoints.getEndpointL3()).thenReturn(endpointL3List);
 
-        Assert.assertEquals(endpointL3List, manager.getL3Endpoints());
+        assertEquals(endpointL3List, manager.getL3Endpoints());
     }
 
     @Test
@@ -301,13 +302,13 @@ public class EndpointManagerTest {
         when(endpointL3.getMacAddress()).thenReturn(mock(MacAddress.class));
 
         Map<EndpointKey, EndpointL3> result = manager.getL3EpWithNatByL2Key();
-        Assert.assertTrue(result.containsValue(endpointL3));
+        assertTrue(result.containsValue(endpointL3));
     }
 
     @Test
     public void getL3EpWithNatByL2KeyTestL3EpsNull() {
         Map<EndpointKey, EndpointL3> result = manager.getL3EpWithNatByL2Key();
-        Assert.assertTrue(result.isEmpty());
+        assertTrue(result.isEmpty());
     }
 
     @Test
@@ -326,7 +327,7 @@ public class EndpointManagerTest {
         when(endpointL3.getMacAddress()).thenReturn(null);
 
         Map<EndpointKey, EndpointL3> result = manager.getL3EpWithNatByL2Key();
-        Assert.assertTrue(result.isEmpty());
+        assertTrue(result.isEmpty());
     }
 
     @Test
@@ -345,26 +346,26 @@ public class EndpointManagerTest {
         when(endpointL3.getMacAddress()).thenReturn(mock(MacAddress.class));
 
         Map<EndpointKey, EndpointL3> result = manager.getL3EpWithNatByL2Key();
-        Assert.assertTrue(result.isEmpty());
+        assertTrue(result.isEmpty());
     }
 
     @Test
     public void getEndpointsForGroupTest() {
         EgKey newEgKey = new EgKey(tenantId, endpointGroupId);
-        Assert.assertTrue(manager.getEndpointsForGroup(newEgKey).isEmpty());
+        assertTrue(manager.getEndpointsForGroup(newEgKey).isEmpty());
         manager.processEndpoint(null, endpoint1);
-        Assert.assertFalse(manager.getEndpointsForGroup(newEgKey).isEmpty());
+        assertFalse(manager.getEndpointsForGroup(newEgKey).isEmpty());
     }
 
     @Test
     public void getConditionsForEndpoint() {
         Endpoint endpoint = mock(Endpoint.class);
         when(endpoint.getCondition()).thenReturn(null);
-        Assert.assertTrue(manager.getConditionsForEndpoint(endpoint).isEmpty());
+        assertTrue(manager.getConditionsForEndpoint(endpoint).isEmpty());
 
         List<ConditionName> conditionNameList = Collections.singletonList(mock(ConditionName.class));
         when(endpoint.getCondition()).thenReturn(conditionNameList);
-        Assert.assertEquals(conditionNameList, manager.getConditionsForEndpoint(endpoint));
+        assertEquals(conditionNameList, manager.getConditionsForEndpoint(endpoint));
     }
 
     @Test
@@ -386,7 +387,7 @@ public class EndpointManagerTest {
         when(endpointL3Key.getIpAddress()).thenReturn(ipAddress);
         when(newL3Ep.getIpAddress()).thenReturn(new IpAddress(new Ipv4Address("1.1.1.1")));
         manager.processL3Endpoint(null, newL3Ep);
-        verify(endpointListener,never()).endpointUpdated(any(EpKey.class));
+        verify(endpointListener, never()).endpointUpdated(any(EpKey.class));
     }
 
     @Test
@@ -407,7 +408,7 @@ public class EndpointManagerTest {
         when(endpointL3Key.getIpAddress()).thenReturn(ipAddress);
         when(newL3Ep.getIpAddress()).thenReturn(new IpAddress(new Ipv4Address("1.1.1.1")));
         manager.processL3Endpoint(null, newL3Ep);
-        verify(endpointListener,never()).endpointUpdated(any(EpKey.class));
+        verify(endpointListener, never()).endpointUpdated(any(EpKey.class));
     }
 
     @Test
@@ -437,7 +438,7 @@ public class EndpointManagerTest {
         when(newL3Ep.getIpAddress()).thenReturn(null);
         when(newL3Ep.getIpAddress()).thenReturn(new IpAddress(new Ipv4Address("1.1.1.1")));
         manager.processL3Endpoint(null, newL3Ep);
-        verify(endpointListener,never()).endpointUpdated(any(EpKey.class));
+        verify(endpointListener, never()).endpointUpdated(any(EpKey.class));
     }
 
     @Test
@@ -447,6 +448,30 @@ public class EndpointManagerTest {
         verify(endpointListener).endpointUpdated(any(EpKey.class));
     }
 
+    @Test
+    public void updateEndpointL3TestUpdate() throws Exception {
+        when(oldL3Ep.getIpAddress()).thenReturn(new IpAddress(new Ipv4Address("1.1.1.1")));
+
+        when(newL3Ep.getTenant()).thenReturn(mock(TenantId.class));
+        when(newL3Ep.getEndpointGroup()).thenReturn(mock(EndpointGroupId.class));
+        when(newL3Ep.getL3Context()).thenReturn(mock(L3ContextId.class));
+        when(newL3Ep.getIpAddress()).thenReturn(mock(IpAddress.class));
+
+        OfOverlayL3Context ofOverlayL3Context = mock(OfOverlayL3Context.class);
+        when(newL3Ep.getAugmentation(OfOverlayL3Context.class)).thenReturn(ofOverlayL3Context);
+
+        when(newL3Ep.getNetworkContainment()).thenReturn(null);
+
+        when(newL3Ep.getL2Context()).thenReturn(mock(L2BridgeDomainId.class));
+        when(newL3Ep.getMacAddress()).thenReturn(mock(MacAddress.class));
+        when(newL3Ep.getIpAddress()).thenReturn(new IpAddress(new Ipv4Address("1.1.1.1")));
+
+        manager.processL3Endpoint(null, oldL3Ep);
+        manager.processL3Endpoint(oldL3Ep, newL3Ep);
+
+        verify(endpointListener).endpointUpdated(any(EpKey.class));
+    }
+
     @Test
     public void updateEndpointTestNewEndpointRemove() {
         Collection<Endpoint> collection;
@@ -454,13 +479,13 @@ public class EndpointManagerTest {
         verify(endpointListener).endpointUpdated(any(EpKey.class));
         verify(endpointListener).nodeEndpointUpdated(any(NodeId.class), any(EpKey.class));
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, endpointGroupId));
-        Assert.assertFalse(collection.isEmpty());
+        assertFalse(collection.isEmpty());
 
         manager.processEndpoint(endpoint2, null);
         verify(endpointListener, times(2)).endpointUpdated(any(EpKey.class));
         verify(endpointListener, times(2)).nodeEndpointUpdated(any(NodeId.class), any(EpKey.class));
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, endpointGroupId));
-        Assert.assertTrue(collection.isEmpty());
+        assertTrue(collection.isEmpty());
     }
 
     @Test
@@ -516,7 +541,7 @@ public class EndpointManagerTest {
         // create: node1, update: node1 -> node2
         verify(endpointListener, times(3)).nodeEndpointUpdated(any(NodeId.class), any(EpKey.class));
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, endpointGroupId));
-        Assert.assertFalse(collection.isEmpty());
+        assertFalse(collection.isEmpty());
     }
 
     /**
@@ -534,9 +559,9 @@ public class EndpointManagerTest {
         verify(endpointListener, times(2)).endpointUpdated(any(EpKey.class));
         verify(endpointListener, times(1)).nodeEndpointUpdated(any(NodeId.class), any(EpKey.class));
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, endpointGroupId));
-        Assert.assertTrue(collection.isEmpty());
+        assertTrue(collection.isEmpty());
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, otherEndpointGroupId));
-        Assert.assertFalse(collection.isEmpty());
+        assertFalse(collection.isEmpty());
     }
 
     /**
@@ -554,9 +579,9 @@ public class EndpointManagerTest {
         // create: node1, update: node1 -> node2
         verify(endpointListener, times(3)).nodeEndpointUpdated(any(NodeId.class), any(EpKey.class));
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, endpointGroupId));
-        Assert.assertTrue(collection.isEmpty());
+        assertTrue(collection.isEmpty());
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, otherEndpointGroupId));
-        Assert.assertFalse(collection.isEmpty());
+        assertFalse(collection.isEmpty());
     }
 
     /**
@@ -573,7 +598,7 @@ public class EndpointManagerTest {
         verify(endpointListener, times(2)).endpointUpdated(any(EpKey.class));
         verify(endpointListener, times(2)).nodeEndpointUpdated(any(NodeId.class), any(EpKey.class));
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, endpointGroupId));
-        Assert.assertTrue(collection.isEmpty());
+        assertTrue(collection.isEmpty());
     }
 
     /**
@@ -590,7 +615,7 @@ public class EndpointManagerTest {
         verify(endpointListener).endpointUpdated(any(EpKey.class));
         verify(endpointListener).nodeEndpointUpdated(any(NodeId.class), any(EpKey.class));
         collection = manager.getEndpointsForGroup(new EgKey(tenantId, endpointGroupId));
-        Assert.assertFalse(collection.isEmpty());
+        assertFalse(collection.isEmpty());
     }
 
     @Test
@@ -599,36 +624,36 @@ public class EndpointManagerTest {
         verify(listenerReg, times(3)).close();
     }
 
-     //**************
-     //Helper Functions
-     //**************
+    // **************
+    // Helper Functions
+    // **************
 
     @Test
     public void getEgKeyTest() {
-        Assert.assertNotNull(manager.getEgKey(endpoint1));
-        Assert.assertNull(manager.getEgKey(null));
+        assertNotNull(manager.getEgKey(endpoint1));
+        assertNull(manager.getEgKey(null));
 
         when(endpoint1.getTenant()).thenReturn(null);
-        Assert.assertNull(manager.getEgKey(endpoint1));
+        assertNull(manager.getEgKey(endpoint1));
 
         when(endpoint1.getTenant()).thenReturn(tenantId);
         when(endpoint1.getEndpointGroup()).thenReturn(null);
-        Assert.assertNull(manager.getEgKey(endpoint1));
+        assertNull(manager.getEgKey(endpoint1));
 
         when(endpoint1.getEndpointGroup()).thenReturn(endpointGroupId);
         when(endpoint1.getEndpointGroups()).thenReturn(null);
-        Assert.assertNotNull(manager.getEgKey(endpoint1));
+        assertNotNull(manager.getEgKey(endpoint1));
 
         when(endpoint1.getEndpointGroup()).thenReturn(null);
-        Assert.assertNull(manager.getEgKey(endpoint1));
+        assertNull(manager.getEgKey(endpoint1));
 
         when(endpoint1.getEndpointGroup()).thenReturn(endpointGroupId);
         when(endpoint1.getL2Context()).thenReturn(null);
-        Assert.assertNull(manager.getEgKey(endpoint1));
+        assertNull(manager.getEgKey(endpoint1));
 
         when(endpoint1.getL2Context()).thenReturn(l2BridgeDomainId);
         when(endpoint1.getMacAddress()).thenReturn(null);
-        Assert.assertNull(manager.getEgKey(endpoint1));
+        assertNull(manager.getEgKey(endpoint1));
     }
 
     @Test
@@ -638,18 +663,18 @@ public class EndpointManagerTest {
 
         when(endpoint.getEndpointGroups()).thenReturn(null);
         egKeys = manager.getEgKeysForEndpoint(endpoint);
-        Assert.assertTrue(egKeys.isEmpty());
+        assertTrue(egKeys.isEmpty());
 
         EndpointGroupId endpointGroupId = mock(EndpointGroupId.class);
         when(endpoint.getEndpointGroup()).thenReturn(endpointGroupId);
         egKeys = manager.getEgKeysForEndpoint(endpoint);
-        Assert.assertEquals(1, egKeys.size());
+        assertEquals(1, egKeys.size());
 
         EndpointGroupId epgId = mock(EndpointGroupId.class);
         List<EndpointGroupId> endpointGroups = Collections.singletonList(epgId);
         when(endpoint.getEndpointGroups()).thenReturn(endpointGroups);
         egKeys = manager.getEgKeysForEndpoint(endpoint);
-        Assert.assertEquals(2, egKeys.size());
+        assertEquals(2, egKeys.size());
     }
 
     @Test
@@ -657,21 +682,42 @@ public class EndpointManagerTest {
         Endpoint endpoint = mock(Endpoint.class);
         when(endpoint.getAugmentation(OfOverlayContext.class)).thenReturn(null);
         // TODO
-//        Assert.assertFalse(manager.isExternal(endpoint));
-//        Assert.assertTrue(manager.isInternal(endpoint));
-//
-//        OfOverlayContext ofc = mock(OfOverlayContext.class);
-//        when(endpoint.getAugmentation(OfOverlayContext.class)).thenReturn(ofc);
-//        when(ofc.getLocationType()).thenReturn(null);
-//        Assert.assertFalse(manager.isExternal(endpoint));
-//        Assert.assertTrue(manager.isInternal(endpoint));
-//
-//        when(ofc.getLocationType()).thenReturn(LocationType.Internal);
-//        Assert.assertFalse(manager.isExternal(endpoint));
-//        Assert.assertTrue(manager.isInternal(endpoint));
-//
-//        when(ofc.getLocationType()).thenReturn(LocationType.External);
-//        Assert.assertTrue(manager.isExternal(endpoint));
-//        Assert.assertFalse(manager.isInternal(endpoint));
+        // assertFalse(manager.isExternal(endpoint));
+        // assertTrue(manager.isInternal(endpoint));
+        //
+        // OfOverlayContext ofc = mock(OfOverlayContext.class);
+        // when(endpoint.getAugmentation(OfOverlayContext.class)).thenReturn(ofc);
+        // when(ofc.getLocationType()).thenReturn(null);
+        // assertFalse(manager.isExternal(endpoint));
+        // assertTrue(manager.isInternal(endpoint));
+        //
+        // when(ofc.getLocationType()).thenReturn(LocationType.Internal);
+        // assertFalse(manager.isExternal(endpoint));
+        // assertTrue(manager.isInternal(endpoint));
+        //
+        // when(ofc.getLocationType()).thenReturn(LocationType.External);
+        // assertTrue(manager.isExternal(endpoint));
+        // assertFalse(manager.isInternal(endpoint));
+    }
+
+    @Test
+    public void testGetL2EndpointFromL3() {
+        when(newL3Ep.getL2Context()).thenReturn(mock(L2BridgeDomainId.class));
+        when(newL3Ep.getMacAddress()).thenReturn(mock(MacAddress.class));
+
+        Endpoint ep = manager.getL2EndpointFromL3(newL3Ep);
+
+        assertNull(ep);
+    }
+
+    @Test
+    public void testGetL2EndpointFromL3_noL2Context_noMacAddr() {
+        when(newL3Ep.getL2Context()).thenReturn(null);
+        when(newL3Ep.getMacAddress()).thenReturn(null);
+
+        Endpoint ep = manager.getL2EndpointFromL3(newL3Ep);
+
+        assertNull(ep);
     }
+
 }
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayAugTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayAugTest.java
new file mode 100644 (file)
index 0000000..ddd3700
--- /dev/null
@@ -0,0 +1,156 @@
+/*\r
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.\r
+ *\r
+ * This program and the accompanying materials are made available under the\r
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
+ * and is available at http://www.eclipse.org/legal/epl-v10.html\r
+ */\r
+\r
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint;\r
+\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertNull;\r
+import static org.mockito.Mockito.mock;\r
+import static org.mockito.Mockito.when;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.concurrent.ExecutionException;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;\r
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;\r
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;\r
+import org.opendaylight.groupbasedpolicy.api.EpRendererAugmentationRegistry;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test.TransactionMockUtils;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Prefix;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInput;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInputBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;\r
+import org.opendaylight.yangtools.yang.binding.Augmentation;\r
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;\r
+\r
+public class OfOverlayAugTest {\r
+\r
+    private static final String PORT_NAME = "portName";\r
+    private DataBroker dataProvider;\r
+    private EpRendererAugmentationRegistry epRendererAugmentationRegistry;\r
+    private OfOverlayAug ofOverlayAug;\r
+\r
+    @Before\r
+    public void init() {\r
+        dataProvider = mock(DataBroker.class);\r
+        epRendererAugmentationRegistry = mock(EpRendererAugmentationRegistry.class);\r
+        ofOverlayAug = new OfOverlayAug(dataProvider, epRendererAugmentationRegistry);\r
+    }\r
+\r
+    @Test\r
+    public void testConstructor() throws Exception {\r
+        OfOverlayAug other = new OfOverlayAug(dataProvider, epRendererAugmentationRegistry);\r
+        other.close();\r
+    }\r
+\r
+    @SuppressWarnings("unchecked")\r
+    @Test\r
+    public void testBuildEndpointAugmentation() throws ExecutionException, InterruptedException {\r
+        Nodes nodes = buildNodes();\r
+\r
+        ReadOnlyTransaction roTx = mock(ReadOnlyTransaction.class);\r
+        TransactionMockUtils.setupRoTx(roTx, LogicalDatastoreType.OPERATIONAL,\r
+                InstanceIdentifier.builder(Nodes.class).build(), true, nodes);\r
+        when(dataProvider.newReadOnlyTransaction()).thenReturn(roTx);\r
+\r
+        OfOverlayContextInput contextInput =\r
+                new OfOverlayContextInputBuilder().setPortName(new Name(PORT_NAME)).build();\r
+\r
+        RegisterEndpointInput input =\r
+                new RegisterEndpointInputBuilder().addAugmentation(OfOverlayContextInput.class, contextInput).build();\r
+\r
+        Map.Entry<Class<? extends Augmentation<Endpoint>>, Augmentation<Endpoint>> entry =\r
+                ofOverlayAug.buildEndpointAugmentation(input);\r
+\r
+        assertNotNull(entry);\r
+        assertNotNull(entry.getValue());\r
+    }\r
+\r
+    @Test\r
+    public void testBuildEndpointAugmentation_null() {\r
+        RegisterEndpointInput input = new RegisterEndpointInputBuilder().build();\r
+\r
+        Map.Entry<Class<? extends Augmentation<Endpoint>>, Augmentation<Endpoint>> entry =\r
+                ofOverlayAug.buildEndpointAugmentation(input);\r
+\r
+        assertNull(entry);\r
+    }\r
+\r
+    @SuppressWarnings("unchecked")\r
+    @Test\r
+    public void testBuildEndpointL3Augmentation() throws ExecutionException, InterruptedException {\r
+        Nodes nodes = buildNodes();\r
+\r
+        ReadOnlyTransaction roTx = mock(ReadOnlyTransaction.class);\r
+        TransactionMockUtils.setupRoTx(roTx, LogicalDatastoreType.OPERATIONAL,\r
+                InstanceIdentifier.builder(Nodes.class).build(), true, nodes);\r
+        when(dataProvider.newReadOnlyTransaction()).thenReturn(roTx);\r
+\r
+        OfOverlayContextInput contextInput =\r
+                new OfOverlayContextInputBuilder().setPortName(new Name(PORT_NAME)).build();\r
+\r
+        RegisterEndpointInput input =\r
+                new RegisterEndpointInputBuilder().addAugmentation(OfOverlayContextInput.class, contextInput).build();\r
+\r
+        Map.Entry<Class<? extends Augmentation<EndpointL3>>, Augmentation<EndpointL3>> entry =\r
+                ofOverlayAug.buildEndpointL3Augmentation(input);\r
+\r
+        assertNotNull(entry);\r
+        assertNotNull(entry.getValue());\r
+    }\r
+\r
+    @Test\r
+    public void testBuildEndpointL3Augmentation_null() {\r
+        RegisterEndpointInput input = new RegisterEndpointInputBuilder().build();\r
+\r
+        Map.Entry<Class<? extends Augmentation<EndpointL3>>, Augmentation<EndpointL3>> entry =\r
+                ofOverlayAug.buildEndpointL3Augmentation(input);\r
+\r
+        assertNull(entry);\r
+    }\r
+\r
+    @Test\r
+    public void testBuildL3PrefixEndpointAugmentation() {\r
+        RegisterL3PrefixEndpointInput input = new RegisterL3PrefixEndpointInputBuilder().build();\r
+        Map.Entry<Class<? extends Augmentation<EndpointL3Prefix>>, Augmentation<EndpointL3Prefix>> entry =\r
+                ofOverlayAug.buildL3PrefixEndpointAugmentation(input);\r
+\r
+        // always returns null\r
+        assertNull(entry);\r
+    }\r
+\r
+    private Nodes buildNodes() {\r
+        FlowCapableNodeConnector fcnc = new FlowCapableNodeConnectorBuilder().setName(PORT_NAME).build();\r
+        NodeConnector nc = new NodeConnectorBuilder().addAugmentation(FlowCapableNodeConnector.class, fcnc).build();\r
+        List<NodeConnector> nodeConnectorList = new ArrayList<>();\r
+        nodeConnectorList.add(nc);\r
+        Node node = new NodeBuilder().setNodeConnector(nodeConnectorList).build();\r
+        List<Node> nodeList = new ArrayList<>();\r
+        nodeList.add(node);\r
+        return new NodesBuilder().setNode(nodeList).build();\r
+    }\r
+\r
+}\r
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayContextListenerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayContextListenerTest.java
new file mode 100644 (file)
index 0000000..3e76591
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Set;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.CheckedFuture;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.node.SwitchManager;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.Endpoints;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContext;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public class OfOverlayContextListenerTest {
+
+    private static final Name OLD_PORT_NAME = new Name("oldPort");
+    private static final Name NEW_PORT_NAME = new Name("newPort");
+    private OfOverlayContextListener listener;
+    private DataObjectModification<OfOverlayContext> rootNode;
+    private Set<DataTreeModification<OfOverlayContext>> changes;
+
+    private DataBroker dataProvider;
+    private SwitchManager switchManager;
+
+    private InstanceIdentifier<OfOverlayContext> rootIdentifier;
+    private OfOverlayContext oldContext;
+    private OfOverlayContext newContext;
+    private OfOverlayContext contextNoPortName;
+
+    @SuppressWarnings("unchecked")
+    @Before
+    public void init() {
+
+        dataProvider = mock(DataBroker.class);
+        switchManager = mock(SwitchManager.class);
+
+        NodeKey nodeKey = new NodeKey(new NodeId("nodeId"));
+        NodeConnectorKey nodeConnectorKey = new NodeConnectorKey(new NodeConnectorId("ncId"));
+        InstanceIdentifier<NodeConnector> ncIid = InstanceIdentifier.builder(Nodes.class)
+            .child(Node.class, nodeKey)
+            .child(NodeConnector.class, nodeConnectorKey)
+            .build();
+        when(switchManager.getNodeConnectorIidForPortName(NEW_PORT_NAME)).thenReturn(ncIid);
+
+        listener = spy(new OfOverlayContextListener(dataProvider, switchManager));
+        EndpointKey epKey = mock(EndpointKey.class);
+
+        rootNode = mock(DataObjectModification.class);
+        rootIdentifier = InstanceIdentifier.builder(Endpoints.class)
+            .child(Endpoint.class, epKey)
+            .augmentation(OfOverlayContext.class)
+            .build();
+        DataTreeIdentifier<OfOverlayContext> rootPath =
+                new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, rootIdentifier);
+
+        DataTreeModification<OfOverlayContext> change = mock(DataTreeModification.class);
+
+        when(change.getRootNode()).thenReturn(rootNode);
+        when(change.getRootPath()).thenReturn(rootPath);
+
+        changes = ImmutableSet.of(change);
+
+        oldContext = new OfOverlayContextBuilder().setPortName(OLD_PORT_NAME).build();
+        newContext = new OfOverlayContextBuilder().setPortName(NEW_PORT_NAME).build();
+        contextNoPortName = new OfOverlayContextBuilder().build();
+    }
+
+    @Test
+    public void testOnDataTreeChanged_Write() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.WRITE);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(oldContext);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_bothNoPortName() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(contextNoPortName);
+        when(rootNode.getDataAfter()).thenReturn(contextNoPortName);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_oneNoPortName() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(oldContext);
+        when(rootNode.getDataAfter()).thenReturn(contextNoPortName);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_oneNoPortName1() {
+        when(switchManager.getNodeConnectorIidForPortName(NEW_PORT_NAME)).thenReturn(null);
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(oldContext);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_samePortName() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(newContext);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_Delete() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.DELETE);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        // no op
+    }
+
+    private WriteTransaction resetTransaction() {
+        WriteTransaction wt = mock(WriteTransaction.class);
+        CheckedFuture checkedFuture = mock(CheckedFuture.class);
+        when(wt.submit()).thenReturn(checkedFuture);
+        when(dataProvider.newWriteOnlyTransaction()).thenReturn(wt);
+        return wt;
+    }
+
+}
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3ContextListenerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3ContextListenerTest.java
new file mode 100644 (file)
index 0000000..78e646a
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.Set;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.CheckedFuture;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.node.SwitchManager;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.Endpoints;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContext;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayL3Context;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayL3ContextBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public class OfOverlayL3ContextListenerTest {
+
+    private static final Name OLD_PORT_NAME = new Name("oldPort");
+    private static final Name NEW_PORT_NAME = new Name("newPort");
+    private OfOverlayL3ContextListener listener;
+    private DataObjectModification<OfOverlayL3Context> rootNode;
+    private Set<DataTreeModification<OfOverlayL3Context>> changes;
+
+    private DataBroker dataProvider;
+    private SwitchManager switchManager;
+
+    private InstanceIdentifier<OfOverlayL3Context> rootIdentifier;
+    private OfOverlayL3Context oldContext;
+    private OfOverlayL3Context newContext;
+    private OfOverlayL3Context contextNoPortName;
+
+    @SuppressWarnings("unchecked")
+    @Before
+    public void init() {
+
+        dataProvider = mock(DataBroker.class);
+        switchManager = mock(SwitchManager.class);
+
+        NodeKey nodeKey = new NodeKey(new NodeId("nodeId"));
+        NodeConnectorKey nodeConnectorKey = new NodeConnectorKey(new NodeConnectorId("ncId"));
+        InstanceIdentifier<NodeConnector> ncIid = InstanceIdentifier.builder(Nodes.class)
+            .child(Node.class, nodeKey)
+            .child(NodeConnector.class, nodeConnectorKey)
+            .build();
+        when(switchManager.getNodeConnectorIidForPortName(NEW_PORT_NAME)).thenReturn(ncIid);
+
+        listener = spy(new OfOverlayL3ContextListener(dataProvider, switchManager));
+        EndpointL3Key epL3Key = mock(EndpointL3Key.class);
+
+        rootNode = mock(DataObjectModification.class);
+        rootIdentifier = InstanceIdentifier.builder(Endpoints.class)
+            .child(EndpointL3.class, epL3Key)
+            .augmentation(OfOverlayL3Context.class)
+            .build();
+        DataTreeIdentifier<OfOverlayL3Context> rootPath =
+                new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, rootIdentifier);
+
+        DataTreeModification<OfOverlayL3Context> change = mock(DataTreeModification.class);
+
+        when(change.getRootNode()).thenReturn(rootNode);
+        when(change.getRootPath()).thenReturn(rootPath);
+
+        changes = ImmutableSet.of(change);
+
+        oldContext = new OfOverlayL3ContextBuilder().setPortName(OLD_PORT_NAME).build();
+        newContext = new OfOverlayL3ContextBuilder().setPortName(NEW_PORT_NAME).build();
+        contextNoPortName = new OfOverlayL3ContextBuilder().build();
+    }
+
+    @Test
+    public void testOnDataTreeChanged_Write() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.WRITE);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(oldContext);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_bothNoPortName() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(contextNoPortName);
+        when(rootNode.getDataAfter()).thenReturn(contextNoPortName);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_oneNoPortName() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(oldContext);
+        when(rootNode.getDataAfter()).thenReturn(contextNoPortName);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_oneNoPortName1() {
+        when(switchManager.getNodeConnectorIidForPortName(NEW_PORT_NAME)).thenReturn(null);
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(oldContext);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_SubtreeModified_samePortName() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.SUBTREE_MODIFIED);
+        when(rootNode.getDataBefore()).thenReturn(newContext);
+        when(rootNode.getDataAfter()).thenReturn(newContext);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        verify(wt, never()).merge(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class),
+                any(OfOverlayContext.class));
+    }
+
+    @Test
+    public void testOnDataTreeChanged_Delete() {
+        when(rootNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.DELETE);
+
+        WriteTransaction wt = resetTransaction();
+
+        listener.onDataTreeChanged(changes);
+
+        // no op
+    }
+
+    private WriteTransaction resetTransaction() {
+        WriteTransaction wt = mock(WriteTransaction.class);
+        CheckedFuture checkedFuture = mock(CheckedFuture.class);
+        when(wt.submit()).thenReturn(checkedFuture);
+        when(dataProvider.newWriteOnlyTransaction()).thenReturn(wt);
+        return wt;
+    }
+
+}
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3NatAugTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3NatAugTest.java
new file mode 100644 (file)
index 0000000..2d03a12
--- /dev/null
@@ -0,0 +1,80 @@
+/*\r
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.\r
+ *\r
+ * This program and the accompanying materials are made available under the\r
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
+ * and is available at http://www.eclipse.org/legal/epl-v10.html\r
+ */\r
+\r
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint;\r
+\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertNull;\r
+import static org.mockito.Mockito.mock;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.groupbasedpolicy.api.EpRendererAugmentationRegistry;\r
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;\r
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddressInput;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddressInputBuilder;\r
+\r
+public class OfOverlayL3NatAugTest {\r
+\r
+    private OfOverlayL3NatAug ofOverlayL3NatAug;\r
+    private EpRendererAugmentationRegistry epRendererAugmentationRegistry;\r
+\r
+    @Before\r
+    public void init() {\r
+        epRendererAugmentationRegistry = mock(EpRendererAugmentationRegistry.class);\r
+        ofOverlayL3NatAug = new OfOverlayL3NatAug(epRendererAugmentationRegistry);\r
+    }\r
+\r
+    @Test\r
+    public void testConstructor() throws Exception {\r
+        OfOverlayL3NatAug other = new OfOverlayL3NatAug(epRendererAugmentationRegistry);\r
+        other.close();\r
+    }\r
+\r
+    @Test\r
+    public void testBuildEndpointAugmentation() {\r
+        RegisterEndpointInput input = new RegisterEndpointInputBuilder().build();\r
+        // no op\r
+        assertNull(ofOverlayL3NatAug.buildEndpointAugmentation(input));\r
+    }\r
+\r
+    @Test\r
+    public void testBuildEndpointL3Augmentation() {\r
+        NatAddressInput natAddressInput = new NatAddressInputBuilder().setNatAddress(\r
+                new IpAddress(new Ipv4Address("10.0.0.2"))).build();\r
+        RegisterEndpointInput input =\r
+                new RegisterEndpointInputBuilder().addAugmentation(NatAddressInput.class,\r
+                        natAddressInput).build();\r
+        assertNotNull(ofOverlayL3NatAug.buildEndpointL3Augmentation(input));\r
+    }\r
+\r
+    @Test\r
+    public void testBuildEndpointL3Augmentation_noAug() {\r
+        RegisterEndpointInput input = new RegisterEndpointInputBuilder().build();\r
+        assertNull(ofOverlayL3NatAug.buildEndpointL3Augmentation(input));\r
+    }\r
+\r
+    @Test\r
+    public void testBuildL3PrefixEndpointAugmentation() {\r
+        RegisterL3PrefixEndpointInput input = new RegisterL3PrefixEndpointInputBuilder().build();\r
+        // no op\r
+\r
+        assertNull(ofOverlayL3NatAug.buildL3PrefixEndpointAugmentation(input));\r
+    }\r
+\r
+    @Test\r
+    public void testClose() {\r
+        //        fail("Not yet implemented");\r
+    }\r
+\r
+}\r
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/BucketsEquivalenceTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/BucketsEquivalenceTest.java
new file mode 100644 (file)
index 0000000..d8b8a18
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.equivalence;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.BucketsBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
+
+public class BucketsEquivalenceTest {
+    BucketsEquivalence eq;
+
+    @Before
+    public void init() {
+        eq = new BucketsEquivalence();
+    }
+
+    @Test
+    public void testDoEquivalent() {
+        Buckets a = new BucketsBuilder().build();
+        Buckets b = new BucketsBuilder().build();
+        eq.doEquivalent(a, b);
+    }
+
+    @Test
+    public void testDoHash() {
+        Buckets a = new BucketsBuilder().build();
+        eq.doHash(a);
+    }
+
+}
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/GroupEquivalenceTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/GroupEquivalenceTest.java
new file mode 100644 (file)
index 0000000..62ea64b
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.equivalence;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
+
+public class GroupEquivalenceTest {
+
+    GroupEquivalence eq;
+
+    @Before
+    public void init() {
+        eq = new GroupEquivalence();
+    }
+
+    @Test
+    public void testDoEquivalent() {
+        Group a = new GroupBuilder().build();
+        Group b = new GroupBuilder().build();
+        eq.doEquivalent(a, b);
+    }
+
+    @Test
+    public void testDoHash() {
+
+        Group a = new GroupBuilder().build();
+        eq.doHash(a);
+    }
+
+}
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientResponseTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientResponseTest.java
new file mode 100644 (file)
index 0000000..cbb15da
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.sun.jersey.api.client.ClientHandlerException;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import org.junit.Before;
+import org.junit.Test;
+
+public class JsonRestClientResponseTest {
+
+    private static final String STRING_ENTITY = "string entity";
+    private ClientResponse clientResponse;
+
+    @Before
+    public void init() {
+        clientResponse = mock(ClientResponse.class);
+
+    }
+
+    @Test
+    public void testResponse_Ok() {
+        when(clientResponse.getEntity(String.class)).thenReturn(STRING_ENTITY);
+        when(clientResponse.getStatus()).thenReturn(200);
+        JsonRestClientResponse response = new JsonRestClientResponse(clientResponse);
+
+        assertSame(clientResponse, response.getClientResponse());
+        assertEquals(STRING_ENTITY, response.getJsonResponse());
+        assertEquals(200, response.getStatusCode());
+        assertNull(response.getClientHandlerException());
+    }
+
+    @Test
+    public void testResponse_UniformInterfaceException() {
+        UniformInterfaceException ex = new UniformInterfaceException(clientResponse);
+        when(clientResponse.getEntity(String.class)).thenThrow(ex);
+        when(clientResponse.getStatus()).thenReturn(204);
+
+        JsonRestClientResponse response = new JsonRestClientResponse(clientResponse);
+
+        assertNull(response.getJsonResponse());
+        assertEquals(204, response.getStatusCode());
+        assertNull(response.getClientHandlerException());
+    }
+
+    @Test
+    public void testResponse_ClientHandlerException() {
+        ClientHandlerException ex = new ClientHandlerException();
+        when(clientResponse.getEntity(String.class)).thenThrow(ex);
+        when(clientResponse.getStatus()).thenReturn(404);
+
+        JsonRestClientResponse response = new JsonRestClientResponse(clientResponse);
+
+        assertNull(response.getJsonResponse());
+        assertEquals(404, response.getStatusCode());
+        assertSame(ex, response.getClientHandlerException());
+    }
+}
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientTest.java
new file mode 100644 (file)
index 0000000..2c83548
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;
+
+import static org.junit.Assert.assertEquals;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+
+import com.google.common.collect.ImmutableList;
+import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
+import com.sun.jersey.api.core.ClassNamesResourceConfig;
+import com.sun.jersey.api.core.ResourceConfig;
+import com.sun.jersey.core.util.MultivaluedMapImpl;
+import com.sun.jersey.test.framework.AppDescriptor;
+import com.sun.jersey.test.framework.JerseyTest;
+import com.sun.jersey.test.framework.WebAppDescriptor;
+import org.glassfish.grizzly.http.server.HttpServer;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util.SFlowQueryParams;
+
+public class JsonRestClientTest extends JerseyTest {
+
+    private static final int CONNECT_TIMEOUT_MILLISEC = 20000;
+    private static final int READ_TIMEOUT_MILLISEC = 30000;
+    private static final String SFLOW_HOST = "localhost";
+    private static final int SFLOW_PORT = 1234;
+    private static HttpServer server;
+    private static final String SFLOW_URI = "http://" + SFLOW_HOST + ":" + SFLOW_PORT;
+
+    private JsonRestClient client;
+    private String uri;
+    private static String responseJson =
+            " { \"resolved-policy-uri\" : \"/restconf/operational/resolved-policy:resolved-policies/resolved-policy/tenant-red/client/tenant-red/webserver/\" } ";
+
+    private static HttpServer startServer() throws IOException {
+        final ResourceConfig resourceConfig = new ClassNamesResourceConfig(dumbServer.class);
+        HttpServer httpServer;
+        httpServer = GrizzlyServerFactory.createHttpServer(java.net.URI.create(SFLOW_URI), resourceConfig);
+        return httpServer;
+    }
+
+    @BeforeClass
+    public static void setUpClass() throws IOException {
+        server = startServer();
+    }
+
+    @AfterClass
+    public static void tearDownClass() {
+        if (server != null && server.isStarted())
+            server.stop();
+    }
+
+    @Before
+    public void init() {
+        client = new JsonRestClient(SFLOW_URI, CONNECT_TIMEOUT_MILLISEC, READ_TIMEOUT_MILLISEC);
+    }
+
+    @Test
+    public void testGetHost() {
+        String host = client.getHost();
+
+        assertEquals(SFLOW_HOST, host);
+    }
+
+    @Test
+    public void testGet_coverageOnly() {
+        client.get("/");
+    }
+
+    @Test
+    public void testGet_params_coverageOnly() {
+        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
+        params.add(SFlowQueryParams.MAX_FLOWS, "20");
+        params.add(SFlowQueryParams.MIN_VALUE, "0.1");
+        params.add(SFlowQueryParams.AGG_MODE, "sum");
+
+        client.get("/", params);
+    }
+
+    @Test
+    public void testPost_coverageOnly() {
+        client.post("/", "json");
+    }
+
+    @Test
+    public void testPut_coverageOnly() {
+        client.put("/", "json");
+    }
+
+    @Test
+    public void testDelete_coverageOnly() {
+        client.delete("/");
+    }
+
+    @Override
+    protected AppDescriptor configure() {
+        return new WebAppDescriptor.Builder().build();
+    }
+
+    @Path("/")
+    public static class dumbServer {
+
+        @GET
+        @Produces(MediaType.APPLICATION_JSON)
+        public Response get200() {
+            return Response.status(Response.Status.OK).entity(responseJson).build();
+        }
+
+        @POST
+        @Consumes(MediaType.APPLICATION_JSON)
+        public Response post200(String json) {
+            return Response.status(Response.Status.OK).build();
+        }
+
+    }
+}
index de1f7c2b7a0b745a96bbf2bc4aef96fe0a7d16f0..f819633e312da8fca3c2432d9872542d81f404b2 100755 (executable)
@@ -1,27 +1,85 @@
+/*\r
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.\r
+ *\r
+ * This program and the accompanying materials are made available under the\r
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
+ * and is available at http://www.eclipse.org/legal/epl-v10.html\r
+ */\r
+\r
 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;\r
 \r
 import static org.mockito.Mockito.mock;\r
 \r
+import java.util.Map;\r
 import java.util.concurrent.ScheduledExecutorService;\r
 \r
 import org.junit.Before;\r
 import org.junit.Test;\r
 import org.opendaylight.groupbasedpolicy.api.StatisticsManager;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test.TestUtils;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.RuleName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.Classifier;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.ClassifierBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.ResolvedPolicy;\r
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;\r
 \r
 public class OFStatisticsManagerTest {\r
 \r
-    ScheduledExecutorService executor;\r
-    StatisticsManager statisticsManager;\r
+    private final EndpointGroupId consumerEpgId = new EndpointGroupId("consumerEpg1");\r
+    private final EndpointGroupId providerEpgId = new EndpointGroupId("providerEpg1");\r
+    private final ContractId contractId = new ContractId("contract1");\r
+    private final TenantId tenantId = new TenantId("tenant1");\r
+    private final ClassifierName classifierName = ClassifierName.getDefaultInstance("classifier1");\r
+    private final SubjectName subjectName = SubjectName.getDefaultInstance("subject1");\r
+    private final RuleName ruleName = new RuleName("rule1");\r
+\r
+    private InstanceIdentifier<ResolvedPolicy> rpIid;\r
+    private ResolvedPolicy resolvedPolicy;\r
+\r
+    private ScheduledExecutorService executor;\r
+    private StatisticsManager statisticsManager;\r
+\r
+    private OFStatisticsManager ofStatisticsManager;\r
+    private Classifier classifier;\r
+    private Map<InstanceIdentifier<Classifier>, Classifier> classifierByIid;\r
 \r
     @Before\r
     public void init() {\r
         executor = mock(ScheduledExecutorService.class);\r
         statisticsManager = mock(StatisticsManager.class);\r
+\r
+        classifier = new ClassifierBuilder()\r
+                .setName(classifierName)\r
+                .build();\r
+        resolvedPolicy = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName,\r
+                consumerEpgId, providerEpgId, classifier);\r
+\r
+        rpIid = InstanceIdentifier.create(ResolvedPolicy.class);\r
+\r
+        ofStatisticsManager = new OFStatisticsManager(executor, statisticsManager);\r
+        ofStatisticsManager.setDelay(20L);\r
+        ofStatisticsManager.setSflowCollectorUri("http://localhost:1234");\r
+\r
+        classifierByIid =\r
+                ResolvedPolicyClassifierListener.resolveClassifiers(resolvedPolicy, rpIid);\r
     }\r
 \r
     @Test\r
     public void testConstructor() throws Exception {\r
-        new OFStatisticsManager(executor, statisticsManager);\r
+        OFStatisticsManager other = new OFStatisticsManager(executor, statisticsManager);\r
+        other.close();\r
     }\r
 \r
+    @Test\r
+    public void testTTT(){\r
+        for (Map.Entry<InstanceIdentifier<Classifier>, Classifier> classifierEntry : classifierByIid.entrySet()) {\r
+            ofStatisticsManager.pullStatsForClassifier(classifierEntry.getKey(),\r
+                    classifierEntry.getValue());\r
+        }\r
+    }\r
 }\r
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ProcessDataTaskTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ProcessDataTaskTest.java
new file mode 100644 (file)
index 0000000..4c82d62
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.opendaylight.groupbasedpolicy.api.StatisticsManager;
+import org.opendaylight.groupbasedpolicy.dto.ConsEpgKey;
+import org.opendaylight.groupbasedpolicy.dto.EpgKeyDto;
+import org.opendaylight.groupbasedpolicy.dto.ProvEpgKey;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache.FlowCache;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache.FlowCacheData;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util.FlowCacheCons;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util.IidSflowNameUtil;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Builder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroupBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.statistics.rev151215.statistic.records.StatRecords;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({OFStatisticsManager.class, IidSflowNameUtil.class, OFStatisticsManager.class})
+public class ProcessDataTaskTest {
+
+    private final String IP_PROTO = "6";
+    private final String SRC_IP = "192.168.35.2";
+    private final String DST_IP = "192.168.36.2";
+    private final TenantId tenantId = new TenantId("tenantId");
+    private final EndpointGroupId srcEpgId = new EndpointGroupId("srcEpgId");
+    private final EndpointGroupId dstEpgId = new EndpointGroupId("dstEpgId");
+    private final ContractId contractId = new ContractId("contractId");
+    private final ClassifierName classifierName = new ClassifierName("classifierName");
+
+    private FlowCache flowCache;
+    private FlowCacheData data;
+    private ProcessDataTask task;
+
+    private EndpointL3 srcEpL3;
+    private EndpointL3 dstEpL3;
+    private EndpointGroup srcEpg;
+    private EndpointGroup dstEpg;
+
+    @Before
+    public void init() {
+        PowerMockito.mockStatic(OFStatisticsManager.class);
+        PowerMockito.mockStatic(IidSflowNameUtil.class);
+        PowerMockito.mockStatic(OFStatisticsManager.class);
+
+        String[] keyNames = {FlowCacheCons.Key.IP_PROTOCOL.get(), FlowCacheCons.Key.IP_SOURCE.get(),
+                FlowCacheCons.Key.IP_DESTINATION.get()};
+        flowCache = mock(FlowCache.class);
+        when(flowCache.getKeyNum()).thenReturn(3);
+        when(flowCache.getKeyNames()).thenReturn(keyNames);
+        when(flowCache.getName()).thenReturn("flowcache1");
+        when(flowCache.getDirection()).thenReturn(HasDirection.Direction.Out);
+        data = mock(FlowCacheData.class);
+        when(data.getKey()).thenReturn(IP_PROTO + "," + SRC_IP + "," + DST_IP);
+        List<FlowCacheData> dataList = new ArrayList<>();
+        dataList.add(data);
+        BigInteger timestamp = BigInteger.ZERO;
+        StatisticsManager statisticsManager = mock(StatisticsManager.class);
+        when(statisticsManager.writeStat(any(StatRecords.class))).thenReturn(true);
+
+        task = new ProcessDataTask(flowCache, dataList, timestamp, statisticsManager);
+
+        srcEpg = new EndpointGroupBuilder().setId(srcEpgId).build();
+        dstEpg = new EndpointGroupBuilder().setId(dstEpgId).build();
+        srcEpL3 = new EndpointL3Builder().setTenant(tenantId).setEndpointGroup(srcEpg.getId()).build();
+        dstEpL3 = new EndpointL3Builder().setTenant(tenantId).setEndpointGroup(dstEpg.getId()).build();
+        ConsEpgKey consEpgKey = new EpgKeyDto(srcEpg.getId(), tenantId);
+        ProvEpgKey provEpgKey = new EpgKeyDto(dstEpg.getId(), tenantId);
+        Pair<ConsEpgKey, ProvEpgKey> pair = Pair.of(consEpgKey, provEpgKey);
+        Set<Pair<ConsEpgKey, ProvEpgKey>> epgsForContract = new HashSet<>();
+        epgsForContract.add(pair);
+
+        when(OFStatisticsManager.getEpgsForContract(contractId)).thenReturn(epgsForContract);
+    }
+
+    @Test
+    public void testRun() {
+        when(OFStatisticsManager.getEndpointL3ForIp(SRC_IP)).thenReturn(srcEpL3);
+        when(OFStatisticsManager.getEndpointL3ForIp(DST_IP)).thenReturn(dstEpL3);
+        when(IidSflowNameUtil.resolveContractIdFromFlowCacheName(flowCache.getName())).thenReturn(contractId);
+        when(IidSflowNameUtil.resolveClassifierNameFromFlowCacheName(flowCache.getName())).thenReturn(classifierName);
+        when(IidSflowNameUtil.resolveFlowCacheValue(flowCache.getName())).thenReturn(FlowCacheCons.Value.BYTES.get());
+
+        task.run();
+    }
+
+    @Test
+    public void testRun_reversedConsProv() {
+        when(OFStatisticsManager.getEndpointL3ForIp(SRC_IP)).thenReturn(srcEpL3);
+        when(OFStatisticsManager.getEndpointL3ForIp(DST_IP)).thenReturn(dstEpL3);
+        when(IidSflowNameUtil.resolveContractIdFromFlowCacheName(flowCache.getName())).thenReturn(contractId);
+        when(IidSflowNameUtil.resolveClassifierNameFromFlowCacheName(flowCache.getName())).thenReturn(classifierName);
+        when(IidSflowNameUtil.resolveFlowCacheValue(flowCache.getName())).thenReturn(FlowCacheCons.Value.FRAMES.get());
+
+        ConsEpgKey consEpgKey = new EpgKeyDto(dstEpg.getId(), tenantId);
+        ProvEpgKey provEpgKey = new EpgKeyDto(srcEpg.getId(), tenantId);
+        Pair<ConsEpgKey, ProvEpgKey> pair = Pair.of(consEpgKey, provEpgKey);
+        Set<Pair<ConsEpgKey, ProvEpgKey>> epgsForContract = new HashSet<>();
+        epgsForContract.add(pair);
+        when(OFStatisticsManager.getEpgsForContract(contractId)).thenReturn(epgsForContract);
+
+        task.run();
+    }
+
+    @Test
+    public void testRun_noConsProv() {
+        when(OFStatisticsManager.getEndpointL3ForIp(SRC_IP)).thenReturn(srcEpL3);
+        when(OFStatisticsManager.getEndpointL3ForIp(DST_IP)).thenReturn(dstEpL3);
+        when(IidSflowNameUtil.resolveContractIdFromFlowCacheName(flowCache.getName())).thenReturn(contractId);
+        when(IidSflowNameUtil.resolveClassifierNameFromFlowCacheName(flowCache.getName())).thenReturn(classifierName);
+        when(IidSflowNameUtil.resolveFlowCacheValue(flowCache.getName())).thenReturn(FlowCacheCons.Value.FRAMES.get());
+
+        Set<Pair<ConsEpgKey, ProvEpgKey>> epgsForContract = new HashSet<>();
+        when(OFStatisticsManager.getEpgsForContract(contractId)).thenReturn(epgsForContract);
+
+        task.run();
+    }
+
+    @Test
+    public void testRun_wrongDataResponse() {
+        when(data.getKey()).thenReturn("1,2");
+        task.run();
+    }
+
+}
index 41bba898d86541aa788dce5b2516774ba7cb510b..873b73dc89840d2032b0a17da941dfdee5f2da51 100755 (executable)
@@ -1,8 +1,14 @@
+/*\r
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.\r
+ *\r
+ * This program and the accompanying materials are made available under the\r
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
+ * and is available at http://www.eclipse.org/legal/epl-v10.html\r
+ */\r
+\r
 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;\r
 \r
 import static org.mockito.Matchers.any;\r
-import static org.mockito.Matchers.anyMap;\r
-import static org.mockito.Matchers.anySet;\r
 import static org.mockito.Matchers.anyString;\r
 import static org.mockito.Mockito.doNothing;\r
 import static org.mockito.Mockito.mock;\r
@@ -10,26 +16,30 @@ import static org.mockito.Mockito.when;
 \r
 import javax.ws.rs.core.MultivaluedMap;\r
 \r
-import java.util.concurrent.ExecutorService;\r
 import java.util.concurrent.ScheduledExecutorService;\r
 \r
+import com.sun.jersey.api.client.ClientResponse;\r
 import org.junit.Before;\r
 import org.junit.Test;\r
+import org.mockito.Mockito;\r
 import org.opendaylight.groupbasedpolicy.api.StatisticsManager;\r
 \r
 public class ReadGbpFlowCacheTaskTest {\r
 \r
     ReadGbpFlowCacheTask task;\r
+    private JsonRestClientResponse response;\r
 \r
     @Before\r
     public void init() {\r
         StatisticsManager statisticsManager = mock(StatisticsManager.class);\r
         ScheduledExecutorService executor = mock(ScheduledExecutorService.class);\r
-        JsonRestClientResponse response = mock(JsonRestClientResponse.class);\r
+        ClientResponse clientResponse = mock(ClientResponse.class);\r
+        response = mock(JsonRestClientResponse.class);\r
         when(response.getJsonResponse()).thenReturn("[{\"one\":1, \"two\":2, \"three\":3}]");\r
         when(response.getStatusCode()).thenReturn(200);\r
+        when(response.getClientResponse()).thenReturn(clientResponse);\r
         SFlowRTConnection connection = mock(SFlowRTConnection.class);\r
-        when(connection.get(anyString(), any(MultivaluedMap.class))).thenReturn(response);\r
+        when(connection.get(anyString(), Mockito.<MultivaluedMap<String, String>>any())).thenReturn(response);\r
         when(connection.getExecutor()).thenReturn(executor);\r
         doNothing().when(executor).execute(any(Runnable.class));\r
 \r
@@ -38,7 +48,18 @@ public class ReadGbpFlowCacheTaskTest {
 \r
     @Test\r
     public void testRun() {\r
+        task.run();\r
+    }\r
+\r
+    @Test\r
+    public void testRun_response300() {\r
+        when(response.getStatusCode()).thenReturn(300);\r
+        task.run();\r
+    }\r
 \r
+    @Test\r
+    public void testRun_response400() {\r
+        when(response.getStatusCode()).thenReturn(400);\r
         task.run();\r
     }\r
 \r
index 14baad9ea04099445cfc82ec441b35a9da6b3b4e..430eb59d2a72672e2e333774ebb2351b6eac3d2a 100755 (executable)
@@ -1,3 +1,11 @@
+/*\r
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.\r
+ *\r
+ * This program and the accompanying materials are made available under the\r
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
+ * and is available at http://www.eclipse.org/legal/epl-v10.html\r
+ */\r
+\r
 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;\r
 \r
 import static org.mockito.Mockito.mock;\r
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnectionTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnectionTest.java
new file mode 100644 (file)
index 0000000..ad3ca90
--- /dev/null
@@ -0,0 +1,223 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import javax.ws.rs.core.MultivaluedMap;
+import java.util.concurrent.ScheduledExecutorService;
+
+import com.sun.jersey.api.client.ClientHandlerException;
+import com.sun.jersey.core.util.MultivaluedMapImpl;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.Mockito;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache.FlowCache;
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util.SFlowQueryParams;
+
+public class SFlowRTConnectionTest {
+
+    private static final String PATH = "/";
+    private static final String JSON_STRING = "jsonString";
+    private static final String JSON_RESPONSE = "jsonResponse";
+
+    private ScheduledExecutorService executor;
+    private String collectorUri;
+    private FlowCache flowCache;
+    private JsonRestClient client;
+    private MultivaluedMap<String, String> params;
+    private SFlowRTConnection connection;
+    private JsonRestClientResponse response;
+
+    @Rule
+    public ExpectedException thrown = ExpectedException.none();
+
+    @Before
+    public void init() {
+        params = new MultivaluedMapImpl();
+        params.add(SFlowQueryParams.MAX_FLOWS, "20");
+        params.add(SFlowQueryParams.MIN_VALUE, "0.1");
+        params.add(SFlowQueryParams.AGG_MODE, "sum");
+
+        executor = mock(ScheduledExecutorService.class);
+        collectorUri = "";
+        flowCache = mock(FlowCache.class);
+        client = mock(JsonRestClient.class);
+        response = mock(JsonRestClientResponse.class);
+        when(response.getJsonResponse()).thenReturn(JSON_RESPONSE);
+        when(response.getStatusCode()).thenReturn(200);
+        when(client.get(any(String.class), Mockito.<MultivaluedMap<String, String>>any())).thenReturn(response);
+        when(client.put(any(String.class), any(String.class))).thenReturn(response);
+        when(client.delete(any(String.class))).thenReturn(response);
+
+        connection = spy(new SFlowRTConnection(executor, collectorUri, flowCache, client));
+    }
+
+    @Test
+    public void testConstructor() {
+        SFlowRTConnection other = new SFlowRTConnection(executor, collectorUri, flowCache, client);
+
+        assertNotNull(other.getExecutor());
+        assertNotNull(other.getFlowCache());
+    }
+
+    @Test
+    public void testGetJsonResponse() {
+        String res = connection.getJsonResponse(PATH, params);
+
+        assertEquals(JSON_RESPONSE, res);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testGetJsonResponse_ClientHandlerException_noCause() {
+        ClientHandlerException ex = new ClientHandlerException();
+        when(client.get(any(String.class), Mockito.<MultivaluedMap<String, String>>any())).thenThrow(ex);
+
+        connection.getJsonResponse(PATH, params);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testGetJsonResponse_ClientHandlerException_caused() {
+        ClientHandlerException ex = new ClientHandlerException();
+        ex.initCause(new java.net.ConnectException());
+        when(client.get(any(String.class), Mockito.<MultivaluedMap<String, String>>any())).thenThrow(ex);
+
+        connection.getJsonResponse(PATH, params);
+    }
+
+    @Test
+    public void testGet() {
+        JsonRestClientResponse res = connection.get(PATH, params);
+
+        assertEquals(response, res);
+    }
+
+    @Test
+    public void testGet_notInitialized() {
+        when(connection.isInitialized()).thenReturn(false);
+
+        thrown.expect(IllegalStateException.class);
+        thrown.expectMessage(SFlowRTConnection.EX_MSG_NOT_INITIALIZED);
+        connection.get(PATH, params);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testGet_ClientHandlerException_noCause() {
+        ClientHandlerException ex = new ClientHandlerException();
+        when(client.get(any(String.class), Mockito.<MultivaluedMap<String, String>>any())).thenThrow(ex);
+
+        connection.get(PATH, params);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testGet_ClientHandlerException_caused() {
+        ClientHandlerException ex = new ClientHandlerException();
+        ex.initCause(new java.net.ConnectException());
+        when(client.get(any(String.class), Mockito.<MultivaluedMap<String, String>>any())).thenThrow(ex);
+
+        connection.get(PATH, params);
+    }
+
+    @Test
+    public void testPut() {
+        JsonRestClientResponse res = connection.put(PATH, JSON_STRING);
+
+        assertEquals(response, res);
+    }
+
+    @Test
+    public void testPut_notInitialized() {
+        when(connection.isInitialized()).thenReturn(false);
+
+        thrown.expect(IllegalStateException.class);
+        thrown.expectMessage(SFlowRTConnection.EX_MSG_NOT_INITIALIZED);
+        connection.put(PATH, JSON_STRING);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testPut_ClientHandlerException_noCause() {
+        ClientHandlerException ex = new ClientHandlerException();
+        when(client.put(any(String.class), any(String.class))).thenThrow(ex);
+
+        connection.put(PATH, JSON_STRING);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testPut_ClientHandlerException_caused() {
+        ClientHandlerException ex = new ClientHandlerException();
+        ex.initCause(new java.net.ConnectException());
+        when(client.put(any(String.class), any(String.class))).thenThrow(ex);
+
+        connection.put(PATH, JSON_STRING);
+    }
+
+    @Test
+    public void testDelete() {
+        JsonRestClientResponse res = connection.delete(PATH);
+
+        assertEquals(response, res);
+    }
+
+    @Test
+    public void testDelete_notInitialized() {
+        when(connection.isInitialized()).thenReturn(false);
+
+        thrown.expect(IllegalStateException.class);
+        thrown.expectMessage(SFlowRTConnection.EX_MSG_NOT_INITIALIZED);
+        connection.delete(PATH);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testDelete_ClientHandlerException_noCause() {
+        ClientHandlerException ex = new ClientHandlerException();
+        when(client.delete(any(String.class))).thenThrow(ex);
+
+        connection.delete(PATH);
+    }
+
+    @Test(expected = ClientHandlerException.class)
+    public void testDelete_ClientHandlerException_caused() {
+        ClientHandlerException ex = new ClientHandlerException();
+        ex.initCause(new java.net.ConnectException());
+        when(client.delete(any(String.class))).thenThrow(ex);
+
+        connection.delete(PATH);
+    }
+
+    @Test
+    public void testInitialize() {
+        when(response.getStatusCode()).thenReturn(300);
+        connection.initialize();
+        assertTrue(connection.isInitialized());
+
+        when(response.getStatusCode()).thenReturn(400);
+        connection.initialize();
+        assertTrue(connection.isInitialized());
+    }
+
+    @Test
+    public void testLogStatusCode_coverage() {
+        when(response.getStatusCode()).thenReturn(300);
+        connection.getJsonResponse(PATH, params);
+        connection.delete(PATH);
+
+        when(response.getStatusCode()).thenReturn(400);
+        connection.getJsonResponse(PATH, params);
+        connection.delete(PATH);
+    }
+
+}
index 349532978ae7586b5ec5b321a454a8a241350072..c5e1b2074ce3605f69adc707a5d513aea4881412 100755 (executable)
@@ -1,3 +1,11 @@
+/*\r
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.\r
+ *\r
+ * This program and the accompanying materials are made available under the\r
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
+ * and is available at http://www.eclipse.org/legal/epl-v10.html\r
+ */\r
+\r
 package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;\r
 \r
 import static org.mockito.Mockito.mock;\r
diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/test/TransactionMockUtils.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/test/TransactionMockUtils.java
new file mode 100644 (file)
index 0000000..96c7744
--- /dev/null
@@ -0,0 +1,47 @@
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.concurrent.ExecutionException;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public class TransactionMockUtils {
+
+    /**
+     * Stubs {@link ReadOnlyTransaction#read(LogicalDatastoreType, InstanceIdentifier)}
+     * to return a given {@link DataObject}
+     *
+     * @param roTx mocked transaction to stub
+     * @param store {@link LogicalDatastoreType}
+     * @param path {@link InstanceIdentifier}
+     * @param isPresent stub {@link Optional#isPresent()}; if {@code true}, stub
+     *        {@link Optional#get()} to return {@code returnObject}
+     * @param returnObject {@link DataObject} to return
+     * @param <T> type of {@code returnObject}
+     * @throws ExecutionException
+     * @throws InterruptedException
+     */
+    @SuppressWarnings("unchecked")
+    public static <T extends DataObject> void setupRoTx(ReadOnlyTransaction roTx, LogicalDatastoreType store,
+            InstanceIdentifier<T> path, boolean isPresent, T returnObject)
+            throws ExecutionException, InterruptedException {
+
+        CheckedFuture<Optional<T>, ReadFailedException> future = mock(CheckedFuture.class);
+        when(roTx.read(store, path)).thenReturn(future);
+        Optional<T> opt = mock(Optional.class);
+        when(future.get()).thenReturn(opt);
+        when(opt.isPresent()).thenReturn(isPresent);
+        if (isPresent) {
+            when(opt.get()).thenReturn(returnObject);
+        }
+    }
+
+}