48db5de78894bf463401c517ef42d4617c23b273
[netconf.git] / restconf / restconf-nb-bierman02 / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / JSONRestconfServiceImplTest.java
1 /*
2  * Copyright (c) 2015 Brocade Communications 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 package org.opendaylight.controller.sal.restconf.impl.test;
9
10 import static org.hamcrest.CoreMatchers.containsString;
11 import static org.hamcrest.MatcherAssert.assertThat;
12 import static org.junit.Assert.assertEquals;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertTrue;
15 import static org.mockito.ArgumentMatchers.any;
16 import static org.mockito.ArgumentMatchers.anyString;
17 import static org.mockito.ArgumentMatchers.eq;
18 import static org.mockito.ArgumentMatchers.isNull;
19 import static org.mockito.ArgumentMatchers.same;
20 import static org.mockito.Mockito.doReturn;
21 import static org.mockito.Mockito.mock;
22 import static org.mockito.Mockito.verify;
23 import static org.mockito.Mockito.when;
24 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
25 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
26
27 import com.google.common.io.Resources;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.nio.charset.StandardCharsets;
31 import java.util.List;
32 import java.util.Optional;
33 import javax.ws.rs.core.Response.Status;
34 import org.junit.Before;
35 import org.junit.BeforeClass;
36 import org.junit.Test;
37 import org.mockito.ArgumentCaptor;
38 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
39 import org.opendaylight.mdsal.common.api.CommitInfo;
40 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
41 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
42 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
43 import org.opendaylight.mdsal.dom.api.DOMRpcException;
44 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
45 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
46 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
47 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
48 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
49 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
50 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
51 import org.opendaylight.netconf.sal.restconf.impl.JSONRestconfServiceImpl;
52 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
53 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
54 import org.opendaylight.restconf.common.patch.PatchContext;
55 import org.opendaylight.restconf.common.patch.PatchStatusContext;
56 import org.opendaylight.restconf.common.patch.PatchStatusEntity;
57 import org.opendaylight.yangtools.yang.common.OperationFailedException;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.common.Uint32;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
64 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
66 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
71 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
72 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
73 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
74
75 /**
76  * Unit tests for JSONRestconfServiceImpl.
77  *
78  * @author Thomas Pantelis
79  */
80 @Deprecated
81 public class JSONRestconfServiceImplTest {
82     static final String IETF_INTERFACES_NS = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
83     static final String IETF_INTERFACES_VERSION = "2013-07-04";
84     static final QName INTERFACES_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "interfaces");
85     static final QName INTERFACE_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "interface");
86     static final QName NAME_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "name");
87     static final QName TYPE_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "type");
88     static final QName ENABLED_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "enabled");
89     static final QName DESC_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "description");
90
91     static final String TEST_MODULE_NS = "test:module";
92     static final String TEST_MODULE_VERSION = "2014-01-09";
93     static final QName TEST_CONT_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "cont");
94     static final QName TEST_CONT1_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "cont1");
95     static final QName TEST_LF11_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "lf11");
96     static final QName TEST_LF12_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "lf12");
97
98     static final String TOASTER_MODULE_NS = "http://netconfcentral.org/ns/toaster";
99     static final String TOASTER_MODULE_VERSION = "2009-11-20";
100     static final QName TOASTER_DONENESS_QNAME =
101             QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "toasterDoneness");
102     static final QName TOASTER_TYPE_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "toasterToastType");
103     static final QName WHEAT_BREAD_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "wheat-bread");
104     static final QName MAKE_TOAST_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "make-toast");
105     static final QName CANCEL_TOAST_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "cancel-toast");
106     static final QName TEST_OUTPUT_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "testOutput");
107     static final QName TEXT_OUT_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "textOut");
108
109     private static EffectiveModelContext schemaContext;
110
111     private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
112     private final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
113     private JSONRestconfServiceImpl service;
114
115     @BeforeClass
116     public static void init() throws IOException, ReactorException {
117         schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs");
118     }
119
120     @Before
121     public void setup() throws FileNotFoundException {
122         final EffectiveModelContext mountPointSchemaContext = TestUtils.loadSchemaContext("/full-versions/test-module");
123         final ControllerContext controllerContext =
124                 TestRestconfUtils.newControllerContext(schemaContext, mockMountPoint);
125         doReturn(java.util.Optional.of(FixedDOMSchemaService.of(() -> mountPointSchemaContext))).when(mockMountPoint)
126                 .getService(eq(DOMSchemaService.class));
127
128         service = new JSONRestconfServiceImpl(controllerContext,
129                 RestconfImpl.newInstance(brokerFacade, controllerContext));
130     }
131
132     private static String loadData(final String path) throws IOException {
133         return Resources.asCharSource(JSONRestconfServiceImplTest.class.getResource(path),
134                 StandardCharsets.UTF_8).read();
135     }
136
137     @Test
138     public void testPut() throws Exception {
139         final PutResult result = mock(PutResult.class);
140         when(brokerFacade.commitConfigurationDataPut(any(EffectiveModelContext.class),
141                 any(YangInstanceIdentifier.class), any(NormalizedNode.class), isNull(), isNull()))
142                 .thenReturn(result);
143         doReturn(CommitInfo.emptyFluentFuture()).when(result).getFutureOfPutData();
144         when(result.getStatus()).thenReturn(Status.OK);
145         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
146         final String payload = loadData("/parts/ietf-interfaces_interfaces.json");
147         service.put(uriPath, payload);
148
149         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
150                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
151         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
152         verify(brokerFacade).commitConfigurationDataPut(any(EffectiveModelContext.class), capturedPath.capture(),
153                 capturedNode.capture(), isNull(), isNull());
154
155         verifyPath(capturedPath.getValue(), INTERFACES_QNAME, INTERFACE_QNAME,
156                 new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
157
158         assertTrue("Expected MapEntryNode. Actual " + capturedNode.getValue().getClass(),
159                 capturedNode.getValue() instanceof MapEntryNode);
160         final MapEntryNode actualNode = (MapEntryNode) capturedNode.getValue();
161         assertEquals("MapEntryNode node type", INTERFACE_QNAME, actualNode.getIdentifier().getNodeType());
162         verifyLeafNode(actualNode, NAME_QNAME, "eth0");
163         verifyLeafNode(actualNode, TYPE_QNAME, "ethernetCsmacd");
164         verifyLeafNode(actualNode, ENABLED_QNAME, Boolean.FALSE);
165         verifyLeafNode(actualNode, DESC_QNAME, "some interface");
166     }
167
168     @Test
169     public void testPutBehindMountPoint() throws Exception {
170         final PutResult result = mock(PutResult.class);
171         when(brokerFacade.commitMountPointDataPut(any(DOMMountPoint.class),
172                 any(YangInstanceIdentifier.class), any(NormalizedNode.class), isNull(), isNull()))
173                 .thenReturn(result);
174         doReturn(CommitInfo.emptyFluentFuture()).when(result).getFutureOfPutData();
175         when(result.getStatus()).thenReturn(Status.OK);
176         final String uriPath = "ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
177         final String payload = loadData("/full-versions/testCont1Data.json");
178
179         service.put(uriPath, payload);
180
181         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
182                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
183         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
184         verify(brokerFacade).commitMountPointDataPut(same(mockMountPoint), capturedPath.capture(),
185                 capturedNode.capture(), isNull(), isNull());
186
187         verifyPath(capturedPath.getValue(), TEST_CONT_QNAME, TEST_CONT1_QNAME);
188
189         assertTrue("Expected ContainerNode", capturedNode.getValue() instanceof ContainerNode);
190         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
191         assertEquals("ContainerNode node type", TEST_CONT1_QNAME, actualNode.getIdentifier().getNodeType());
192         verifyLeafNode(actualNode, TEST_LF11_QNAME, "lf11 data");
193         verifyLeafNode(actualNode, TEST_LF12_QNAME, "lf12 data");
194     }
195
196     @Test(expected = OperationFailedException.class)
197     @SuppressWarnings("checkstyle:IllegalThrows")
198     public void testPutFailure() throws Throwable {
199         final PutResult result = mock(PutResult.class);
200
201         doReturn(immediateFailedFluentFuture(new TransactionCommitFailedException("mock"))).when(result)
202         .getFutureOfPutData();
203         when(result.getStatus()).thenReturn(Status.OK);
204         when(brokerFacade.commitConfigurationDataPut(any(EffectiveModelContext.class),
205                 any(YangInstanceIdentifier.class), any(NormalizedNode.class), anyString(),
206                 anyString())).thenReturn(result);
207
208         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
209         final String payload = loadData("/parts/ietf-interfaces_interfaces.json");
210
211         service.put(uriPath, payload);
212     }
213
214     @Test
215     public void testPost() throws Exception {
216         doReturn(CommitInfo.emptyFluentFuture()).when(brokerFacade).commitConfigurationDataPost(
217                 any(EffectiveModelContext.class), any(YangInstanceIdentifier.class), any(NormalizedNode.class),
218                 isNull(), isNull());
219
220         final String uriPath = null;
221         final String payload = loadData("/parts/ietf-interfaces_interfaces_absolute_path.json");
222
223         service.post(uriPath, payload);
224
225         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
226                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
227         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
228         verify(brokerFacade).commitConfigurationDataPost(any(EffectiveModelContext.class), capturedPath.capture(),
229                 capturedNode.capture(), isNull(), isNull());
230
231         verifyPath(capturedPath.getValue(), INTERFACES_QNAME);
232
233         assertTrue("Expected ContainerNode", capturedNode.getValue() instanceof ContainerNode);
234         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
235         assertEquals("ContainerNode node type", INTERFACES_QNAME, actualNode.getIdentifier().getNodeType());
236
237         final java.util.Optional<DataContainerChild> mapChild = actualNode.findChildByArg(
238             new NodeIdentifier(INTERFACE_QNAME));
239         assertEquals(INTERFACE_QNAME.toString() + " present", true, mapChild.isPresent());
240         assertTrue("Expected MapNode. Actual " + mapChild.get().getClass(), mapChild.get() instanceof MapNode);
241         final MapNode mapNode = (MapNode)mapChild.get();
242
243         final NodeIdentifierWithPredicates entryNodeID = NodeIdentifierWithPredicates.of(
244                 INTERFACE_QNAME, NAME_QNAME, "eth0");
245         final java.util.Optional<MapEntryNode> entryChild = mapNode.findChildByArg(entryNodeID);
246         assertEquals(entryNodeID.toString() + " present", true, entryChild.isPresent());
247         final MapEntryNode entryNode = entryChild.get();
248         verifyLeafNode(entryNode, NAME_QNAME, "eth0");
249         verifyLeafNode(entryNode, TYPE_QNAME, "ethernetCsmacd");
250         verifyLeafNode(entryNode, ENABLED_QNAME, Boolean.FALSE);
251         verifyLeafNode(entryNode, DESC_QNAME, "some interface");
252     }
253
254     @Test
255     public void testPostBehindMountPoint() throws Exception {
256         doReturn(CommitInfo.emptyFluentFuture()).when(brokerFacade).commitConfigurationDataPost(
257                 any(DOMMountPoint.class), any(YangInstanceIdentifier.class), any(NormalizedNode.class),
258                 isNull(), isNull());
259
260         final String uriPath = "ietf-interfaces:interfaces/yang-ext:mount/test-module:cont";
261         final String payload = loadData("/full-versions/testCont1Data.json");
262
263         service.post(uriPath, payload);
264
265         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
266                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
267         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
268         verify(brokerFacade).commitConfigurationDataPost(same(mockMountPoint), capturedPath.capture(),
269                 capturedNode.capture(), isNull(), isNull());
270
271         verifyPath(capturedPath.getValue(), TEST_CONT_QNAME, TEST_CONT1_QNAME);
272
273         assertTrue("Expected ContainerNode", capturedNode.getValue() instanceof ContainerNode);
274         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
275         assertEquals("ContainerNode node type", TEST_CONT1_QNAME, actualNode.getIdentifier().getNodeType());
276         verifyLeafNode(actualNode, TEST_LF11_QNAME, "lf11 data");
277         verifyLeafNode(actualNode, TEST_LF12_QNAME, "lf12 data");
278     }
279
280     @Test(expected = TransactionCommitFailedException.class)
281     @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" })
282     public void testPostFailure() throws Throwable {
283         doReturn(immediateFailedFluentFuture(new TransactionCommitFailedException("mock"))).when(brokerFacade)
284                 .commitConfigurationDataPost(any(EffectiveModelContext.class), any(YangInstanceIdentifier.class),
285                         any(NormalizedNode.class), isNull(), isNull());
286
287         final String uriPath = null;
288         final String payload = loadData("/parts/ietf-interfaces_interfaces_absolute_path.json");
289
290         try {
291             service.post(uriPath, payload);
292         } catch (final OperationFailedException e) {
293             assertNotNull(e.getCause());
294             throw e.getCause();
295         }
296     }
297
298     @Test
299     public void testPatch() throws Exception {
300         final PatchStatusContext result = mock(PatchStatusContext.class);
301         when(brokerFacade.patchConfigurationDataWithinTransaction(any(PatchContext.class)))
302             .thenReturn(result);
303
304         when(result.getEditCollection()).thenReturn(List.of(new PatchStatusEntity("edit1", true, null)));
305         when(result.getGlobalErrors()).thenReturn(List.of());
306         when(result.getPatchId()).thenReturn("1");
307         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
308         final String payload = loadData("/parts/ietf-interfaces_interfaces_patch.json");
309         final Optional<String> patchResult = service.patch(uriPath, payload);
310
311         assertTrue(patchResult.get().contains("\"ok\":[null]"));
312     }
313
314     @Test
315     public void testPatchBehindMountPoint() throws Exception {
316         final PatchStatusContext result = mock(PatchStatusContext.class);
317         when(brokerFacade.patchConfigurationDataWithinTransaction(any(PatchContext.class))).thenReturn(result);
318
319         when(result.getEditCollection()).thenReturn(List.of(new PatchStatusEntity("edit1", true, null)));
320         when(result.getGlobalErrors()).thenReturn(List.of());
321         when(result.getPatchId()).thenReturn("1");
322
323         final String uriPath = "ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
324         final String payload = loadData("/full-versions/testCont1DataPatch.json");
325
326         final Optional<String> patchResult = service.patch(uriPath, payload);
327
328         assertTrue(patchResult.get().contains("\"ok\":[null]"));
329     }
330
331     @Test(expected = OperationFailedException.class)
332     @SuppressWarnings("checkstyle:IllegalThrows")
333     public void testPatchFailure() throws Throwable {
334         final PatchStatusContext result = mock(PatchStatusContext.class);
335         when(brokerFacade.patchConfigurationDataWithinTransaction(any(PatchContext.class)))
336             .thenThrow(new TransactionCommitFailedException("Transaction failed"));
337
338         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
339         final String payload = loadData("/parts/ietf-interfaces_interfaces_patch.json");
340
341         final Optional<String> patchResult = service.patch(uriPath, payload);
342
343         assertTrue("Patch output is not null", patchResult.isPresent());
344         String patch = patchResult.get();
345         assertTrue(patch.contains("TransactionCommitFailedException"));
346     }
347
348     @Test
349     public void testDelete() throws Exception {
350         doReturn(CommitInfo.emptyFluentFuture()).when(brokerFacade)
351                 .commitConfigurationDataDelete(any(YangInstanceIdentifier.class));
352
353         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
354
355         service.delete(uriPath);
356
357         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
358                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
359         verify(brokerFacade).commitConfigurationDataDelete(capturedPath.capture());
360
361         verifyPath(capturedPath.getValue(), INTERFACES_QNAME, INTERFACE_QNAME,
362                 new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
363     }
364
365     @Test(expected = OperationFailedException.class)
366     public void testDeleteFailure() throws Exception {
367         final String invalidUriPath = "ietf-interfaces:interfaces/invalid";
368
369         service.delete(invalidUriPath);
370     }
371
372     @Test
373     public void testGetConfig() throws Exception {
374         testGet(LogicalDatastoreType.CONFIGURATION);
375     }
376
377     @Test
378     public void testGetOperational() throws Exception {
379         testGet(LogicalDatastoreType.OPERATIONAL);
380     }
381
382     @Test
383     public void testGetWithNoData() throws OperationFailedException {
384         doReturn(null).when(brokerFacade).readConfigurationData(any(YangInstanceIdentifier.class), anyString());
385         final String uriPath = "ietf-interfaces:interfaces";
386         service.get(uriPath, LogicalDatastoreType.CONFIGURATION);
387     }
388
389     @Test(expected = OperationFailedException.class)
390     public void testGetFailure() throws Exception {
391         final String invalidUriPath = "/ietf-interfaces:interfaces/invalid";
392         service.get(invalidUriPath, LogicalDatastoreType.CONFIGURATION);
393     }
394
395     @Test
396     public void testInvokeRpcWithInput() throws Exception {
397         final DOMRpcResult expResult = new DefaultDOMRpcResult((NormalizedNode)null);
398         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(MAKE_TOAST_QNAME),
399             any(NormalizedNode.class));
400
401         final String uriPath = "toaster:make-toast";
402         final String input = loadData("/full-versions/make-toast-rpc-input.json");
403
404         final Optional<String> output = service.invokeRpc(uriPath, Optional.of(input));
405
406         assertEquals("Output present", false, output.isPresent());
407
408         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
409         verify(brokerFacade).invokeRpc(eq(MAKE_TOAST_QNAME), capturedNode.capture());
410
411         assertTrue("Expected ContainerNode. Actual " + capturedNode.getValue().getClass(),
412                 capturedNode.getValue() instanceof ContainerNode);
413         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
414         verifyLeafNode(actualNode, TOASTER_DONENESS_QNAME, Uint32.valueOf(10));
415         verifyLeafNode(actualNode, TOASTER_TYPE_QNAME, WHEAT_BREAD_QNAME);
416     }
417
418     @Test
419     public void testInvokeRpcWithNoInput() throws Exception {
420         final DOMRpcResult expResult = new DefaultDOMRpcResult((NormalizedNode)null);
421         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(any(QName.class), any());
422
423         final String uriPath = "toaster:cancel-toast";
424
425         final Optional<String> output = service.invokeRpc(uriPath, Optional.empty());
426
427         assertEquals("Output present", false, output.isPresent());
428
429         verify(brokerFacade).invokeRpc(eq(CANCEL_TOAST_QNAME), any());
430     }
431
432     @Test
433     public void testInvokeRpcWithOutput() throws Exception {
434         final NormalizedNode outputNode = ImmutableContainerNodeBuilder.create()
435                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_OUTPUT_QNAME))
436                 .withChild(ImmutableNodes.leafNode(TEXT_OUT_QNAME, "foo")).build();
437         final DOMRpcResult expResult = new DefaultDOMRpcResult(outputNode);
438         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(any(QName.class), any());
439
440         final String uriPath = "toaster:testOutput";
441
442         final Optional<String> output = service.invokeRpc(uriPath, Optional.empty());
443
444         assertEquals("Output present", true, output.isPresent());
445         assertNotNull("Returned null response", output.get());
446         assertThat("Missing \"textOut\"", output.get(), containsString("\"textOut\":\"foo\""));
447
448         verify(brokerFacade).invokeRpc(eq(TEST_OUTPUT_QNAME), any());
449     }
450
451     @Test(expected = OperationFailedException.class)
452     public void testInvokeRpcFailure() throws Exception {
453         final DOMRpcException exception = new DOMRpcImplementationNotAvailableException("testExeption");
454         doReturn(immediateFailedFluentFuture(exception)).when(brokerFacade).invokeRpc(any(QName.class),
455                 any(NormalizedNode.class));
456
457         final String uriPath = "toaster:cancel-toast";
458
459         service.invokeRpc(uriPath, Optional.empty());
460     }
461
462     void testGet(final LogicalDatastoreType datastoreType) throws OperationFailedException {
463         final MapEntryNode entryNode = ImmutableNodes.mapEntryBuilder(INTERFACE_QNAME, NAME_QNAME, "eth0")
464                 .withChild(ImmutableNodes.leafNode(NAME_QNAME, "eth0"))
465                 .withChild(ImmutableNodes.leafNode(TYPE_QNAME, "ethernetCsmacd"))
466                 .withChild(ImmutableNodes.leafNode(ENABLED_QNAME, Boolean.TRUE))
467                 .withChild(ImmutableNodes.leafNode(DESC_QNAME, "eth interface"))
468                 .build();
469
470         if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
471             doReturn(entryNode).when(brokerFacade).readConfigurationData(any(YangInstanceIdentifier.class),
472                     isNull());
473         } else {
474             doReturn(entryNode).when(brokerFacade).readOperationalData(any(YangInstanceIdentifier.class));
475         }
476
477         final String uriPath = "/ietf-interfaces:interfaces/interface/eth0";
478
479         final Optional<String> optionalResp = service.get(uriPath, datastoreType);
480         assertEquals("Response present", true, optionalResp.isPresent());
481         final String jsonResp = optionalResp.get();
482
483         assertNotNull("Returned null response", jsonResp);
484         assertThat("Missing \"name\"", jsonResp, containsString("\"name\":\"eth0\""));
485         assertThat("Missing \"type\"", jsonResp, containsString("\"type\":\"ethernetCsmacd\""));
486         assertThat("Missing \"enabled\"", jsonResp, containsString("\"enabled\":true"));
487         assertThat("Missing \"description\"", jsonResp, containsString("\"description\":\"eth interface\""));
488
489         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
490                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
491         if (datastoreType == LogicalDatastoreType.CONFIGURATION) {
492             verify(brokerFacade).readConfigurationData(capturedPath.capture(), isNull());
493         } else {
494             verify(brokerFacade).readOperationalData(capturedPath.capture());
495         }
496
497         verifyPath(capturedPath.getValue(), INTERFACES_QNAME, INTERFACE_QNAME,
498                 new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
499     }
500
501     void verifyLeafNode(final DataContainerNode parent, final QName leafType, final Object leafValue) {
502         final java.util.Optional<DataContainerChild> leafChild = parent.findChildByArg(new NodeIdentifier(leafType));
503         assertTrue(leafType.toString() + " present", leafChild.isPresent());
504         assertEquals(leafType.toString() + " value", leafValue, leafChild.get().body());
505     }
506
507     void verifyPath(final YangInstanceIdentifier path, final Object... expArgs) {
508         final List<PathArgument> pathArgs = path.getPathArguments();
509         assertEquals("Arg count for actual path " + path, expArgs.length, pathArgs.size());
510         int index = 0;
511         for (final PathArgument actual: pathArgs) {
512             QName expNodeType;
513             if (expArgs[index] instanceof Object[]) {
514                 final Object[] listEntry = (Object[]) expArgs[index];
515                 expNodeType = (QName) listEntry[0];
516
517                 assertTrue(actual instanceof NodeIdentifierWithPredicates);
518                 final NodeIdentifierWithPredicates nip = (NodeIdentifierWithPredicates)actual;
519                 assertEquals(String.format("Path arg %d keyValues size", index + 1), 1, nip.size());
520                 final QName expKey = (QName) listEntry[1];
521                 assertEquals(String.format("Path arg %d keyValue for %s", index + 1, expKey), listEntry[2],
522                     nip.getValue(expKey));
523             } else {
524                 expNodeType = (QName) expArgs[index];
525             }
526
527             assertEquals(String.format("Path arg %d node type", index + 1), expNodeType, actual.getNodeType());
528             index++;
529         }
530
531     }
532 }