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