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.Ignore;
33 import org.junit.Test;
34 import org.mockito.InOrder;
35 import org.mockito.Mock;
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.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.PATCHEntity;
57 import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
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.yangtools.concepts.ListenerRegistration;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
75 * Unit tests for BrokerFacade.
77 * @author Thomas Pantelis
79 public class BrokerFacadeTest {
82 private DOMDataBroker domDataBroker;
84 private DOMNotificationService domNotification;
86 private ConsumerSession context;
88 private DOMRpcService mockRpcService;
90 private DOMMountPoint mockMountInstance;
92 private DOMDataReadOnlyTransaction rTransaction;
94 private DOMDataWriteTransaction wTransaction;
96 private DOMDataReadWriteTransaction rwTransaction;
98 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
99 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
100 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
101 wrapDummyNode(dummyNode);
102 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
103 private final SchemaPath type = SchemaPath.create(true, qname);
104 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).build();
107 public void setUp() throws Exception {
108 MockitoAnnotations.initMocks(this);
109 brokerFacade.setDomDataBroker(domDataBroker);
110 brokerFacade.setDomNotificationService(domNotification);
111 brokerFacade.setRpcService(mockRpcService);
112 brokerFacade.setContext(context);
113 when(domDataBroker.newReadOnlyTransaction()).thenReturn(rTransaction);
114 when(domDataBroker.newWriteOnlyTransaction()).thenReturn(wTransaction);
115 when(domDataBroker.newReadWriteTransaction()).thenReturn(rwTransaction);
117 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
120 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
121 final NormalizedNode<?, ?> dummyNode) {
122 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
125 private CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
126 return Futures.immediateCheckedFuture(exists);
130 * Value of this node shouldn't be important for testing purposes
132 private NormalizedNode<?, ?> createDummyNode(final String namespace, final String date, final String localName) {
133 return Builders.containerBuilder()
134 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
138 public void testReadConfigurationData() {
139 when(rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
142 final NormalizedNode<?, ?> actualNode = brokerFacade.readConfigurationData(instanceID);
144 assertSame("readConfigurationData", dummyNode, actualNode);
148 public void testReadOperationalData() {
149 when(rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
152 final NormalizedNode<?, ?> actualNode = brokerFacade.readOperationalData(instanceID);
154 assertSame("readOperationalData", dummyNode, actualNode);
157 @Test(expected = RestconfDocumentedException.class)
158 public void testReadOperationalDataWithNoDataBroker() {
159 brokerFacade.setDomDataBroker(null);
161 brokerFacade.readOperationalData(instanceID);
165 public void testInvokeRpc() throws Exception {
166 final DOMRpcResult expResult = mock(DOMRpcResult.class);
167 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
168 when(mockRpcService.invokeRpc(type, dummyNode)).thenReturn(future);
170 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = brokerFacade.invokeRpc(type, dummyNode);
171 assertNotNull("Future is null", actualFuture);
172 final DOMRpcResult actualResult = actualFuture.get();
173 assertSame("invokeRpc", expResult, actualResult);
176 @Test(expected = RestconfDocumentedException.class)
177 public void testInvokeRpcWithNoConsumerSession() {
178 brokerFacade.setContext(null);
179 brokerFacade.invokeRpc(type, dummyNode);
184 public void testCommitConfigurationDataPut() {
185 @SuppressWarnings("unchecked")
186 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
188 when(wTransaction.submit()).thenReturn(expFuture);
190 final Future<Void> actualFuture = brokerFacade.commitConfigurationDataPut((SchemaContext)null, instanceID, dummyNode);
192 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
194 final InOrder inOrder = inOrder(domDataBroker, wTransaction);
195 inOrder.verify(domDataBroker).newWriteOnlyTransaction();
196 inOrder.verify(wTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
197 inOrder.verify(wTransaction).submit();
201 public void testCommitConfigurationDataPost() {
202 @SuppressWarnings("unchecked")
203 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
205 when(rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class))).thenReturn(
206 wrapExistence(false));
208 when(rwTransaction.submit()).thenReturn(expFuture);
210 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = brokerFacade.commitConfigurationDataPost(
211 (SchemaContext)null, instanceID, dummyNode);
213 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
215 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
216 inOrder.verify(domDataBroker).newReadWriteTransaction();
217 inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
218 inOrder.verify(rwTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
219 inOrder.verify(rwTransaction).submit();
222 @Test(expected = RestconfDocumentedException.class)
223 public void testCommitConfigurationDataPostAlreadyExists() {
224 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
225 when(rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class))).thenReturn(
228 // Schema context is only necessary for ensuring parent structure
229 brokerFacade.commitConfigurationDataPost((SchemaContext)null, instanceID, dummyNode);
230 } catch (final RestconfDocumentedException e) {
231 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
237 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
240 public void testCommitConfigurationDataDelete() throws Exception {
241 // assume that data to delete exists
242 prepareDataForDelete(true);
245 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
246 when(rwTransaction.submit()).thenReturn(expFuture);
249 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = brokerFacade
250 .commitConfigurationDataDelete(instanceID);
252 // verify result and interactions
253 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
255 // check exists, delete, submit
256 final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
257 inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
258 inOrder.verify(rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, instanceID);
259 inOrder.verify(rwTransaction).submit();
263 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
266 public void testCommitConfigurationDataDeleteNoData() throws Exception {
267 // assume that data to delete does not exist
268 prepareDataForDelete(false);
270 // try to delete and expect 404 error
272 brokerFacade.commitConfigurationDataDelete(instanceID);
273 fail("Delete operation should fail due to missing data");
274 } catch (final RestconfDocumentedException e) {
275 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
276 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
277 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
282 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
283 * {@code assumeDataExists} parameter.
284 * @param assumeDataExists
287 private void prepareDataForDelete(final boolean assumeDataExists) throws Exception {
288 final CheckedFuture<Boolean, ReadFailedException> checkDataExistFuture = mock(CheckedFuture.class);
289 when(checkDataExistFuture.get()).thenReturn(assumeDataExists);
290 when(rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, instanceID)).thenReturn(checkDataExistFuture);
293 @SuppressWarnings("unchecked")
295 public void testRegisterToListenDataChanges() {
296 final ListenerAdapter listener = Notificator.createListener(instanceID, "stream");
298 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
301 domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(instanceID), eq(listener),
302 eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
304 brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
306 verify(domDataBroker).registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, instanceID, listener,
307 DataChangeScope.BASE);
309 assertEquals("isListening", true, listener.isListening());
311 brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
312 verifyNoMoreInteractions(domDataBroker);
316 * Create, register, close and remove notification listener.
319 public void testRegisterToListenNotificationChanges() {
320 // create test notification listener
321 final String identifier = "create-notification-stream/toaster:toastDone";
322 final SchemaPath path = SchemaPath.create(true,
323 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
324 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
325 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
328 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
329 when(domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
330 .thenReturn(registration);
332 // test to register listener for the first time
333 brokerFacade.registerToListenNotification(listener);
334 assertEquals("Registration was not successful", true, listener.isListening());
336 // try to register for the second time
337 brokerFacade.registerToListenNotification(listener);
338 assertEquals("Registration was not successful", true, listener.isListening());
340 // registrations should be invoked only once
341 verify(domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
343 // close and remove test notification listener
345 Notificator.removeNotificationListenerIfNoSubscriberExists(listener);
349 * Test PATCH method on the server with no data
352 @SuppressWarnings("unchecked")
353 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
354 final PATCHContext patchContext = mock(PATCHContext.class);
355 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
356 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
358 when(patchContext.getData()).thenReturn(Lists.<PATCHEntity>newArrayList());
359 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
362 when(identifierContext.getMountPoint()).thenReturn(null);
364 when(this.rwTransaction.submit()).thenReturn(expFuture);
366 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
369 assertTrue("PATCH operation should be successful on server", status.isOk());
373 * Test PATCH method on mounted device with no data
376 @SuppressWarnings("unchecked")
377 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
378 final PATCHContext patchContext = mock(PATCHContext.class);
379 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
380 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
381 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
382 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
383 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
385 when(patchContext.getData()).thenReturn(Lists.<PATCHEntity>newArrayList());
386 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
388 // return mount point with broker
389 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
390 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
391 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
392 when(transaction.submit()).thenReturn(expFuture);
394 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
397 assertTrue("PATCH operation should be successful on mounted device", status.isOk());
401 * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
402 * PATCH operation should fail with global error.
405 @SuppressWarnings("unchecked")
406 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
407 final PATCHContext patchContext = mock(PATCHContext.class);
408 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
409 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
410 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
411 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
412 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
414 when(patchContext.getData()).thenReturn(Lists.<PATCHEntity>newArrayList());
415 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
416 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
418 // missing broker on mounted device
419 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.<DOMDataBroker>absent());
421 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
422 when(transaction.submit()).thenReturn(expFuture);
424 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
426 // assert not successful operation with error
427 assertNotNull(status.getGlobalErrors());
428 assertEquals(1, status.getGlobalErrors().size());
429 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
430 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
432 assertFalse("PATCH operation should fail on mounted device without Broker", status.isOk());