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