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.assertTrue;
15 import static org.junit.Assert.fail;
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.collect.ImmutableList;
32 import com.google.common.collect.Lists;
33 import com.google.common.util.concurrent.FluentFuture;
34 import com.google.common.util.concurrent.ListenableFuture;
35 import java.util.ArrayList;
36 import java.util.Optional;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.InOrder;
40 import org.mockito.Mock;
41 import org.mockito.Mockito;
42 import org.mockito.MockitoAnnotations;
43 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
44 import org.opendaylight.mdsal.common.api.CommitInfo;
45 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
46 import org.opendaylight.mdsal.common.api.ReadFailedException;
47 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
48 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
49 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
51 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
52 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
53 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
54 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
55 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
56 import org.opendaylight.mdsal.dom.api.DOMRpcService;
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.context.InstanceIdentifierContext;
65 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
66 import org.opendaylight.restconf.common.errors.RestconfError;
67 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
68 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
69 import org.opendaylight.restconf.common.patch.PatchContext;
70 import org.opendaylight.restconf.common.patch.PatchStatusContext;
71 import org.opendaylight.restconf.common.util.DataChangeScope;
72 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
73 import org.opendaylight.yangtools.concepts.ListenerRegistration;
74 import org.opendaylight.yangtools.yang.common.QName;
75 import org.opendaylight.yangtools.yang.common.RpcError;
76 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
80 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
81 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
82 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
83 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
86 * Unit tests for BrokerFacade.
88 * @author Thomas Pantelis
90 public class BrokerFacadeTest {
93 private DOMDataBroker domDataBroker;
95 private DOMNotificationService domNotification;
97 private DOMRpcService mockRpcService;
99 private DOMMountPoint mockMountInstance;
101 private DOMDataTreeReadTransaction readTransaction;
103 private DOMDataTreeWriteTransaction writeTransaction;
105 private DOMDataTreeReadWriteTransaction rwTransaction;
107 private BrokerFacade brokerFacade;
108 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
109 private final FluentFuture<Optional<NormalizedNode<?, ?>>> dummyNodeInFuture = wrapDummyNode(this.dummyNode);
110 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
111 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
112 private ControllerContext controllerContext;
115 public void setUp() throws Exception {
116 MockitoAnnotations.initMocks(this);
118 controllerContext = TestRestconfUtils.newControllerContext(
119 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
121 brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
123 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
124 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
125 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
126 when(this.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,
142 final String localName) {
143 return Builders.containerBuilder()
144 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
148 public void testReadConfigurationData() {
149 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
150 this.dummyNodeInFuture);
152 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
154 assertSame("readConfigurationData", this.dummyNode, actualNode);
158 public void testReadOperationalData() {
159 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
160 this.dummyNodeInFuture);
162 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
164 assertSame("readOperationalData", this.dummyNode, actualNode);
168 public void test503() throws Exception {
169 final RpcError error = RpcResultBuilder.newError(
170 RpcError.ErrorType.TRANSPORT,
171 ErrorTag.RESOURCE_DENIED.getTagValue(),
172 "Master is down. Please try again.");
173 doReturn(immediateFailedFluentFuture(new ReadFailedException("Read from transaction failed", error)))
174 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
176 brokerFacade.readConfigurationData(this.instanceID, "explicit");
177 fail("This test should fail.");
178 } catch (final RestconfDocumentedException e) {
179 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
180 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
181 assertEquals("getErrorMessage", "Master is down. Please try again.",
182 e.getErrors().get(0).getErrorMessage());
187 public void testInvokeRpc() throws Exception {
188 final DOMRpcResult expResult = mock(DOMRpcResult.class);
189 doReturn(immediateFluentFuture(expResult)).when(this.mockRpcService).invokeRpc(this.qname, this.dummyNode);
191 final ListenableFuture<? extends DOMRpcResult> actualFuture = this.brokerFacade.invokeRpc(this.qname,
193 assertNotNull("Future is null", actualFuture);
194 final DOMRpcResult actualResult = actualFuture.get();
195 assertSame("invokeRpc", expResult, actualResult);
199 public void testCommitConfigurationDataPut() throws Exception {
200 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
202 doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(this.rwTransaction)
203 .read(LogicalDatastoreType.CONFIGURATION, this.instanceID);
205 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(EffectiveModelContext.class),
206 this.instanceID, this.dummyNode, null, null);
208 assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
210 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
211 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
212 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
213 inOrder.verify(this.rwTransaction).commit();
217 public void testCommitConfigurationDataPost() {
218 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
219 .thenReturn(wrapExistence(false));
221 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
223 final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
224 .commitConfigurationDataPost(mock(EffectiveModelContext.class), this.instanceID, this.dummyNode, null,
227 assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
229 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
230 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
231 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
232 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
233 inOrder.verify(this.rwTransaction).commit();
236 @Test(expected = RestconfDocumentedException.class)
237 public void testCommitConfigurationDataPostAlreadyExists() {
238 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
239 .thenReturn(immediateTrueFluentFuture());
241 // Schema context is only necessary for ensuring parent structure
242 this.brokerFacade.commitConfigurationDataPost((EffectiveModelContext) null, this.instanceID, this.dummyNode,
244 } catch (final RestconfDocumentedException e) {
245 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
251 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
254 public void testCommitConfigurationDataDelete() throws Exception {
255 // assume that data to delete exists
256 prepareDataForDelete(true);
259 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
262 final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
263 .commitConfigurationDataDelete(this.instanceID);
265 // verify result and interactions
266 assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
268 // check exists, delete, submit
269 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
270 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
271 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
272 inOrder.verify(this.rwTransaction).commit();
276 * Negative test of delete operation when data to delete does not exist. Error DATA_MISSING should be returned.
279 public void testCommitConfigurationDataDeleteNoData() throws Exception {
280 // assume that data to delete does not exist
281 prepareDataForDelete(false);
283 // try to delete and expect DATA_MISSING error
285 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
286 fail("Delete operation should fail due to missing data");
287 } catch (final RestconfDocumentedException e) {
288 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
289 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
294 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
295 * {@code assumeDataExists} parameter.
296 * @param assumeDataExists boolean to assume if data exists
298 private void prepareDataForDelete(final boolean assumeDataExists) {
299 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
300 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
304 public void testRegisterToListenDataChanges() {
305 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
306 NotificationOutputType.XML, controllerContext);
308 @SuppressWarnings("unchecked")
309 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
311 DOMDataTreeChangeService changeService = this.domDataBroker.getExtensions()
312 .getInstance(DOMDataTreeChangeService.class);
313 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
314 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
316 this.brokerFacade.registerToListenDataChanges(
317 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
319 verify(changeService).registerDataTreeChangeListener(loc, listener);
321 assertEquals("isListening", true, listener.isListening());
323 this.brokerFacade.registerToListenDataChanges(
324 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
325 verifyNoMoreInteractions(changeService);
329 * Create, register, close and remove notification listener.
332 public void testRegisterToListenNotificationChanges() throws Exception {
333 // create test notification listener
334 final String identifier = "create-notification-stream/toaster:toastDone";
335 final SchemaPath path = SchemaPath.create(true,
336 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
337 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
338 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
341 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
342 when(this.domNotification.registerNotificationListener(listener,
343 Absolute.of(ImmutableList.copyOf(listener.getSchemaPath().getPathFromRoot()))))
344 .thenReturn(registration);
346 // test to register listener for the first time
347 this.brokerFacade.registerToListenNotification(listener);
348 assertEquals("Registration was not successful", true, listener.isListening());
350 // try to register for the second time
351 this.brokerFacade.registerToListenNotification(listener);
352 assertEquals("Registration was not successful", true, listener.isListening());
354 // registrations should be invoked only once
355 verify(this.domNotification, times(1)).registerNotificationListener(listener,
356 Absolute.of(ImmutableList.copyOf(listener.getSchemaPath().getPathFromRoot())));
358 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
359 final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
360 doReturn(CommitInfo.emptyFluentFuture()).when(wTx).commit();
361 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
362 // close and remove test notification listener
364 Notificator.removeListenerIfNoSubscriberExists(listener);
368 * Test Patch method on the server with no data.
371 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
372 final PatchContext patchContext = mock(PatchContext.class);
373 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
375 when(patchContext.getData()).thenReturn(new ArrayList<>());
376 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
379 when(identifierContext.getMountPoint()).thenReturn(null);
381 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
383 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
386 assertTrue("Patch operation should be successful on server", status.isOk());
390 * Test Patch method on mounted device with no data.
393 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
394 final PatchContext patchContext = mock(PatchContext.class);
395 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
396 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
397 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
398 final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
400 when(patchContext.getData()).thenReturn(new ArrayList<>());
401 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
403 // return mount point with broker
404 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
405 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
406 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
407 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
409 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
412 assertTrue("Patch operation should be successful on mounted device", status.isOk());
416 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
417 * Patch operation should fail with global error.
420 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
421 final PatchContext patchContext = mock(PatchContext.class);
422 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
423 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
424 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
425 final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
427 when(patchContext.getData()).thenReturn(new ArrayList<>());
428 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
429 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
431 // missing broker on mounted device
432 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
434 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
435 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
437 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
439 // assert not successful operation with error
440 assertNotNull(status.getGlobalErrors());
441 assertEquals(1, status.getGlobalErrors().size());
442 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
443 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
445 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());