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
9 package org.opendaylight.controller.sal.restconf.impl.test;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertSame;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.Matchers.any;
18 import static org.mockito.Matchers.eq;
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;
26 import com.google.common.base.Optional;
27 import com.google.common.collect.Lists;
28 import com.google.common.util.concurrent.CheckedFuture;
29 import com.google.common.util.concurrent.Futures;
30 import java.util.concurrent.Future;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.mockito.InOrder;
34 import org.mockito.Mock;
35 import org.mockito.Mockito;
36 import org.mockito.MockitoAnnotations;
37 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
42 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
43 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
44 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
45 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
46 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
47 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
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.sal.core.api.Broker.ConsumerSession;
53 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
54 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
55 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
56 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
57 import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
58 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
61 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
62 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.restconf.handlers.SchemaContextHandler;
67 import org.opendaylight.restconf.handlers.TransactionChainHandler;
68 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
69 import org.opendaylight.yangtools.concepts.ListenerRegistration;
70 import org.opendaylight.yangtools.yang.common.QName;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
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;
76 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
79 * Unit tests for BrokerFacade.
81 * @author Thomas Pantelis
83 public class BrokerFacadeTest {
86 private DOMDataBroker domDataBroker;
88 private DOMNotificationService domNotification;
90 private ConsumerSession context;
92 private DOMRpcService mockRpcService;
94 private DOMMountPoint mockMountInstance;
96 private DOMDataReadOnlyTransaction rTransaction;
98 private DOMDataWriteTransaction wTransaction;
100 private DOMDataReadWriteTransaction rwTransaction;
102 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
103 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
104 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
105 wrapDummyNode(this.dummyNode);
106 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
107 private final SchemaPath type = SchemaPath.create(true, this.qname);
108 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
111 public void setUp() throws Exception {
112 MockitoAnnotations.initMocks(this);
113 this.brokerFacade.setDomDataBroker(this.domDataBroker);
114 this.brokerFacade.setDomNotificationService(this.domNotification);
115 this.brokerFacade.setRpcService(this.mockRpcService);
116 this.brokerFacade.setContext(this.context);
117 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
118 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
119 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
121 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
124 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
125 final NormalizedNode<?, ?> dummyNode) {
126 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
129 private CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
130 return Futures.immediateCheckedFuture(exists);
134 * Value of this node shouldn't be important for testing purposes
136 private NormalizedNode<?, ?> createDummyNode(final String namespace, final String date, final String localName) {
137 return Builders.containerBuilder()
138 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
142 public void testReadConfigurationData() {
143 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
144 this.dummyNodeInFuture);
146 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
148 assertSame("readConfigurationData", this.dummyNode, actualNode);
152 public void testReadOperationalData() {
153 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
154 this.dummyNodeInFuture);
156 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
158 assertSame("readOperationalData", this.dummyNode, actualNode);
161 @Test(expected = RestconfDocumentedException.class)
162 public void testReadOperationalDataWithNoDataBroker() {
163 this.brokerFacade.setDomDataBroker(null);
165 this.brokerFacade.readOperationalData(this.instanceID);
169 public void testInvokeRpc() throws Exception {
170 final DOMRpcResult expResult = mock(DOMRpcResult.class);
171 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
172 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
174 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
175 .invokeRpc(this.type, this.dummyNode);
176 assertNotNull("Future is null", actualFuture);
177 final DOMRpcResult actualResult = actualFuture.get();
178 assertSame("invokeRpc", expResult, actualResult);
181 @Test(expected = RestconfDocumentedException.class)
182 public void testInvokeRpcWithNoConsumerSession() {
183 this.brokerFacade.setContext(null);
184 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
188 public void testCommitConfigurationDataPut() throws Exception {
189 @SuppressWarnings("unchecked")
190 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
191 when(this.rwTransaction.submit()).thenReturn(expFuture);
193 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
194 when(optionalMock.get()).thenReturn(null);
196 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
197 .immediateCheckedFuture(optionalMock);
198 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
200 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
201 this.instanceID, this.dummyNode, null, null);
203 final Future<Void> actualFuture = result.getFutureOfPutData();
205 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
207 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
208 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
209 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
210 inOrder.verify(this.rwTransaction).submit();
214 public void testCommitConfigurationDataPost() {
215 @SuppressWarnings("unchecked")
216 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
218 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
219 .thenReturn(wrapExistence(false));
221 when(this.rwTransaction.submit()).thenReturn(expFuture);
223 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
224 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
226 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
228 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
229 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
230 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
231 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
232 inOrder.verify(this.rwTransaction).submit();
235 @Test(expected = RestconfDocumentedException.class)
236 public void testCommitConfigurationDataPostAlreadyExists() {
237 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
238 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
239 .thenReturn(successFuture);
241 // Schema context is only necessary for ensuring parent structure
242 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
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 @SuppressWarnings("unchecked")
260 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
261 when(this.rwTransaction.submit()).thenReturn(expFuture);
264 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
265 .commitConfigurationDataDelete(this.instanceID);
267 // verify result and interactions
268 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
270 // check exists, delete, submit
271 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
272 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
273 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
274 inOrder.verify(this.rwTransaction).submit();
278 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
281 public void testCommitConfigurationDataDeleteNoData() throws Exception {
282 // assume that data to delete does not exist
283 prepareDataForDelete(false);
285 // try to delete and expect 404 error
287 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
288 fail("Delete operation should fail due to missing data");
289 } catch (final RestconfDocumentedException e) {
290 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
291 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
292 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
297 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
298 * {@code assumeDataExists} parameter.
299 * @param assumeDataExists
301 private void prepareDataForDelete(final boolean assumeDataExists) {
302 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
303 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
307 public void testRegisterToListenDataChanges() {
308 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
309 NotificationOutputType.XML);
311 @SuppressWarnings("unchecked")
312 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
314 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
315 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
317 this.brokerFacade.registerToListenDataChanges(
318 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
320 verify(this.domDataBroker).registerDataChangeListener(
321 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
323 assertEquals("isListening", true, listener.isListening());
325 this.brokerFacade.registerToListenDataChanges(
326 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
327 verifyNoMoreInteractions(this.domDataBroker);
331 * Create, register, close and remove notification listener.
334 public void testRegisterToListenNotificationChanges() throws Exception {
335 // create test notification listener
336 final String identifier = "create-notification-stream/toaster:toastDone";
337 final SchemaPath path = SchemaPath.create(true,
338 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
339 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
340 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
343 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
344 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
345 .thenReturn(registration);
347 // test to register listener for the first time
348 this.brokerFacade.registerToListenNotification(listener);
349 assertEquals("Registration was not successful", true, listener.isListening());
351 // try to register for the second time
352 this.brokerFacade.registerToListenNotification(listener);
353 assertEquals("Registration was not successful", true, listener.isListening());
355 // registrations should be invoked only once
356 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
358 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
359 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
360 final CheckedFuture checked = Futures.immediateCheckedFuture("");
361 when(wTx.submit()).thenReturn(checked);
362 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
363 final TransactionChainHandler transactionChainHandler = new TransactionChainHandler(transactionChain);
364 final SchemaContextHandler schemaHandler = Mockito.mock(SchemaContextHandler.class);
365 final SchemaContext schCtx = TestUtils.loadSchemaContext("/modules");
366 when(schemaHandler.get()).thenReturn(schCtx);
367 listener.setCloseVars(transactionChainHandler, schemaHandler);
368 // close and remove test notification listener
370 Notificator.removeListenerIfNoSubscriberExists(listener);
374 * Test PATCH method on the server with no data
377 @SuppressWarnings("unchecked")
378 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
379 final PATCHContext patchContext = mock(PATCHContext.class);
380 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
381 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
383 when(patchContext.getData()).thenReturn(Lists.newArrayList());
384 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
387 when(identifierContext.getMountPoint()).thenReturn(null);
389 when(this.rwTransaction.submit()).thenReturn(expFuture);
391 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
394 assertTrue("PATCH operation should be successful on server", status.isOk());
398 * Test PATCH method on mounted device with no data
401 @SuppressWarnings("unchecked")
402 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
403 final PATCHContext patchContext = mock(PATCHContext.class);
404 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
405 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
406 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
407 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
408 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
410 when(patchContext.getData()).thenReturn(Lists.newArrayList());
411 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
413 // return mount point with broker
414 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
415 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
416 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
417 when(transaction.submit()).thenReturn(expFuture);
419 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
422 assertTrue("PATCH operation should be successful on mounted device", status.isOk());
426 * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
427 * PATCH operation should fail with global error.
430 @SuppressWarnings("unchecked")
431 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
432 final PATCHContext patchContext = mock(PATCHContext.class);
433 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
434 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
435 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
436 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
437 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
439 when(patchContext.getData()).thenReturn(Lists.newArrayList());
440 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
441 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
443 // missing broker on mounted device
444 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
446 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
447 when(transaction.submit()).thenReturn(expFuture);
449 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
451 // assert not successful operation with error
452 assertNotNull(status.getGlobalErrors());
453 assertEquals(1, status.getGlobalErrors().size());
454 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
455 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
457 assertFalse("PATCH operation should fail on mounted device without Broker", status.isOk());