2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.netconf.confignetconfconnector;
11 import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
12 import static org.hamcrest.CoreMatchers.containsString;
13 import static org.hamcrest.CoreMatchers.not;
14 import static org.junit.Assert.assertEquals;
15 import static org.junit.Assert.assertThat;
16 import static org.junit.Assert.assertTrue;
17 import static org.junit.Assert.fail;
18 import static org.mockito.Matchers.any;
19 import static org.mockito.Matchers.anyString;
20 import static org.mockito.Mockito.doNothing;
21 import static org.mockito.Mockito.doReturn;
22 import static org.mockito.Mockito.doThrow;
23 import static org.mockito.Mockito.mock;
24 import static org.mockito.Mockito.verify;
25 import static org.mockito.Mockito.verifyNoMoreInteractions;
26 import static org.opendaylight.controller.config.util.xml.XmlUtil.readXmlToElement;
27 import static org.opendaylight.netconf.util.test.XmlUnitUtil.assertContainsElement;
28 import static org.opendaylight.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
30 import com.google.common.base.Optional;
31 import com.google.common.base.Preconditions;
32 import com.google.common.collect.BiMap;
33 import com.google.common.collect.HashBiMap;
34 import com.google.common.collect.ImmutableMap;
35 import com.google.common.collect.Lists;
36 import com.google.common.collect.Maps;
37 import com.google.common.collect.Sets;
38 import io.netty.channel.Channel;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.math.BigInteger;
42 import java.net.URISyntaxException;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Collection;
46 import java.util.Collections;
47 import java.util.HashSet;
48 import java.util.List;
50 import java.util.Map.Entry;
52 import java.util.regex.Matcher;
53 import java.util.regex.Pattern;
54 import javax.management.InstanceAlreadyExistsException;
55 import javax.management.InstanceNotFoundException;
56 import javax.management.ObjectName;
57 import javax.xml.parsers.ParserConfigurationException;
58 import org.custommonkey.xmlunit.AbstractNodeTester;
59 import org.custommonkey.xmlunit.NodeTest;
60 import org.custommonkey.xmlunit.NodeTestException;
61 import org.custommonkey.xmlunit.NodeTester;
62 import org.custommonkey.xmlunit.XMLAssert;
63 import org.custommonkey.xmlunit.XMLUnit;
64 import org.junit.Before;
65 import org.junit.Ignore;
66 import org.junit.Test;
67 import org.mockito.Mock;
68 import org.mockito.MockitoAnnotations;
69 import org.opendaylight.controller.config.api.ConflictingVersionException;
70 import org.opendaylight.controller.config.api.ValidationException;
71 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
72 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
73 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
74 import org.opendaylight.controller.config.facade.xml.osgi.EnumResolver;
75 import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
76 import org.opendaylight.controller.config.facade.xml.transactions.TransactionProvider;
77 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
78 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
79 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
80 import org.opendaylight.controller.config.util.xml.DocumentedException;
81 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
82 import org.opendaylight.controller.config.util.xml.XmlUtil;
83 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
84 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
85 import org.opendaylight.controller.config.yang.test.impl.Deep;
86 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
87 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
88 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
89 import org.opendaylight.controller.config.yang.test.impl.DtoC;
90 import org.opendaylight.controller.config.yang.test.impl.DtoD;
91 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
92 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
93 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
94 import org.opendaylight.controller.config.yang.test.impl.Peers;
95 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
96 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
97 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
98 import org.opendaylight.netconf.confignetconfconnector.operations.Commit;
99 import org.opendaylight.netconf.confignetconfconnector.operations.DiscardChanges;
100 import org.opendaylight.netconf.confignetconfconnector.operations.Lock;
101 import org.opendaylight.netconf.confignetconfconnector.operations.UnLock;
102 import org.opendaylight.netconf.confignetconfconnector.operations.editconfig.EditConfig;
103 import org.opendaylight.netconf.confignetconfconnector.operations.get.Get;
104 import org.opendaylight.netconf.confignetconfconnector.operations.getconfig.GetConfig;
105 import org.opendaylight.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
106 import org.opendaylight.netconf.impl.NetconfServerSession;
107 import org.opendaylight.netconf.impl.NetconfServerSessionListener;
108 import org.opendaylight.netconf.impl.mapping.operations.DefaultCloseSession;
109 import org.opendaylight.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
110 import org.opendaylight.netconf.impl.osgi.NetconfOperationRouter;
111 import org.opendaylight.netconf.mapping.api.HandlingPriority;
112 import org.opendaylight.netconf.mapping.api.NetconfOperation;
113 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
114 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
115 import org.opendaylight.netconf.util.test.XmlFileLoader;
116 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
117 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
118 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
119 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
120 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
121 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
122 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
123 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
124 import org.osgi.framework.Filter;
125 import org.osgi.framework.ServiceListener;
126 import org.osgi.framework.ServiceReference;
127 import org.slf4j.Logger;
128 import org.slf4j.LoggerFactory;
129 import org.w3c.dom.Document;
130 import org.w3c.dom.Element;
131 import org.w3c.dom.Node;
132 import org.w3c.dom.NodeList;
133 import org.w3c.dom.Text;
134 import org.w3c.dom.traversal.DocumentTraversal;
135 import org.xml.sax.SAXException;
138 public class NetconfMappingTest extends AbstractConfigTest {
139 private static final Logger LOG = LoggerFactory.getLogger(NetconfMappingTest.class);
141 private static final String INSTANCE_NAME = "instance-from-code";
142 private static final String NETCONF_SESSION_ID = "foo";
143 private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
144 private NetconfTestImplModuleFactory factory;
145 private DepTestImplModuleFactory factory2;
146 private IdentityTestModuleFactory factory3;
147 private TestImplModuleFactory factory4;
150 YangStoreService yangStoreSnapshot;
152 NetconfOperationRouter netconfOperationRouter;
154 AggregatedNetconfOperationServiceFactory netconfOperationServiceSnapshot;
156 private AutoCloseable sessionCloseable;
158 private TransactionProvider transactionProvider;
160 private ConfigSubsystemFacade configSubsystemFacade;
163 public void setUp() throws Exception {
164 MockitoAnnotations.initMocks(this);
167 final Filter filter = mock(Filter.class);
168 doReturn(filter).when(mockedContext).createFilter(anyString());
169 doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
170 doReturn(new ServiceReference<?>[]{}).when(mockedContext).getServiceReferences(anyString(), anyString());
172 doReturn(yangStoreSnapshot).when(yangStoreSnapshot).getCurrentSnapshot();
173 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
174 doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
175 doReturn(new EnumResolver() {
177 public String fromYang(final String enumType, final String enumYangValue) {
178 return Preconditions.checkNotNull(getEnumMapping().get(enumYangValue),
179 "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping());
183 public String toYang(final String enumType, final String enumYangValue) {
184 return Preconditions.checkNotNull(getEnumMapping().inverse().get(enumYangValue),
185 "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping().inverse());
187 }).when(this.yangStoreSnapshot).getEnumResolver();
189 this.factory = new NetconfTestImplModuleFactory();
190 this.factory2 = new DepTestImplModuleFactory();
191 this.factory3 = new IdentityTestModuleFactory();
192 factory4 = new TestImplModuleFactory();
193 doNothing().when(sessionCloseable).close();
195 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
196 this.factory3, factory4));
198 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
200 configSubsystemFacade = new ConfigSubsystemFacade(configRegistryClient, configRegistryClient, yangStoreSnapshot, "mapping-test");
203 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
204 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
206 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
207 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
208 setModule(mxBean, transaction, instanceName + "_dep");
211 for (final Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
212 final ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
213 transaction.saveServiceReference(
214 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
218 transaction.commit();
223 public void testIdentityRefs() throws Exception {
224 edit("netconfMessages/editConfig_identities.xml");
227 Document configRunning = getConfigRunning();
228 String asString = XmlUtil.toString(configRunning);
229 assertThat(asString, containsString("test-identity2"));
230 assertThat(asString, containsString("test-identity1"));
231 assertEquals(2, countSubstringOccurence(asString, "</identities>"));
233 edit("netconfMessages/editConfig_identities_inner_replace.xml");
235 configRunning = getConfigRunning();
236 asString = XmlUtil.toString(configRunning);
237 // test-identity1 was removed by replace
238 assertThat(asString, not(containsString("test-identity2")));
239 // now only 1 identities entry is present
240 assertEquals(1, countSubstringOccurence(asString, "</identities>"));
243 private static int countSubstringOccurence(final String string, final String substring) {
244 final Matcher matches = Pattern.compile(substring).matcher(string);
246 while (matches.find()) {
253 protected BindingRuntimeContext getBindingRuntimeContext() {
254 final BindingRuntimeContext ret = super.getBindingRuntimeContext();
255 doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME);
256 doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME);
257 final List<InputStream> streams = getYangs();
259 doReturn(YangParserTestUtils.parseYangStreams(streams)).when(ret).getSchemaContext();
260 } catch (final ReactorException e) {
261 throw new RuntimeException("Unable to build schema context from " + streams, e);
267 public void testServicePersistance() throws Exception {
268 createModule(INSTANCE_NAME);
270 edit("netconfMessages/editConfig.xml");
271 Document config = getConfigCandidate();
272 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
273 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
274 "ref_from_code_to_instance-from-code_1"));
277 edit("netconfMessages/editConfig_addServiceName.xml");
278 config = getConfigCandidate();
279 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
280 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
281 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
283 edit("netconfMessages/editConfig_addServiceNameOnTest.xml");
284 config = getConfigCandidate();
285 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
286 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
287 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
290 config = getConfigRunning();
291 assertCorrectRefNamesForDependencies(config);
292 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
293 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
294 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
296 edit("netconfMessages/editConfig_removeServiceNameOnTest.xml");
297 config = getConfigCandidate();
298 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
299 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
300 "ref_from_code_to_instance-from-code_1"));
303 edit("netconfMessages/editConfig_removeServiceNameOnTest.xml");
304 fail("Should've failed, non-existing service instance");
305 } catch (final DocumentedException e) {
306 assertEquals(e.getErrorSeverity(), DocumentedException.ErrorSeverity.ERROR);
307 assertEquals(e.getErrorTag(), DocumentedException.ErrorTag.OPERATION_FAILED);
308 assertEquals(e.getErrorType(), DocumentedException.ErrorType.APPLICATION);
311 edit("netconfMessages/editConfig_replace_default.xml");
312 config = getConfigCandidate();
313 assertCorrectServiceNames(config, Collections.<String>emptySet());
315 edit("netconfMessages/editConfig_remove.xml");
316 config = getConfigCandidate();
317 assertCorrectServiceNames(config, Collections.<String>emptySet());
320 config = getConfigCandidate();
321 assertCorrectServiceNames(config, Collections.<String>emptySet());
326 public void testUnLock() throws Exception {
327 assertTrue(NetconfMessageUtil.isOKMessage(lockCandidate()));
328 assertTrue(NetconfMessageUtil.isOKMessage(unlockCandidate()));
331 private static void assertCorrectRefNamesForDependencies(final Document config) throws NodeTestException {
332 final NodeList modulesList = config.getElementsByTagName("modules");
333 assertEquals(1, modulesList.getLength());
335 final NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
336 final NodeTester tester = new AbstractNodeTester() {
337 private int defaultRefNameCount = 0;
338 private int userRefNameCount = 0;
341 public void testText(final Text text) throws NodeTestException {
342 if(text.getData().equals("ref_dep2")) {
343 defaultRefNameCount++;
344 } else if(text.getData().equals("ref_dep_user_two")) {
350 public void noMoreNodes(final NodeTest forTest) throws NodeTestException {
351 assertEquals(0, defaultRefNameCount);
352 assertEquals(2, userRefNameCount);
355 nt.performTest(tester, Node.TEXT_NODE);
358 private static void assertCorrectServiceNames(final Document configCandidate, final Set<String> refNames) throws NodeTestException {
359 final Set<String> refNames2 = new HashSet<>(refNames);
360 final NodeList servicesNodes = configCandidate.getElementsByTagName("services");
361 assertEquals(1, servicesNodes.getLength());
363 final NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
364 final NodeTester tester = new AbstractNodeTester() {
367 public void testElement(final Element element) throws NodeTestException {
368 if(element.getNodeName() != null) {
369 if(element.getNodeName().equals("name")) {
370 final String elmText = element.getTextContent();
371 if(refNames2.contains(elmText)) {
372 refNames2.remove(elmText);
374 throw new NodeTestException("Unexpected services defined: " + elmText);
381 public void noMoreNodes(final NodeTest forTest) throws NodeTestException {
382 assertEquals(Collections.<String>emptySet(), refNames2);
383 assertTrue(refNames2.toString(), refNames2.isEmpty());
386 nt.performTest(tester, Node.ELEMENT_NODE);
390 public void testConfigNetconfUnionTypes() throws Exception {
392 createModule(INSTANCE_NAME);
394 edit("netconfMessages/editConfig.xml");
396 Document response = getConfigRunning();
397 final Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
398 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
400 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
403 edit("netconfMessages/editConfig_setUnions.xml");
405 response = getConfigRunning();
406 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
407 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
412 public void testConfigNetconf() throws Exception {
414 createModule(INSTANCE_NAME);
416 edit("netconfMessages/editConfig.xml");
417 final Document configCandidate = getConfigCandidate();
418 checkBinaryLeafEdited(configCandidate);
421 // default-operation:none, should not affect binary leaf
422 edit("netconfMessages/editConfig_none.xml");
423 checkBinaryLeafEdited(getConfigCandidate());
427 final Document response = getConfigRunning();
429 checkBinaryLeafEdited(response);
430 checkTypeConfigAttribute(response);
431 checkTypedefs(response);
432 checkTestingDeps(response);
434 checkBigDecimal(response);
436 edit("netconfMessages/editConfig_remove.xml");
439 assertXMLEqual(getConfigCandidate(), getConfigRunning());
441 final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
442 XMLUnit.setIgnoreWhitespace(true);
443 assertXMLEqual(expectedResult, getConfigRunning());
444 assertXMLEqual(expectedResult, getConfigCandidate());
446 edit("netconfMessages/editConfig_none.xml");
448 verify(sessionCloseable).close();
449 verifyNoMoreInteractions(netconfOperationRouter);
450 verifyNoMoreInteractions(netconfOperationServiceSnapshot);
453 private static void checkBigDecimal(final Document response) throws NodeTestException, SAXException, IOException {
454 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
456 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
459 private void closeSession() throws ParserConfigurationException, SAXException,
460 IOException, DocumentedException {
461 final Channel channel = mock(Channel.class);
462 doReturn("channel").when(channel).toString();
463 final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
464 final NetconfServerSession session =
465 new NetconfServerSession(listener, channel, 1L,
466 NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
467 final DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
468 closeOp.setNetconfSession(session);
469 executeOp(closeOp, "netconfMessages/closeSession.xml");
472 private void edit(final String resource) throws ParserConfigurationException, SAXException, IOException,
473 DocumentedException {
474 final EditConfig editOp = new EditConfig(configSubsystemFacade, NETCONF_SESSION_ID);
475 executeOp(editOp, resource);
478 private void commit() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
479 final Commit commitOp = new Commit(configSubsystemFacade, NETCONF_SESSION_ID);
480 executeOp(commitOp, "netconfMessages/commit.xml");
483 private static Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
484 final Lock commitOp = new Lock(NETCONF_SESSION_ID);
485 return executeOp(commitOp, "netconfMessages/lock.xml");
488 private static Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
489 final UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
490 return executeOp(commitOp, "netconfMessages/unlock.xml");
493 private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
494 DocumentedException {
495 final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(), NETCONF_SESSION_ID);
496 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
499 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
500 DocumentedException {
501 final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(), NETCONF_SESSION_ID);
502 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
505 @Ignore("second edit message corrupted")
506 @Test(expected = DocumentedException.class)
507 public void testConfigNetconfReplaceDefaultEx() throws Exception {
509 createModule(INSTANCE_NAME);
511 edit("netconfMessages/editConfig.xml");
512 edit("netconfMessages/editConfig_replace_default_ex.xml");
516 public void testConfigNetconfReplaceDefault() throws Exception {
518 createModule(INSTANCE_NAME);
520 edit("netconfMessages/editConfig.xml");
522 Document response = getConfigRunning();
523 final int allInstances = response.getElementsByTagName("module").getLength();
525 edit("netconfMessages/editConfig_replace_default.xml");
528 response = getConfigRunning();
530 final int afterReplace = response.getElementsByTagName("module").getLength();
531 assertEquals(4, allInstances);
532 assertEquals(2, afterReplace);
536 public void testSameAttrDifferentNamespaces() throws Exception {
538 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
540 } catch (final DocumentedException e) {
541 final String message = e.getMessage();
542 assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
543 assertContainsString(message, TEST_NAMESPACE);
544 assertContainsString(message, XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
549 public void testDifferentNamespaceInTO() throws Exception {
551 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
553 } catch (final DocumentedException e) {
554 final String message = e.getMessage();
555 assertContainsString(message, "Unrecognised elements");
556 assertContainsString(message, "simple-int2");
557 assertContainsString(message, "dto_d");
562 public void testSameAttrDifferentNamespacesList() throws Exception {
564 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
566 } catch (final DocumentedException e) {
567 final String message = e.getMessage();
568 assertContainsString(message, "Element allow-user present multiple times with different namespaces");
569 assertContainsString(message, TEST_NAMESPACE);
570 assertContainsString(message, XmlMappingConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
575 public void testTypeNameConfigAttributeMatching() throws Exception {
576 edit("netconfMessages/editConfig.xml");
578 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
581 final Document response = getConfigRunning();
582 checkTypeConfigAttribute(response);
585 // TODO add <modules operation="replace"> functionality
586 @Test(expected = DocumentedException.class)
587 public void testConfigNetconfReplaceModuleEx() throws Exception {
589 createModule(INSTANCE_NAME);
591 edit("netconfMessages/editConfig.xml");
592 edit("netconfMessages/editConfig_replace_module_ex.xml");
596 public void testUnrecognisedConfigElements() throws Exception {
598 final String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
599 final int TESTS_COUNT = 8;
601 for (int i = 0; i < TESTS_COUNT; i++) {
602 final String file = String.format(format, i + 1);
603 LOG.info("Reading {}", file);
606 } catch (final DocumentedException e) {
607 assertContainsString(e.getMessage(), "Unrecognised elements");
608 assertContainsString(e.getMessage(), "unknownAttribute");
611 fail("Unrecognised test should throw exception " + file);
618 public void testConfigNetconfReplaceModule() throws Exception {
620 createModule(INSTANCE_NAME);
622 edit("netconfMessages/editConfig.xml");
624 Document response = getConfigRunning();
625 final int allInstances = response.getElementsByTagName("instance").getLength();
627 edit("netconfMessages/editConfig_replace_module.xml");
630 response = getConfigRunning();
631 final int afterReplace = response.getElementsByTagName("instance").getLength();
633 assertEquals(4 + 4 /* Instances from services */, allInstances);
634 assertEquals(3 + 3, afterReplace);
638 public void testEx2() throws Exception {
639 //check abort before tx creation
640 assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
642 //check abort after tx creation
643 edit("netconfMessages/editConfig.xml");
644 assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
648 public void testFailedDiscardChangesAbort() throws Exception {
649 final ConfigSubsystemFacade facade = mock(ConfigSubsystemFacade.class);
650 doThrow(new RuntimeException("Mocked runtime exception, Abort has to fail")).when(facade).abortConfiguration();
652 final DiscardChanges discardOp = new DiscardChanges(facade, NETCONF_SESSION_ID);
655 executeOp(discardOp, "netconfMessages/discardChanges.xml");
656 fail("Should've failed, abort on mocked is supposed to throw RuntimeException");
657 } catch (final DocumentedException e) {
658 assertTrue(e.getErrorTag() == DocumentedException.ErrorTag.OPERATION_FAILED);
659 assertTrue(e.getErrorSeverity() == DocumentedException.ErrorSeverity.ERROR);
660 assertTrue(e.getErrorType() == DocumentedException.ErrorType.APPLICATION);
664 private Document discard() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
665 final DiscardChanges discardOp = new DiscardChanges(configSubsystemFacade, NETCONF_SESSION_ID);
666 return executeOp(discardOp, "netconfMessages/discardChanges.xml");
669 private static void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
670 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
671 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
674 private static void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
676 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
678 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
680 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
682 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
684 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
686 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
689 private static void assertContainsString(final String string, final String substring) {
690 assertThat(string, containsString(substring));
693 private static void checkEnum(final Document response) throws Exception {
695 final String expectedEnumContent = "two";
697 XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
698 getXpathForNetconfImplSubnode(INSTANCE_NAME, "extended-enum"),
702 private static void checkTestingDeps(final Document response) {
703 final int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
704 assertEquals(2, testingDepsSize);
707 private static String getXpathForNetconfImplSubnode(final String instanceName, final String subnode) {
708 return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
709 "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
710 "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
711 "/urn:opendaylight:params:xml:ns:yang:controller:config:module" +
712 "[urn:opendaylight:params:xml:ns:yang:controller:config:name='" + instanceName + "']" +
713 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
714 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:" + subnode;
717 private static void checkTypeConfigAttribute(final Document response) throws Exception {
719 final Map<String, String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
720 "test2", "default-string");
721 for (final Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
722 XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
723 getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
728 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
729 final List<InputStream> yangDependencies = getYangs();
731 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
733 final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(yangDependencies);
734 final YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
735 @Override public SchemaContext getSchemaContext() {
736 return schemaContext;
738 }, mock(SchemaSourceProvider.class));
739 final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
740 doReturn(schemaContext).when(bindingRuntimeContext).getSchemaContext();
741 doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class));
742 yangStoreService.refresh(bindingRuntimeContext);
743 mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
748 private static BiMap<String, String> getEnumMapping() {
749 final HashBiMap<String, String> enumBiMap = HashBiMap.create();
750 // Enum constants mapping from yang -> Java and back
751 enumBiMap.put("one", "One");
752 enumBiMap.put("two", "Two");
753 enumBiMap.put("version1", "Version1");
754 enumBiMap.put("version2", "Version2");
758 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
759 final SchemaContext resolveSchemaContext = YangParserTestUtils.parseYangStreams(getYangs());
760 return resolveSchemaContext.getModules();
764 public void testConfigNetconfRuntime() throws Exception {
766 createModule(INSTANCE_NAME);
768 edit("netconfMessages/editConfig.xml");
769 checkBinaryLeafEdited(getConfigCandidate());
773 Document response = get();
775 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
777 assertEquals(2, getElementsSize(response, "asdf"));
778 // data from running config
779 assertEquals(2, getElementsSize(response, "simple-short"));
781 assertEquals(8, getElementsSize(response, "inner-running-data"));
782 assertEquals(8, getElementsSize(response, "deep2"));
783 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
784 assertEquals(8 * 4, getElementsSize(response, "deep3"));
785 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
786 assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
787 assertEquals(8, getElementsSize(response, "deep4"));
790 final RuntimeRpc netconf = new RuntimeRpc(configSubsystemFacade, NETCONF_SESSION_ID);
792 response = executeOp(netconf, "netconfMessages/rpc.xml");
793 assertContainsElementWithText(response, "testarg1");
795 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
796 final Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
797 XMLUnit.setIgnoreWhitespace(true);
798 XMLAssert.assertXMLEqual(expectedReplyOk, response);
800 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
801 assertContainsElementWithText(response, "true");
803 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
804 assertContainsElementWithText(response, "1");
805 assertContainsElementWithText(response, "2");
808 private Document get() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
809 final Get getOp = new Get(configSubsystemFacade, NETCONF_SESSION_ID);
810 return executeOp(getOp, "netconfMessages/get.xml");
813 private static int getElementsSize(final Document response, final String elementName) {
814 return response.getElementsByTagName(elementName).getLength();
817 private static int getElementsSize(final Document response, final String elementName, final String namespace) {
818 return response.getElementsByTagNameNS(namespace, elementName).getLength();
821 private static Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
822 SAXException, IOException, DocumentedException {
824 final Document request = XmlFileLoader.xmlFileToDocument(filename);
826 LOG.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
827 final HandlingPriority priority = op.canHandle(request);
829 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
831 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
832 LOG.debug("Got response\n{}", XmlUtil.toString(response));
836 private List<InputStream> getYangs() {
837 final List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
838 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
839 "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
840 final Collection<InputStream> yangDependencies = new ArrayList<>();
841 for (final String path : paths) {
842 final InputStream is = Preconditions
843 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
844 yangDependencies.add(is);
846 return Lists.newArrayList(yangDependencies);
849 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, final String depName)
850 throws InstanceAlreadyExistsException, InstanceNotFoundException {
851 mxBean.setSimpleInt((long) 44);
852 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
853 final DtoD dtob = getDtoD();
854 mxBean.setDtoD(dtob);
856 final DtoC dtoa = getDtoC();
857 mxBean.setDtoC(dtoa);
858 mxBean.setSimpleBoolean(false);
860 final Peers p1 = new Peers();
863 p1.setSimpleInt3(456);
864 final Peers p2 = new Peers();
866 p2.setPort("port23");
867 p2.setSimpleInt3(456);
868 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
870 mxBean.setSimpleLong(454545L);
871 mxBean.setSimpleLong2(44L);
872 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
873 mxBean.setSimpleByte(new Byte((byte) 4));
874 mxBean.setSimpleShort(new Short((short) 4));
875 mxBean.setSimpleTest(545);
877 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
878 mxBean.setSimpleList(Lists.<Integer> newArrayList());
880 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
882 for (final Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
883 final ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
884 transaction.saveServiceReference(
885 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
889 mxBean.setTestingDep(testingDepOn);
892 private static DtoD getDtoD() {
893 final DtoD dtob = new DtoD();
894 dtob.setSimpleInt1((long) 444);
895 dtob.setSimpleInt2((long) 4444);
896 dtob.setSimpleInt3(454);
897 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
898 final Deep deep = new Deep();
899 deep.setSimpleInt3(4);
900 dtobInner.setDeep(deep);
901 dtobInner.setSimpleInt3(44);
902 dtobInner.setSimpleList(Lists.newArrayList(4));
903 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
904 dtob.setSimpleList(Lists.newArrayList(4));
908 private static DtoC getDtoC() {
909 final DtoC dtoa = new DtoC();
910 // dtoa.setSimpleArg((long) 55);
911 final DtoAInner dtoAInner = new DtoAInner();
912 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
913 dtoAInnerInner.setSimpleArg(456L);
914 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
915 dtoAInner.setSimpleArg(44L);
916 dtoa.setDtoAInner(dtoAInner);