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 com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Maps;
15 import org.junit.Before;
16 import org.junit.Ignore;
17 import org.junit.Test;
18 import org.junit.matchers.JUnitMatchers;
19 import org.mockito.Mock;
20 import org.mockito.MockitoAnnotations;
21 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
22 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
23 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
24 import org.opendaylight.controller.config.yang.store.api.YangStoreSnapshot;
25 import org.opendaylight.controller.config.yang.store.impl.MbeParser;
26 import org.opendaylight.controller.config.yang.test.impl.ComplexDtoBInner;
27 import org.opendaylight.controller.config.yang.test.impl.ComplexList;
28 import org.opendaylight.controller.config.yang.test.impl.Deep;
29 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
30 import org.opendaylight.controller.config.yang.test.impl.DtoAInner;
31 import org.opendaylight.controller.config.yang.test.impl.DtoAInnerInner;
32 import org.opendaylight.controller.config.yang.test.impl.DtoC;
33 import org.opendaylight.controller.config.yang.test.impl.DtoD;
34 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
35 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
36 import org.opendaylight.controller.config.yang.test.impl.Peers;
37 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
38 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
39 import org.opendaylight.controller.netconf.api.NetconfOperationRouter;
40 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
41 import org.opendaylight.controller.netconf.confignetconfconnector.operations.DiscardChanges;
42 import org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig.EditConfig;
43 import org.opendaylight.controller.netconf.confignetconfconnector.operations.get.Get;
44 import org.opendaylight.controller.netconf.confignetconfconnector.operations.getconfig.GetConfig;
45 import org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc.RuntimeRpc;
46 import org.opendaylight.controller.netconf.confignetconfconnector.transactions.TransactionProvider;
47 import org.opendaylight.controller.netconf.impl.mapping.operations.DefaultCloseSession;
48 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
49 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
50 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
51 import org.opendaylight.controller.netconf.util.xml.XmlElement;
52 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
53 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.NodeList;
59 import org.xml.sax.SAXException;
61 import javax.management.InstanceAlreadyExistsException;
62 import javax.management.ObjectName;
63 import javax.xml.parsers.ParserConfigurationException;
64 import java.io.FileNotFoundException;
65 import java.io.IOException;
66 import java.io.InputStream;
67 import java.math.BigInteger;
68 import java.util.ArrayList;
69 import java.util.Arrays;
70 import java.util.Collection;
71 import java.util.List;
74 import static org.junit.Assert.assertEquals;
75 import static org.junit.Assert.assertThat;
76 import static org.junit.Assert.fail;
77 import static org.mockito.Mockito.doNothing;
78 import static org.mockito.Mockito.doReturn;
79 import static org.mockito.Mockito.verify;
80 import static org.mockito.Mockito.verifyNoMoreInteractions;
83 public class NetconfMappingTest extends AbstractConfigTest {
84 private static final Logger logger = LoggerFactory.getLogger(NetconfMappingTest.class);
86 private static final String INSTANCE_NAME = "test1";
87 private static final String NETCONF_SESSION_ID = "foo";
88 private NetconfTestImplModuleFactory factory;
89 private DepTestImplModuleFactory factory2;
92 YangStoreSnapshot yangStoreSnapshot;
94 NetconfOperationRouter netconfOperationRouter;
96 private TransactionProvider transactionProvider;
99 public void setUp() throws Exception {
100 MockitoAnnotations.initMocks(this);
101 doReturn(getMbes()).when(this.yangStoreSnapshot).getModuleMXBeanEntryMap();
102 this.factory = new NetconfTestImplModuleFactory();
103 this.factory2 = new DepTestImplModuleFactory();
104 super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(this.factory, this.factory2));
106 transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
109 private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException {
110 final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
112 final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
113 final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
114 setModule(mxBean, transaction);
116 transaction.commit();
121 public void testConfigNetconf() throws Exception {
123 createModule(INSTANCE_NAME);
125 edit("netconfMessages/editConfig.xml");
126 checkBinaryLeafEdited(getConfigCandidate());
128 // default-operation:none, should not affect binary leaf
129 edit("netconfMessages/editConfig_none.xml");
130 checkBinaryLeafEdited(getConfigCandidate());
134 Element response = getConfigRunning();
135 System.err.println(XmlUtil.toString(response));
137 checkBinaryLeafEdited(response);
138 checkTypeConfigAttribute(response);
139 checkTypedefs(response);
140 checkTestingDeps(response);
142 checkBigDecimal(response);
144 edit("netconfMessages/editConfig_remove.xml");
147 response = getConfigCandidate();
148 final String responseFromCandidate = XmlUtil.toString(response).replaceAll("\\s+", "");
149 // System.out.println(responseFromCandidate);
150 response = getConfigRunning();
151 final String responseFromRunning = XmlUtil.toString(response).replaceAll("\\s+", "");
152 // System.out.println(responseFromRunning);
153 assertEquals(responseFromCandidate, responseFromRunning);
155 final String expectedResult = XmlFileLoader.fileToString("netconfMessages/editConfig_expectedResult.xml")
156 .replaceAll("\\s+", "");
158 assertEquals(expectedResult, responseFromRunning);
159 assertEquals(expectedResult, responseFromCandidate);
161 edit("netconfMessages/editConfig_none.xml");
162 doNothing().when(netconfOperationRouter).close();
164 verify(netconfOperationRouter).close();
165 verifyNoMoreInteractions(netconfOperationRouter);
168 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
170 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID);
171 executeOp(closeOp, "netconfMessages/closeSession.xml");
174 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
175 NetconfDocumentedException {
176 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
178 executeOp(editOp, resource);
181 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
182 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
183 executeOp(commitOp, "netconfMessages/commit.xml");
186 private Element getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
187 NetconfDocumentedException {
188 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
189 configRegistryClient, NETCONF_SESSION_ID);
190 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
193 private Element getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
194 NetconfDocumentedException {
195 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
196 configRegistryClient, NETCONF_SESSION_ID);
197 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
200 @Test(expected = NetconfDocumentedException.class)
201 public void testConfigNetconfReplaceDefaultEx() throws Exception {
203 createModule(INSTANCE_NAME);
205 edit("netconfMessages/editConfig.xml");
206 edit("netconfMessages/editConfig_replace_default_ex.xml");
210 public void testConfigNetconfReplaceDefault() throws Exception {
212 createModule(INSTANCE_NAME);
214 edit("netconfMessages/editConfig.xml");
216 Element response = getConfigRunning();
217 final int allInstances = response.getElementsByTagName("module").getLength();
219 edit("netconfMessages/editConfig_replace_default.xml");
222 response = getConfigRunning();
224 final int afterReplace = response.getElementsByTagName("module").getLength();
225 assertEquals(4, allInstances);
226 assertEquals(2, afterReplace);
229 @Test(expected = NetconfDocumentedException.class)
230 public void testSameAttrDifferentNamespaces() throws Exception {
232 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
233 } catch (NetconfDocumentedException e) {
234 String message = e.getMessage();
237 .containsString("Element simple-long-2 present multiple times with different namespaces"));
239 JUnitMatchers.containsString("urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
242 .containsString(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
247 @Test(expected = NetconfDocumentedException.class)
248 public void testDifferentNamespaceInTO() throws Exception {
250 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
251 } catch (NetconfDocumentedException e) {
252 String message = e.getMessage();
253 assertThat(message, JUnitMatchers.containsString("Unrecognised elements"));
254 assertThat(message, JUnitMatchers.containsString("simple-int2"));
255 assertThat(message, JUnitMatchers.containsString("dto_d"));
260 @Test(expected = NetconfDocumentedException.class)
261 public void testSameAttrDifferentNamespacesList() throws Exception {
263 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
264 } catch (NetconfDocumentedException e) {
265 String message = e.getMessage();
267 JUnitMatchers.containsString("Element binaryLeaf present multiple times with different namespaces"));
269 JUnitMatchers.containsString("urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
272 .containsString(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
278 public void testTypeNameConfigAttributeMatching() throws Exception {
279 edit("netconfMessages/editConfig.xml");
281 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
284 Element response = getConfigRunning();
285 checkTypeConfigAttribute(response);
288 // TODO add <modules operation="replace"> functionality
289 @Test(expected = NetconfDocumentedException.class)
290 public void testConfigNetconfReplaceModuleEx() throws Exception {
292 createModule(INSTANCE_NAME);
294 edit("netconfMessages/editConfig.xml");
295 edit("netconfMessages/editConfig_replace_module_ex.xml");
299 public void testUnrecognisedConfigElements() throws Exception {
301 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
302 final int TESTS_COUNT = 8;
304 for (int i = 0; i < TESTS_COUNT; i++) {
305 String file = String.format(format, i + 1);
308 } catch (NetconfDocumentedException e) {
309 assertThat(e.getMessage(), JUnitMatchers.containsString("Unrecognised elements"));
310 assertThat(e.getMessage(), JUnitMatchers.containsString("unknownAttribute"));
313 fail("Unrecognised test should throw exception " + file);
320 public void testConfigNetconfReplaceModule() throws Exception {
322 createModule(INSTANCE_NAME);
324 edit("netconfMessages/editConfig.xml");
326 Element response = getConfigRunning();
327 final int allInstances = response.getElementsByTagName("instance").getLength();
329 edit("netconfMessages/editConfig_replace_module.xml");
332 response = getConfigRunning();
333 final int afterReplace = response.getElementsByTagName("instance").getLength();
335 assertEquals(4 + 4 /* Instances from services */, allInstances);
336 assertEquals(3 + 3, afterReplace);
339 @Test(expected = NetconfDocumentedException.class)
340 public void testEx() throws Exception {
345 @Test(expected = NetconfDocumentedException.class)
346 public void testEx2() throws Exception {
350 private void discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
351 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
352 executeOp(discardOp, "netconfMessages/discardChanges.xml");
355 private void checkBinaryLeafEdited(final Element response) {
356 final NodeList children = response.getElementsByTagName("binaryLeaf");
357 assertEquals(3, children.getLength());
358 final StringBuffer buf = new StringBuffer();
359 for (int i = 0; i < 3; i++) {
360 final Element e = (Element) children.item(i);
361 buf.append(XmlElement.fromDomElement(e).getTextContent());
363 assertEquals("810", buf.toString());
366 private void checkTypedefs(final Element response) {
367 NodeList children = response.getElementsByTagName("extended");
368 assertEquals(1, children.getLength());
370 children = response.getElementsByTagName("extended-twice");
371 assertEquals(1, children.getLength());
374 private void checkEnum(final Element response) {
375 XmlElement modulesElement = XmlElement.fromDomElement(response).getOnlyChildElement("data")
376 .getOnlyChildElement("modules");
378 String enumName = "extended-enum";
379 String enumContent = "TWO";
381 for (XmlElement moduleElement : modulesElement.getChildElements("module")) {
382 String name = moduleElement.getOnlyChildElement("name").getTextContent();
383 if(name.equals("test1")) {
384 XmlElement enumAttr = moduleElement.getOnlyChildElement(enumName);
385 assertEquals(enumContent, enumAttr.getTextContent());
391 fail("Enum attribute " + enumName + ":" + enumContent + " not present in " + XmlUtil.toString(response));
394 private void checkTestingDeps(Element response) {
395 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
396 assertEquals(2, testingDepsSize);
399 private void checkBigDecimal(Element response) {
400 int size = response.getElementsByTagName("sleep-factor").getLength();
401 assertEquals(1, size);
405 private void checkTypeConfigAttribute(Element response) {
407 XmlElement modulesElement = XmlElement.fromDomElement(response).getOnlyChildElement("data")
408 .getOnlyChildElement("modules");
410 XmlElement configAttributeType = null;
411 for (XmlElement moduleElement : modulesElement.getChildElements("module")) {
412 for (XmlElement type : moduleElement.getChildElements("type")) {
413 if (type.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY).equals("") == false) {
414 configAttributeType = type;
419 assertEquals("configAttributeType", configAttributeType.getTextContent());
422 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
423 final List<InputStream> yangDependencies = getYangs();
425 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
426 mBeanEntries.putAll(new MbeParser().parseYangFiles(yangDependencies).getModuleMXBeanEntryMap());
432 public void testConfigNetconfRuntime() throws Exception {
434 createModule(INSTANCE_NAME);
436 edit("netconfMessages/editConfig.xml");
437 checkBinaryLeafEdited(getConfigCandidate());
441 Element response = get();
443 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
445 assertEquals(2, getElementsSize(response, "asdf"));
446 // data from running config
447 assertEquals(2, getElementsSize(response, "simple-short"));
449 assertEquals(8, getElementsSize(response, "inner-running-data"));
450 assertEquals(8, getElementsSize(response, "deep2"));
451 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
452 assertEquals(8 * 4, getElementsSize(response, "deep3"));
453 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
454 assertEquals(8, getElementsSize(response, "inner-running-data-additional"));
455 assertEquals(8, getElementsSize(response, "deep4"));
458 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
460 response = executeOp(netconf, "netconfMessages/rpc.xml");
461 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("testarg1".toUpperCase()));
463 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
464 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("ok"));
466 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
467 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("true"));
469 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
470 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("1"));
471 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("2"));
474 private Element get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
475 Get getOp = new Get(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
476 return executeOp(getOp, "netconfMessages/get.xml");
479 private int getElementsSize(Element response, String elementName) {
480 return response.getElementsByTagName(elementName).getLength();
483 private Element executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
484 SAXException, IOException, NetconfDocumentedException {
486 final Document request = XmlFileLoader.xmlFileToDocument(filename);
488 logger.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
489 HandlingPriority priority = op.canHandle(request);
491 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
493 final Document response = op.handle(request, netconfOperationRouter);
494 logger.debug("Got response\n{}", XmlUtil.toString(response));
495 return response.getDocumentElement();
498 private List<InputStream> getYangs() throws FileNotFoundException {
499 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
500 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
501 "/META-INF/yang/ietf-inet-types.yang");
502 final Collection<InputStream> yangDependencies = new ArrayList<>();
503 for (String path : paths) {
504 final InputStream is = Preconditions
505 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
506 yangDependencies.add(is);
508 return Lists.newArrayList(yangDependencies);
511 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction)
512 throws InstanceAlreadyExistsException {
513 mxBean.setSimpleInt((long) 44);
514 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
515 final DtoD dtob = getDtoD();
516 mxBean.setDtoD(dtob);
518 final DtoC dtoa = getDtoC();
519 mxBean.setDtoC(dtoa);
520 mxBean.setSimpleBoolean(false);
522 final Peers p1 = new Peers();
525 p1.setSimpleInt3(456);
526 final Peers p2 = new Peers();
528 p2.setPort("port23");
529 p2.setSimpleInt3(456);
530 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
532 mxBean.setSimpleLong(454545L);
533 mxBean.setSimpleLong2(44L);
534 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
535 mxBean.setSimpleByte(new Byte((byte) 4));
536 mxBean.setSimpleShort(new Short((short) 4));
537 mxBean.setSimpleTest(545);
539 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
540 mxBean.setSimpleList(Lists.<Integer> newArrayList());
542 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), "dep");
543 mxBean.setTestingDep(testingDepOn);
546 private static DtoD getDtoD() {
547 final DtoD dtob = new DtoD();
548 dtob.setSimpleInt1((long) 444);
549 dtob.setSimpleInt2((long) 4444);
550 dtob.setSimpleInt3(454);
551 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
552 final Deep deep = new Deep();
553 deep.setSimpleInt3(4);
554 dtobInner.setDeep(deep);
555 dtobInner.setSimpleInt3(44);
556 dtobInner.setSimpleList(Lists.newArrayList(4));
557 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
558 dtob.setSimpleList(Lists.newArrayList(4));
562 private static DtoC getDtoC() {
563 final DtoC dtoa = new DtoC();
564 // dtoa.setSimpleArg((long) 55);
565 final DtoAInner dtoAInner = new DtoAInner();
566 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
567 dtoAInnerInner.setSimpleArg(456L);
568 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
569 dtoAInner.setSimpleArg(44L);
570 dtoa.setDtoAInner(dtoAInner);