2 * Copyright (c) 2014, 2015 Brocade Communications 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.controller.sal.restconf.impl.test;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertSame;
14 import static org.junit.Assert.assertThrows;
15 import static org.junit.Assert.assertTrue;
16 import static org.mockito.ArgumentMatchers.any;
17 import static org.mockito.ArgumentMatchers.eq;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.inOrder;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.times;
22 import static org.mockito.Mockito.verify;
23 import static org.mockito.Mockito.verifyNoMoreInteractions;
24 import static org.mockito.Mockito.when;
25 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateBooleanFluentFuture;
26 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
27 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
28 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateTrueFluentFuture;
30 import com.google.common.collect.ImmutableClassToInstanceMap;
31 import com.google.common.util.concurrent.FluentFuture;
32 import com.google.common.util.concurrent.ListenableFuture;
33 import java.util.List;
34 import java.util.Optional;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.junit.runner.RunWith;
38 import org.mockito.InOrder;
39 import org.mockito.Mock;
40 import org.mockito.Mockito;
41 import org.mockito.junit.MockitoJUnitRunner;
42 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
43 import org.opendaylight.mdsal.common.api.CommitInfo;
44 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
45 import org.opendaylight.mdsal.common.api.ReadFailedException;
46 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
47 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
48 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
49 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
51 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
52 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
53 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
54 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
55 import org.opendaylight.mdsal.dom.api.DOMRpcService;
56 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
57 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
58 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
59 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
60 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
61 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
62 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
64 import org.opendaylight.restconf.common.ErrorTags;
65 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
66 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
67 import org.opendaylight.restconf.common.errors.RestconfError;
68 import org.opendaylight.restconf.common.patch.PatchContext;
69 import org.opendaylight.restconf.common.patch.PatchStatusContext;
70 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
71 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
72 import org.opendaylight.yangtools.concepts.ListenerRegistration;
73 import org.opendaylight.yangtools.yang.common.ErrorTag;
74 import org.opendaylight.yangtools.yang.common.ErrorType;
75 import org.opendaylight.yangtools.yang.common.QName;
76 import org.opendaylight.yangtools.yang.common.RpcError;
77 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
82 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
84 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
85 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
88 * Unit tests for BrokerFacade.
90 * @author Thomas Pantelis
92 @RunWith(MockitoJUnitRunner.StrictStubs.class)
93 public class BrokerFacadeTest {
96 private DOMDataBroker domDataBroker;
98 private DOMNotificationService domNotification;
100 private DOMRpcService mockRpcService;
102 private DOMMountPoint mockMountInstance;
104 private DOMDataTreeReadTransaction readTransaction;
106 private DOMDataTreeWriteTransaction writeTransaction;
108 private DOMDataTreeReadWriteTransaction rwTransaction;
110 private BrokerFacade brokerFacade;
111 private final NormalizedNode dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
112 private final FluentFuture<Optional<NormalizedNode>> dummyNodeInFuture = wrapDummyNode(dummyNode);
113 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
114 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).build();
115 private ControllerContext controllerContext;
118 public void setUp() throws Exception {
119 controllerContext = TestRestconfUtils.newControllerContext(
120 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
122 brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
124 when(domDataBroker.newReadOnlyTransaction()).thenReturn(readTransaction);
125 when(domDataBroker.newReadWriteTransaction()).thenReturn(rwTransaction);
126 when(domDataBroker.getExtensions()).thenReturn(ImmutableClassToInstanceMap.of(
127 DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class)));
130 private static FluentFuture<Optional<NormalizedNode>> wrapDummyNode(final NormalizedNode dummyNode) {
131 return immediateFluentFuture(Optional.of(dummyNode));
134 private static FluentFuture<Boolean> wrapExistence(final boolean exists) {
135 return immediateBooleanFluentFuture(exists);
139 * Value of this node shouldn't be important for testing purposes.
141 private static NormalizedNode createDummyNode(final String namespace, final String date, final String localName) {
142 return Builders.containerBuilder()
143 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName)))
148 public void testReadConfigurationData() {
149 when(readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
152 final NormalizedNode actualNode = brokerFacade.readConfigurationData(instanceID);
154 assertSame("readConfigurationData", dummyNode, actualNode);
158 public void testReadOperationalData() {
159 when(readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
162 final NormalizedNode actualNode = brokerFacade.readOperationalData(instanceID);
164 assertSame("readOperationalData", dummyNode, actualNode);
168 public void test503() throws Exception {
169 final RpcError error = RpcResultBuilder.newError(ErrorType.TRANSPORT, ErrorTag.RESOURCE_DENIED,
170 "Master is down. Please try again.");
171 doReturn(immediateFailedFluentFuture(new ReadFailedException("Read from transaction failed", error)))
172 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
174 final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
175 () -> brokerFacade.readConfigurationData(instanceID, "explicit"));
176 final List<RestconfError> errors = ex.getErrors();
177 assertEquals(1, errors.size());
178 assertEquals("getErrorTag", ErrorTags.RESOURCE_DENIED_TRANSPORT, errors.get(0).getErrorTag());
179 assertEquals("getErrorType", ErrorType.TRANSPORT,errors.get(0).getErrorType());
180 assertEquals("getErrorMessage", "Master is down. Please try again.", errors.get(0).getErrorMessage());
184 public void testInvokeRpc() throws Exception {
185 final DOMRpcResult expResult = mock(DOMRpcResult.class);
186 doReturn(immediateFluentFuture(expResult)).when(mockRpcService).invokeRpc(qname, dummyNode);
188 final ListenableFuture<? extends DOMRpcResult> actualFuture = brokerFacade.invokeRpc(qname,
190 assertNotNull("Future is null", actualFuture);
191 final DOMRpcResult actualResult = actualFuture.get();
192 assertSame("invokeRpc", expResult, actualResult);
196 public void testCommitConfigurationDataPut() throws Exception {
197 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
199 doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(rwTransaction)
200 .read(LogicalDatastoreType.CONFIGURATION, instanceID);
202 final PutResult result = brokerFacade.commitConfigurationDataPut(mock(EffectiveModelContext.class),
203 instanceID, dummyNode, null, null);
205 assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
207 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
208 inOrder.verify(domDataBroker).newReadWriteTransaction();
209 inOrder.verify(rwTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
210 inOrder.verify(rwTransaction).commit();
214 public void testCommitConfigurationDataPost() {
215 when(rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, instanceID))
216 .thenReturn(wrapExistence(false));
218 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
220 final FluentFuture<? extends CommitInfo> actualFuture = brokerFacade
221 .commitConfigurationDataPost(mock(EffectiveModelContext.class), instanceID, dummyNode, null,
224 assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
226 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
227 inOrder.verify(domDataBroker).newReadWriteTransaction();
228 inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
229 inOrder.verify(rwTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
230 inOrder.verify(rwTransaction).commit();
233 @Test(expected = RestconfDocumentedException.class)
234 public void testCommitConfigurationDataPostAlreadyExists() {
235 when(rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
236 .thenReturn(immediateTrueFluentFuture());
238 // Schema context is only necessary for ensuring parent structure
239 brokerFacade.commitConfigurationDataPost((EffectiveModelContext) null, instanceID, dummyNode,
241 } catch (final RestconfDocumentedException e) {
242 assertEquals("getErrorTag", ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
248 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
251 public void testCommitConfigurationDataDelete() throws Exception {
252 // assume that data to delete exists
253 prepareDataForDelete(true);
256 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
259 final FluentFuture<? extends CommitInfo> actualFuture = brokerFacade
260 .commitConfigurationDataDelete(instanceID);
262 // verify result and interactions
263 assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
265 // check exists, delete, submit
266 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
267 inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
268 inOrder.verify(rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, instanceID);
269 inOrder.verify(rwTransaction).commit();
273 * Negative test of delete operation when data to delete does not exist. Error DATA_MISSING should be returned.
276 public void testCommitConfigurationDataDeleteNoData() throws Exception {
277 // assume that data to delete does not exist
278 prepareDataForDelete(false);
280 // try to delete and expect DATA_MISSING error
281 final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
282 () -> brokerFacade.commitConfigurationDataDelete(instanceID));
283 final List<RestconfError> errors = ex.getErrors();
284 assertEquals(1, errors.size());
285 assertEquals(ErrorType.PROTOCOL, errors.get(0).getErrorType());
286 assertEquals(ErrorTag.DATA_MISSING, errors.get(0).getErrorTag());
290 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
291 * {@code assumeDataExists} parameter.
292 * @param assumeDataExists boolean to assume if data exists
294 private void prepareDataForDelete(final boolean assumeDataExists) {
295 when(rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, instanceID))
296 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
300 public void testRegisterToListenDataChanges() {
301 final ListenerAdapter listener = Notificator.createListener(instanceID, "stream",
302 NotificationOutputType.XML, controllerContext);
304 @SuppressWarnings("unchecked")
305 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
307 DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
308 .getInstance(DOMDataTreeChangeService.class);
309 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, instanceID);
310 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
312 brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, Scope.BASE, listener);
314 verify(changeService).registerDataTreeChangeListener(loc, listener);
316 assertEquals("isListening", true, listener.isListening());
318 brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, Scope.BASE, listener);
319 verifyNoMoreInteractions(changeService);
323 * Create, register, close and remove notification listener.
326 public void testRegisterToListenNotificationChanges() throws Exception {
327 // create test notification listener
328 final String identifier = "create-notification-stream/toaster:toastDone";
329 Notificator.createNotificationListener(
330 List.of(Absolute.of(QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"))),
331 identifier, "XML", controllerContext);
332 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
335 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
336 when(domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
337 .thenReturn(registration);
339 // test to register listener for the first time
340 brokerFacade.registerToListenNotification(listener);
341 assertEquals("Registration was not successful", true, listener.isListening());
343 // try to register for the second time
344 brokerFacade.registerToListenNotification(listener);
345 assertEquals("Registration was not successful", true, listener.isListening());
347 // registrations should be invoked only once
348 verify(domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
350 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
351 final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
352 // close and remove test notification listener
354 Notificator.removeListenerIfNoSubscriberExists(listener);
358 * Test Patch method on the server with no data.
361 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
362 final PatchContext patchContext = mock(PatchContext.class);
364 when(patchContext.getData()).thenReturn(List.of());
366 doReturn(InstanceIdentifierContext.ofPath(SchemaInferenceStack.of(mock(EffectiveModelContext.class)),
367 mock(DataSchemaNode.class), YangInstanceIdentifier.empty(), null))
368 .when(patchContext).getInstanceIdentifierContext();
370 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
372 final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
375 assertTrue("Patch operation should be successful on server", status.isOk());
379 * Test Patch method on mounted device with no data.
382 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
383 final PatchContext patchContext = mock(PatchContext.class);
384 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
385 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
386 final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
388 when(patchContext.getData()).thenReturn(List.of());
389 // return mount point with broker
390 doReturn(InstanceIdentifierContext.ofPath(SchemaInferenceStack.of(mock(EffectiveModelContext.class)),
391 mock(DataSchemaNode.class), YangInstanceIdentifier.empty(), mountPoint))
392 .when(patchContext).getInstanceIdentifierContext();
394 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
395 when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
396 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
397 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
399 final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
402 assertTrue("Patch operation should be successful on mounted device", status.isOk());
406 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
407 * Patch operation should fail with global error.
410 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
411 final PatchContext patchContext = mock(PatchContext.class);
412 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
414 doReturn(InstanceIdentifierContext.ofPath(SchemaInferenceStack.of(mock(EffectiveModelContext.class)),
415 mock(DataSchemaNode.class), YangInstanceIdentifier.empty(), mountPoint))
416 .when(patchContext).getInstanceIdentifierContext();
418 // missing broker on mounted device
419 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
420 when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
422 final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
424 // assert not successful operation with error
425 assertNotNull(status.getGlobalErrors());
426 assertEquals(1, status.getGlobalErrors().size());
427 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
428 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
430 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());