From 11e9cef2263b38788495e8e17a541d8f2a3c3f64 Mon Sep 17 00:00:00 2001 From: Konstantin Blagov Date: Thu, 2 Jun 2016 09:48:01 +0200 Subject: [PATCH] Unit tests for ofoverlay Change-Id: I1b3773ac70a0ce2d00ed4bf0e97d3eb0462eaa0b Signed-off-by: Konstantin Blagov --- renderers/ofoverlay/pom.xml | 5 + .../statistics/OFStatisticsManager.java | 5 +- .../statistics/ReadGbpFlowCacheTask.java | 10 +- .../ResolvedPolicyClassifierListener.java | 8 +- .../statistics/SFlowRTConnection.java | 16 +- .../statistics/util/SFlowQueryParams.java | 16 ++ .../renderer/ofoverlay/arp/ArpTaskerTest.java | 86 ++++--- .../renderer/ofoverlay/arp/ArpUtilsTest.java | 10 + .../endpoint/EndpointManagerListenerTest.java | 12 +- .../endpoint/EndpointManagerTest.java | 210 ++++++++++------- .../ofoverlay/endpoint/OfOverlayAugTest.java | 156 ++++++++++++ .../OfOverlayContextListenerTest.java | 204 ++++++++++++++++ .../OfOverlayL3ContextListenerTest.java | 205 ++++++++++++++++ .../endpoint/OfOverlayL3NatAugTest.java | 80 +++++++ .../equivalence/BucketsEquivalenceTest.java | 39 +++ .../equivalence/GroupEquivalenceTest.java | 39 +++ .../JsonRestClientResponseTest.java | 71 ++++++ .../statistics/JsonRestClientTest.java | 133 +++++++++++ .../statistics/OFStatisticsManagerTest.java | 64 ++++- .../statistics/ProcessDataTaskTest.java | 154 ++++++++++++ .../statistics/ReadGbpFlowCacheTaskTest.java | 31 ++- .../ResolvedPolicyClassifierListenerTest.java | 8 + .../statistics/SFlowRTConnectionTest.java | 223 ++++++++++++++++++ .../SflowClientSettingsListenerTest.java | 8 + .../ofoverlay/test/TransactionMockUtils.java | 47 ++++ 25 files changed, 1691 insertions(+), 149 deletions(-) create mode 100644 renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/util/SFlowQueryParams.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayAugTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayContextListenerTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3ContextListenerTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3NatAugTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/BucketsEquivalenceTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/GroupEquivalenceTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientResponseTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ProcessDataTaskTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnectionTest.java create mode 100644 renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/test/TransactionMockUtils.java diff --git a/renderers/ofoverlay/pom.xml b/renderers/ofoverlay/pom.xml index d092fbdeb..801a90c16 100755 --- a/renderers/ofoverlay/pom.xml +++ b/renderers/ofoverlay/pom.xml @@ -93,6 +93,11 @@ powermock-api-mockito test + + com.sun.jersey.jersey-test-framework + jersey-test-framework-grizzly2 + test + diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManager.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManager.java index a17c3159f..e28d119b8 100755 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManager.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManager.java @@ -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 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); diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTask.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTask.java index bd476cf56..85db48d24 100755 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTask.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTask.java @@ -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>() {}.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 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) { diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListener.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListener.java index 51ccc0f91..af9bec180 100755 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListener.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListener.java @@ -51,9 +51,11 @@ public class ResolvedPolicyClassifierListener extends DataTreeChangeHandler, Classifier> classifierByIid = resolveClassifiers(resolvedPolicy, rootIdentifier); - for (Entry, Classifier> classfierEntry : classifierByIid.entrySet()) { - LOG.trace("New classifier created: {}\n{}", classfierEntry.getKey(), classfierEntry.getValue()); - ofStatsManager.pullStatsForClassifier(classfierEntry.getKey(), classfierEntry.getValue()); + for (Entry, Classifier> classifierEntry : classifierByIid.entrySet()) { + LOG.trace("New classifier created: {}\n{}", classifierEntry.getKey(), + classifierEntry.getValue()); + ofStatsManager.pullStatsForClassifier(classifierEntry.getKey(), + classifierEntry.getValue()); } } diff --git a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnection.java b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnection.java index 9a390fec7..7189982c8 100755 --- a/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnection.java +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnection.java @@ -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 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 index 000000000..8e1b9cf4e --- /dev/null +++ b/renderers/ofoverlay/src/main/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/util/SFlowQueryParams.java @@ -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"; + +} diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpTaskerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpTaskerTest.java index 6d6b1eb7e..15453a075 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpTaskerTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpTaskerTest.java @@ -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, ReadFailedException> future = Futures.immediateCheckedFuture(Optional.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> flowFuture = Mockito.mock(Future.class); - Mockito.when(flowService.addFlow(Mockito.any(AddFlowInput.class))).thenReturn(flowFuture); + Future> flowFuture = mock(Future.class); + when(flowService.addFlow(any(AddFlowInput.class))).thenReturn(flowFuture); epL3.setNetworkContainment(domainId).setTenant(tenantId); arpTasker.addMacForL3EpAndCreateEp(epL3.build()); ArgumentCaptor 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 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 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)); } } diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpUtilsTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpUtilsTest.java index 7e46d9621..3586f03bb 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpUtilsTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/arp/ArpUtilsTest.java @@ -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)); + } } diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerListenerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerListenerTest.java index 0f92fac41..c7dc70c39 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerListenerTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerListenerTest.java @@ -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)); } } diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerTest.java index 2b59de469..aa54188d2 100644 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/EndpointManagerTest.java @@ -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 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 checkedFutureWrite = mock(CheckedFuture.class); when(writeTransaction.submit()).thenReturn(checkedFutureWrite); - BindingAwareBroker.RpcRegistration rpcRegistration = mock(BindingAwareBroker.RpcRegistration.class); + BindingAwareBroker.RpcRegistration 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, 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 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, 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 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 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, 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 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 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 result = manager.getL3EpWithNatByL2Key(); - Assert.assertTrue(result.containsValue(endpointL3)); + assertTrue(result.containsValue(endpointL3)); } @Test public void getL3EpWithNatByL2KeyTestL3EpsNull() { Map result = manager.getL3EpWithNatByL2Key(); - Assert.assertTrue(result.isEmpty()); + assertTrue(result.isEmpty()); } @Test @@ -326,7 +327,7 @@ public class EndpointManagerTest { when(endpointL3.getMacAddress()).thenReturn(null); Map 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 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 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 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 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 index 000000000..ddd370007 --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayAugTest.java @@ -0,0 +1,156 @@ +/* + * 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.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; + +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.ReadOnlyTransaction; +import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; +import org.opendaylight.groupbasedpolicy.api.EpRendererAugmentationRegistry; +import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test.TransactionMockUtils; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; +import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder; +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.EndpointL3; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Prefix; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContextInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; +import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder; +import org.opendaylight.yangtools.yang.binding.Augmentation; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +public class OfOverlayAugTest { + + private static final String PORT_NAME = "portName"; + private DataBroker dataProvider; + private EpRendererAugmentationRegistry epRendererAugmentationRegistry; + private OfOverlayAug ofOverlayAug; + + @Before + public void init() { + dataProvider = mock(DataBroker.class); + epRendererAugmentationRegistry = mock(EpRendererAugmentationRegistry.class); + ofOverlayAug = new OfOverlayAug(dataProvider, epRendererAugmentationRegistry); + } + + @Test + public void testConstructor() throws Exception { + OfOverlayAug other = new OfOverlayAug(dataProvider, epRendererAugmentationRegistry); + other.close(); + } + + @SuppressWarnings("unchecked") + @Test + public void testBuildEndpointAugmentation() throws ExecutionException, InterruptedException { + Nodes nodes = buildNodes(); + + ReadOnlyTransaction roTx = mock(ReadOnlyTransaction.class); + TransactionMockUtils.setupRoTx(roTx, LogicalDatastoreType.OPERATIONAL, + InstanceIdentifier.builder(Nodes.class).build(), true, nodes); + when(dataProvider.newReadOnlyTransaction()).thenReturn(roTx); + + OfOverlayContextInput contextInput = + new OfOverlayContextInputBuilder().setPortName(new Name(PORT_NAME)).build(); + + RegisterEndpointInput input = + new RegisterEndpointInputBuilder().addAugmentation(OfOverlayContextInput.class, contextInput).build(); + + Map.Entry>, Augmentation> entry = + ofOverlayAug.buildEndpointAugmentation(input); + + assertNotNull(entry); + assertNotNull(entry.getValue()); + } + + @Test + public void testBuildEndpointAugmentation_null() { + RegisterEndpointInput input = new RegisterEndpointInputBuilder().build(); + + Map.Entry>, Augmentation> entry = + ofOverlayAug.buildEndpointAugmentation(input); + + assertNull(entry); + } + + @SuppressWarnings("unchecked") + @Test + public void testBuildEndpointL3Augmentation() throws ExecutionException, InterruptedException { + Nodes nodes = buildNodes(); + + ReadOnlyTransaction roTx = mock(ReadOnlyTransaction.class); + TransactionMockUtils.setupRoTx(roTx, LogicalDatastoreType.OPERATIONAL, + InstanceIdentifier.builder(Nodes.class).build(), true, nodes); + when(dataProvider.newReadOnlyTransaction()).thenReturn(roTx); + + OfOverlayContextInput contextInput = + new OfOverlayContextInputBuilder().setPortName(new Name(PORT_NAME)).build(); + + RegisterEndpointInput input = + new RegisterEndpointInputBuilder().addAugmentation(OfOverlayContextInput.class, contextInput).build(); + + Map.Entry>, Augmentation> entry = + ofOverlayAug.buildEndpointL3Augmentation(input); + + assertNotNull(entry); + assertNotNull(entry.getValue()); + } + + @Test + public void testBuildEndpointL3Augmentation_null() { + RegisterEndpointInput input = new RegisterEndpointInputBuilder().build(); + + Map.Entry>, Augmentation> entry = + ofOverlayAug.buildEndpointL3Augmentation(input); + + assertNull(entry); + } + + @Test + public void testBuildL3PrefixEndpointAugmentation() { + RegisterL3PrefixEndpointInput input = new RegisterL3PrefixEndpointInputBuilder().build(); + Map.Entry>, Augmentation> entry = + ofOverlayAug.buildL3PrefixEndpointAugmentation(input); + + // always returns null + assertNull(entry); + } + + private Nodes buildNodes() { + FlowCapableNodeConnector fcnc = new FlowCapableNodeConnectorBuilder().setName(PORT_NAME).build(); + NodeConnector nc = new NodeConnectorBuilder().addAugmentation(FlowCapableNodeConnector.class, fcnc).build(); + List nodeConnectorList = new ArrayList<>(); + nodeConnectorList.add(nc); + Node node = new NodeBuilder().setNodeConnector(nodeConnectorList).build(); + List nodeList = new ArrayList<>(); + nodeList.add(node); + return new NodesBuilder().setNode(nodeList).build(); + } + +} 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 index 000000000..3e76591f7 --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayContextListenerTest.java @@ -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 rootNode; + private Set> changes; + + private DataBroker dataProvider; + private SwitchManager switchManager; + + private InstanceIdentifier 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 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 rootPath = + new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, rootIdentifier); + + DataTreeModification 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 index 000000000..78e646a73 --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3ContextListenerTest.java @@ -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 rootNode; + private Set> changes; + + private DataBroker dataProvider; + private SwitchManager switchManager; + + private InstanceIdentifier 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 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 rootPath = + new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, rootIdentifier); + + DataTreeModification 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 index 000000000..2d03a120b --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/endpoint/OfOverlayL3NatAugTest.java @@ -0,0 +1,80 @@ +/* + * 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.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; + +import org.junit.Before; +import org.junit.Test; +import org.opendaylight.groupbasedpolicy.api.EpRendererAugmentationRegistry; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddressInput; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddressInputBuilder; + +public class OfOverlayL3NatAugTest { + + private OfOverlayL3NatAug ofOverlayL3NatAug; + private EpRendererAugmentationRegistry epRendererAugmentationRegistry; + + @Before + public void init() { + epRendererAugmentationRegistry = mock(EpRendererAugmentationRegistry.class); + ofOverlayL3NatAug = new OfOverlayL3NatAug(epRendererAugmentationRegistry); + } + + @Test + public void testConstructor() throws Exception { + OfOverlayL3NatAug other = new OfOverlayL3NatAug(epRendererAugmentationRegistry); + other.close(); + } + + @Test + public void testBuildEndpointAugmentation() { + RegisterEndpointInput input = new RegisterEndpointInputBuilder().build(); + // no op + assertNull(ofOverlayL3NatAug.buildEndpointAugmentation(input)); + } + + @Test + public void testBuildEndpointL3Augmentation() { + NatAddressInput natAddressInput = new NatAddressInputBuilder().setNatAddress( + new IpAddress(new Ipv4Address("10.0.0.2"))).build(); + RegisterEndpointInput input = + new RegisterEndpointInputBuilder().addAugmentation(NatAddressInput.class, + natAddressInput).build(); + assertNotNull(ofOverlayL3NatAug.buildEndpointL3Augmentation(input)); + } + + @Test + public void testBuildEndpointL3Augmentation_noAug() { + RegisterEndpointInput input = new RegisterEndpointInputBuilder().build(); + assertNull(ofOverlayL3NatAug.buildEndpointL3Augmentation(input)); + } + + @Test + public void testBuildL3PrefixEndpointAugmentation() { + RegisterL3PrefixEndpointInput input = new RegisterL3PrefixEndpointInputBuilder().build(); + // no op + + assertNull(ofOverlayL3NatAug.buildL3PrefixEndpointAugmentation(input)); + } + + @Test + public void testClose() { + // fail("Not yet implemented"); + } + +} 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 index 000000000..d8b8a1826 --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/BucketsEquivalenceTest.java @@ -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 index 000000000..62ea64bff --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/equivalence/GroupEquivalenceTest.java @@ -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 index 000000000..cbb15daa8 --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientResponseTest.java @@ -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 index 000000000..2c8354829 --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/JsonRestClientTest.java @@ -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 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(); + } + + } +} diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManagerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManagerTest.java index de1f7c2b7..f819633e3 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManagerTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/OFStatisticsManagerTest.java @@ -1,27 +1,85 @@ +/* + * 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.Mockito.mock; +import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import org.junit.Before; import org.junit.Test; import org.opendaylight.groupbasedpolicy.api.StatisticsManager; +import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test.TestUtils; +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.RuleName; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.Classifier; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.ClassifierBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.ResolvedPolicy; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; public class OFStatisticsManagerTest { - ScheduledExecutorService executor; - StatisticsManager statisticsManager; + private final EndpointGroupId consumerEpgId = new EndpointGroupId("consumerEpg1"); + private final EndpointGroupId providerEpgId = new EndpointGroupId("providerEpg1"); + private final ContractId contractId = new ContractId("contract1"); + private final TenantId tenantId = new TenantId("tenant1"); + private final ClassifierName classifierName = ClassifierName.getDefaultInstance("classifier1"); + private final SubjectName subjectName = SubjectName.getDefaultInstance("subject1"); + private final RuleName ruleName = new RuleName("rule1"); + + private InstanceIdentifier rpIid; + private ResolvedPolicy resolvedPolicy; + + private ScheduledExecutorService executor; + private StatisticsManager statisticsManager; + + private OFStatisticsManager ofStatisticsManager; + private Classifier classifier; + private Map, Classifier> classifierByIid; @Before public void init() { executor = mock(ScheduledExecutorService.class); statisticsManager = mock(StatisticsManager.class); + + classifier = new ClassifierBuilder() + .setName(classifierName) + .build(); + resolvedPolicy = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, + consumerEpgId, providerEpgId, classifier); + + rpIid = InstanceIdentifier.create(ResolvedPolicy.class); + + ofStatisticsManager = new OFStatisticsManager(executor, statisticsManager); + ofStatisticsManager.setDelay(20L); + ofStatisticsManager.setSflowCollectorUri("http://localhost:1234"); + + classifierByIid = + ResolvedPolicyClassifierListener.resolveClassifiers(resolvedPolicy, rpIid); } @Test public void testConstructor() throws Exception { - new OFStatisticsManager(executor, statisticsManager); + OFStatisticsManager other = new OFStatisticsManager(executor, statisticsManager); + other.close(); } + @Test + public void testTTT(){ + for (Map.Entry, Classifier> classifierEntry : classifierByIid.entrySet()) { + ofStatisticsManager.pullStatsForClassifier(classifierEntry.getKey(), + classifierEntry.getValue()); + } + } } 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 index 000000000..4c82d62cf --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ProcessDataTaskTest.java @@ -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 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 pair = Pair.of(consEpgKey, provEpgKey); + Set> 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 pair = Pair.of(consEpgKey, provEpgKey); + Set> 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> epgsForContract = new HashSet<>(); + when(OFStatisticsManager.getEpgsForContract(contractId)).thenReturn(epgsForContract); + + task.run(); + } + + @Test + public void testRun_wrongDataResponse() { + when(data.getKey()).thenReturn("1,2"); + task.run(); + } + +} diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTaskTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTaskTest.java index 41bba898d..873b73dc8 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTaskTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ReadGbpFlowCacheTaskTest.java @@ -1,8 +1,14 @@ +/* + * 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.Matchers.anyMap; -import static org.mockito.Matchers.anySet; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; @@ -10,26 +16,30 @@ import static org.mockito.Mockito.when; import javax.ws.rs.core.MultivaluedMap; -import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; +import com.sun.jersey.api.client.ClientResponse; import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; import org.opendaylight.groupbasedpolicy.api.StatisticsManager; public class ReadGbpFlowCacheTaskTest { ReadGbpFlowCacheTask task; + private JsonRestClientResponse response; @Before public void init() { StatisticsManager statisticsManager = mock(StatisticsManager.class); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); - JsonRestClientResponse response = mock(JsonRestClientResponse.class); + ClientResponse clientResponse = mock(ClientResponse.class); + response = mock(JsonRestClientResponse.class); when(response.getJsonResponse()).thenReturn("[{\"one\":1, \"two\":2, \"three\":3}]"); when(response.getStatusCode()).thenReturn(200); + when(response.getClientResponse()).thenReturn(clientResponse); SFlowRTConnection connection = mock(SFlowRTConnection.class); - when(connection.get(anyString(), any(MultivaluedMap.class))).thenReturn(response); + when(connection.get(anyString(), Mockito.>any())).thenReturn(response); when(connection.getExecutor()).thenReturn(executor); doNothing().when(executor).execute(any(Runnable.class)); @@ -38,7 +48,18 @@ public class ReadGbpFlowCacheTaskTest { @Test public void testRun() { + task.run(); + } + + @Test + public void testRun_response300() { + when(response.getStatusCode()).thenReturn(300); + task.run(); + } + @Test + public void testRun_response400() { + when(response.getStatusCode()).thenReturn(400); task.run(); } diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListenerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListenerTest.java index 14baad9ea..430eb59d2 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListenerTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/ResolvedPolicyClassifierListenerTest.java @@ -1,3 +1,11 @@ +/* + * 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.Mockito.mock; 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 index 000000000..ad3ca904f --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SFlowRTConnectionTest.java @@ -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 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.>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.>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.>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.>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.>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); + } + +} diff --git a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SflowClientSettingsListenerTest.java b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SflowClientSettingsListenerTest.java index 349532978..c5e1b2074 100755 --- a/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SflowClientSettingsListenerTest.java +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/statistics/SflowClientSettingsListenerTest.java @@ -1,3 +1,11 @@ +/* + * 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.Mockito.mock; 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 index 000000000..96c774494 --- /dev/null +++ b/renderers/ofoverlay/src/test/java/org/opendaylight/groupbasedpolicy/renderer/ofoverlay/test/TransactionMockUtils.java @@ -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 type of {@code returnObject} + * @throws ExecutionException + * @throws InterruptedException + */ + @SuppressWarnings("unchecked") + public static void setupRoTx(ReadOnlyTransaction roTx, LogicalDatastoreType store, + InstanceIdentifier path, boolean isPresent, T returnObject) + throws ExecutionException, InterruptedException { + + CheckedFuture, ReadFailedException> future = mock(CheckedFuture.class); + when(roTx.read(store, path)).thenReturn(future); + Optional opt = mock(Optional.class); + when(future.get()).thenReturn(opt); + when(opt.isPresent()).thenReturn(isPresent); + if (isPresent) { + when(opt.get()).thenReturn(returnObject); + } + } + +} -- 2.36.6