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;
25 import com.google.common.base.Optional;
26 import com.google.common.collect.Lists;
27 import com.google.common.util.concurrent.CheckedFuture;
28 import com.google.common.util.concurrent.Futures;
29 import java.util.concurrent.Future;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.mockito.InOrder;
33 import org.mockito.Mock;
34 import org.mockito.Mockito;
35 import org.mockito.MockitoAnnotations;
36 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
37 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
38 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
41 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
42 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
43 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
44 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
45 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
46 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
47 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
50 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
51 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
52 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
53 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
54 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
55 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
56 import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
57 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
58 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
61 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
62 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
65 import org.opendaylight.restconf.handlers.SchemaContextHandler;
66 import org.opendaylight.restconf.handlers.TransactionChainHandler;
67 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
68 import org.opendaylight.yangtools.concepts.ListenerRegistration;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
72 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
73 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
78 * Unit tests for BrokerFacade.
80 * @author Thomas Pantelis
82 public class BrokerFacadeTest {
85 private DOMDataBroker domDataBroker;
87 private DOMNotificationService domNotification;
89 private ConsumerSession context;
91 private DOMRpcService mockRpcService;
93 private DOMMountPoint mockMountInstance;
95 private DOMDataReadOnlyTransaction rTransaction;
97 private DOMDataWriteTransaction wTransaction;
99 private DOMDataReadWriteTransaction rwTransaction;
101 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
102 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
103 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
104 wrapDummyNode(this.dummyNode);
105 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
106 private final SchemaPath type = SchemaPath.create(true, this.qname);
107 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
110 public void setUp() throws Exception {
111 MockitoAnnotations.initMocks(this);
112 this.brokerFacade.setDomDataBroker(this.domDataBroker);
113 this.brokerFacade.setDomNotificationService(this.domNotification);
114 this.brokerFacade.setRpcService(this.mockRpcService);
115 this.brokerFacade.setContext(this.context);
116 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
117 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
118 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
120 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
123 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
124 final NormalizedNode<?, ?> dummyNode) {
125 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
128 private CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
129 return Futures.immediateCheckedFuture(exists);
133 * Value of this node shouldn't be important for testing purposes
135 private NormalizedNode<?, ?> createDummyNode(final String namespace, final String date, final String localName) {
136 return Builders.containerBuilder()
137 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
141 public void testReadConfigurationData() {
142 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
143 this.dummyNodeInFuture);
145 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
147 assertSame("readConfigurationData", this.dummyNode, actualNode);
151 public void testReadOperationalData() {
152 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
153 this.dummyNodeInFuture);
155 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
157 assertSame("readOperationalData", this.dummyNode, actualNode);
160 @Test(expected = RestconfDocumentedException.class)
161 public void testReadOperationalDataWithNoDataBroker() {
162 this.brokerFacade.setDomDataBroker(null);
164 this.brokerFacade.readOperationalData(this.instanceID);
168 public void testInvokeRpc() throws Exception {
169 final DOMRpcResult expResult = mock(DOMRpcResult.class);
170 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
171 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
173 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
174 .invokeRpc(this.type, this.dummyNode);
175 assertNotNull("Future is null", actualFuture);
176 final DOMRpcResult actualResult = actualFuture.get();
177 assertSame("invokeRpc", expResult, actualResult);
180 @Test(expected = RestconfDocumentedException.class)
181 public void testInvokeRpcWithNoConsumerSession() {
182 this.brokerFacade.setContext(null);
183 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
187 public void testCommitConfigurationDataPut() throws Exception {
188 @SuppressWarnings("unchecked")
189 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
190 when(this.rwTransaction.submit()).thenReturn(expFuture);
192 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
193 when(optionalMock.get()).thenReturn(null);
195 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
196 .immediateCheckedFuture(optionalMock);
197 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
199 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
200 this.instanceID, this.dummyNode, null, null);
202 final Future<Void> actualFuture = result.getFutureOfPutData();
204 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
206 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
207 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
208 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
209 inOrder.verify(this.rwTransaction).submit();
213 public void testCommitConfigurationDataPost() {
214 @SuppressWarnings("unchecked")
215 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
217 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
218 .thenReturn(wrapExistence(false));
220 when(this.rwTransaction.submit()).thenReturn(expFuture);
222 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
223 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
225 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
227 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
228 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
229 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
230 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
231 inOrder.verify(this.rwTransaction).submit();
234 @Test(expected = RestconfDocumentedException.class)
235 public void testCommitConfigurationDataPostAlreadyExists() {
236 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
237 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
238 .thenReturn(successFuture);
240 // Schema context is only necessary for ensuring parent structure
241 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
243 } catch (final RestconfDocumentedException e) {
244 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
250 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
253 public void testCommitConfigurationDataDelete() throws Exception {
254 // assume that data to delete exists
255 prepareDataForDelete(true);
258 @SuppressWarnings("unchecked")
259 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
260 when(this.rwTransaction.submit()).thenReturn(expFuture);
263 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
264 .commitConfigurationDataDelete(this.instanceID);
266 // verify result and interactions
267 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
269 // check exists, delete, submit
270 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
271 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
272 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
273 inOrder.verify(this.rwTransaction).submit();
277 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
280 public void testCommitConfigurationDataDeleteNoData() throws Exception {
281 // assume that data to delete does not exist
282 prepareDataForDelete(false);
284 // try to delete and expect 404 error
286 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
287 fail("Delete operation should fail due to missing data");
288 } catch (final RestconfDocumentedException e) {
289 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
290 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
291 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
296 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
297 * {@code assumeDataExists} parameter.
298 * @param assumeDataExists
300 private void prepareDataForDelete(final boolean assumeDataExists) {
301 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
302 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
306 public void testRegisterToListenDataChanges() {
307 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
308 NotificationOutputType.XML);
310 @SuppressWarnings("unchecked")
311 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
313 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
314 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
316 this.brokerFacade.registerToListenDataChanges(
317 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
319 verify(this.domDataBroker).registerDataChangeListener(
320 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
322 assertEquals("isListening", true, listener.isListening());
324 this.brokerFacade.registerToListenDataChanges(
325 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
326 verifyNoMoreInteractions(this.domDataBroker);
330 * Create, register, close and remove notification listener.
333 public void testRegisterToListenNotificationChanges() throws Exception {
334 // create test notification listener
335 final String identifier = "create-notification-stream/toaster:toastDone";
336 final SchemaPath path = SchemaPath.create(true,
337 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
338 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
339 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
342 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
343 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
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, listener.getSchemaPath());
357 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
358 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
359 final CheckedFuture checked = Futures.immediateCheckedFuture("");
360 when(wTx.submit()).thenReturn(checked);
361 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
362 final TransactionChainHandler transactionChainHandler = new TransactionChainHandler(transactionChain);
363 final SchemaContextHandler schemaHandler = Mockito.mock(SchemaContextHandler.class);
364 final SchemaContext schCtx = TestUtils.loadSchemaContext("/modules");
365 when(schemaHandler.get()).thenReturn(schCtx);
366 listener.setCloseVars(transactionChainHandler, schemaHandler);
367 // close and remove test notification listener
369 Notificator.removeListenerIfNoSubscriberExists(listener);
373 * Test PATCH method on the server with no data
376 @SuppressWarnings("unchecked")
377 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
378 final PATCHContext patchContext = mock(PATCHContext.class);
379 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
380 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
382 when(patchContext.getData()).thenReturn(Lists.newArrayList());
383 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
386 when(identifierContext.getMountPoint()).thenReturn(null);
388 when(this.rwTransaction.submit()).thenReturn(expFuture);
390 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
393 assertTrue("PATCH operation should be successful on server", status.isOk());
397 * Test PATCH method on mounted device with no data
400 @SuppressWarnings("unchecked")
401 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
402 final PATCHContext patchContext = mock(PATCHContext.class);
403 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
404 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
405 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
406 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
407 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
409 when(patchContext.getData()).thenReturn(Lists.newArrayList());
410 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
412 // return mount point with broker
413 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
414 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
415 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
416 when(transaction.submit()).thenReturn(expFuture);
418 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
421 assertTrue("PATCH operation should be successful on mounted device", status.isOk());
425 * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
426 * PATCH operation should fail with global error.
429 @SuppressWarnings("unchecked")
430 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
431 final PATCHContext patchContext = mock(PATCHContext.class);
432 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
433 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
434 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
435 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
436 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
438 when(patchContext.getData()).thenReturn(Lists.newArrayList());
439 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
440 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
442 // missing broker on mounted device
443 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
445 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
446 when(transaction.submit()).thenReturn(expFuture);
448 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
450 // assert not successful operation with error
451 assertNotNull(status.getGlobalErrors());
452 assertEquals(1, status.getGlobalErrors().size());
453 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
454 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
456 assertFalse("PATCH operation should fail on mounted device without Broker", status.isOk());