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