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();
136 checkBinaryLeafEdited(response);
137 checkTypeConfigAttribute(response);
138 checkTypedefs(response);
139 checkTestingDeps(response);
141 checkBigDecimal(response);
143 edit("netconfMessages/editConfig_remove.xml");
146 response = getConfigCandidate();
147 final String responseFromCandidate = XmlUtil.toString(response).replaceAll("\\s+", "");
148 // System.out.println(responseFromCandidate);
149 response = getConfigRunning();
150 final String responseFromRunning = XmlUtil.toString(response).replaceAll("\\s+", "");
151 // System.out.println(responseFromRunning);
152 assertEquals(responseFromCandidate, responseFromRunning);
154 final String expectedResult = XmlFileLoader.fileToString("netconfMessages/editConfig_expectedResult.xml")
155 .replaceAll("\\s+", "");
157 assertEquals(expectedResult, responseFromRunning);
158 assertEquals(expectedResult, responseFromCandidate);
160 edit("netconfMessages/editConfig_none.xml");
161 doNothing().when(netconfOperationRouter).close();
163 verify(netconfOperationRouter).close();
164 verifyNoMoreInteractions(netconfOperationRouter);
167 private void closeSession() throws NetconfDocumentedException, ParserConfigurationException, SAXException,
169 DefaultCloseSession closeOp = new DefaultCloseSession(NETCONF_SESSION_ID);
170 executeOp(closeOp, "netconfMessages/closeSession.xml");
173 private void edit(String resource) throws ParserConfigurationException, SAXException, IOException,
174 NetconfDocumentedException {
175 EditConfig editOp = new EditConfig(yangStoreSnapshot, transactionProvider, configRegistryClient,
177 executeOp(editOp, resource);
180 private void commit() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
181 Commit commitOp = new Commit(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
182 executeOp(commitOp, "netconfMessages/commit.xml");
185 private Element getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
186 NetconfDocumentedException {
187 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
188 configRegistryClient, NETCONF_SESSION_ID);
189 return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
192 private Element getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
193 NetconfDocumentedException {
194 GetConfig getConfigOp = new GetConfig(yangStoreSnapshot, Optional.<String> absent(), transactionProvider,
195 configRegistryClient, NETCONF_SESSION_ID);
196 return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
199 @Test(expected = NetconfDocumentedException.class)
200 public void testConfigNetconfReplaceDefaultEx() throws Exception {
202 createModule(INSTANCE_NAME);
204 edit("netconfMessages/editConfig.xml");
205 edit("netconfMessages/editConfig_replace_default_ex.xml");
209 public void testConfigNetconfReplaceDefault() throws Exception {
211 createModule(INSTANCE_NAME);
213 edit("netconfMessages/editConfig.xml");
215 Element response = getConfigRunning();
216 final int allInstances = response.getElementsByTagName("module").getLength();
218 edit("netconfMessages/editConfig_replace_default.xml");
221 response = getConfigRunning();
223 final int afterReplace = response.getElementsByTagName("module").getLength();
224 assertEquals(4, allInstances);
225 assertEquals(2, afterReplace);
228 @Test(expected = NetconfDocumentedException.class)
229 public void testSameAttrDifferentNamespaces() throws Exception {
231 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespaces.xml");
232 } catch (NetconfDocumentedException e) {
233 String message = e.getMessage();
236 .containsString("Element simple-long-2 present multiple times with different namespaces"));
238 JUnitMatchers.containsString("urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
241 .containsString(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
246 @Test(expected = NetconfDocumentedException.class)
247 public void testDifferentNamespaceInTO() throws Exception {
249 edit("netconfMessages/namespaces/editConfig_differentNamespaceTO.xml");
250 } catch (NetconfDocumentedException e) {
251 String message = e.getMessage();
252 assertThat(message, JUnitMatchers.containsString("Unrecognised elements"));
253 assertThat(message, JUnitMatchers.containsString("simple-int2"));
254 assertThat(message, JUnitMatchers.containsString("dto_d"));
259 @Test(expected = NetconfDocumentedException.class)
260 public void testSameAttrDifferentNamespacesList() throws Exception {
262 edit("netconfMessages/namespaces/editConfig_sameAttrDifferentNamespacesList.xml");
263 } catch (NetconfDocumentedException e) {
264 String message = e.getMessage();
266 JUnitMatchers.containsString("Element binaryLeaf present multiple times with different namespaces"));
268 JUnitMatchers.containsString("urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
271 .containsString(XmlNetconfConstants.URN_OPENDAYLIGHT_PARAMS_XML_NS_YANG_CONTROLLER_CONFIG));
277 public void testTypeNameConfigAttributeMatching() throws Exception {
278 edit("netconfMessages/editConfig.xml");
280 edit("netconfMessages/namespaces/editConfig_typeNameConfigAttributeMatching.xml");
283 Element response = getConfigRunning();
284 checkTypeConfigAttribute(response);
287 // TODO add <modules operation="replace"> functionality
288 @Test(expected = NetconfDocumentedException.class)
289 public void testConfigNetconfReplaceModuleEx() throws Exception {
291 createModule(INSTANCE_NAME);
293 edit("netconfMessages/editConfig.xml");
294 edit("netconfMessages/editConfig_replace_module_ex.xml");
298 public void testUnrecognisedConfigElements() throws Exception {
300 String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
301 final int TESTS_COUNT = 8;
303 for (int i = 0; i < TESTS_COUNT; i++) {
304 String file = String.format(format, i + 1);
307 } catch (NetconfDocumentedException e) {
308 assertThat(e.getMessage(), JUnitMatchers.containsString("Unrecognised elements"));
309 assertThat(e.getMessage(), JUnitMatchers.containsString("unknownAttribute"));
312 fail("Unrecognised test should throw exception " + file);
319 public void testConfigNetconfReplaceModule() throws Exception {
321 createModule(INSTANCE_NAME);
323 edit("netconfMessages/editConfig.xml");
325 Element response = getConfigRunning();
326 final int allInstances = response.getElementsByTagName("instance").getLength();
328 edit("netconfMessages/editConfig_replace_module.xml");
331 response = getConfigRunning();
332 final int afterReplace = response.getElementsByTagName("instance").getLength();
334 assertEquals(4 + 4 /* Instances from services */, allInstances);
335 assertEquals(3 + 3, afterReplace);
338 @Test(expected = NetconfDocumentedException.class)
339 public void testEx() throws Exception {
344 @Test(expected = NetconfDocumentedException.class)
345 public void testEx2() throws Exception {
349 private void discard() throws ParserConfigurationException, SAXException, IOException, NetconfDocumentedException {
350 DiscardChanges discardOp = new DiscardChanges(transactionProvider, configRegistryClient, NETCONF_SESSION_ID);
351 executeOp(discardOp, "netconfMessages/discardChanges.xml");
354 private void checkBinaryLeafEdited(final Element response) {
355 final NodeList children = response.getElementsByTagName("binaryLeaf");
356 assertEquals(3, children.getLength());
357 final StringBuffer buf = new StringBuffer();
358 for (int i = 0; i < 3; i++) {
359 final Element e = (Element) children.item(i);
360 buf.append(XmlElement.fromDomElement(e).getTextContent());
362 assertEquals("810", buf.toString());
365 private void checkTypedefs(final Element response) {
366 NodeList children = response.getElementsByTagName("extended");
367 assertEquals(1, children.getLength());
369 children = response.getElementsByTagName("extended-twice");
370 assertEquals(1, children.getLength());
373 private void checkEnum(final Element response) {
374 XmlElement modulesElement = XmlElement.fromDomElement(response).getOnlyChildElement("data")
375 .getOnlyChildElement("modules");
377 String enumName = "extended-enum";
378 String enumContent = "TWO";
380 for (XmlElement moduleElement : modulesElement.getChildElements("module")) {
381 String name = moduleElement.getOnlyChildElement("name").getTextContent();
382 if(name.equals("test1")) {
383 XmlElement enumAttr = moduleElement.getOnlyChildElement(enumName);
384 assertEquals(enumContent, enumAttr.getTextContent());
390 fail("Enum attribute " + enumName + ":" + enumContent + " not present in " + XmlUtil.toString(response));
393 private void checkTestingDeps(Element response) {
394 int testingDepsSize = response.getElementsByTagName("testing-deps").getLength();
395 assertEquals(2, testingDepsSize);
398 private void checkBigDecimal(Element response) {
399 int size = response.getElementsByTagName("sleep-factor").getLength();
400 assertEquals(1, size);
404 private void checkTypeConfigAttribute(Element response) {
406 XmlElement modulesElement = XmlElement.fromDomElement(response).getOnlyChildElement("data")
407 .getOnlyChildElement("modules");
409 XmlElement configAttributeType = null;
410 for (XmlElement moduleElement : modulesElement.getChildElements("module")) {
411 for (XmlElement type : moduleElement.getChildElements("type")) {
412 if (type.getAttribute(XmlUtil.XMLNS_ATTRIBUTE_KEY).equals("") == false) {
413 configAttributeType = type;
418 assertEquals("configAttributeType", configAttributeType.getTextContent());
421 private Map<String, Map<String, ModuleMXBeanEntry>> getMbes() throws Exception {
422 final List<InputStream> yangDependencies = getYangs();
424 final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries = Maps.newHashMap();
425 mBeanEntries.putAll(new MbeParser().parseYangFiles(yangDependencies).getModuleMXBeanEntryMap());
431 public void testConfigNetconfRuntime() throws Exception {
433 createModule(INSTANCE_NAME);
435 edit("netconfMessages/editConfig.xml");
436 checkBinaryLeafEdited(getConfigCandidate());
440 Element response = get();
442 assertEquals(2/*With runtime beans*/ + 2 /*Without runtime beans*/, getElementsSize(response, "module"));
444 assertEquals(2, getElementsSize(response, "asdf"));
445 // data from running config
446 assertEquals(2, getElementsSize(response, "simple-short"));
448 assertEquals(8, getElementsSize(response, "inner-running-data"));
449 assertEquals(8, getElementsSize(response, "deep2"));
450 assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
451 assertEquals(8 * 4, getElementsSize(response, "deep3"));
452 assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
453 assertEquals(8, getElementsSize(response, "inner-running-data-additional"));
454 assertEquals(8, getElementsSize(response, "deep4"));
457 RuntimeRpc netconf = new RuntimeRpc(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
459 response = executeOp(netconf, "netconfMessages/rpc.xml");
460 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("testarg1".toUpperCase()));
462 response = executeOp(netconf, "netconfMessages/rpcInner.xml");
463 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("ok"));
465 response = executeOp(netconf, "netconfMessages/rpcInnerInner.xml");
466 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("true"));
468 response = executeOp(netconf, "netconfMessages/rpcInnerInner_complex_output.xml");
469 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("1"));
470 assertThat(XmlUtil.toString(response), JUnitMatchers.containsString("2"));
473 private Element get() throws NetconfDocumentedException, ParserConfigurationException, SAXException, IOException {
474 Get getOp = new Get(yangStoreSnapshot, configRegistryClient, NETCONF_SESSION_ID);
475 return executeOp(getOp, "netconfMessages/get.xml");
478 private int getElementsSize(Element response, String elementName) {
479 return response.getElementsByTagName(elementName).getLength();
482 private Element executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
483 SAXException, IOException, NetconfDocumentedException {
485 final Document request = XmlFileLoader.xmlFileToDocument(filename);
487 logger.debug("Executing netconf operation\n{}", XmlUtil.toString(request));
488 HandlingPriority priority = op.canHandle(request);
490 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
492 final Document response = op.handle(request, netconfOperationRouter);
493 logger.debug("Got response\n{}", XmlUtil.toString(response));
494 return response.getDocumentElement();
497 private List<InputStream> getYangs() throws FileNotFoundException {
498 List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
499 "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
500 "/META-INF/yang/ietf-inet-types.yang");
501 final Collection<InputStream> yangDependencies = new ArrayList<>();
502 for (String path : paths) {
503 final InputStream is = Preconditions
504 .checkNotNull(getClass().getResourceAsStream(path), path + " not found");
505 yangDependencies.add(is);
507 return Lists.newArrayList(yangDependencies);
510 private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction)
511 throws InstanceAlreadyExistsException {
512 mxBean.setSimpleInt((long) 44);
513 mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
514 final DtoD dtob = getDtoD();
515 mxBean.setDtoD(dtob);
517 final DtoC dtoa = getDtoC();
518 mxBean.setDtoC(dtoa);
519 mxBean.setSimpleBoolean(false);
521 final Peers p1 = new Peers();
524 p1.setSimpleInt3(456);
525 final Peers p2 = new Peers();
527 p2.setPort("port23");
528 p2.setSimpleInt3(456);
529 mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
531 mxBean.setSimpleLong(454545L);
532 mxBean.setSimpleLong2(44L);
533 mxBean.setSimpleBigInteger(BigInteger.valueOf(999L));
534 mxBean.setSimpleByte(new Byte((byte) 4));
535 mxBean.setSimpleShort(new Short((short) 4));
536 mxBean.setSimpleTest(545);
538 mxBean.setComplexList(Lists.<ComplexList> newArrayList());
539 mxBean.setSimpleList(Lists.<Integer> newArrayList());
541 final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), "dep");
542 mxBean.setTestingDep(testingDepOn);
545 private static DtoD getDtoD() {
546 final DtoD dtob = new DtoD();
547 dtob.setSimpleInt1((long) 444);
548 dtob.setSimpleInt2((long) 4444);
549 dtob.setSimpleInt3(454);
550 final ComplexDtoBInner dtobInner = new ComplexDtoBInner();
551 final Deep deep = new Deep();
552 deep.setSimpleInt3(4);
553 dtobInner.setDeep(deep);
554 dtobInner.setSimpleInt3(44);
555 dtobInner.setSimpleList(Lists.newArrayList(4));
556 dtob.setComplexDtoBInner(Lists.newArrayList(dtobInner));
557 dtob.setSimpleList(Lists.newArrayList(4));
561 private static DtoC getDtoC() {
562 final DtoC dtoa = new DtoC();
563 // dtoa.setSimpleArg((long) 55);
564 final DtoAInner dtoAInner = new DtoAInner();
565 final DtoAInnerInner dtoAInnerInner = new DtoAInnerInner();
566 dtoAInnerInner.setSimpleArg(456L);
567 dtoAInner.setDtoAInnerInner(dtoAInnerInner);
568 dtoAInner.setSimpleArg(44L);
569 dtoa.setDtoAInner(dtoAInner);