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