Fix license header violations in netconf
[controller.git] / opendaylight / netconf / config-netconf-connector / src / test / java / org / opendaylight / controller / netconf / confignetconfconnector / NetconfMappingTest.java
index e1ffcdddffc679e33ccd823322ba2dce8cfdf199..388a131a5611642d58cb046d45b1b6da4fe9a967 100644 (file)
@@ -9,6 +9,8 @@
 package org.opendaylight.controller.netconf.confignetconfconnector;
 
 import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.not;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
@@ -17,6 +19,7 @@ import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
@@ -26,10 +29,13 @@ import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElem
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import com.google.common.collect.BiMap;
+import com.google.common.collect.HashBiMap;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
+import io.netty.channel.Channel;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
@@ -44,6 +50,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import javax.management.InstanceAlreadyExistsException;
 import javax.management.InstanceNotFoundException;
 import javax.management.ObjectName;
@@ -54,7 +62,6 @@ import org.custommonkey.xmlunit.NodeTestException;
 import org.custommonkey.xmlunit.NodeTester;
 import org.custommonkey.xmlunit.XMLAssert;
 import org.custommonkey.xmlunit.XMLUnit;
-import org.hamcrest.CoreMatchers;
 import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -82,6 +89,9 @@ import org.opendaylight.controller.config.yang.test.impl.Peers;
 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
+import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
@@ -91,15 +101,19 @@ import org.opendaylight.controller.netconf.confignetconfconnector.operations.edi
 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
+import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
+import org.opendaylight.controller.netconf.impl.NetconfServerSession;
+import org.opendaylight.controller.netconf.impl.NetconfServerSessionListener;
 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
+import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
@@ -158,6 +172,19 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
         doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
         doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
+        doReturn(new EnumResolver() {
+            @Override
+            public String fromYang(final String enumType, final String enumYangValue) {
+                return Preconditions.checkNotNull(getEnumMapping().get(enumYangValue),
+                        "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping());
+            }
+
+            @Override
+            public String toYang(final String enumType, final String enumYangValue) {
+                return Preconditions.checkNotNull(getEnumMapping().inverse().get(enumYangValue),
+                        "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping().inverse());
+            }
+        }).when(this.yangStoreSnapshot).getEnumResolver();
 
         this.factory = new NetconfTestImplModuleFactory();
         this.factory2 = new DepTestImplModuleFactory();
@@ -195,7 +222,29 @@ public class NetconfMappingTest extends AbstractConfigTest {
         edit("netconfMessages/editConfig_identities.xml");
 
         commit();
-        getConfigRunning();
+        Document configRunning = getConfigRunning();
+        String asString = XmlUtil.toString(configRunning);
+        assertThat(asString, containsString("test-identity2"));
+        assertThat(asString, containsString("test-identity1"));
+        assertEquals(2, countSubstringOccurence(asString, "</identities>"));
+
+        edit("netconfMessages/editConfig_identities_inner_replace.xml");
+        commit();
+        configRunning = getConfigRunning();
+        asString = XmlUtil.toString(configRunning);
+        // test-identity1 was removed by replace
+        assertThat(asString, not(containsString("test-identity2")));
+        // now only 1 identities entry is present
+        assertEquals(1, countSubstringOccurence(asString, "</identities>"));
+    }
+
+    private int countSubstringOccurence(final String string, final String substring) {
+        final Matcher matches = Pattern.compile(substring).matcher(string);
+        int count = 0;
+        while (matches.find()) {
+            count++;
+        }
+        return count;
     }
 
     @Override
@@ -236,6 +285,21 @@ public class NetconfMappingTest extends AbstractConfigTest {
                 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
                 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
 
+        edit("netconfMessages/editConfig_removeServiceNameOnTest.xml");
+        config = getConfigCandidate();
+        assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
+                "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
+                "ref_from_code_to_instance-from-code_1"));
+
+        try {
+            edit("netconfMessages/editConfig_removeServiceNameOnTest.xml");
+            fail("Should've failed, non-existing service instance");
+        } catch (NetconfDocumentedException e) {
+            assertEquals(e.getErrorSeverity(), ErrorSeverity.error);
+            assertEquals(e.getErrorTag(), ErrorTag.operation_failed);
+            assertEquals(e.getErrorType(), ErrorType.application);
+        }
+
         edit("netconfMessages/editConfig_replace_default.xml");
         config = getConfigCandidate();
         assertCorrectServiceNames(config, Collections.<String>emptySet());
@@ -387,7 +451,14 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
     private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
             IOException {
+        final Channel channel = mock(Channel.class);
+        doReturn("channel").when(channel).toString();
+        final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
+        final NetconfServerSession session =
+                new NetconfServerSession(listener, channel, 1L,
+                        NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
         DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
+        closeOp.setNetconfSession(session);
         executeOp(closeOp, "netconfMessages/closeSession.xml");
     }
 
@@ -567,9 +638,34 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
     @Test
     public void testEx2() throws Exception {
+        //check abort before tx creation
+        assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
+
+        //check abort after tx creation
+        edit("netconfMessages/editConfig.xml");
         assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
     }
 
+    @Test
+    public void testFailedDiscardChangesAbort() throws Exception {
+
+        TransactionProvider mockedTxProvider = mock(TransactionProvider.class);
+        doThrow(new RuntimeException("Mocked runtime exception, Abort has to fail")).when(mockedTxProvider).abortTransaction();
+        doReturn(Optional.of(ObjectName.getInstance("dummyDomain", "DummyKey", "DummyValue"))).when(mockedTxProvider).getTransaction();
+
+        DiscardChanges discardOp = new DiscardChanges(mockedTxProvider, configRegistryClient, NETCONF_SESSION_ID);
+
+        try {
+            executeOp(discardOp, "netconfMessages/discardChanges.xml");
+            fail("Should've failed, abort on mocked is supposed to throw RuntimeException");
+        } catch (NetconfDocumentedException e) {
+            assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
+            assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
+            assertTrue(e.getErrorType() == ErrorType.application);
+        }
+
+    }
+
     private Document discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
         DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
         return executeOp(discardOp, "netconfMessages/discardChanges.xml");
@@ -590,18 +686,18 @@ public class NetconfMappingTest extends AbstractConfigTest {
         // Default
         assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
 
-        assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">TWO</extended-enum>"));
+        assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
         // Default
-        assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ONE</extended-enum>"));
+        assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
     }
 
     private void assertContainsString(String string, String substring) {
-        assertThat(string, CoreMatchers.containsString(substring));
+        assertThat(string, containsString(substring));
     }
 
     private void checkEnum(final Document response) throws Exception {
 
-        String expectedEnumContent = "TWO";
+        String expectedEnumContent = "two";
 
         XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
                 getXpathForNetconfImplSubnode(INSTANCE_NAME,"extended-enum"),
@@ -646,11 +742,24 @@ public class NetconfMappingTest extends AbstractConfigTest {
                 return schemaContext ;
             }
         }, mockedContext);
+        final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
+        doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class));
+        yangStoreService.refresh(bindingRuntimeContext);
         mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
 
         return mBeanEntries;
     }
 
+    private BiMap<String, String> getEnumMapping() {
+        final HashBiMap<String, String> enumBiMap = HashBiMap.create();
+        // Enum constants mapping from yang -> Java and back
+        enumBiMap.put("one", "One");
+        enumBiMap.put("two", "Two");
+        enumBiMap.put("version1", "Version1");
+        enumBiMap.put("version2", "Version2");
+        return enumBiMap;
+    }
+
     private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
         SchemaContext resolveSchemaContext = getSchemaContext();
         return resolveSchemaContext.getModules();