2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
10 import static org.junit.jupiter.api.Assertions.assertEquals;
11 import static org.junit.jupiter.api.Assertions.assertFalse;
12 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
13 import static org.junit.jupiter.api.Assertions.assertNotNull;
14 import static org.junit.jupiter.api.Assertions.assertNull;
15 import static org.junit.jupiter.api.Assertions.assertThrows;
16 import static org.junit.jupiter.api.Assertions.assertTrue;
17 import static org.mockito.ArgumentMatchers.any;
18 import static org.mockito.Mockito.doNothing;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.mock;
21 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFalseFluentFuture;
22 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
23 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateTrueFluentFuture;
25 import java.io.ByteArrayInputStream;
26 import java.io.InputStream;
28 import java.nio.charset.StandardCharsets;
29 import java.util.Collection;
30 import java.util.List;
31 import java.util.Optional;
33 import javax.ws.rs.container.AsyncResponse;
34 import javax.ws.rs.core.MultivaluedHashMap;
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.Response;
37 import javax.ws.rs.core.UriBuilder;
38 import javax.ws.rs.core.UriInfo;
39 import org.junit.Before;
40 import org.junit.Test;
41 import org.junit.runner.RunWith;
42 import org.mockito.ArgumentCaptor;
43 import org.mockito.Captor;
44 import org.mockito.Mock;
45 import org.mockito.junit.MockitoJUnitRunner;
46 import org.opendaylight.mdsal.common.api.CommitInfo;
47 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
48 import org.opendaylight.mdsal.dom.api.DOMActionService;
49 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
51 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
52 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
53 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
54 import org.opendaylight.mdsal.dom.api.DOMRpcService;
55 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
56 import org.opendaylight.mdsal.dom.spi.FixedDOMSchemaService;
57 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
58 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
59 import org.opendaylight.restconf.common.patch.PatchContext;
60 import org.opendaylight.restconf.common.patch.PatchEntity;
61 import org.opendaylight.restconf.common.patch.PatchStatusContext;
62 import org.opendaylight.restconf.nb.rfc8040.AbstractJukeboxTest;
63 import org.opendaylight.restconf.nb.rfc8040.databind.DatabindContext;
64 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
65 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.RestconfStreamsSubscriptionService;
66 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.patch.rev170222.yang.patch.yang.patch.Edit.Operation;
67 import org.opendaylight.yangtools.yang.common.ErrorTag;
68 import org.opendaylight.yangtools.yang.common.ErrorType;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 @RunWith(MockitoJUnitRunner.StrictStubs.class)
78 public class RestconfDataServiceImplTest extends AbstractJukeboxTest {
79 private static final NodeIdentifier PLAYLIST_NID = new NodeIdentifier(PLAYLIST_QNAME);
80 private static final NodeIdentifier LIBRARY_NID = new NodeIdentifier(LIBRARY_QNAME);
82 // config contains one child the same as in operational and one additional
83 private static final ContainerNode CONFIG_JUKEBOX = Builders.containerBuilder()
84 .withNodeIdentifier(new NodeIdentifier(JUKEBOX_QNAME))
85 .withChild(CONT_PLAYER)
86 .withChild(Builders.containerBuilder().withNodeIdentifier(LIBRARY_NID).build())
88 // operational contains one child the same as in config and one additional
89 private static final ContainerNode OPER_JUKEBOX = Builders.containerBuilder()
90 .withNodeIdentifier(new NodeIdentifier(JUKEBOX_QNAME))
91 .withChild(CONT_PLAYER)
92 .withChild(Builders.mapBuilder().withNodeIdentifier(PLAYLIST_NID).build())
96 private UriInfo uriInfo;
98 private DOMDataTreeReadWriteTransaction readWrite;
100 private DOMDataTreeReadTransaction read;
102 private DOMMountPointService mountPointService;
104 private DOMMountPoint mountPoint;
106 private DOMDataBroker mountDataBroker;
108 private NetconfDataTreeService netconfService;
110 private DOMActionService actionService;
112 private DOMRpcService rpcService;
114 private RestconfStreamsSubscriptionService delegRestconfSubscrService;
116 private MultivaluedMap<String, String> queryParamenters;
118 private AsyncResponse asyncResponse;
120 private ArgumentCaptor<Response> responseCaptor;
122 private RestconfDataServiceImpl dataService;
125 public void setUp() throws Exception {
126 doReturn(Set.of()).when(queryParamenters).entrySet();
127 doReturn(queryParamenters).when(uriInfo).getQueryParameters();
129 doReturn(CommitInfo.emptyFluentFuture()).when(readWrite).commit();
131 final var dataBroker = mock(DOMDataBroker.class);
132 doReturn(read).when(dataBroker).newReadOnlyTransaction();
133 doReturn(readWrite).when(dataBroker).newReadWriteTransaction();
135 dataService = new RestconfDataServiceImpl(() -> DatabindContext.ofModel(JUKEBOX_SCHEMA),
136 new MdsalRestconfServer(dataBroker, rpcService, mountPointService), dataBroker, delegRestconfSubscrService,
138 doReturn(Optional.of(mountPoint)).when(mountPointService)
139 .getMountPoint(any(YangInstanceIdentifier.class));
140 doReturn(Optional.of(FixedDOMSchemaService.of(JUKEBOX_SCHEMA))).when(mountPoint)
141 .getService(DOMSchemaService.class);
142 doReturn(Optional.of(mountDataBroker)).when(mountPoint).getService(DOMDataBroker.class);
143 doReturn(Optional.of(rpcService)).when(mountPoint).getService(DOMRpcService.class);
144 doReturn(Optional.empty()).when(mountPoint).getService(NetconfDataTreeService.class);
145 doReturn(read).when(mountDataBroker).newReadOnlyTransaction();
146 doReturn(readWrite).when(mountDataBroker).newReadWriteTransaction();
150 public void testReadData() {
151 doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters();
152 doReturn(immediateFluentFuture(Optional.of(EMPTY_JUKEBOX))).when(read)
153 .read(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
154 doReturn(immediateFluentFuture(Optional.empty()))
155 .when(read).read(LogicalDatastoreType.OPERATIONAL, JUKEBOX_IID);
156 final Response response = dataService.readData("example-jukebox:jukebox", uriInfo);
157 assertNotNull(response);
158 assertEquals(200, response.getStatus());
159 assertEquals(EMPTY_JUKEBOX, ((NormalizedNodePayload) response.getEntity()).data());
163 public void testReadRootData() {
164 doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters();
165 doReturn(immediateFluentFuture(Optional.of(wrapNodeByDataRootContainer(CONFIG_JUKEBOX))))
167 .read(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.of());
168 doReturn(immediateFluentFuture(Optional.of(wrapNodeByDataRootContainer(OPER_JUKEBOX))))
170 .read(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of());
171 final Response response = dataService.readData(uriInfo);
172 assertNotNull(response);
173 assertEquals(200, response.getStatus());
175 final NormalizedNode data = ((NormalizedNodePayload) response.getEntity()).data();
176 assertTrue(data instanceof ContainerNode);
177 final Collection<DataContainerChild> rootNodes = ((ContainerNode) data).body();
178 assertEquals(1, rootNodes.size());
179 final Collection<DataContainerChild> allDataChildren = ((ContainerNode) rootNodes.iterator().next()).body();
180 assertEquals(3, allDataChildren.size());
183 private static ContainerNode wrapNodeByDataRootContainer(final DataContainerChild data) {
184 return Builders.containerBuilder()
185 .withNodeIdentifier(NodeIdentifier.create(SchemaContext.NAME))
191 * Test read data from mount point when both {@link LogicalDatastoreType#CONFIGURATION} and
192 * {@link LogicalDatastoreType#OPERATIONAL} contains the same data and some additional data to be merged.
195 public void testReadDataMountPoint() {
196 doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters();
197 doReturn(immediateFluentFuture(Optional.of(CONFIG_JUKEBOX))).when(read)
198 .read(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
199 doReturn(immediateFluentFuture(Optional.of(OPER_JUKEBOX))).when(read)
200 .read(LogicalDatastoreType.OPERATIONAL, JUKEBOX_IID);
202 final Response response = dataService.readData(
203 "example-jukebox:jukebox/yang-ext:mount/example-jukebox:jukebox", uriInfo);
205 assertNotNull(response);
206 assertEquals(200, response.getStatus());
208 // response must contain all child nodes from config and operational containers merged in one container
209 final NormalizedNode data = ((NormalizedNodePayload) response.getEntity()).data();
210 assertTrue(data instanceof ContainerNode);
211 assertEquals(3, ((ContainerNode) data).size());
212 assertNotNull(((ContainerNode) data).childByArg(CONT_PLAYER.name()));
213 assertNotNull(((ContainerNode) data).childByArg(LIBRARY_NID));
214 assertNotNull(((ContainerNode) data).childByArg(PLAYLIST_NID));
218 public void testReadDataNoData() {
219 doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters();
220 doReturn(immediateFluentFuture(Optional.empty()))
221 .when(read).read(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
222 doReturn(immediateFluentFuture(Optional.empty()))
223 .when(read).read(LogicalDatastoreType.OPERATIONAL, JUKEBOX_IID);
225 final var errors = assertThrows(RestconfDocumentedException.class,
226 () -> dataService.readData("example-jukebox:jukebox", uriInfo)).getErrors();
227 assertEquals(1, errors.size());
228 final var error = errors.get(0);
229 assertEquals(ErrorType.PROTOCOL, error.getErrorType());
230 assertEquals(ErrorTag.DATA_MISSING, error.getErrorTag());
231 assertEquals("Request could not be completed because the relevant data model content does not exist",
232 error.getErrorMessage());
236 * Read data from config datastore according to content parameter.
239 public void testReadDataConfigTest() {
240 final MultivaluedHashMap<String, String> parameters = new MultivaluedHashMap<>();
241 parameters.put("content", List.of("config"));
243 doReturn(parameters).when(uriInfo).getQueryParameters();
244 doReturn(immediateFluentFuture(Optional.of(CONFIG_JUKEBOX))).when(read)
245 .read(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
247 final Response response = dataService.readData("example-jukebox:jukebox", uriInfo);
249 assertNotNull(response);
250 assertEquals(200, response.getStatus());
252 // response must contain only config data
253 final NormalizedNode data = ((NormalizedNodePayload) response.getEntity()).data();
255 // config data present
256 assertNotNull(((ContainerNode) data).childByArg(CONT_PLAYER.name()));
257 assertNotNull(((ContainerNode) data).childByArg(LIBRARY_NID));
260 assertNull(((ContainerNode) data).childByArg(PLAYLIST_NID));
264 * Read data from operational datastore according to content parameter.
267 public void testReadDataOperationalTest() {
268 final MultivaluedHashMap<String, String> parameters = new MultivaluedHashMap<>();
269 parameters.put("content", List.of("nonconfig"));
271 doReturn(parameters).when(uriInfo).getQueryParameters();
272 doReturn(immediateFluentFuture(Optional.of(OPER_JUKEBOX))).when(read)
273 .read(LogicalDatastoreType.OPERATIONAL, JUKEBOX_IID);
275 final Response response = dataService.readData("example-jukebox:jukebox", uriInfo);
277 assertNotNull(response);
278 assertEquals(200, response.getStatus());
280 // response must contain only operational data
281 final NormalizedNode data = ((NormalizedNodePayload) response.getEntity()).data();
283 // state data present
284 assertNotNull(((ContainerNode) data).childByArg(CONT_PLAYER.name()));
285 assertNotNull(((ContainerNode) data).childByArg(PLAYLIST_NID));
287 // config data absent
288 assertNull(((ContainerNode) data).childByArg(LIBRARY_NID));
292 public void testPutData() {
293 doReturn(immediateTrueFluentFuture()).when(read)
294 .exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
295 doNothing().when(readWrite).put(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID, EMPTY_JUKEBOX);
297 doReturn(true).when(asyncResponse).resume(responseCaptor.capture());
298 dataService.putDataJSON("example-jukebox:jukebox", uriInfo, stringInputStream("""
300 "example-jukebox:jukebox" : {
305 }"""), asyncResponse);
306 final var response = responseCaptor.getValue();
307 assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
311 public void testPutDataWithMountPoint() {
312 doReturn(immediateTrueFluentFuture()).when(read)
313 .exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
314 doNothing().when(readWrite).put(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID, EMPTY_JUKEBOX);
316 doReturn(true).when(asyncResponse).resume(responseCaptor.capture());
317 dataService.putDataXML("example-jukebox:jukebox/yang-ext:mount/example-jukebox:jukebox",
318 uriInfo, stringInputStream("""
319 <jukebox xmlns="http://example.com/ns/example-jukebox">
323 </jukebox>"""), asyncResponse);
324 final var response = responseCaptor.getValue();
325 assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
328 private static InputStream stringInputStream(final String str) {
329 return new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
333 public void testPostData() {
334 doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters();
335 doReturn(immediateFalseFluentFuture()).when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
336 doNothing().when(readWrite).put(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID,
337 Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(JUKEBOX_QNAME)).build());
338 doReturn(UriBuilder.fromUri("http://localhost:8181/rests/")).when(uriInfo).getBaseUriBuilder();
340 final var captor = ArgumentCaptor.forClass(Response.class);
341 doReturn(true).when(asyncResponse).resume(captor.capture());
342 dataService.postDataJSON(stringInputStream("""
344 "example-jukebox:jukebox" : {
346 }"""), uriInfo, asyncResponse);
347 final var response = captor.getValue();
348 assertEquals(201, response.getStatus());
349 assertEquals(URI.create("http://localhost:8181/rests/data/example-jukebox:jukebox"), response.getLocation());
353 public void testPostMapEntryData() {
354 doReturn(new MultivaluedHashMap<>()).when(uriInfo).getQueryParameters();
355 final var node = PLAYLIST_IID.node(BAND_ENTRY.name());
356 doReturn(immediateFalseFluentFuture()).when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, node);
357 doNothing().when(readWrite).put(LogicalDatastoreType.CONFIGURATION, node, BAND_ENTRY);
358 doReturn(UriBuilder.fromUri("http://localhost:8181/rests/")).when(uriInfo).getBaseUriBuilder();
360 final var captor = ArgumentCaptor.forClass(Response.class);
361 doReturn(true).when(asyncResponse).resume(captor.capture());
362 dataService.postDataJSON("example-jukebox:jukebox", stringInputStream("""
364 "example-jukebox:playlist" : {
365 "name" : "name of band",
366 "description" : "band description"
368 }"""), uriInfo, asyncResponse);
369 final var response = captor.getValue();
370 assertEquals(201, response.getStatus());
371 assertEquals(URI.create("http://localhost:8181/rests/data/example-jukebox:jukebox/playlist=name%20of%20band"),
372 response.getLocation());
376 public void testDeleteData() {
377 doNothing().when(readWrite).delete(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
378 doReturn(immediateTrueFluentFuture())
379 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
380 final var captor = ArgumentCaptor.forClass(Response.class);
381 doReturn(true).when(asyncResponse).resume(captor.capture());
382 dataService.deleteData("example-jukebox:jukebox", asyncResponse);
384 assertEquals(204, captor.getValue().getStatus());
388 public void testDeleteDataNotExisting() {
389 doReturn(immediateFalseFluentFuture())
390 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
391 final var captor = ArgumentCaptor.forClass(RestconfDocumentedException.class);
392 doReturn(true).when(asyncResponse).resume(captor.capture());
393 dataService.deleteData("example-jukebox:jukebox", asyncResponse);
395 final var errors = captor.getValue().getErrors();
396 assertEquals(1, errors.size());
397 final var error = errors.get(0);
398 assertEquals(ErrorType.PROTOCOL, error.getErrorType());
399 assertEquals(ErrorTag.DATA_MISSING, error.getErrorTag());
403 * Test of deleting data on mount point.
406 public void testDeleteDataMountPoint() {
407 doNothing().when(readWrite).delete(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
408 doReturn(immediateTrueFluentFuture())
409 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
410 final var captor = ArgumentCaptor.forClass(Response.class);
411 doReturn(true).when(asyncResponse).resume(captor.capture());
412 dataService.deleteData("example-jukebox:jukebox/yang-ext:mount/example-jukebox:jukebox", asyncResponse);
414 assertEquals(204, captor.getValue().getStatus());
418 public void testPatchData() {
419 final var patch = new PatchContext("test patch id", List.of(
420 new PatchEntity("create data", Operation.Create, JUKEBOX_IID, EMPTY_JUKEBOX),
421 new PatchEntity("replace data", Operation.Replace, JUKEBOX_IID, EMPTY_JUKEBOX),
422 new PatchEntity("delete data", Operation.Delete, GAP_IID)));
424 doNothing().when(readWrite).delete(LogicalDatastoreType.CONFIGURATION, GAP_IID);
425 doReturn(immediateFalseFluentFuture())
426 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
427 doReturn(immediateTrueFluentFuture())
428 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, GAP_IID);
429 doReturn(true).when(asyncResponse).resume(responseCaptor.capture());
430 dataService.yangPatchData(JUKEBOX_SCHEMA, patch, null, asyncResponse);
431 final var response = responseCaptor.getValue();
432 assertEquals(200, response.getStatus());
433 final var status = assertInstanceOf(PatchStatusContext.class, response.getEntity());
435 assertTrue(status.ok());
436 assertEquals(3, status.editCollection().size());
437 assertEquals("replace data", status.editCollection().get(1).getEditId());
441 public void testPatchDataMountPoint() throws Exception {
442 final var patch = new PatchContext("test patch id", List.of(
443 new PatchEntity("create data", Operation.Create, JUKEBOX_IID, EMPTY_JUKEBOX),
444 new PatchEntity("replace data", Operation.Replace, JUKEBOX_IID, EMPTY_JUKEBOX),
445 new PatchEntity("delete data", Operation.Delete, GAP_IID)));
447 doNothing().when(readWrite).delete(LogicalDatastoreType.CONFIGURATION, GAP_IID);
448 doReturn(immediateFalseFluentFuture())
449 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
450 doReturn(immediateTrueFluentFuture()).when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, GAP_IID);
452 doReturn(true).when(asyncResponse).resume(responseCaptor.capture());
453 dataService.yangPatchData(JUKEBOX_SCHEMA, patch, mountPoint, asyncResponse);
454 final var response = responseCaptor.getValue();
455 assertEquals(200, response.getStatus());
456 final var status = assertInstanceOf(PatchStatusContext.class, response.getEntity());
458 assertTrue(status.ok());
459 assertEquals(3, status.editCollection().size());
460 assertNull(status.globalErrors());
464 public void testPatchDataDeleteNotExist() {
465 final var patch = new PatchContext("test patch id", List.of(
466 new PatchEntity("create data", Operation.Create, JUKEBOX_IID, EMPTY_JUKEBOX),
467 new PatchEntity("remove data", Operation.Remove, GAP_IID),
468 new PatchEntity("delete data", Operation.Delete, GAP_IID)));
470 doNothing().when(readWrite).delete(LogicalDatastoreType.CONFIGURATION, GAP_IID);
471 doReturn(immediateFalseFluentFuture())
472 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, JUKEBOX_IID);
473 doReturn(immediateFalseFluentFuture())
474 .when(readWrite).exists(LogicalDatastoreType.CONFIGURATION, GAP_IID);
475 doReturn(true).when(readWrite).cancel();
477 doReturn(true).when(asyncResponse).resume(responseCaptor.capture());
478 dataService.yangPatchData(JUKEBOX_SCHEMA, patch, null, asyncResponse);
479 final var response = responseCaptor.getValue();
480 assertEquals(200, response.getStatus());
481 final var status = assertInstanceOf(PatchStatusContext.class, response.getEntity());
483 assertFalse(status.ok());
484 assertEquals(3, status.editCollection().size());
485 assertTrue(status.editCollection().get(0).isOk());
486 assertTrue(status.editCollection().get(1).isOk());
487 assertFalse(status.editCollection().get(2).isOk());
488 assertFalse(status.editCollection().get(2).getEditErrors().isEmpty());
489 final String errorMessage = status.editCollection().get(2).getEditErrors().get(0).getErrorMessage();
490 assertEquals("Data does not exist", errorMessage);