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