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.doReturn;
20 import static org.mockito.Mockito.inOrder;
21 import static org.mockito.Mockito.mock;
22 import static org.mockito.Mockito.times;
23 import static org.mockito.Mockito.verify;
24 import static org.mockito.Mockito.verifyNoMoreInteractions;
25 import static org.mockito.Mockito.when;
27 import com.google.common.base.Optional;
28 import com.google.common.collect.Lists;
29 import com.google.common.util.concurrent.CheckedFuture;
30 import com.google.common.util.concurrent.Futures;
31 import java.util.HashMap;
32 import java.util.concurrent.Future;
33 import org.junit.Before;
34 import org.junit.Test;
35 import org.mockito.InOrder;
36 import org.mockito.Mock;
37 import org.mockito.Mockito;
38 import org.mockito.MockitoAnnotations;
39 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
40 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
41 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
42 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
43 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
44 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
45 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
46 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
47 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
48 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
49 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
50 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
54 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
55 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
56 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
57 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
58 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
59 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
60 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
61 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
62 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
63 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
64 import org.opendaylight.restconf.common.errors.RestconfError;
65 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
66 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
67 import org.opendaylight.restconf.common.patch.PatchContext;
68 import org.opendaylight.restconf.common.patch.PatchStatusContext;
69 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
70 import org.opendaylight.yangtools.concepts.ListenerRegistration;
71 import org.opendaylight.yangtools.yang.common.QName;
72 import org.opendaylight.yangtools.yang.common.RpcError;
73 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
75 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
76 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
77 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
78 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
79 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
82 * Unit tests for BrokerFacade.
84 * @author Thomas Pantelis
86 public class BrokerFacadeTest {
89 private DOMDataBroker domDataBroker;
91 private DOMNotificationService domNotification;
93 private DOMRpcService mockRpcService;
95 private DOMMountPoint mockMountInstance;
97 private DOMDataReadOnlyTransaction readTransaction;
99 private DOMDataWriteTransaction writeTransaction;
101 private DOMDataReadWriteTransaction rwTransaction;
103 private BrokerFacade brokerFacade;
104 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
105 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
106 wrapDummyNode(this.dummyNode);
107 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
108 private final SchemaPath type = SchemaPath.create(true, this.qname);
109 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
110 private ControllerContext controllerContext;
113 public void setUp() throws Exception {
114 MockitoAnnotations.initMocks(this);
116 controllerContext = TestRestconfUtils.newControllerContext(
117 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
119 brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
121 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
122 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
123 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
124 HashMap extensions = new HashMap();
125 extensions.put(DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class));
126 when(this.domDataBroker.getSupportedExtensions()).thenReturn(extensions);
129 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
130 final NormalizedNode<?, ?> dummyNode) {
131 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
134 private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
135 return Futures.immediateCheckedFuture(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);
167 @Test(expected = RestconfDocumentedException.class)
168 public void testReadOperationalDataWithNoDataBroker() {
169 this.brokerFacade.close();
171 this.brokerFacade.readOperationalData(this.instanceID);
175 public void test503() throws Exception {
176 final RpcError error = RpcResultBuilder.newError(
177 RpcError.ErrorType.TRANSPORT,
178 ErrorTag.RESOURCE_DENIED.getTagValue(),
179 "Master is down. Please try again.");
180 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
181 doReturn(Futures.immediateFailedCheckedFuture(exception503))
182 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
184 brokerFacade.readConfigurationData(this.instanceID, "explicit");
185 fail("This test should fail.");
186 } catch (final RestconfDocumentedException e) {
187 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
188 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
189 assertEquals("getErrorMessage", "Master is down. Please try again.",
190 e.getErrors().get(0).getErrorMessage());
195 public void testInvokeRpc() throws Exception {
196 final DOMRpcResult expResult = mock(DOMRpcResult.class);
197 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
198 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
200 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
201 .invokeRpc(this.type, this.dummyNode);
202 assertNotNull("Future is null", actualFuture);
203 final DOMRpcResult actualResult = actualFuture.get();
204 assertSame("invokeRpc", expResult, actualResult);
207 @Test(expected = RestconfDocumentedException.class)
208 public void testInvokeRpcWithNoConsumerSession() {
209 brokerFacade.close();
210 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
214 public void testCommitConfigurationDataPut() throws Exception {
215 @SuppressWarnings("unchecked")
216 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
217 when(this.rwTransaction.submit()).thenReturn(expFuture);
219 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
220 when(optionalMock.get()).thenReturn(null);
222 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
223 .immediateCheckedFuture(optionalMock);
224 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
226 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
227 this.instanceID, this.dummyNode, null, null);
229 final Future<Void> actualFuture = result.getFutureOfPutData();
231 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
233 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
234 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
235 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
236 inOrder.verify(this.rwTransaction).submit();
240 public void testCommitConfigurationDataPost() {
241 @SuppressWarnings("unchecked")
242 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
244 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
245 .thenReturn(wrapExistence(false));
247 when(this.rwTransaction.submit()).thenReturn(expFuture);
249 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
250 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
252 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
254 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
255 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
256 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
257 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
258 inOrder.verify(this.rwTransaction).submit();
261 @Test(expected = RestconfDocumentedException.class)
262 public void testCommitConfigurationDataPostAlreadyExists() {
263 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
264 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
265 .thenReturn(successFuture);
267 // Schema context is only necessary for ensuring parent structure
268 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
270 } catch (final RestconfDocumentedException e) {
271 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
277 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
280 public void testCommitConfigurationDataDelete() throws Exception {
281 // assume that data to delete exists
282 prepareDataForDelete(true);
285 @SuppressWarnings("unchecked")
286 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
287 when(this.rwTransaction.submit()).thenReturn(expFuture);
290 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
291 .commitConfigurationDataDelete(this.instanceID);
293 // verify result and interactions
294 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
296 // check exists, delete, submit
297 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
298 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
299 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
300 inOrder.verify(this.rwTransaction).submit();
304 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
307 public void testCommitConfigurationDataDeleteNoData() throws Exception {
308 // assume that data to delete does not exist
309 prepareDataForDelete(false);
311 // try to delete and expect 404 error
313 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
314 fail("Delete operation should fail due to missing data");
315 } catch (final RestconfDocumentedException e) {
316 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
317 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
318 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
323 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
324 * {@code assumeDataExists} parameter.
325 * @param assumeDataExists boolean to assume if data exists
327 private void prepareDataForDelete(final boolean assumeDataExists) {
328 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
329 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
333 public void testRegisterToListenDataChanges() {
334 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
335 NotificationOutputType.XML, controllerContext);
337 @SuppressWarnings("unchecked")
338 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
340 DOMDataTreeChangeService changeService = (DOMDataTreeChangeService)
341 this.domDataBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
342 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
343 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
345 this.brokerFacade.registerToListenDataChanges(
346 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
348 verify(changeService).registerDataTreeChangeListener(loc, listener);
350 assertEquals("isListening", true, listener.isListening());
352 this.brokerFacade.registerToListenDataChanges(
353 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
354 verifyNoMoreInteractions(changeService);
358 * Create, register, close and remove notification listener.
361 public void testRegisterToListenNotificationChanges() throws Exception {
362 // create test notification listener
363 final String identifier = "create-notification-stream/toaster:toastDone";
364 final SchemaPath path = SchemaPath.create(true,
365 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
366 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
367 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
370 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
371 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
372 .thenReturn(registration);
374 // test to register listener for the first time
375 this.brokerFacade.registerToListenNotification(listener);
376 assertEquals("Registration was not successful", true, listener.isListening());
378 // try to register for the second time
379 this.brokerFacade.registerToListenNotification(listener);
380 assertEquals("Registration was not successful", true, listener.isListening());
382 // registrations should be invoked only once
383 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
385 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
386 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
387 final CheckedFuture<Void, TransactionCommitFailedException> checked = Futures.immediateCheckedFuture(null);
388 when(wTx.submit()).thenReturn(checked);
389 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
390 // close and remove test notification listener
392 Notificator.removeListenerIfNoSubscriberExists(listener);
396 * Test Patch method on the server with no data.
399 @SuppressWarnings("unchecked")
400 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
401 final PatchContext patchContext = mock(PatchContext.class);
402 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
403 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
405 when(patchContext.getData()).thenReturn(Lists.newArrayList());
406 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
409 when(identifierContext.getMountPoint()).thenReturn(null);
411 when(this.rwTransaction.submit()).thenReturn(expFuture);
413 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
416 assertTrue("Patch operation should be successful on server", status.isOk());
420 * Test Patch method on mounted device with no data.
423 @SuppressWarnings("unchecked")
424 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
425 final PatchContext patchContext = mock(PatchContext.class);
426 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
427 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
428 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
429 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
430 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
432 when(patchContext.getData()).thenReturn(Lists.newArrayList());
433 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
435 // return mount point with broker
436 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
437 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
438 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
439 when(transaction.submit()).thenReturn(expFuture);
441 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
444 assertTrue("Patch operation should be successful on mounted device", status.isOk());
448 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
449 * Patch operation should fail with global error.
452 @SuppressWarnings("unchecked")
453 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
454 final PatchContext patchContext = mock(PatchContext.class);
455 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
456 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
457 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
458 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
459 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
461 when(patchContext.getData()).thenReturn(Lists.newArrayList());
462 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
463 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
465 // missing broker on mounted device
466 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
468 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
469 when(transaction.submit()).thenReturn(expFuture);
471 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
473 // assert not successful operation with error
474 assertNotNull(status.getGlobalErrors());
475 assertEquals(1, status.getGlobalErrors().size());
476 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
477 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
479 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());