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;
87 * Unit tests for BrokerFacade.
89 * @author Thomas Pantelis
91 @RunWith(MockitoJUnitRunner.StrictStubs.class)
92 public class BrokerFacadeTest {
95 private DOMDataBroker domDataBroker;
97 private DOMNotificationService domNotification;
99 private DOMRpcService mockRpcService;
101 private DOMMountPoint mockMountInstance;
103 private DOMDataTreeReadTransaction readTransaction;
105 private DOMDataTreeWriteTransaction writeTransaction;
107 private DOMDataTreeReadWriteTransaction rwTransaction;
109 private BrokerFacade brokerFacade;
110 private final NormalizedNode dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
111 private final FluentFuture<Optional<NormalizedNode>> dummyNodeInFuture = wrapDummyNode(dummyNode);
112 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
113 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).build();
114 private ControllerContext controllerContext;
117 public void setUp() throws Exception {
118 controllerContext = TestRestconfUtils.newControllerContext(
119 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
121 brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
123 when(domDataBroker.newReadOnlyTransaction()).thenReturn(readTransaction);
124 when(domDataBroker.newReadWriteTransaction()).thenReturn(rwTransaction);
125 when(domDataBroker.getExtensions()).thenReturn(ImmutableClassToInstanceMap.of(
126 DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class)));
129 private static FluentFuture<Optional<NormalizedNode>> wrapDummyNode(final NormalizedNode dummyNode) {
130 return immediateFluentFuture(Optional.of(dummyNode));
133 private static FluentFuture<Boolean> wrapExistence(final boolean exists) {
134 return immediateBooleanFluentFuture(exists);
138 * Value of this node shouldn't be important for testing purposes.
140 private static NormalizedNode createDummyNode(final String namespace, final String date, final String localName) {
141 return Builders.containerBuilder()
142 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName)))
147 public void testReadConfigurationData() {
148 when(readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
151 final NormalizedNode actualNode = brokerFacade.readConfigurationData(instanceID);
153 assertSame("readConfigurationData", dummyNode, actualNode);
157 public void testReadOperationalData() {
158 when(readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
161 final NormalizedNode actualNode = brokerFacade.readOperationalData(instanceID);
163 assertSame("readOperationalData", dummyNode, actualNode);
167 public void test503() throws Exception {
168 final RpcError error = RpcResultBuilder.newError(
169 RpcError.ErrorType.TRANSPORT,
170 ErrorTag.RESOURCE_DENIED.elementBody(),
171 "Master is down. Please try again.");
172 doReturn(immediateFailedFluentFuture(new ReadFailedException("Read from transaction failed", error)))
173 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
175 final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
176 () -> brokerFacade.readConfigurationData(instanceID, "explicit"));
177 final List<RestconfError> errors = ex.getErrors();
178 assertEquals(1, errors.size());
179 assertEquals("getErrorTag", ErrorTags.RESOURCE_DENIED_TRANSPORT, errors.get(0).getErrorTag());
180 assertEquals("getErrorType", ErrorType.TRANSPORT,errors.get(0).getErrorType());
181 assertEquals("getErrorMessage", "Master is down. Please try again.", errors.get(0).getErrorMessage());
185 public void testInvokeRpc() throws Exception {
186 final DOMRpcResult expResult = mock(DOMRpcResult.class);
187 doReturn(immediateFluentFuture(expResult)).when(mockRpcService).invokeRpc(qname, dummyNode);
189 final ListenableFuture<? extends DOMRpcResult> actualFuture = brokerFacade.invokeRpc(qname,
191 assertNotNull("Future is null", actualFuture);
192 final DOMRpcResult actualResult = actualFuture.get();
193 assertSame("invokeRpc", expResult, actualResult);
197 public void testCommitConfigurationDataPut() throws Exception {
198 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
200 doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(rwTransaction)
201 .read(LogicalDatastoreType.CONFIGURATION, instanceID);
203 final PutResult result = brokerFacade.commitConfigurationDataPut(mock(EffectiveModelContext.class),
204 instanceID, dummyNode, null, null);
206 assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
208 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
209 inOrder.verify(domDataBroker).newReadWriteTransaction();
210 inOrder.verify(rwTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
211 inOrder.verify(rwTransaction).commit();
215 public void testCommitConfigurationDataPost() {
216 when(rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, instanceID))
217 .thenReturn(wrapExistence(false));
219 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
221 final FluentFuture<? extends CommitInfo> actualFuture = brokerFacade
222 .commitConfigurationDataPost(mock(EffectiveModelContext.class), instanceID, dummyNode, null,
225 assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
227 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
228 inOrder.verify(domDataBroker).newReadWriteTransaction();
229 inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
230 inOrder.verify(rwTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
231 inOrder.verify(rwTransaction).commit();
234 @Test(expected = RestconfDocumentedException.class)
235 public void testCommitConfigurationDataPostAlreadyExists() {
236 when(rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
237 .thenReturn(immediateTrueFluentFuture());
239 // Schema context is only necessary for ensuring parent structure
240 brokerFacade.commitConfigurationDataPost((EffectiveModelContext) null, instanceID, dummyNode,
242 } catch (final RestconfDocumentedException e) {
243 assertEquals("getErrorTag", ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
249 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
252 public void testCommitConfigurationDataDelete() throws Exception {
253 // assume that data to delete exists
254 prepareDataForDelete(true);
257 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
260 final FluentFuture<? extends CommitInfo> actualFuture = brokerFacade
261 .commitConfigurationDataDelete(instanceID);
263 // verify result and interactions
264 assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
266 // check exists, delete, submit
267 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
268 inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
269 inOrder.verify(rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, instanceID);
270 inOrder.verify(rwTransaction).commit();
274 * Negative test of delete operation when data to delete does not exist. Error DATA_MISSING should be returned.
277 public void testCommitConfigurationDataDeleteNoData() throws Exception {
278 // assume that data to delete does not exist
279 prepareDataForDelete(false);
281 // try to delete and expect DATA_MISSING error
282 final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
283 () -> brokerFacade.commitConfigurationDataDelete(instanceID));
284 final List<RestconfError> errors = ex.getErrors();
285 assertEquals(1, errors.size());
286 assertEquals(ErrorType.PROTOCOL, errors.get(0).getErrorType());
287 assertEquals(ErrorTag.DATA_MISSING, errors.get(0).getErrorTag());
291 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
292 * {@code assumeDataExists} parameter.
293 * @param assumeDataExists boolean to assume if data exists
295 private void prepareDataForDelete(final boolean assumeDataExists) {
296 when(rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, instanceID))
297 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
301 public void testRegisterToListenDataChanges() {
302 final ListenerAdapter listener = Notificator.createListener(instanceID, "stream",
303 NotificationOutputType.XML, controllerContext);
305 @SuppressWarnings("unchecked")
306 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
308 DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
309 .getInstance(DOMDataTreeChangeService.class);
310 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, instanceID);
311 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
313 brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, Scope.BASE, listener);
315 verify(changeService).registerDataTreeChangeListener(loc, listener);
317 assertEquals("isListening", true, listener.isListening());
319 brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, Scope.BASE, listener);
320 verifyNoMoreInteractions(changeService);
324 * Create, register, close and remove notification listener.
327 public void testRegisterToListenNotificationChanges() throws Exception {
328 // create test notification listener
329 final String identifier = "create-notification-stream/toaster:toastDone";
330 final Absolute path = Absolute.of(
331 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
332 Notificator.createNotificationListener(List.of(path), identifier, "XML", controllerContext);
333 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
336 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
337 when(domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
338 .thenReturn(registration);
340 // test to register listener for the first time
341 brokerFacade.registerToListenNotification(listener);
342 assertEquals("Registration was not successful", true, listener.isListening());
344 // try to register for the second time
345 brokerFacade.registerToListenNotification(listener);
346 assertEquals("Registration was not successful", true, listener.isListening());
348 // registrations should be invoked only once
349 verify(domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
351 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
352 final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
353 // close and remove test notification listener
355 Notificator.removeListenerIfNoSubscriberExists(listener);
359 * Test Patch method on the server with no data.
362 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
363 final PatchContext patchContext = mock(PatchContext.class);
365 when(patchContext.getData()).thenReturn(List.of());
367 doReturn(InstanceIdentifierContext.ofDataSchemaNode(
368 mock(EffectiveModelContext.class), mock(DataSchemaNode.class)))
369 .when(patchContext).getInstanceIdentifierContext();
371 doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
373 final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
376 assertTrue("Patch operation should be successful on server", status.isOk());
380 * Test Patch method on mounted device with no data.
383 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
384 final PatchContext patchContext = mock(PatchContext.class);
385 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
386 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
387 final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
389 when(patchContext.getData()).thenReturn(List.of());
390 // return mount point with broker
391 doReturn(InstanceIdentifierContext.ofDataSchemaNode(
392 mock(EffectiveModelContext.class), mock(DataSchemaNode.class), mountPoint))
393 .when(patchContext).getInstanceIdentifierContext();
395 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
396 when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
397 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
398 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
400 final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
403 assertTrue("Patch operation should be successful on mounted device", status.isOk());
407 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
408 * Patch operation should fail with global error.
411 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
412 final PatchContext patchContext = mock(PatchContext.class);
413 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
415 doReturn(InstanceIdentifierContext.ofDataSchemaNode(
416 mock(EffectiveModelContext.class), mock(DataSchemaNode.class), mountPoint))
417 .when(patchContext).getInstanceIdentifierContext();
419 // missing broker on mounted device
420 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
421 when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
423 final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
425 // assert not successful operation with error
426 assertNotNull(status.getGlobalErrors());
427 assertEquals(1, status.getGlobalErrors().size());
428 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
429 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
431 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());