Adjust to yangtools-2.0.0/odlparent-3.0.0 changes
[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.reset;
23 import static org.mockito.Mockito.verify;
24 import static org.mockito.Mockito.when;
25
26 import com.google.common.base.Optional;
27 import com.google.common.io.Resources;
28 import com.google.common.util.concurrent.Futures;
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 java.util.Map;
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.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
43 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
44 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
47 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
48 import org.opendaylight.controller.md.sal.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.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
65 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
70 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
73 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
74
75 /**
76  * Unit tests for JSONRestconfServiceImpl.
77  *
78  * @author Thomas Pantelis
79  */
80 @Deprecated
81 public class JSONRestconfServiceImplTest {
82     static final String IETF_INTERFACES_NS = "urn:ietf:params:xml:ns:yang:ietf-interfaces";
83     static final String IETF_INTERFACES_VERSION = "2013-07-04";
84     static final QName INTERFACES_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "interfaces");
85     static final QName INTERFACE_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "interface");
86     static final QName NAME_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "name");
87     static final QName TYPE_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "type");
88     static final QName ENABLED_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "enabled");
89     static final QName DESC_QNAME = QName.create(IETF_INTERFACES_NS, IETF_INTERFACES_VERSION, "description");
90
91     static final String TEST_MODULE_NS = "test:module";
92     static final String TEST_MODULE_VERSION = "2014-01-09";
93     static final QName TEST_CONT_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "cont");
94     static final QName TEST_CONT1_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "cont1");
95     static final QName TEST_LF11_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "lf11");
96     static final QName TEST_LF12_QNAME = QName.create(TEST_MODULE_NS, TEST_MODULE_VERSION, "lf12");
97
98     static final String TOASTER_MODULE_NS = "http://netconfcentral.org/ns/toaster";
99     static final String TOASTER_MODULE_VERSION = "2009-11-20";
100     static final QName TOASTER_DONENESS_QNAME =
101             QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "toasterDoneness");
102     static final QName TOASTER_TYPE_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "toasterToastType");
103     static final QName WHEAT_BREAD_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "wheat-bread");
104     static final QName MAKE_TOAST_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "make-toast");
105     static final QName CANCEL_TOAST_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "cancel-toast");
106     static final QName TEST_OUTPUT_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "testOutput");
107     static final QName TEXT_OUT_QNAME = QName.create(TOASTER_MODULE_NS, TOASTER_MODULE_VERSION, "textOut");
108
109     private static BrokerFacade brokerFacade;
110
111     private final JSONRestconfServiceImpl service = new JSONRestconfServiceImpl();
112
113     @BeforeClass
114     public static void init() throws IOException, ReactorException {
115         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/yangs"));
116         brokerFacade = mock(BrokerFacade.class);
117         RestconfImpl.getInstance().setBroker(brokerFacade);
118         RestconfImpl.getInstance().setControllerContext(ControllerContext.getInstance());
119     }
120
121     @Before
122     public void setup() {
123         reset(brokerFacade);
124     }
125
126     private static String loadData(final String path) throws IOException {
127         return Resources.asCharSource(JSONRestconfServiceImplTest.class.getResource(path),
128                 StandardCharsets.UTF_8).read();
129     }
130
131     @SuppressWarnings("rawtypes")
132     @Test
133     public void testPut() throws Exception {
134         final PutResult result = mock(PutResult.class);
135         when(brokerFacade.commitConfigurationDataPut(notNull(SchemaContext.class),
136                 notNull(YangInstanceIdentifier.class), notNull(NormalizedNode.class), Mockito.anyString(),
137                 Mockito.anyString())).thenReturn(result);
138         when(result.getFutureOfPutData())
139                 .thenReturn(Futures.immediateCheckedFuture(null));
140         when(result.getStatus()).thenReturn(Status.OK);
141         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
142         final String payload = loadData("/parts/ietf-interfaces_interfaces.json");
143         this.service.put(uriPath, payload);
144
145         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
146                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
147         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
148         verify(brokerFacade).commitConfigurationDataPut(notNull(SchemaContext.class), capturedPath.capture(),
149                 capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
150
151         verifyPath(capturedPath.getValue(), INTERFACES_QNAME, INTERFACE_QNAME,
152                 new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
153
154         assertTrue("Expected MapEntryNode. Actual " + capturedNode.getValue().getClass(),
155                 capturedNode.getValue() instanceof MapEntryNode);
156         final MapEntryNode actualNode = (MapEntryNode) capturedNode.getValue();
157         assertEquals("MapEntryNode node type", INTERFACE_QNAME, actualNode.getNodeType());
158         verifyLeafNode(actualNode, NAME_QNAME, "eth0");
159         verifyLeafNode(actualNode, TYPE_QNAME, "ethernetCsmacd");
160         verifyLeafNode(actualNode, ENABLED_QNAME, Boolean.FALSE);
161         verifyLeafNode(actualNode, DESC_QNAME, "some interface");
162     }
163
164     @SuppressWarnings("rawtypes")
165     @Test
166     public void testPutBehindMountPoint() throws Exception {
167         final DOMMountPoint mockMountPoint = setupTestMountPoint();
168         final PutResult result = mock(PutResult.class);
169         when(brokerFacade.commitMountPointDataPut(notNull(DOMMountPoint.class),
170                 notNull(YangInstanceIdentifier.class), notNull(NormalizedNode.class), Mockito.anyString(),
171                 Mockito.anyString())).thenReturn(result);
172         when(result.getFutureOfPutData()).thenReturn(Futures.immediateCheckedFuture(null));
173         when(result.getStatus()).thenReturn(Status.OK);
174         final String uriPath = "ietf-interfaces:interfaces/yang-ext:mount/test-module:cont/cont1";
175         final String payload = loadData("/full-versions/testCont1Data.json");
176
177         this.service.put(uriPath, payload);
178
179         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
180                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
181         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
182         verify(brokerFacade).commitMountPointDataPut(same(mockMountPoint), capturedPath.capture(),
183                 capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
184
185         verifyPath(capturedPath.getValue(), TEST_CONT_QNAME, TEST_CONT1_QNAME);
186
187         assertTrue("Expected ContainerNode", capturedNode.getValue() instanceof ContainerNode);
188         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
189         assertEquals("ContainerNode node type", TEST_CONT1_QNAME, actualNode.getNodeType());
190         verifyLeafNode(actualNode, TEST_LF11_QNAME, "lf11 data");
191         verifyLeafNode(actualNode, TEST_LF12_QNAME, "lf12 data");
192     }
193
194     @Test(expected = OperationFailedException.class)
195     @SuppressWarnings("checkstyle:IllegalThrows")
196     public void testPutFailure() throws Throwable {
197         final PutResult result = mock(PutResult.class);
198
199         when(result.getFutureOfPutData())
200                 .thenReturn(Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("mock")));
201         when(result.getStatus()).thenReturn(Status.OK);
202         when(brokerFacade.commitConfigurationDataPut(notNull(SchemaContext.class),
203                 notNull(YangInstanceIdentifier.class), notNull(NormalizedNode.class), Mockito.anyString(),
204                 Mockito.anyString())).thenReturn(result);
205
206         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
207         final String payload = loadData("/parts/ietf-interfaces_interfaces.json");
208
209         this.service.put(uriPath, payload);
210     }
211
212     @SuppressWarnings("rawtypes")
213     @Test
214     public void testPost() throws Exception {
215         doReturn(Futures.immediateCheckedFuture(null)).when(brokerFacade).commitConfigurationDataPost(
216                 any(SchemaContext.class), any(YangInstanceIdentifier.class), any(NormalizedNode.class),
217                 Mockito.anyString(), Mockito.anyString());
218
219         final String uriPath = null;
220         final String payload = loadData("/parts/ietf-interfaces_interfaces_absolute_path.json");
221
222         this.service.post(uriPath, payload);
223
224         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
225                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
226         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
227         verify(brokerFacade).commitConfigurationDataPost(notNull(SchemaContext.class), capturedPath.capture(),
228                 capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
229
230         verifyPath(capturedPath.getValue(), INTERFACES_QNAME);
231
232         assertTrue("Expected ContainerNode", capturedNode.getValue() instanceof ContainerNode);
233         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
234         assertEquals("ContainerNode node type", INTERFACES_QNAME, actualNode.getNodeType());
235
236         final java.util.Optional<DataContainerChild<?, ?>> mapChild = actualNode.getChild(
237             new NodeIdentifier(INTERFACE_QNAME));
238         assertEquals(INTERFACE_QNAME.toString() + " present", true, mapChild.isPresent());
239         assertTrue("Expected MapNode. Actual " + mapChild.get().getClass(), mapChild.get() instanceof MapNode);
240         final MapNode mapNode = (MapNode)mapChild.get();
241
242         final NodeIdentifierWithPredicates entryNodeID = new NodeIdentifierWithPredicates(
243                 INTERFACE_QNAME, NAME_QNAME, "eth0");
244         final java.util.Optional<MapEntryNode> entryChild = mapNode.getChild(entryNodeID);
245         assertEquals(entryNodeID.toString() + " present", true, entryChild.isPresent());
246         final MapEntryNode entryNode = entryChild.get();
247         verifyLeafNode(entryNode, NAME_QNAME, "eth0");
248         verifyLeafNode(entryNode, TYPE_QNAME, "ethernetCsmacd");
249         verifyLeafNode(entryNode, ENABLED_QNAME, Boolean.FALSE);
250         verifyLeafNode(entryNode, DESC_QNAME, "some interface");
251     }
252
253     @SuppressWarnings("rawtypes")
254     @Test
255     public void testPostBehindMountPoint() throws Exception {
256         final DOMMountPoint mockMountPoint = setupTestMountPoint();
257         doReturn(Futures.immediateCheckedFuture(null)).when(brokerFacade).commitConfigurationDataPost(
258                 notNull(DOMMountPoint.class), notNull(YangInstanceIdentifier.class), notNull(NormalizedNode.class),
259                 Mockito.anyString(), Mockito.anyString());
260
261         final String uriPath = "ietf-interfaces:interfaces/yang-ext:mount/test-module:cont";
262         final String payload = loadData("/full-versions/testCont1Data.json");
263
264         this.service.post(uriPath, payload);
265
266         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
267                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
268         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
269         verify(brokerFacade).commitConfigurationDataPost(same(mockMountPoint), capturedPath.capture(),
270                 capturedNode.capture(), Mockito.anyString(), Mockito.anyString());
271
272         verifyPath(capturedPath.getValue(), TEST_CONT_QNAME, TEST_CONT1_QNAME);
273
274         assertTrue("Expected ContainerNode", capturedNode.getValue() instanceof ContainerNode);
275         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
276         assertEquals("ContainerNode node type", TEST_CONT1_QNAME, actualNode.getNodeType());
277         verifyLeafNode(actualNode, TEST_LF11_QNAME, "lf11 data");
278         verifyLeafNode(actualNode, TEST_LF12_QNAME, "lf12 data");
279     }
280
281     @Test(expected = TransactionCommitFailedException.class)
282     @SuppressWarnings({ "checkstyle:IllegalThrows", "checkstyle:avoidHidingCauseException" })
283     public void testPostFailure() throws Throwable {
284         doReturn(Futures.immediateFailedCheckedFuture(new TransactionCommitFailedException("mock"))).when(brokerFacade)
285                 .commitConfigurationDataPost(any(SchemaContext.class), any(YangInstanceIdentifier.class),
286                         any(NormalizedNode.class), Mockito.anyString(), Mockito.anyString());
287
288         final String uriPath = null;
289         final String payload = loadData("/parts/ietf-interfaces_interfaces_absolute_path.json");
290
291         try {
292             this.service.post(uriPath, payload);
293         } catch (final OperationFailedException e) {
294             assertNotNull(e.getCause());
295             throw e.getCause();
296         }
297     }
298
299     @SuppressWarnings("rawtypes")
300     @Test
301     public void testPatch() throws Exception {
302         final PatchStatusContext result = mock(PatchStatusContext.class);
303         when(brokerFacade.patchConfigurationDataWithinTransaction(notNull(PatchContext.class)))
304             .thenReturn(result);
305
306         List<PatchStatusEntity> patchSTatus = new ArrayList<>();
307
308         PatchStatusEntity entity = new PatchStatusEntity("edit1", true, null);
309
310         patchSTatus.add(entity);
311
312         when(result.getEditCollection())
313                 .thenReturn(patchSTatus);
314         when(result.getGlobalErrors()).thenReturn(new ArrayList<>());
315         when(result.getPatchId()).thenReturn("1");
316         final String uriPath = "ietf-interfaces:interfaces/interface/eth0";
317         final String payload = loadData("/parts/ietf-interfaces_interfaces_patch.json");
318         final Optional<String> patchResult = this.service.patch(uriPath, payload);
319
320         assertTrue(patchResult.get().contains("\"ok\":[null]"));
321     }
322
323     @SuppressWarnings("rawtypes")
324     @Test
325     public void testPatchBehindMountPoint() throws Exception {
326         final DOMMountPoint mockMountPoint = setupTestMountPoint();
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(Futures.immediateCheckedFuture(null)).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(Futures.immediateCheckedFuture(expResult)).when(brokerFacade).invokeRpc(eq(path),
422                 any(NormalizedNode.class));
423
424         final String uriPath = "toaster:make-toast";
425         final String input = loadData("/full-versions/make-toast-rpc-input.json");
426
427         final Optional<String> output = this.service.invokeRpc(uriPath, Optional.of(input));
428
429         assertEquals("Output present", false, output.isPresent());
430
431         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
432         verify(brokerFacade).invokeRpc(eq(path), capturedNode.capture());
433
434         assertTrue("Expected ContainerNode. Actual " + capturedNode.getValue().getClass(),
435                 capturedNode.getValue() instanceof ContainerNode);
436         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
437         verifyLeafNode(actualNode, TOASTER_DONENESS_QNAME, Long.valueOf(10));
438         verifyLeafNode(actualNode, TOASTER_TYPE_QNAME, WHEAT_BREAD_QNAME);
439     }
440
441     @Test
442     public void testInvokeRpcWithNoInput() throws Exception {
443         final SchemaPath path = SchemaPath.create(true, CANCEL_TOAST_QNAME);
444
445         final DOMRpcResult expResult = new DefaultDOMRpcResult((NormalizedNode<?, ?>)null);
446         doReturn(Futures.immediateCheckedFuture(expResult)).when(brokerFacade).invokeRpc(any(SchemaPath.class),
447                 any(NormalizedNode.class));
448
449         final String uriPath = "toaster:cancel-toast";
450
451         final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>absent());
452
453         assertEquals("Output present", false, output.isPresent());
454
455         verify(brokerFacade).invokeRpc(eq(path), isNull(NormalizedNode.class));
456     }
457
458     @Test
459     public void testInvokeRpcWithOutput() throws Exception {
460         final SchemaPath path = SchemaPath.create(true, TEST_OUTPUT_QNAME);
461
462         final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
463                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_OUTPUT_QNAME))
464                 .withChild(ImmutableNodes.leafNode(TEXT_OUT_QNAME, "foo")).build();
465         final DOMRpcResult expResult = new DefaultDOMRpcResult(outputNode);
466         doReturn(Futures.immediateCheckedFuture(expResult)).when(brokerFacade).invokeRpc(any(SchemaPath.class),
467                 any(NormalizedNode.class));
468
469         final String uriPath = "toaster:testOutput";
470
471         final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>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(NormalizedNode.class));
478     }
479
480     @Test(expected = OperationFailedException.class)
481     public void testInvokeRpcFailure() throws Exception {
482         final DOMRpcException exception = new DOMRpcImplementationNotAvailableException("testExeption");
483         doReturn(Futures.immediateFailedCheckedFuture(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.<String>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                     Mockito.anyString());
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(), Mockito.anyString());
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     DOMMountPoint setupTestMountPoint() throws FileNotFoundException, ReactorException {
531         final SchemaContext schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
532         final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
533         doReturn(schemaContextTestModule).when(mockMountPoint).getSchemaContext();
534
535         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
536         doReturn(Optional.of(mockMountPoint))
537                 .when(mockMountService).getMountPoint(notNull(YangInstanceIdentifier.class));
538
539         ControllerContext.getInstance().setMountService(mockMountService);
540         return mockMountPoint;
541     }
542
543     void verifyLeafNode(final DataContainerNode<?> parent, final QName leafType, final Object leafValue) {
544         final java.util.Optional<DataContainerChild<?, ?>> leafChild = parent.getChild(new NodeIdentifier(leafType));
545         assertEquals(leafType.toString() + " present", true, leafChild.isPresent());
546         assertEquals(leafType.toString() + " value", leafValue, leafChild.get().getValue());
547     }
548
549     void verifyPath(final YangInstanceIdentifier path, final Object... expArgs) {
550         final List<PathArgument> pathArgs = path.getPathArguments();
551         assertEquals("Arg count for actual path " + path, expArgs.length, pathArgs.size());
552         int index = 0;
553         for (final PathArgument actual: pathArgs) {
554             QName expNodeType;
555             if (expArgs[index] instanceof Object[]) {
556                 final Object[] listEntry = (Object[]) expArgs[index];
557                 expNodeType = (QName) listEntry[0];
558
559                 assertTrue(actual instanceof NodeIdentifierWithPredicates);
560                 final Map<QName, Object> keyValues = ((NodeIdentifierWithPredicates)actual).getKeyValues();
561                 assertEquals(String.format("Path arg %d keyValues size", index + 1), 1, keyValues.size());
562                 final QName expKey = (QName) listEntry[1];
563                 assertEquals(String.format("Path arg %d keyValue for %s", index + 1, expKey), listEntry[2],
564                         keyValues.get(expKey));
565             } else {
566                 expNodeType = (QName) expArgs[index];
567             }
568
569             assertEquals(String.format("Path arg %d node type", index + 1), expNodeType, actual.getNodeType());
570             index++;
571         }
572
573     }
574 }