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.concurrent.Future;
32 import org.junit.Before;
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.md.sal.dom.api.DOMTransactionChain;
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.PutResult;
55 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
56 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
57 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
58 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
59 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
60 import org.opendaylight.restconf.common.errors.RestconfError;
61 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
62 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
63 import org.opendaylight.restconf.common.patch.PatchContext;
64 import org.opendaylight.restconf.common.patch.PatchStatusContext;
65 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
66 import org.opendaylight.yangtools.concepts.ListenerRegistration;
67 import org.opendaylight.yangtools.yang.common.QName;
68 import org.opendaylight.yangtools.yang.common.RpcError;
69 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
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 DOMRpcService mockRpcService;
91 private DOMMountPoint mockMountInstance;
93 private DOMDataReadOnlyTransaction readTransaction;
95 private DOMDataWriteTransaction writeTransaction;
97 private DOMDataReadWriteTransaction rwTransaction;
99 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
100 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
101 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
102 wrapDummyNode(this.dummyNode);
103 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
104 private final SchemaPath type = SchemaPath.create(true, this.qname);
105 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
108 public void setUp() throws Exception {
109 MockitoAnnotations.initMocks(this);
110 this.brokerFacade.setDomDataBroker(this.domDataBroker);
111 this.brokerFacade.setDomNotificationService(this.domNotification);
112 this.brokerFacade.setRpcService(this.mockRpcService);
113 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
114 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
115 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
117 ControllerContext.getInstance()
118 .setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
121 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
122 final NormalizedNode<?, ?> dummyNode) {
123 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
126 private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
127 return Futures.immediateCheckedFuture(exists);
131 * Value of this node shouldn't be important for testing purposes.
133 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
134 final String localName) {
135 return Builders.containerBuilder()
136 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
140 public void testReadConfigurationData() {
141 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
142 this.dummyNodeInFuture);
144 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
146 assertSame("readConfigurationData", this.dummyNode, actualNode);
150 public void testReadOperationalData() {
151 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
152 this.dummyNodeInFuture);
154 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
156 assertSame("readOperationalData", this.dummyNode, actualNode);
159 @Test(expected = RestconfDocumentedException.class)
160 public void testReadOperationalDataWithNoDataBroker() {
161 this.brokerFacade.setDomDataBroker(null);
163 this.brokerFacade.readOperationalData(this.instanceID);
167 public void test503() throws Exception {
168 final RpcError error = RpcResultBuilder.newError(
169 RpcError.ErrorType.TRANSPORT,
170 ErrorTag.RESOURCE_DENIED.getTagValue(),
171 "Master is down. Please try again.");
172 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
173 doReturn(Futures.immediateFailedCheckedFuture(exception503))
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 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
190 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
192 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
193 .invokeRpc(this.type, this.dummyNode);
194 assertNotNull("Future is null", actualFuture);
195 final DOMRpcResult actualResult = actualFuture.get();
196 assertSame("invokeRpc", expResult, actualResult);
199 @Test(expected = RestconfDocumentedException.class)
200 public void testInvokeRpcWithNoConsumerSession() {
201 brokerFacade.setDomDataBroker(null);
202 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
206 public void testCommitConfigurationDataPut() throws Exception {
207 @SuppressWarnings("unchecked")
208 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
209 when(this.rwTransaction.submit()).thenReturn(expFuture);
211 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
212 when(optionalMock.get()).thenReturn(null);
214 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
215 .immediateCheckedFuture(optionalMock);
216 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
218 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
219 this.instanceID, this.dummyNode, null, null);
221 final Future<Void> actualFuture = result.getFutureOfPutData();
223 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
225 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
226 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
227 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
228 inOrder.verify(this.rwTransaction).submit();
232 public void testCommitConfigurationDataPost() {
233 @SuppressWarnings("unchecked")
234 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
236 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
237 .thenReturn(wrapExistence(false));
239 when(this.rwTransaction.submit()).thenReturn(expFuture);
241 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
242 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
244 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
246 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
247 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
248 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
249 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
250 inOrder.verify(this.rwTransaction).submit();
253 @Test(expected = RestconfDocumentedException.class)
254 public void testCommitConfigurationDataPostAlreadyExists() {
255 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
256 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
257 .thenReturn(successFuture);
259 // Schema context is only necessary for ensuring parent structure
260 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
262 } catch (final RestconfDocumentedException e) {
263 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
269 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
272 public void testCommitConfigurationDataDelete() throws Exception {
273 // assume that data to delete exists
274 prepareDataForDelete(true);
277 @SuppressWarnings("unchecked")
278 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
279 when(this.rwTransaction.submit()).thenReturn(expFuture);
282 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
283 .commitConfigurationDataDelete(this.instanceID);
285 // verify result and interactions
286 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
288 // check exists, delete, submit
289 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
290 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
291 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
292 inOrder.verify(this.rwTransaction).submit();
296 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
299 public void testCommitConfigurationDataDeleteNoData() throws Exception {
300 // assume that data to delete does not exist
301 prepareDataForDelete(false);
303 // try to delete and expect 404 error
305 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
306 fail("Delete operation should fail due to missing data");
307 } catch (final RestconfDocumentedException e) {
308 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
309 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
310 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
315 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
316 * {@code assumeDataExists} parameter.
317 * @param assumeDataExists boolean to assume if data exists
319 private void prepareDataForDelete(final boolean assumeDataExists) {
320 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
321 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
325 public void testRegisterToListenDataChanges() {
326 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
327 NotificationOutputType.XML);
329 @SuppressWarnings("unchecked")
330 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
332 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
333 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
335 this.brokerFacade.registerToListenDataChanges(
336 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
338 verify(this.domDataBroker).registerDataChangeListener(
339 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
341 assertEquals("isListening", true, listener.isListening());
343 this.brokerFacade.registerToListenDataChanges(
344 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
345 verifyNoMoreInteractions(this.domDataBroker);
349 * Create, register, close and remove notification listener.
352 public void testRegisterToListenNotificationChanges() throws Exception {
353 // create test notification listener
354 final String identifier = "create-notification-stream/toaster:toastDone";
355 final SchemaPath path = SchemaPath.create(true,
356 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
357 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
358 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
361 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
362 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
363 .thenReturn(registration);
365 // test to register listener for the first time
366 this.brokerFacade.registerToListenNotification(listener);
367 assertEquals("Registration was not successful", true, listener.isListening());
369 // try to register for the second time
370 this.brokerFacade.registerToListenNotification(listener);
371 assertEquals("Registration was not successful", true, listener.isListening());
373 // registrations should be invoked only once
374 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
376 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
377 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
378 final CheckedFuture<Void, TransactionCommitFailedException> checked = Futures.immediateCheckedFuture(null);
379 when(wTx.submit()).thenReturn(checked);
380 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
381 // close and remove test notification listener
383 Notificator.removeListenerIfNoSubscriberExists(listener);
387 * Test Patch method on the server with no data.
390 @SuppressWarnings("unchecked")
391 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
392 final PatchContext patchContext = mock(PatchContext.class);
393 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
394 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
396 when(patchContext.getData()).thenReturn(Lists.newArrayList());
397 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
400 when(identifierContext.getMountPoint()).thenReturn(null);
402 when(this.rwTransaction.submit()).thenReturn(expFuture);
404 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
407 assertTrue("Patch operation should be successful on server", status.isOk());
411 * Test Patch method on mounted device with no data.
414 @SuppressWarnings("unchecked")
415 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
416 final PatchContext patchContext = mock(PatchContext.class);
417 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
418 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
419 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
420 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
421 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
423 when(patchContext.getData()).thenReturn(Lists.newArrayList());
424 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
426 // return mount point with broker
427 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
428 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
429 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
430 when(transaction.submit()).thenReturn(expFuture);
432 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
435 assertTrue("Patch operation should be successful on mounted device", status.isOk());
439 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
440 * Patch operation should fail with global error.
443 @SuppressWarnings("unchecked")
444 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
445 final PatchContext patchContext = mock(PatchContext.class);
446 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
447 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
448 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
449 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
450 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
452 when(patchContext.getData()).thenReturn(Lists.newArrayList());
453 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
454 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
456 // missing broker on mounted device
457 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
459 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
460 when(transaction.submit()).thenReturn(expFuture);
462 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
464 // assert not successful operation with error
465 assertNotNull(status.getGlobalErrors());
466 assertEquals(1, status.getGlobalErrors().size());
467 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
468 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
470 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());