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