Split Restconf implementations (draft02 and RFC) - Application
[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     @Test
341     public void testDelete() throws Exception {
342         doReturn(Futures.immediateCheckedFuture(Boolean.TRUE)).when(mockReadWriteTx).exists(
343                 eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class));
344
345         final String uriPath = "ietf-interfaces:interfaces/interface=eth0";
346
347         this.service.delete(uriPath);
348
349         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
350                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
351
352         verify(mockReadWriteTx).delete(eq(LogicalDatastoreType.CONFIGURATION), capturedPath.capture());
353
354         verifyPath(capturedPath.getValue(), INTERFACES_QNAME, INTERFACE_QNAME,
355                 new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
356     }
357
358     @Test(expected = OperationFailedException.class)
359     public void testDeleteFailure() throws Exception {
360         final String invalidUriPath = "ietf-interfaces:interfaces/invalid";
361
362         this.service.delete(invalidUriPath);
363     }
364
365     @Test
366     public void testGetConfig() throws Exception {
367         testGet(LogicalDatastoreType.CONFIGURATION);
368     }
369
370     @Test
371     public void testGetOperational() throws Exception {
372         testGet(LogicalDatastoreType.OPERATIONAL);
373     }
374
375     @Test
376     public void testGetWithNoData() throws OperationFailedException {
377         final String uriPath = "ietf-interfaces:interfaces";
378         this.service.get(uriPath, LogicalDatastoreType.CONFIGURATION);
379     }
380
381     @Test(expected = OperationFailedException.class)
382     public void testGetFailure() throws Exception {
383         final String invalidUriPath = "/ietf-interfaces:interfaces/invalid";
384         this.service.get(invalidUriPath, LogicalDatastoreType.CONFIGURATION);
385     }
386
387     @SuppressWarnings("rawtypes")
388     @Test
389     public void testInvokeRpcWithInput() throws Exception {
390         final SchemaPath path = SchemaPath.create(true, MAKE_TOAST_QNAME);
391
392         final DOMRpcResult expResult = new DefaultDOMRpcResult((NormalizedNode<?, ?>)null);
393         doReturn(Futures.immediateCheckedFuture(expResult)).when(mockRpcService).invokeRpc(eq(path),
394                 any(NormalizedNode.class));
395
396         final String uriPath = "toaster:make-toast";
397         final String input = loadData("/full-versions/make-toast-rpc-input.json");
398
399         final Optional<String> output = this.service.invokeRpc(uriPath, Optional.of(input));
400
401         assertEquals("Output present", false, output.isPresent());
402
403         final ArgumentCaptor<NormalizedNode> capturedNode = ArgumentCaptor.forClass(NormalizedNode.class);
404         verify(mockRpcService).invokeRpc(eq(path), capturedNode.capture());
405
406         assertTrue("Expected ContainerNode. Actual " + capturedNode.getValue().getClass(),
407                 capturedNode.getValue() instanceof ContainerNode);
408         final ContainerNode actualNode = (ContainerNode) capturedNode.getValue();
409         verifyLeafNode(actualNode, TOASTER_DONENESS_QNAME, Long.valueOf(10));
410         verifyLeafNode(actualNode, TOASTER_TYPE_QNAME, WHEAT_BREAD_QNAME);
411     }
412
413     @Test
414     public void testInvokeRpcWithNoInput() throws Exception {
415         final SchemaPath path = SchemaPath.create(true, CANCEL_TOAST_QNAME);
416
417         final DOMRpcResult expResult = new DefaultDOMRpcResult((NormalizedNode<?, ?>)null);
418         doReturn(Futures.immediateCheckedFuture(expResult)).when(mockRpcService).invokeRpc(eq(path),
419                 any(NormalizedNode.class));
420
421         final String uriPath = "toaster:cancel-toast";
422
423         final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>absent());
424
425         assertEquals("Output present", false, output.isPresent());
426
427         verify(mockRpcService).invokeRpc(eq(path), isNull(NormalizedNode.class));
428     }
429
430     @Test
431     public void testInvokeRpcWithOutput() throws Exception {
432         final SchemaPath path = SchemaPath.create(true, TEST_OUTPUT_QNAME);
433
434         final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
435                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(TEST_OUTPUT_QNAME))
436                 .withChild(ImmutableNodes.leafNode(TEXT_OUT_QNAME, "foo")).build();
437         final DOMRpcResult expResult = new DefaultDOMRpcResult(outputNode);
438         doReturn(Futures.immediateCheckedFuture(expResult)).when(mockRpcService).invokeRpc(eq(path),
439                 any(NormalizedNode.class));
440
441         final String uriPath = "toaster:testOutput";
442
443         final Optional<String> output = this.service.invokeRpc(uriPath, Optional.<String>absent());
444
445         assertEquals("Output present", true, output.isPresent());
446         assertNotNull("Returned null response", output.get());
447         assertThat("Missing \"textOut\"", output.get(), containsString("\"textOut\":\"foo\""));
448
449         verify(mockRpcService).invokeRpc(eq(path), isNull(NormalizedNode.class));
450     }
451
452     @Test(expected = OperationFailedException.class)
453     public void testInvokeRpcFailure() throws Exception {
454         final DOMRpcException exception = new DOMRpcImplementationNotAvailableException("testExeption");
455         doReturn(Futures.immediateFailedCheckedFuture(exception)).when(mockRpcService).invokeRpc(any(SchemaPath.class),
456                 any(NormalizedNode.class));
457
458         final String uriPath = "toaster:cancel-toast";
459
460         this.service.invokeRpc(uriPath, Optional.<String>absent());
461     }
462
463     void testGet(final LogicalDatastoreType datastoreType) throws OperationFailedException {
464         final MapEntryNode entryNode = ImmutableNodes.mapEntryBuilder(INTERFACE_QNAME, NAME_QNAME, "eth0")
465                 .withChild(ImmutableNodes.leafNode(NAME_QNAME, "eth0"))
466                 .withChild(ImmutableNodes.leafNode(TYPE_QNAME, "ethernetCsmacd"))
467                 .withChild(ImmutableNodes.leafNode(ENABLED_QNAME, Boolean.TRUE))
468                 .withChild(ImmutableNodes.leafNode(DESC_QNAME, "eth interface"))
469                 .build();
470
471         doReturn(Futures.immediateCheckedFuture(Optional.of(entryNode))).when(mockReadOnlyTx).read(
472                 eq(datastoreType), any(YangInstanceIdentifier.class));
473
474         final String uriPath = "ietf-interfaces:interfaces/interface=eth0";
475
476         final Optional<String> optionalResp = this.service.get(uriPath, datastoreType);
477         assertEquals("Response present", true, optionalResp.isPresent());
478         final String jsonResp = optionalResp.get();
479
480         assertNotNull("Returned null response", jsonResp);
481         assertThat("Missing \"name\"", jsonResp, containsString("\"name\":\"eth0\""));
482         assertThat("Missing \"type\"", jsonResp, containsString("\"type\":\"ethernetCsmacd\""));
483         assertThat("Missing \"enabled\"", jsonResp, containsString("\"enabled\":true"));
484         assertThat("Missing \"description\"", jsonResp, containsString("\"description\":\"eth interface\""));
485
486         final ArgumentCaptor<YangInstanceIdentifier> capturedPath =
487                 ArgumentCaptor.forClass(YangInstanceIdentifier.class);
488         verify(mockReadOnlyTx).read(eq(datastoreType), capturedPath.capture());
489
490         verifyPath(capturedPath.getValue(), INTERFACES_QNAME, INTERFACE_QNAME,
491                 new Object[]{INTERFACE_QNAME, NAME_QNAME, "eth0"});
492     }
493
494     DOMMountPoint setupTestMountPoint() throws FileNotFoundException, ReactorException {
495         final SchemaContext schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
496         final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
497         doReturn(schemaContextTestModule).when(mockMountPoint).getSchemaContext();
498
499         doReturn(Optional.of(mockDOMDataBroker)).when(mockMountPoint).getService(DOMDataBroker.class);
500
501         doReturn(Optional.of(mockMountPoint))
502                 .when(mockMountPointService).getMountPoint(notNull(YangInstanceIdentifier.class));
503
504         return mockMountPoint;
505     }
506
507     void verifyLeafNode(final DataContainerNode<?> parent, final QName leafType, final Object leafValue) {
508         final Optional<DataContainerChild<?, ?>> leafChild = parent.getChild(new NodeIdentifier(leafType));
509         assertEquals(leafType.toString() + " present", true, leafChild.isPresent());
510         assertEquals(leafType.toString() + " value", leafValue, leafChild.get().getValue());
511     }
512
513     void verifyPath(final YangInstanceIdentifier path, final Object... expArgs) {
514         final List<PathArgument> pathArgs = path.getPathArguments();
515         assertEquals("Arg count for actual path " + path, expArgs.length, pathArgs.size());
516         int index = 0;
517         for (final PathArgument actual: pathArgs) {
518             QName expNodeType;
519             if (expArgs[index] instanceof Object[]) {
520                 final Object[] listEntry = (Object[]) expArgs[index];
521                 expNodeType = (QName) listEntry[0];
522
523                 assertTrue(actual instanceof NodeIdentifierWithPredicates);
524                 final Map<QName, Object> keyValues = ((NodeIdentifierWithPredicates)actual).getKeyValues();
525                 assertEquals(String.format("Path arg %d keyValues size", index + 1), 1, keyValues.size());
526                 final QName expKey = (QName) listEntry[1];
527                 assertEquals(String.format("Path arg %d keyValue for %s", index + 1, expKey), listEntry[2],
528                         keyValues.get(expKey));
529             } else {
530                 expNodeType = (QName) expArgs[index];
531             }
532
533             assertEquals(String.format("Path arg %d node type", index + 1), expNodeType, actual.getNodeType());
534             index++;
535         }
536
537     }
538 }