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.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.mock;
23 import static org.mockito.Mockito.verify;
24 import static org.mockito.Mockito.verifyNoMoreInteractions;
25 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElement;
26 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
27 import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToElement;
29 import com.google.common.base.Optional;
30 import com.google.common.base.Preconditions;
31 import com.google.common.collect.BiMap;
32 import com.google.common.collect.HashBiMap;
33 import com.google.common.collect.ImmutableMap;
34 import com.google.common.collect.Lists;
35 import com.google.common.collect.Maps;
36 import com.google.common.collect.Sets;
37 import io.netty.channel.Channel;
38 import java.io.FileNotFoundException;
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.manager.impl.AbstractConfigTest;
74 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
75 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
76 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
77 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
78 import org.opendaylight.controller.config.yang.test.impl.Deep;
79 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
80 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
81 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
82 import org.opendaylight.controller.config.yang.test.impl.DtoC;
83 import org.opendaylight.controller.config.yang.test.impl.DtoD;
84 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
85 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
86 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
87 import org.opendaylight.controller.config.yang.test.impl.Peers;
88 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
89 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
90 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
91 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
92 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
93 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
94 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Lock;
95 import org.opendaylight.controller.netconf.confignetconfconnector.operations.UnLock;
96 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
97 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
98 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
99 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
100 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.EnumResolver;
101 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreContext;
102 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
103 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
104 import org.opendaylight.controller.netconf.impl.NetconfServerSession;
105 import org.opendaylight.controller.netconf.impl.NetconfServerSessionListener;
106 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
107 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
108 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationRouter;
109 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
110 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
111 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
112 import org.opendaylight.controller.netconf.util.messages.NetconfHelloMessageAdditionalHeader;
113 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
114 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
115 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
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.Module;
120 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
121 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
122 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
123 import org.osgi.framework.Filter;
124 import org.osgi.framework.ServiceListener;
125 import org.osgi.framework.ServiceReference;
126 import org.slf4j.Logger;
127 import org.slf4j.LoggerFactory;
128 import org.w3c.dom.Document;
129 import org.w3c.dom.Element;
130 import org.w3c.dom.Node;
131 import org.w3c.dom.NodeList;
132 import org.w3c.dom.Text;
133 import org.w3c.dom.traversal.DocumentTraversal;
134 import org.xml.sax.SAXException;
137 public class NetconfMappingTest extends AbstractConfigTest {
138 private static final Logger LOG = LoggerFactory.getLogger(NetconfMappingTest.class);
140 private static final String INSTANCE_NAME = "instance-from-code";
141 private static final String NETCONF_SESSION_ID = "foo";
142 private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
143 private NetconfTestImplModuleFactory factory;
144 private DepTestImplModuleFactory factory2;
145 private IdentityTestModuleFactory factory3;
146 private TestImplModuleFactory factory4;
149 YangStoreContext yangStoreSnapshot;
151 NetconfOperationRouter netconfOperationRouter;
153 AggregatedNetconfOperationServiceFactory netconfOperationServiceSnapshot;
155 private AutoCloseable sessionCloseable;
157 private TransactionProvider transactionProvider;
160 public void setUp() throws Exception {
161 MockitoAnnotations.initMocks(this);
164 final Filter filter = mock(Filter.class);
165 doReturn(filter).when(mockedContext).createFilter(anyString());
166 doNothing().when(mockedContext).addServiceListener(any(ServiceListener.class), anyString());
167 doReturn(new ServiceReference<?>[]{}).when(mockedContext).getServiceReferences(anyString(), anyString());
169 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
170 doReturn(getModules()).when(this.yangStoreSnapshot).getModules();
171 doReturn(new EnumResolver() {
173 public String fromYang(final String enumType, final String enumYangValue) {
174 return Preconditions.checkNotNull(getEnumMapping().get(enumYangValue),
175 "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping());
179 public String toYang(final String enumType, final String enumYangValue) {
180 return Preconditions.checkNotNull(getEnumMapping().inverse().get(enumYangValue),
181 "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping().inverse());
183 }).when(this.yangStoreSnapshot).getEnumResolver();
185 this.factory = new NetconfTestImplModuleFactory();
186 this.factory2 = new DepTestImplModuleFactory();
187 this.factory3 = new IdentityTestModuleFactory();
188 factory4 = new TestImplModuleFactory();
189 doNothing().when(sessionCloseable).close();
191 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
192 this.factory3, factory4));
194 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
197 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
198 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
200 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
201 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
202 setModule(mxBean, transaction, instanceName + "_dep");
205 for (Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
206 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
207 transaction.saveServiceReference(
208 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
212 transaction.commit();
217 public void testIdentityRefs() throws Exception {
218 edit("netconfMessages/editConfig_identities.xml");
221 Document configRunning = getConfigRunning();
222 String asString = XmlUtil.toString(configRunning);
223 assertThat(asString, containsString("test-identity2"));
224 assertThat(asString, containsString("test-identity1"));
225 assertEquals(2, countSubstringOccurence(asString, "</identities>"));
227 edit("netconfMessages/editConfig_identities_inner_replace.xml");
229 configRunning = getConfigRunning();
230 asString = XmlUtil.toString(configRunning);
231 // test-identity1 was removed by replace
232 assertThat(asString, not(containsString("test-identity2")));
233 // now only 1 identities entry is present
234 assertEquals(1, countSubstringOccurence(asString, "</identities>"));
237 private int countSubstringOccurence(final String string, final String substring) {
238 final Matcher matches = Pattern.compile(substring).matcher(string);
240 while (matches.find()) {
247 protected BindingRuntimeContext getBindingRuntimeContext() {
248 final BindingRuntimeContext ret = super.getBindingRuntimeContext();
249 doReturn(TestIdentity1.class).when(ret).getIdentityClass(TestIdentity1.QNAME);
250 doReturn(TestIdentity2.class).when(ret).getIdentityClass(TestIdentity2.QNAME);
255 public void testServicePersistance() throws Exception {
256 createModule(INSTANCE_NAME);
258 edit("netconfMessages/editConfig.xml");
259 Document config = getConfigCandidate();
260 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
261 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
262 "ref_from_code_to_instance-from-code_1"));
265 edit("netconfMessages/editConfig_addServiceName.xml");
266 config = getConfigCandidate();
267 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
268 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
269 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
271 edit("netconfMessages/editConfig_addServiceNameOnTest.xml");
272 config = getConfigCandidate();
273 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
274 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
275 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
278 config = getConfigRunning();
279 assertCorrectRefNamesForDependencies(config);
280 assertCorrectServiceNames(config, Sets.newHashSet("user_to_instance_from_code", "ref_dep_user",
281 "ref_dep_user_two", "ref_from_code_to_instance-from-code_dep_1",
282 "ref_from_code_to_instance-from-code_1", "ref_dep_user_another"));
284 edit("netconfMessages/editConfig_replace_default.xml");
285 config = getConfigCandidate();
286 assertCorrectServiceNames(config, Collections.<String>emptySet());
288 edit("netconfMessages/editConfig_remove.xml");
289 config = getConfigCandidate();
290 assertCorrectServiceNames(config, Collections.<String>emptySet());
293 config = getConfigCandidate();
294 assertCorrectServiceNames(config, Collections.<String>emptySet());
299 public void testUnLock() throws Exception {
300 assertTrue(NetconfMessageUtil.isOKMessage(lockCandidate()));
301 assertTrue(NetconfMessageUtil.isOKMessage(unlockCandidate()));
304 private void assertCorrectRefNamesForDependencies(Document config) throws NodeTestException {
305 NodeList modulesList = config.getElementsByTagName("modules");
306 assertEquals(1, modulesList.getLength());
308 NodeTest nt = new NodeTest((DocumentTraversal) config, modulesList.item(0));
309 NodeTester tester = new AbstractNodeTester() {
310 private int defaultRefNameCount = 0;
311 private int userRefNameCount = 0;
314 public void testText(Text text) throws NodeTestException {
315 if(text.getData().equals("ref_dep2")) {
316 defaultRefNameCount++;
317 } else if(text.getData().equals("ref_dep_user_two")) {
323 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
324 assertEquals(0, defaultRefNameCount);
325 assertEquals(2, userRefNameCount);
328 nt.performTest(tester, Node.TEXT_NODE);
331 private void assertCorrectServiceNames(Document configCandidate, Set<String> refNames) throws NodeTestException {
332 final Set<String> refNames2 = new HashSet<>(refNames);
333 NodeList servicesNodes = configCandidate.getElementsByTagName("services");
334 assertEquals(1, servicesNodes.getLength());
336 NodeTest nt = new NodeTest((DocumentTraversal) configCandidate, servicesNodes.item(0));
337 NodeTester tester = new AbstractNodeTester() {
340 public void testElement(Element element) throws NodeTestException {
341 if(element.getNodeName() != null) {
342 if(element.getNodeName().equals("name")) {
343 String elmText = element.getTextContent();
344 if(refNames2.contains(elmText)) {
345 refNames2.remove(elmText);
347 throw new NodeTestException("Unexpected services defined: " + elmText);
354 public void noMoreNodes(NodeTest forTest) throws NodeTestException {
355 assertEquals(Collections.<String>emptySet(), refNames2);
356 assertTrue(refNames2.toString(), refNames2.isEmpty());
359 nt.performTest(tester, Node.ELEMENT_NODE);
363 public void testConfigNetconfUnionTypes() throws Exception {
365 createModule(INSTANCE_NAME);
367 edit("netconfMessages/editConfig.xml");
369 Document response = getConfigRunning();
370 Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
371 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
373 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
376 edit("netconfMessages/editConfig_setUnions.xml");
378 response = getConfigRunning();
379 assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
380 assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
385 public void testConfigNetconf() throws Exception {
387 createModule(INSTANCE_NAME);
389 edit("netconfMessages/editConfig.xml");
390 Document configCandidate = getConfigCandidate();
391 checkBinaryLeafEdited(configCandidate);
394 // default-operation:none, should not affect binary leaf
395 edit("netconfMessages/editConfig_none.xml");
396 checkBinaryLeafEdited(getConfigCandidate());
400 Document response = getConfigRunning();
402 checkBinaryLeafEdited(response);
403 checkTypeConfigAttribute(response);
404 checkTypedefs(response);
405 checkTestingDeps(response);
407 checkBigDecimal(response);
409 edit("netconfMessages/editConfig_remove.xml");
412 assertXMLEqual(getConfigCandidate(), getConfigRunning());
414 final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
415 XMLUnit.setIgnoreWhitespace(true);
416 assertXMLEqual(expectedResult, getConfigRunning());
417 assertXMLEqual(expectedResult, getConfigCandidate());
419 edit("netconfMessages/editConfig_none.xml");
421 verify(sessionCloseable).close();
422 verifyNoMoreInteractions(netconfOperationRouter);
423 verifyNoMoreInteractions(netconfOperationServiceSnapshot);
426 private void checkBigDecimal(Document response) throws NodeTestException, SAXException, IOException {
427 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
429 assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
433 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
435 final Channel channel = mock(Channel.class);
436 doReturn("channel").when(channel).toString();
437 final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
438 final NetconfServerSession session =
439 new NetconfServerSession(listener, channel, 1L,
440 NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
441 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID, sessionCloseable);
442 closeOp.setNetconfSession(session);
443 executeOp(closeOp, "netconfMessages/closeSession.xml");
446 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
447 NetconfDocumentedException {
448 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
450 executeOp(editOp, resource);
453 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
454 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
455 executeOp(commitOp, "netconfMessages/commit.xml");
458 private Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
459 Lock commitOp = new Lock(NETCONF_SESSION_ID);
460 return executeOp(commitOp, "netconfMessages/lock.xml");
463 private Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
464 UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
465 return executeOp(commitOp, "netconfMessages/unlock.xml");
468 private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
469 NetconfDocumentedException {
470 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
471 configRegistryClient, NETCONF_SESSION_ID);
472 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
475 private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
476 NetconfDocumentedException {
477 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
478 configRegistryClient, NETCONF_SESSION_ID);
479 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
482 @Ignore("second edit message corrupted")
483 @Test(expected = NetconfDocumentedException.class)
484 public void testConfigNetconfReplaceDefaultEx() throws Exception {
486 createModule(INSTANCE_NAME);
488 edit("netconfMessages/editConfig.xml");
489 edit("netconfMessages/editConfig_replace_default_ex.xml");
493 public void testConfigNetconfReplaceDefault() throws Exception {
495 createModule(INSTANCE_NAME);
497 edit("netconfMessages/editConfig.xml");
499 Document response = getConfigRunning();
500 final int allInstances = response.getElementsByTagName("module").getLength();
502 edit("netconfMessages/editConfig_replace_default.xml");
505 response = getConfigRunning();
507 final int afterReplace = response.getElementsByTagName("module").getLength();
508 assertEquals(4, allInstances);
509 assertEquals(2, afterReplace);
513 public void testSameAttrDifferentNamespaces() throws Exception {
515 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
517 } catch (NetconfDocumentedException e) {
518 String message = e.getMessage();
519 assertContainsString(message, "Element simpleInt present multiple times with different namespaces");
520 assertContainsString(message, TEST_NAMESPACE);
521 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
526 public void testDifferentNamespaceInTO() throws Exception {
528 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
530 } catch (NetconfDocumentedException e) {
531 String message = e.getMessage();
532 assertContainsString(message, "Unrecognised elements");
533 assertContainsString(message, "simple-int2");
534 assertContainsString(message, "dto_d");
539 public void testSameAttrDifferentNamespacesList() throws Exception {
541 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
543 } catch (NetconfDocumentedException e) {
544 String message = e.getMessage();
545 assertContainsString(message, "Element allow-user present multiple times with different namespaces");
546 assertContainsString(message, TEST_NAMESPACE);
547 assertContainsString(message, XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG);
552 public void testTypeNameConfigAttributeMatching() throws Exception {
553 edit("netconfMessages/editConfig.xml");
555 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
558 Document response = getConfigRunning();
559 checkTypeConfigAttribute(response);
562 // TODO add <modules operation="replace"> functionality
563 @Test(expected = NetconfDocumentedException.class)
564 public void testConfigNetconfReplaceModuleEx() throws Exception {
566 createModule(INSTANCE_NAME);
568 edit("netconfMessages/editConfig.xml");
569 edit("netconfMessages/editConfig_replace_module_ex.xml");
573 public void testUnrecognisedConfigElements() throws Exception {
575 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
576 final int TESTS_COUNT = 8;
578 for (int i = 0; i < TESTS_COUNT; i++) {
579 String file = String.format(format, i + 1);
580 LOG.info("Reading {}", file);
583 } catch (NetconfDocumentedException e) {
584 assertContainsString(e.getMessage(), "Unrecognised elements");
585 assertContainsString(e.getMessage(), "unknownAttribute");
588 fail("Unrecognised test should throw exception " + file);
595 public void testConfigNetconfReplaceModule() throws Exception {
597 createModule(INSTANCE_NAME);
599 edit("netconfMessages/editConfig.xml");
601 Document response = getConfigRunning();
602 final int allInstances = response.getElementsByTagName("instance").getLength();
604 edit("netconfMessages/editConfig_replace_module.xml");
607 response = getConfigRunning();
608 final int afterReplace = response.getElementsByTagName("instance").getLength();
610 assertEquals(4 + 4 /* Instances from services */, allInstances);
611 assertEquals(3 + 3, afterReplace);
614 @Test(expected = NetconfDocumentedException.class)
615 public void testEx() throws Exception {
621 public void testEx2() throws Exception {
622 assertContainsElement(discard(), readXmlToElement("<ok xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
625 private Document discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
626 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
627 return executeOp(discardOp, "netconfMessages/discardChanges.xml");
630 private void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
631 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
632 assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
635 private void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
637 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
639 assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
641 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
643 assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
645 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
647 assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
650 private void assertContainsString(String string, String substring) {
651 assertThat(string, containsString(substring));
654 private void checkEnum(final Document response) throws Exception {
656 String expectedEnumContent = "two";
658 XMLAssert.assertXpathEvaluatesTo(expectedEnumContent,
659 getXpathForNetconfImplSubnode(INSTANCE_NAME,"extended-enum"),
663 private void checkTestingDeps(Document response) {
664 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
665 assertEquals(2, testingDepsSize);
668 private String getXpathForNetconfImplSubnode(String instanceName, String subnode) {
669 return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
670 "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
671 "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
672 "/module[name='"+instanceName+"']" +
673 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
674 "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:"+subnode;
677 private void checkTypeConfigAttribute(Document response) throws Exception {
679 Map<String,String> namesToTypeValues = ImmutableMap.of("instance-from-code", "configAttributeType",
680 "test2", "default-string");
681 for (Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
682 XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
683 getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
688 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
689 final List<InputStream> yangDependencies = getYangs();
691 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
693 YangParserImpl yangParser = new YangParserImpl();
694 final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(yangDependencies).values()));
695 YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
697 public SchemaContext getSchemaContext() {
698 return schemaContext ;
701 final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
702 doReturn(getEnumMapping()).when(bindingRuntimeContext).getEnumMapping(any(Class.class));
703 yangStoreService.refresh(bindingRuntimeContext);
704 mBeanEntries.putAll(yangStoreService.getModuleMXBeanEntryMap());
709 private BiMap<String, String> getEnumMapping() {
710 final HashBiMap<String, String> enumBiMap = HashBiMap.create();
711 // Enum constants mapping from yang -> Java and back
712 enumBiMap.put("one", "One");
713 enumBiMap.put("two", "Two");
714 enumBiMap.put("version1", "Version1");
715 enumBiMap.put("version2", "Version2");
719 private Set<org.opendaylight.yangtools.yang.model.api.Module> getModules() throws Exception {
720 SchemaContext resolveSchemaContext = getSchemaContext();
721 return resolveSchemaContext.getModules();
724 private SchemaContext getSchemaContext() throws Exception {
725 final List<InputStream> yangDependencies = getYangs();
726 YangParserImpl parser = new YangParserImpl();
728 Set<Module> allYangModules = parser.parseYangModelsFromStreams(yangDependencies);
730 return parser.resolveSchemaContext(Sets
731 .newHashSet(allYangModules));
735 public void testConfigNetconfRuntime() throws Exception {
737 createModule(INSTANCE_NAME);
739 edit("netconfMessages/editConfig.xml");
740 checkBinaryLeafEdited(getConfigCandidate());
744 Document response = get();
746 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
748 assertEquals(2, getElementsSize(response, "asdf"));
749 // data from running config
750 assertEquals(2, getElementsSize(response, "simple-short"));
752 assertEquals(8, getElementsSize(response, "inner-running-data"));
753 assertEquals(8, getElementsSize(response, "deep2"));
754 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
755 assertEquals(8 * 4, getElementsSize(response, "deep3"));
756 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
757 assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
758 assertEquals(8, getElementsSize(response, "deep4"));
761 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
763 response = executeOp(netconf, "netconfMessages/rpc.xml");
764 assertContainsElementWithText(response, "testarg1");
766 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
767 Document expectedReplyOk = XmlFileLoader.xmlFileToDocument("netconfMessages/rpc-reply_ok.xml");
768 XMLUnit.setIgnoreWhitespace(true);
769 XMLAssert.assertXMLEqual(expectedReplyOk, response);
771 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
772 assertContainsElementWithText(response, "true");
774 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
775 assertContainsElementWithText(response, "1");
776 assertContainsElementWithText(response, "2");
779 private Document get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
780 Get getOp = new Get(transactionProvider, yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
781 return executeOp(getOp, "netconfMessages/get.xml");
784 private int getElementsSize(Document response, String elementName) {
785 return response.getElementsByTagName(elementName).getLength();
788 private int getElementsSize(Document response, String elementName, String namespace) {
789 return response.getElementsByTagNameNS(namespace, elementName).getLength();
792 private Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
793 SAXException, IOException, NetconfDocumentedException {
795 final Document request = XmlFileLoader.xmlFileToDocument(filename);
797 LOG.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
798 HandlingPriority priority = op.canHandle(request);
800 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
802 final Document response = op.handle(request, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
803 LOG.debug("Got response\n{}", XmlUtil.toString(response));
807 private List<InputStream> getYangs() throws FileNotFoundException {
808 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
809 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
810 "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types.yang");
811 final Collection<InputStream> yangDependencies = new ArrayList<>();
812 for (String path : paths) {
813 final InputStream is = Preconditions
814 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
815 yangDependencies.add(is);
817 return Lists.newArrayList(yangDependencies);
820 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, String depName)
821 throws InstanceAlreadyExistsException, InstanceNotFoundException {
822 mxBean.setSimpleInt((long) 44);
823 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
824 final DtoD dtob = getDtoD();
825 mxBean.setDtoD(dtob);
827 final DtoC dtoa = getDtoC();
828 mxBean.setDtoC(dtoa);
829 mxBean.setSimpleBoolean(false);
831 final Peers p1 = new Peers();
834 p1.setSimpleInt3(456);
835 final Peers p2 = new Peers();
837 p2.setPort("port23");
838 p2.setSimpleInt3(456);
839 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
841 mxBean.setSimpleLong(454545L);
842 mxBean.setSimpleLong2(44L);
843 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
844 mxBean.setSimpleByte(new Byte((byte) 4));
845 mxBean.setSimpleShort(new Short((short) 4));
846 mxBean.setSimpleTest(545);
848 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
849 mxBean.setSimpleList(Lists.<Integer> newArrayList());
851 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
853 for (Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
854 ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
855 transaction.saveServiceReference(
856 transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
860 mxBean.setTestingDep(testingDepOn);
863 private static DtoD getDtoD() {
864 final DtoD dtob = new DtoD();
865 dtob.setSimpleInt1((long) 444);
866 dtob.setSimpleInt2((long) 4444);
867 dtob.setSimpleInt3(454);
868 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
869 final Deep deep = new Deep();
870 deep.setSimpleInt3(4);
871 dtobInner.setDeep(deep);
872 dtobInner.setSimpleInt3(44);
873 dtobInner.setSimpleList(Lists.newArrayList(4));
874 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
875 dtob.setSimpleList(Lists.newArrayList(4));
879 private static DtoC getDtoC() {
880 final DtoC dtoa = new DtoC();
881 // dtoa.setSimpleArg((long) 55);
882 final DtoAInner dtoAInner = new DtoAInner();
883 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
884 dtoAInnerInner.setSimpleArg(456L);
885 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
886 dtoAInner.setSimpleArg(44L);
887 dtoa.setDtoAInner(dtoAInner);