BUG-1521 netconf-client line coverage
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / NetconfITTest.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.it;
10
11 import static org.hamcrest.CoreMatchers.containsString;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertThat;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18
19 import com.google.common.base.Function;
20 import com.google.common.base.Throwables;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Sets;
23 import java.io.IOException;
24 import java.net.InetSocketAddress;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Set;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.TimeoutException;
30 import javax.management.ObjectName;
31 import javax.xml.parsers.ParserConfigurationException;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
35 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
36 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
37 import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
38 import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
39 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
40 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
41 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
42 import org.opendaylight.controller.netconf.api.NetconfMessage;
43 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
44 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
45 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
46 import org.opendaylight.controller.netconf.util.xml.XmlElement;
47 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity1;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.test.types.rev131127.TestIdentity2;
50 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
51 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
52 import org.w3c.dom.Document;
53 import org.w3c.dom.Element;
54 import org.w3c.dom.NamedNodeMap;
55 import org.w3c.dom.Node;
56 import org.xml.sax.SAXException;
57
58 public class NetconfITTest extends AbstractNetconfConfigTest {
59
60     public static final int PORT = 12023;
61     public static final InetSocketAddress TCP_ADDRESS = new InetSocketAddress(LOOPBACK_ADDRESS, PORT);
62
63     private NetconfMessage getConfigCandidate, editConfig, closeSession;
64     private NetconfClientDispatcher clientDispatcher;
65
66     @Before
67     public void setUp() throws Exception {
68         loadMessages();
69         clientDispatcher = getClientDispatcher();
70     }
71
72     @Override
73     protected InetSocketAddress getTcpServerAddress() {
74         return TCP_ADDRESS;
75     }
76
77     private void loadMessages() throws IOException, SAXException, ParserConfigurationException {
78         this.editConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/edit_config.xml");
79         this.getConfigCandidate = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig_candidate.xml");
80         this.closeSession = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/closeSession.xml");
81     }
82
83     @Test
84     public void testNetconfClientDemonstration() throws Exception {
85         try (TestingNetconfClient netconfClient = new TestingNetconfClient("client", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 4000))) {
86
87             final Set<String> capabilitiesFromNetconfServer = netconfClient.getCapabilities();
88             final long sessionId = netconfClient.getSessionId();
89
90             // NetconfMessage can be created :
91             // new NetconfMessage(XmlUtil.readXmlToDocument("<xml/>"));
92
93             final NetconfMessage response = netconfClient.sendMessage(getGetConfig());
94             response.getDocument();
95         }
96     }
97
98     @Test
99     public void testTwoSessions() throws Exception {
100         try (TestingNetconfClient netconfClient = new TestingNetconfClient("1", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 10000)))  {
101             try (TestingNetconfClient netconfClient2 = new TestingNetconfClient("2", clientDispatcher, getClientConfiguration(TCP_ADDRESS, 10000))) {
102                 assertNotNull(netconfClient2.getCapabilities());
103             }
104         }
105     }
106
107     @Test
108     public void rpcReplyContainsAllAttributesTest() throws Exception {
109         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
110             final String rpc = "<rpc message-id=\"5\" a=\"a\" b=\"44\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><get/>" + "</rpc>";
111             final Document doc = XmlUtil.readXmlToDocument(rpc);
112             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
113             assertNotNull(message);
114             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
115             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
116
117             assertSameAttributes(expectedAttributes, returnedAttributes);
118         }
119     }
120
121     private void assertSameAttributes(final NamedNodeMap expectedAttributes, final NamedNodeMap returnedAttributes) {
122         assertNotNull("Expecting 4 attributes", returnedAttributes);
123         assertEquals(expectedAttributes.getLength(), returnedAttributes.getLength());
124
125         for (int i = 0; i < expectedAttributes.getLength(); i++) {
126             final Node expAttr = expectedAttributes.item(i);
127             final Node attr = returnedAttributes.item(i);
128             assertEquals(expAttr.getNodeName(), attr.getNodeName());
129             assertEquals(expAttr.getNamespaceURI(), attr.getNamespaceURI());
130             assertEquals(expAttr.getTextContent(), attr.getTextContent());
131         }
132     }
133
134     @Test
135     public void rpcReplyErrorContainsAllAttributesTest() throws Exception {
136         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
137             final String rpc = "<rpc message-id=\"1\" a=\"adada\" b=\"4\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><commit/>" + "</rpc>";
138             final Document doc = XmlUtil.readXmlToDocument(rpc);
139             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
140             final NamedNodeMap expectedAttributes = doc.getDocumentElement().getAttributes();
141             final NamedNodeMap returnedAttributes = message.getDocument().getDocumentElement().getAttributes();
142
143             assertSameAttributes(expectedAttributes, returnedAttributes);
144         }
145     }
146
147     @Test
148     public void rpcOutputContainsCorrectNamespace() throws Exception {
149         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
150         final ObjectName dep = transaction.createModule(DepTestImplModuleFactory.NAME, "instanceD");
151         final ObjectName impl = transaction.createModule(NetconfTestImplModuleFactory.NAME, "instance");
152         final NetconfTestImplModuleMXBean proxy = configRegistryClient
153                 .newMXBeanProxy(impl, NetconfTestImplModuleMXBean.class);
154         proxy.setTestingDep(dep);
155         proxy.setSimpleShort((short) 0);
156
157         transaction.commit();
158
159         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
160             final String expectedNamespace = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
161
162             final String rpc = "<rpc message-id=\"5\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
163                     + "<no-arg xmlns=\""
164                     + expectedNamespace
165                     + "\">    "
166                     + "<context-instance>/modules/module[type='impl-netconf'][name='instance']</context-instance>"
167                     + "<arg1>argument1</arg1>" + "</no-arg>" + "</rpc>";
168             final Document doc = XmlUtil.readXmlToDocument(rpc);
169             final NetconfMessage message = netconfClient.sendMessage(new NetconfMessage(doc));
170
171             final Element rpcReply = message.getDocument().getDocumentElement();
172             final XmlElement resultElement = XmlElement.fromDomElement(rpcReply).getOnlyChildElement();
173             assertEquals("result", resultElement.getName());
174
175             final String namespace = resultElement.getNamespaceAttribute();
176             assertEquals(expectedNamespace, namespace);
177         }
178     }
179
180     @Test
181     public void testCloseSession() throws Exception {
182         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
183
184             // edit config
185             Document rpcReply = netconfClient.sendMessage(this.editConfig)
186                     .getDocument();
187             assertIsOK(rpcReply);
188
189             rpcReply = netconfClient.sendMessage(this.closeSession)
190                     .getDocument();
191
192             assertIsOK(rpcReply);
193         }
194     }
195
196     @Test
197     public void testEditConfig() throws Exception {
198         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
199             // send edit_config.xml
200             final Document rpcReply = netconfClient.sendMessage(this.editConfig).getDocument();
201             assertIsOK(rpcReply);
202         }
203     }
204
205     @Test
206     public void testValidate() throws Exception {
207         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
208             // begin transaction
209             Document rpcReply = netconfClient.sendMessage(getConfigCandidate).getDocument();
210             assertEquals("data", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
211
212             // operations empty
213             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/validate.xml"))
214                     .getDocument();
215             assertIsOK(rpcReply);
216         }
217     }
218
219     private void assertIsOK(final Document rpcReply) throws NetconfDocumentedException {
220         assertEquals("rpc-reply", rpcReply.getDocumentElement().getLocalName());
221         assertEquals("ok", XmlElement.fromDomDocument(rpcReply).getOnlyChildElement().getName());
222     }
223
224     private Document assertGetConfigWorks(final TestingNetconfClient netconfClient) throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
225         return assertGetConfigWorks(netconfClient, getGetConfig());
226     }
227
228     private Document assertGetConfigWorks(final TestingNetconfClient netconfClient, final NetconfMessage getConfigMessage)
229             throws InterruptedException, ExecutionException, TimeoutException, NetconfDocumentedException {
230         final NetconfMessage rpcReply = netconfClient.sendMessage(getConfigMessage);
231         assertNotNull(rpcReply);
232         assertEquals("data", XmlElement.fromDomDocument(rpcReply.getDocument()).getOnlyChildElement().getName());
233         return rpcReply.getDocument();
234     }
235
236     @Test
237     public void testGetConfig() throws Exception {
238         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
239             assertGetConfigWorks(netconfClient);
240         }
241     }
242
243     @Test
244     public void createYangTestBasedOnYuma() throws Exception {
245         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
246             Document rpcReply = netconfClient.sendMessage(
247                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_yang-test.xml"))
248                     .getDocument();
249             assertEquals("rpc-reply", rpcReply.getDocumentElement().getTagName());
250             assertIsOK(rpcReply);
251             assertGetConfigWorks(netconfClient, this.getConfigCandidate);
252             rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
253                     .getDocument();
254             assertIsOK(rpcReply);
255
256             final ObjectName on = new ObjectName(
257                     "org.opendaylight.controller:instanceName=impl-dep-instance,type=Module,moduleFactoryName=impl-dep");
258             final Set<ObjectName> cfgBeans = configRegistryClient.lookupConfigBeans();
259             assertEquals(cfgBeans, Sets.newHashSet(on));
260         }
261     }
262
263     private TestingNetconfClient createSession(final InetSocketAddress address, final String expected) throws Exception {
264         final TestingNetconfClient netconfClient = new TestingNetconfClient("test " + address.toString(), clientDispatcher, getClientConfiguration(address, 5000));
265         assertEquals(expected, Long.toString(netconfClient.getSessionId()));
266         return netconfClient;
267     }
268
269     @Test
270     public void testIdRef() throws Exception {
271         final NetconfMessage editId = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_identities.xml");
272         final NetconfMessage commit = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml");
273
274         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
275             assertIsOK(netconfClient.sendMessage(editId).getDocument());
276             assertIsOK(netconfClient.sendMessage(commit).getDocument());
277
278             final NetconfMessage response = netconfClient.sendMessage(getGetConfig());
279
280             assertThat(XmlUtil.toString(response.getDocument()), containsString("<afi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity1</afi>"));
281             assertThat(XmlUtil.toString(response.getDocument()), containsString("<afi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity2</afi>"));
282             assertThat(XmlUtil.toString(response.getDocument()), containsString("<safi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity2</safi>"));
283             assertThat(XmlUtil.toString(response.getDocument()), containsString("<safi xmlns:prefix=\"urn:opendaylight:params:xml:ns:yang:controller:config:test:types\">prefix:test-identity1</safi>"));
284
285         } catch (final Exception e) {
286             fail(Throwables.getStackTraceAsString(e));
287         }
288     }
289
290     @Override
291     protected CodecRegistry getCodecRegistry() {
292         final IdentityCodec<?> codec = mock(IdentityCodec.class);
293         doReturn(TestIdentity1.class).when(codec).deserialize(TestIdentity1.QNAME);
294         doReturn(TestIdentity2.class).when(codec).deserialize(TestIdentity2.QNAME);
295
296         final CodecRegistry ret = super.getCodecRegistry();
297         doReturn(codec).when(ret).getIdentityCodec();
298         return ret;
299     }
300
301     @Test
302     public void testMultipleDependencies() throws Exception {
303         // push first xml, should add parent and d1,d2 dependencies
304         try (TestingNetconfClient netconfClient = createSession(TCP_ADDRESS, "1")) {
305             final Document rpcReply = netconfClient.sendMessage(
306                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps1.xml"))
307                     .getDocument();
308             assertIsOK(rpcReply);
309             commit(netconfClient);
310         }
311         // verify that parent.getTestingDeps == d1,d2
312         final MultipleDependenciesModuleMXBean parentProxy = configRegistryClient.newMXBeanProxy(
313                 configRegistryClient.lookupConfigBean(MultipleDependenciesModuleFactory.NAME, "parent"),
314                 MultipleDependenciesModuleMXBean.class);
315         {
316             final List<ObjectName> testingDeps = parentProxy.getTestingDeps();
317             assertEquals(2, testingDeps.size());
318             final Set<String> actualRefs = getServiceReferences(testingDeps);
319             assertEquals(Sets.newHashSet("ref_d1", "ref_d2"), actualRefs);
320         }
321
322         // push second xml, should add d3 to parent's dependencies
323         mergeD3(parentProxy);
324         // push second xml again, to test that d3 is not added again
325         mergeD3(parentProxy);
326     }
327
328     public void mergeD3(final MultipleDependenciesModuleMXBean parentProxy) throws Exception {
329         try (TestingNetconfClient netconfClient = new TestingNetconfClient(
330                 "test " + TCP_ADDRESS.toString(), clientDispatcher, getClientConfiguration(TCP_ADDRESS, 5000))) {
331
332             final Document rpcReply = netconfClient.sendMessage(
333                     XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps2.xml"))
334                     .getDocument();
335             assertIsOK(rpcReply);
336             commit(netconfClient);
337         }
338         {
339             final List<ObjectName> testingDeps = parentProxy.getTestingDeps();
340             assertEquals(3, testingDeps.size());
341             final Set<String> actualRefs = getServiceReferences(testingDeps);
342             assertEquals(Sets.newHashSet("ref_d1", "ref_d2", "ref_d3"), actualRefs);
343         }
344     }
345
346     public Set<String> getServiceReferences(final List<ObjectName> testingDeps) {
347         return new HashSet<>(Lists.transform(testingDeps, new Function<ObjectName, String>() {
348             @Override
349             public String apply(final ObjectName input) {
350                 return ObjectNameUtil.getReferenceName(input);
351             }
352         }));
353     }
354
355     public void commit(final TestingNetconfClient netconfClient) throws Exception {
356         final Document rpcReply;
357         rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
358                 .getDocument();
359         assertIsOK(rpcReply);
360     }
361 }