Adjust to yangtools-2.0.0/odlparent-3.0.0 changes
[netconf.git] / netconf / sal-netconf-connector / src / test / java / org / opendaylight / netconf / sal / connect / netconf / util / NetconfBaseOpsTest.java
1 /*
2  * Copyright (c) 2016 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.netconf.sal.connect.netconf.util;
10
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Matchers.argThat;
13 import static org.mockito.Matchers.eq;
14 import static org.mockito.Mockito.verify;
15 import static org.mockito.Mockito.when;
16
17 import com.google.common.base.Optional;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.net.InetSocketAddress;
21 import java.util.ArrayList;
22 import java.util.List;
23 import org.custommonkey.xmlunit.Diff;
24 import org.custommonkey.xmlunit.XMLUnit;
25 import org.hamcrest.BaseMatcher;
26 import org.hamcrest.Description;
27 import org.junit.Assert;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.mockito.Mock;
31 import org.mockito.MockitoAnnotations;
32 import org.opendaylight.controller.config.util.xml.XmlUtil;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
34 import org.opendaylight.netconf.api.NetconfMessage;
35 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
36 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
37 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
38 import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
39 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
42 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
45 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
50 import org.w3c.dom.Document;
51 import org.w3c.dom.Element;
52 import org.w3c.dom.NamedNodeMap;
53 import org.xml.sax.SAXException;
54
55 public class NetconfBaseOpsTest {
56
57     static {
58         XMLUnit.setIgnoreWhitespace(true);
59         XMLUnit.setIgnoreComments(true);
60     }
61
62     private static final QName CONTAINER_Q_NAME = QName.create("test:namespace", "2013-07-22", "c");
63
64     @Mock
65     private RemoteDeviceCommunicator<NetconfMessage> listener;
66     private NetconfRpcFutureCallback callback;
67     private NetconfBaseOps baseOps;
68
69     @Before
70     public void setUp() throws Exception {
71         MockitoAnnotations.initMocks(this);
72         final InputStream okStream = getClass().getResourceAsStream("/netconfMessages/rpc-reply_ok.xml");
73         final InputStream dataStream = getClass().getResourceAsStream("/netconfMessages/rpc-reply_get.xml");
74         final NetconfMessage ok = new NetconfMessage(XmlUtil.readXmlToDocument(okStream));
75         final NetconfMessage data = new NetconfMessage(XmlUtil.readXmlToDocument(dataStream));
76         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)))
77                 .thenReturn(RpcResultBuilder.success(data).buildFuture());
78         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_GET_QNAME)))
79                 .thenReturn(RpcResultBuilder.success(data).buildFuture());
80         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)))
81                 .thenReturn(RpcResultBuilder.success(ok).buildFuture());
82         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME)))
83                 .thenReturn(RpcResultBuilder.success(ok).buildFuture());
84         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)))
85                 .thenReturn(RpcResultBuilder.success(ok).buildFuture());
86         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME)))
87                 .thenReturn(RpcResultBuilder.success(ok).buildFuture());
88         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME)))
89                 .thenReturn(RpcResultBuilder.success(ok).buildFuture());
90         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)))
91                 .thenReturn(RpcResultBuilder.success(ok).buildFuture());
92         when(listener.sendRequest(any(), eq(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME)))
93                 .thenReturn(RpcResultBuilder.success(ok).buildFuture());
94         final SchemaContext schemaContext =
95                 YangParserTestUtils.parseYangResource("/schemas/test-module.yang");
96         final MessageTransformer<NetconfMessage> transformer = new NetconfMessageTransformer(schemaContext, true);
97         final DOMRpcService rpc = new NetconfDeviceRpc(schemaContext, listener, transformer);
98         final RemoteDeviceId id =
99                 new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830));
100         callback = new NetconfRpcFutureCallback("prefix", id);
101         baseOps = new NetconfBaseOps(rpc, schemaContext);
102     }
103
104     @Test
105     public void testLock() throws Exception {
106         baseOps.lock(callback, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
107         verifyMessageSent("lock", NetconfMessageTransformUtil.NETCONF_LOCK_QNAME);
108     }
109
110     @Test
111     public void testLockCandidate() throws Exception {
112         baseOps.lockCandidate(callback);
113         verifyMessageSent("lock", NetconfMessageTransformUtil.NETCONF_LOCK_QNAME);
114     }
115
116     @Test
117     public void testUnlock() throws Exception {
118         baseOps.unlock(callback, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
119         verifyMessageSent("unlock", NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME);
120     }
121
122     @Test
123     public void testUnlockCandidate() throws Exception {
124         baseOps.unlockCandidate(callback);
125         verifyMessageSent("unlock", NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME);
126     }
127
128     @Test
129     public void testLockRunning() throws Exception {
130         baseOps.lockRunning(callback);
131         verifyMessageSent("lock-running", NetconfMessageTransformUtil.NETCONF_LOCK_QNAME);
132     }
133
134     @Test
135     public void testUnlockRunning() throws Exception {
136         baseOps.unlockRunning(callback);
137         verifyMessageSent("unlock-running", NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME);
138     }
139
140     @Test
141     public void testDiscardChanges() throws Exception {
142         baseOps.discardChanges(callback);
143         verifyMessageSent("discardChanges", NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME);
144     }
145
146     @Test
147     public void testCommit() throws Exception {
148         baseOps.commit(callback);
149         verifyMessageSent("commit", NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME);
150     }
151
152     @Test
153     public void testValidateCandidate() throws Exception {
154         baseOps.validateCandidate(callback);
155         verifyMessageSent("validate", NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME);
156     }
157
158     @Test
159     public void testValidateRunning() throws Exception {
160         baseOps.validateRunning(callback);
161         verifyMessageSent("validate-running", NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME);
162     }
163
164
165     @Test
166     public void testCopyConfig() throws Exception {
167         baseOps.copyConfig(callback, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME,
168                 NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
169         verifyMessageSent("copy-config", NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME);
170     }
171
172     @Test
173     public void testCopyRunningToCandidate() throws Exception {
174         baseOps.copyRunningToCandidate(callback);
175         verifyMessageSent("copy-config", NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME);
176     }
177
178
179     @Test
180     public void testGetConfigRunningData() throws Exception {
181         final Optional<NormalizedNode<?, ?>> dataOpt =
182                 baseOps.getConfigRunningData(callback, Optional.of(YangInstanceIdentifier.EMPTY)).get();
183         Assert.assertTrue(dataOpt.isPresent());
184         Assert.assertEquals(NetconfMessageTransformUtil.NETCONF_DATA_QNAME, dataOpt.get().getNodeType());
185     }
186
187     @Test
188     public void testGetData() throws Exception {
189         final Optional<NormalizedNode<?, ?>> dataOpt =
190                 baseOps.getData(callback, Optional.of(YangInstanceIdentifier.EMPTY)).get();
191         Assert.assertTrue(dataOpt.isPresent());
192         Assert.assertEquals(NetconfMessageTransformUtil.NETCONF_DATA_QNAME, dataOpt.get().getNodeType());
193     }
194
195     @Test
196     public void testGetConfigRunning() throws Exception {
197         baseOps.getConfigRunning(callback, Optional.absent());
198         verifyMessageSent("getConfig", NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME);
199     }
200
201     @Test
202     public void testGetConfigCandidate() throws Exception {
203         baseOps.getConfigCandidate(callback, Optional.absent());
204         verifyMessageSent("getConfig_candidate", NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME);
205     }
206
207     @Test
208     public void testGetConfigCandidateWithFilter() throws Exception {
209         final YangInstanceIdentifier id = YangInstanceIdentifier.builder()
210                 .node(CONTAINER_Q_NAME)
211                 .build();
212         baseOps.getConfigCandidate(callback, Optional.of(id));
213         verifyMessageSent("getConfig_candidate-filter", NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME);
214     }
215
216     @Test
217     public void testGet() throws Exception {
218         baseOps.get(callback, Optional.absent());
219         verifyMessageSent("get", NetconfMessageTransformUtil.NETCONF_GET_QNAME);
220     }
221
222     @Test
223     public void testEditConfigCandidate() throws Exception {
224         final QName leafQName = QName.create(CONTAINER_Q_NAME, "a");
225         final LeafNode<Object> leaf = Builders.leafBuilder()
226                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(leafQName))
227                 .withValue("leaf-value")
228                 .build();
229         final YangInstanceIdentifier leafId = YangInstanceIdentifier.builder()
230                 .node(CONTAINER_Q_NAME)
231                 .node(leafQName)
232                 .build();
233         final DataContainerChild<?, ?> structure = baseOps.createEditConfigStrcture(Optional.of(leaf),
234                 Optional.of(ModifyAction.REPLACE), leafId);
235         baseOps.editConfigCandidate(callback, structure, true);
236         verifyMessageSent("edit-config-test-module", NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME);
237     }
238
239     @Test
240     public void testEditConfigRunning() throws Exception {
241         final QName containerQName = QName.create("test:namespace", "2013-07-22", "c");
242         final QName leafQName = QName.create(containerQName, "a");
243         final LeafNode<Object> leaf = Builders.leafBuilder()
244                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(leafQName))
245                 .withValue("leaf-value")
246                 .build();
247         final YangInstanceIdentifier leafId = YangInstanceIdentifier.builder()
248                 .node(containerQName)
249                 .node(leafQName)
250                 .build();
251         final DataContainerChild<?, ?> structure = baseOps.createEditConfigStrcture(Optional.of(leaf),
252                 Optional.of(ModifyAction.REPLACE), leafId);
253         baseOps.editConfigRunning(callback, structure, ModifyAction.MERGE, true);
254         verifyMessageSent("edit-config-test-module-running", NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME);
255     }
256
257     private void verifyMessageSent(final String fileName, final QName name) {
258         final String path = "/netconfMessages/" + fileName + ".xml";
259         verify(listener).sendRequest(msg(path), eq(name));
260     }
261
262     private static NetconfMessage msg(final String name) {
263         final InputStream stream = NetconfBaseOpsTest.class.getResourceAsStream(name);
264         try {
265             return argThat(new NetconfMessageMatcher(XmlUtil.readXmlToDocument(stream)));
266         } catch (SAXException | IOException e) {
267             throw new IllegalStateException("Failed to read xml file " + name, e);
268         }
269     }
270
271     private static class NetconfMessageMatcher extends BaseMatcher<NetconfMessage> {
272
273         private final Document expected;
274
275         NetconfMessageMatcher(final Document expected) {
276             this.expected = removeAttrs(expected);
277         }
278
279         @Override
280         public boolean matches(final Object item) {
281             if (!(item instanceof NetconfMessage)) {
282                 return false;
283             }
284             final NetconfMessage message = (NetconfMessage) item;
285             final Document actualDoc = removeAttrs(message.getDocument());
286             actualDoc.normalizeDocument();
287             expected.normalizeDocument();
288             final Diff diff = XMLUnit.compareXML(expected, actualDoc);
289             return diff.similar();
290         }
291
292         @Override
293         public void describeTo(final Description description) {
294             description.appendText(XmlUtil.toString(expected));
295         }
296
297         private static Document removeAttrs(final Document input) {
298             final Document copy = XmlUtil.newDocument();
299             copy.appendChild(copy.importNode(input.getDocumentElement(), true));
300             final Element element = copy.getDocumentElement();
301             final List<String> attrNames = new ArrayList<>();
302             final NamedNodeMap attributes = element.getAttributes();
303             for (int i = 0; i < attributes.getLength(); i++) {
304                 final String nodeName = attributes.item(i).getNodeName();
305                 if ("xmlns".equals(nodeName)) {
306                     continue;
307                 }
308                 attrNames.add(nodeName);
309             }
310             attrNames.forEach(element::removeAttribute);
311             return copy;
312         }
313     }
314
315 }