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