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.controller.netconf.confignetconfconnector;
11 import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertThat;
14 import static org.junit.Assert.assertTrue;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Matchers.any;
17 import static org.mockito.Matchers.anyString;
18 import static org.mockito.Mockito.doNothing;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.verify;
22 import static org.mockito.Mockito.verifyNoMoreInteractions;
23 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElement;
24 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
25 import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElement;
27 import com.google.common.base.Optional;
28 import com.google.common.base.Preconditions;
29 import com.google.common.collect.BiMap;
30 import com.google.common.collect.HashBiMap;
31 import com.google.common.collect.ImmutableMap;
32 import com.google.common.collect.Lists;
33 import com.google.common.collect.Maps;
34 import com.google.common.collect.Sets;
35 import io.netty.channel.Channel;
36 import java.io.FileNotFoundException;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.math.BigInteger;
40 import java.net.URISyntaxException;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Collection;
44 import java.util.Collections;
45 import java.util.HashSet;
46 import java.util.List;
48 import java.util.Map.Entry;
50 import javax.management.InstanceAlreadyExistsException;
51 import javax.management.InstanceNotFoundException;
52 import javax.management.ObjectName;
53 import javax.xml.parsers.ParserConfigurationException;
54 import org.custommonkey.xmlunit.AbstractNodeTester;
55 import org.custommonkey.xmlunit.NodeTest;
56 import org.custommonkey.xmlunit.NodeTestException;
57 import org.custommonkey.xmlunit.NodeTester;
58 import org.custommonkey.xmlunit.XMLAssert;
59 import org.custommonkey.xmlunit.XMLUnit;
60 import org.hamcrest.CoreMatchers;
61 import org.junit.Before;
62 import org.junit.Ignore;
63 import org.junit.Test;
64 import org.mockito.Mock;
65 import org.mockito.MockitoAnnotations;
66 import org.opendaylight.controller.config.api.ConflictingVersionException;
67 import org.opendaylight.controller.config.api.ValidationException;
68 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
69 import org.opendaylight.controller.config.api.annotations.ServiceInterfaceAnnotation;
70 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
71 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
72 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
73 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
74 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
75 import org.opendaylight.controller.config.yang.test.impl.Deep;
76 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
77 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
78 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
79 import org.opendaylight.controller.config.yang.test.impl.DtoC;
80 import org.opendaylight.controller.config.yang.test.impl.DtoD;
81 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
82 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
83 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
84 import org.opendaylight.controller.config.yang.test.impl.Peers;
85 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
86 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
87 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
88 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
89 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
90 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
91 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Lock;
92 import org.opendaylight.controller.netconf.confignetconfconnector.operations.UnLock;
93 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
94 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
95 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
96 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
97 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
98 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
99 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
100 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
101 import org.opendaylight.controller.netconf.impl.NetconfServerSession;
102 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListener;
103 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
104 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
105 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
106 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
107 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
108 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
109 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
110 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
111 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
112 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
113 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
114 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
115 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
116 import org.opendaylight.yangtools.yang.model.api.Module;
117 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
118 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
119 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
120 import org.osgi.framework.Filter;
121 import org.osgi.framework.ServiceListener;
122 import org.osgi.framework.ServiceReference;
123 import org.slf4j.Logger;
124 import org.slf4j.LoggerFactory;
125 import org.w3c.dom.Document;
126 import org.w3c.dom.Element;
127 import org.w3c.dom.Node;
128 import org.w3c.dom.NodeList;
129 import org.w3c.dom.Text;
130 import org.w3c.dom.traversal.DocumentTraversal;
131 import org.xml.sax.SAXException;
134 public class NetconfMappingTest extends AbstractConfigTest {
135 private static final Logger LOG = LoggerFactory.getLogger(NetconfMappingTest.class);
137 private static final String INSTANCE_NAME = "instance-from-code";
138 private static final String NETCONF_SESSION_ID = "foo";
139 private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
140 private NetconfTestImplModuleFactory factory;
141 private DepTestImplModuleFactory factory2;
142 private IdentityTestModuleFactory factory3;
143 private TestImplModuleFactory factory4;
146 YangStoreContext yangStoreSnapshot;
148 NetconfOperationRouter netconfOperationRouter;
150 AggregatedNetconfOperationServiceFactory netconfOperationServiceSnapshot;
152 private AutoCloseable sessionCloseable;
154 private TransactionProvider transactionProvider;
157 public void setUp() throws Exception {
158 MockitoAnnotations.initMocks(this);
161 final Filter filter = mock(Filter.class);
162 doReturn(filter).when(mockedContext).createFilter(anyString());
163 doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
164 doReturn(new ServiceReference<?>[]{}).when(mockedContext).getServiceReferences(anyString(), anyString());
166 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
167 doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
168 doReturn(new EnumResolver() {
170 public String fromYang(final String enumType, final String enumYangValue) {
171 return Preconditions.checkNotNull(getEnumMapping().get(enumYangValue),
172 "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping());
176 public String toYang(final String enumType, final String enumYangValue) {
177 return Preconditions.checkNotNull(getEnumMapping().inverse().get(enumYangValue),
178 "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping().inverse());
180 }).when(this.yangStoreSnapshot).getEnumResolver();
182 this.factory = new NetconfTestImplModuleFactory();
183 this.factory2 = new DepTestImplModuleFactory();
184 this.factory3 = new IdentityTestModuleFactory();
185 factory4 = new TestImplModuleFactory();
186 doNothing().when(sessionCloseable).close();
188 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
189 this.factory3, factory4));
191 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
194 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
195 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
197 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
198 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
199 setModule(mxBean, transaction, instanceName + "_dep");
202 for (Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
203 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
204 transaction.saveServiceReference(
205 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
209 transaction.commit();
214 public void testIdentityRefs() throws Exception {
215 edit("netconfMessages/editConfig_identities.xml");
222 protected BindingRuntimeContext getBindingRuntimeContext() {
223 final BindingRuntimeContext ret = super.getBindingRuntimeContext();
224 doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME);
225 doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME);
230 public void testServicePersistance() throws Exception {
231 createModule(INSTANCE_NAME);
233 edit("netconfMessages/editConfig.xml");
234 Document config = getConfigCandidate();
235 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
236 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
237 "ref_from_code_to_instance-from-code_1"));
240 edit("netconfMessages/editConfig_addServiceName.xml");
241 config = getConfigCandidate();
242 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
243 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
244 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
246 edit("netconfMessages/editConfig_addServiceNameOnTest.xml");
247 config = getConfigCandidate();
248 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
249 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
250 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
253 config = getConfigRunning();
254 assertCorrectRefNamesForDependencies(config);
255 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
256 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
257 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
259 edit("netconfMessages/editConfig_replace_default.xml");
260 config = getConfigCandidate();
261 assertCorrectServiceNames(config, Collections.<String>emptySet());
263 edit("netconfMessages/editConfig_remove.xml");
264 config = getConfigCandidate();
265 assertCorrectServiceNames(config, Collections.<String>emptySet());
268 config = getConfigCandidate();
269 assertCorrectServiceNames(config, Collections.<String>emptySet());
274 public void testUnLock() throws Exception {
275 assertTrue(NetconfMessageUtil.isOKMessage(lockCandidate()));
276 assertTrue(NetconfMessageUtil.isOKMessage(unlockCandidate()));
279 private void assertCorrectRefNamesForDependencies(Document config) throws NodeTestException {
280 NodeList modulesList = config.getElementsByTagName("modules");
281 assertEquals(1, modulesList.getLength());
283 NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
284 NodeTester tester = new AbstractNodeTester() {
285 private int defaultRefNameCount = 0;
286 private int userRefNameCount = 0;
289 public void testText(Text text) throws NodeTestException {
290 if(text.getData().equals("ref_dep2")) {
291 defaultRefNameCount++;
292 } else if(text.getData().equals("ref_dep_user_two")) {
298 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
299 assertEquals(0, defaultRefNameCount);
300 assertEquals(2, userRefNameCount);
303 nt.performTest(tester, Node.TEXT_NODE);
306 private void assertCorrectServiceNames(Document configCandidate, Set<String> refNames) throws NodeTestException {
307 final Set<String> refNames2 = new HashSet<>(refNames);
308 NodeList servicesNodes = configCandidate.getElementsByTagName("services");
309 assertEquals(1, servicesNodes.getLength());
311 NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
312 NodeTester tester = new AbstractNodeTester() {
315 public void testElement(Element element) throws NodeTestException {
316 if(element.getNodeName() != null) {
317 if(element.getNodeName().equals("name")) {
318 String elmText = element.getTextContent();
319 if(refNames2.contains(elmText)) {
320 refNames2.remove(elmText);
322 throw new NodeTestException("Unexpected services defined: " + elmText);
329 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
330 assertEquals(Collections.<String>emptySet(), refNames2);
331 assertTrue(refNames2.toString(), refNames2.isEmpty());
334 nt.performTest(tester, Node.ELEMENT_NODE);
338 public void testConfigNetconfUnionTypes() throws Exception {
340 createModule(INSTANCE_NAME);
342 edit("netconfMessages/editConfig.xml");
344 Document response = getConfigRunning();
345 Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
346 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
348 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
351 edit("netconfMessages/editConfig_setUnions.xml");
353 response = getConfigRunning();
354 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
355 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
360 public void testConfigNetconf() throws Exception {
362 createModule(INSTANCE_NAME);
364 edit("netconfMessages/editConfig.xml");
365 Document configCandidate = getConfigCandidate();
366 checkBinaryLeafEdited(configCandidate);
369 // default-operation:none, should not affect binary leaf
370 edit("netconfMessages/editConfig_none.xml");
371 checkBinaryLeafEdited(getConfigCandidate());
375 Document response = getConfigRunning();
377 checkBinaryLeafEdited(response);
378 checkTypeConfigAttribute(response);
379 checkTypedefs(response);
380 checkTestingDeps(response);
382 checkBigDecimal(response);
384 edit("netconfMessages/editConfig_remove.xml");
387 assertXMLEqual(getConfigCandidate(), getConfigRunning());
389 final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
390 XMLUnit.setIgnoreWhitespace(true);
391 assertXMLEqual(expectedResult, getConfigRunning());
392 assertXMLEqual(expectedResult, getConfigCandidate());
394 edit("netconfMessages/editConfig_none.xml");
396 verify(sessionCloseable).close();
397 verifyNoMoreInteractions(netconfOperationRouter);
398 verifyNoMoreInteractions(netconfOperationServiceSnapshot);
401 private void checkBigDecimal(Document response) throws NodeTestException, SAXException, IOException {
402 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
404 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
408 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
410 final Channel channel = mock(Channel.class);
411 doReturn("channel").when(channel).toString();
412 final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
413 final NetconfServerSession session =
414 new NetconfServerSession(listener, channel, 1L,
415 NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
416 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
417 closeOp.setNetconfSession(session);
418 executeOp(closeOp, "netconfMessages/closeSession.xml");
421 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
422 NetconfDocumentedException {
423 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
425 executeOp(editOp, resource);
428 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
429 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
430 executeOp(commitOp, "netconfMessages/commit.xml");
433 private Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
434 Lock commitOp = new Lock(NETCONF_SESSION_ID);
435 return executeOp(commitOp, "netconfMessages/lock.xml");
438 private Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
439 UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
440 return executeOp(commitOp, "netconfMessages/unlock.xml");
443 private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
444 NetconfDocumentedException {
445 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
446 configRegistryClient, NETCONF_SESSION_ID);
447 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
450 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
451 NetconfDocumentedException {
452 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
453 configRegistryClient, NETCONF_SESSION_ID);
454 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
457 @Ignore("second edit message corrupted")
458 @Test(expected = NetconfDocumentedException.class)
459 public void testConfigNetconfReplaceDefaultEx() throws Exception {
461 createModule(INSTANCE_NAME);
463 edit("netconfMessages/editConfig.xml");
464 edit("netconfMessages/editConfig_replace_default_ex.xml");
468 public void testConfigNetconfReplaceDefault() throws Exception {
470 createModule(INSTANCE_NAME);
472 edit("netconfMessages/editConfig.xml");
474 Document response = getConfigRunning();
475 final int allInstances = response.getElementsByTagName("module").getLength();
477 edit("netconfMessages/editConfig_replace_default.xml");
480 response = getConfigRunning();
482 final int afterReplace = response.getElementsByTagName("module").getLength();
483 assertEquals(4, allInstances);
484 assertEquals(2, afterReplace);
488 public void testSameAttrDifferentNamespaces() throws Exception {
490 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
492 } catch (NetconfDocumentedException e) {
493 String message = e.getMessage();
494 assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
495 assertContainsString(message, TEST_NAMESPACE);
496 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
501 public void testDifferentNamespaceInTO() throws Exception {
503 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
505 } catch (NetconfDocumentedException e) {
506 String message = e.getMessage();
507 assertContainsString(message, "Unrecognised elements");
508 assertContainsString(message, "simple-int2");
509 assertContainsString(message, "dto_d");
514 public void testSameAttrDifferentNamespacesList() throws Exception {
516 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
518 } catch (NetconfDocumentedException e) {
519 String message = e.getMessage();
520 assertContainsString(message, "Element allow-user present multiple times with different namespaces");
521 assertContainsString(message, TEST_NAMESPACE);
522 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
527 public void testTypeNameConfigAttributeMatching() throws Exception {
528 edit("netconfMessages/editConfig.xml");
530 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
533 Document response = getConfigRunning();
534 checkTypeConfigAttribute(response);
537 // TODO add <modules operation="replace"> functionality
538 @Test(expected = NetconfDocumentedException.class)
539 public void testConfigNetconfReplaceModuleEx() throws Exception {
541 createModule(INSTANCE_NAME);
543 edit("netconfMessages/editConfig.xml");
544 edit("netconfMessages/editConfig_replace_module_ex.xml");
548 public void testUnrecognisedConfigElements() throws Exception {
550 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
551 final int TESTS_COUNT = 8;
553 for (int i = 0; i < TESTS_COUNT; i++) {
554 String file = String.format(format, i + 1);
555 LOG.info("Reading {}", file);
558 } catch (NetconfDocumentedException e) {
559 assertContainsString(e.getMessage(), "Unrecognised elements");
560 assertContainsString(e.getMessage(), "unknownAttribute");
563 fail("Unrecognised test should throw exception " + file);
570 public void testConfigNetconfReplaceModule() throws Exception {
572 createModule(INSTANCE_NAME);
574 edit("netconfMessages/editConfig.xml");
576 Document response = getConfigRunning();
577 final int allInstances = response.getElementsByTagName("instance").getLength();
579 edit("netconfMessages/editConfig_replace_module.xml");
582 response = getConfigRunning();
583 final int afterReplace = response.getElementsByTagName("instance").getLength();
585 assertEquals(4 + 4 /* Instances from services */, allInstances);
586 assertEquals(3 + 3, afterReplace);
589 @Test(expected = NetconfDocumentedException.class)
590 public void testEx() throws Exception {
596 public void testEx2() throws Exception {
597 assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
600 private Document discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
601 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
602 return executeOp(discardOp, "netconfMessages/discardChanges.xml");
605 private void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
606 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
607 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
610 private void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
612 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
614 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
616 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
618 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
620 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
622 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
625 private void assertContainsString(String string, String substring) {
626 assertThat(string, CoreMatchers.containsString(substring));
629 private void checkEnum(final Document response) throws Exception {
631 String expectedEnumContent = "two";
633 XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
634 getXpathForNetconfImplSubnode(INSTANCE_NAME,"extended-enum"),
638 private void checkTestingDeps(Document response) {
639 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
640 assertEquals(2, testingDepsSize);
643 private String getXpathForNetconfImplSubnode(String instanceName, String subnode) {
644 return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
645 "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
646 "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
647 "/module[name='"+instanceName+"']" +
648 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
649 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:"+subnode;
652 private void checkTypeConfigAttribute(Document response) throws Exception {
654 Map<String,String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
655 "test2", "default-string");
656 for (Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
657 XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
658 getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
663 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
664 final List<InputStream> yangDependencies = getYangs();
666 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
668 YangParserImpl yangParser = new YangParserImpl();
669 final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(yangDependencies).values()));
670 YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
672 public SchemaContext getSchemaContext() {
673 return schemaContext ;
676 final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
677 doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class));
678 yangStoreService.refresh(bindingRuntimeContext);
679 mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
684 private BiMap<String, String> getEnumMapping() {
685 final HashBiMap<String, String> enumBiMap = HashBiMap.create();
686 // Enum constants mapping from yang -> Java and back
687 enumBiMap.put("one", "One");
688 enumBiMap.put("two", "Two");
689 enumBiMap.put("version1", "Version1");
690 enumBiMap.put("version2", "Version2");
694 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
695 SchemaContext resolveSchemaContext = getSchemaContext();
696 return resolveSchemaContext.getModules();
699 private SchemaContext getSchemaContext() throws Exception {
700 final List<InputStream> yangDependencies = getYangs();
701 YangParserImpl parser = new YangParserImpl();
703 Set<Module> allYangModules = parser.parseYangModelsFromStreams(yangDependencies);
705 return parser.resolveSchemaContext(Sets
706 .newHashSet(allYangModules));
710 public void testConfigNetconfRuntime() throws Exception {
712 createModule(INSTANCE_NAME);
714 edit("netconfMessages/editConfig.xml");
715 checkBinaryLeafEdited(getConfigCandidate());
719 Document response = get();
721 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
723 assertEquals(2, getElementsSize(response, "asdf"));
724 // data from running config
725 assertEquals(2, getElementsSize(response, "simple-short"));
727 assertEquals(8, getElementsSize(response, "inner-running-data"));
728 assertEquals(8, getElementsSize(response, "deep2"));
729 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
730 assertEquals(8 * 4, getElementsSize(response, "deep3"));
731 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
732 assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
733 assertEquals(8, getElementsSize(response, "deep4"));
736 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
738 response = executeOp(netconf, "netconfMessages/rpc.xml");
739 assertContainsElementWithText(response, "testarg1");
741 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
742 Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
743 XMLUnit.setIgnoreWhitespace(true);
744 XMLAssert.assertXMLEqual(expectedReplyOk, response);
746 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
747 assertContainsElementWithText(response, "true");
749 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
750 assertContainsElementWithText(response, "1");
751 assertContainsElementWithText(response, "2");
754 private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
755 Get getOp = new Get(transactionProvider, yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
756 return executeOp(getOp, "netconfMessages/get.xml");
759 private int getElementsSize(Document response, String elementName) {
760 return response.getElementsByTagName(elementName).getLength();
763 private int getElementsSize(Document response, String elementName, String namespace) {
764 return response.getElementsByTagNameNS(namespace, elementName).getLength();
767 private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
768 SAXException, IOException, NetconfDocumentedException {
770 final Document request = XmlFileLoader.xmlFileToDocument(filename);
772 LOG.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
773 HandlingPriority priority = op.canHandle(request);
775 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
777 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
778 LOG.debug("Got response\n{}", XmlUtil.toString(response));
782 private List<InputStream> getYangs() throws FileNotFoundException {
783 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
784 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
785 "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types.yang");
786 final Collection<InputStream> yangDependencies = new ArrayList<>();
787 for (String path : paths) {
788 final InputStream is = Preconditions
789 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
790 yangDependencies.add(is);
792 return Lists.newArrayList(yangDependencies);
795 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, String depName)
796 throws InstanceAlreadyExistsException, InstanceNotFoundException {
797 mxBean.setSimpleInt((long) 44);
798 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
799 final DtoD dtob = getDtoD();
800 mxBean.setDtoD(dtob);
802 final DtoC dtoa = getDtoC();
803 mxBean.setDtoC(dtoa);
804 mxBean.setSimpleBoolean(false);
806 final Peers p1 = new Peers();
809 p1.setSimpleInt3(456);
810 final Peers p2 = new Peers();
812 p2.setPort("port23");
813 p2.setSimpleInt3(456);
814 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
816 mxBean.setSimpleLong(454545L);
817 mxBean.setSimpleLong2(44L);
818 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
819 mxBean.setSimpleByte(new Byte((byte) 4));
820 mxBean.setSimpleShort(new Short((short) 4));
821 mxBean.setSimpleTest(545);
823 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
824 mxBean.setSimpleList(Lists.<Integer> newArrayList());
826 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
828 for (Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
829 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
830 transaction.saveServiceReference(
831 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
835 mxBean.setTestingDep(testingDepOn);
838 private static DtoD getDtoD() {
839 final DtoD dtob = new DtoD();
840 dtob.setSimpleInt1((long) 444);
841 dtob.setSimpleInt2((long) 4444);
842 dtob.setSimpleInt3(454);
843 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
844 final Deep deep = new Deep();
845 deep.setSimpleInt3(4);
846 dtobInner.setDeep(deep);
847 dtobInner.setSimpleInt3(44);
848 dtobInner.setSimpleList(Lists.newArrayList(4));
849 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
850 dtob.setSimpleList(Lists.newArrayList(4));
854 private static DtoC getDtoC() {
855 final DtoC dtoa = new DtoC();
856 // dtoa.setSimpleArg((long) 55);
857 final DtoAInner dtoAInner = new DtoAInner();
858 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
859 dtoAInnerInner.setSimpleArg(456L);
860 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
861 dtoAInner.setSimpleArg(44L);
862 dtoa.setDtoAInner(dtoAInner);