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