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.Mockito;
37 import org.mockito.MockitoAnnotations;
38 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
39 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
40 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
41 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
42 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
43 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
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.DOMDataWriteTransaction;
47 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
48 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
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.PutResult;
56 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
57 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
58 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
59 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
60 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
61 import org.opendaylight.restconf.common.errors.RestconfError;
62 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
63 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
64 import org.opendaylight.restconf.common.patch.PatchContext;
65 import org.opendaylight.restconf.common.patch.PatchStatusContext;
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.common.RpcError;
72 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
74 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
75 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
76 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
81 * Unit tests for BrokerFacade.
83 * @author Thomas Pantelis
85 public class BrokerFacadeTest {
88 private DOMDataBroker domDataBroker;
90 private DOMNotificationService domNotification;
92 private DOMRpcService mockRpcService;
94 private DOMMountPoint mockMountInstance;
96 private DOMDataReadOnlyTransaction readTransaction;
98 private DOMDataWriteTransaction writeTransaction;
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 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
117 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
118 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
120 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
123 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
124 final NormalizedNode<?, ?> dummyNode) {
125 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
128 private static 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 static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
136 final String localName) {
137 return Builders.containerBuilder()
138 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
142 public void testReadConfigurationData() {
143 when(this.readTransaction.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.readTransaction.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 test503() throws Exception {
170 final RpcError error = RpcResultBuilder.newError(
171 RpcError.ErrorType.TRANSPORT,
172 ErrorTag.RESOURCE_DENIED.getTagValue(),
173 "Master is down. Please try again.");
174 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
175 doReturn(Futures.immediateFailedCheckedFuture(exception503))
176 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
178 brokerFacade.readConfigurationData(this.instanceID, "explicit");
179 fail("This test should fail.");
180 } catch (final RestconfDocumentedException e) {
181 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
182 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
183 assertEquals("getErrorMessage", "Master is down. Please try again.",
184 e.getErrors().get(0).getErrorMessage());
189 public void testInvokeRpc() throws Exception {
190 final DOMRpcResult expResult = mock(DOMRpcResult.class);
191 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
192 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
194 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
195 .invokeRpc(this.type, this.dummyNode);
196 assertNotNull("Future is null", actualFuture);
197 final DOMRpcResult actualResult = actualFuture.get();
198 assertSame("invokeRpc", expResult, actualResult);
201 @Test(expected = RestconfDocumentedException.class)
202 public void testInvokeRpcWithNoConsumerSession() {
203 brokerFacade.setDomDataBroker(null);
204 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
208 public void testCommitConfigurationDataPut() throws Exception {
209 @SuppressWarnings("unchecked")
210 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
211 when(this.rwTransaction.submit()).thenReturn(expFuture);
213 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
214 when(optionalMock.get()).thenReturn(null);
216 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
217 .immediateCheckedFuture(optionalMock);
218 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
220 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
221 this.instanceID, this.dummyNode, null, null);
223 final Future<Void> actualFuture = result.getFutureOfPutData();
225 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
227 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
228 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
229 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
230 inOrder.verify(this.rwTransaction).submit();
234 public void testCommitConfigurationDataPost() {
235 @SuppressWarnings("unchecked")
236 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
238 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
239 .thenReturn(wrapExistence(false));
241 when(this.rwTransaction.submit()).thenReturn(expFuture);
243 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
244 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
246 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
248 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
249 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
250 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
251 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
252 inOrder.verify(this.rwTransaction).submit();
255 @Test(expected = RestconfDocumentedException.class)
256 public void testCommitConfigurationDataPostAlreadyExists() {
257 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
258 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
259 .thenReturn(successFuture);
261 // Schema context is only necessary for ensuring parent structure
262 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
264 } catch (final RestconfDocumentedException e) {
265 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
271 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
274 public void testCommitConfigurationDataDelete() throws Exception {
275 // assume that data to delete exists
276 prepareDataForDelete(true);
279 @SuppressWarnings("unchecked")
280 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
281 when(this.rwTransaction.submit()).thenReturn(expFuture);
284 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
285 .commitConfigurationDataDelete(this.instanceID);
287 // verify result and interactions
288 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
290 // check exists, delete, submit
291 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
292 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
293 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
294 inOrder.verify(this.rwTransaction).submit();
298 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
301 public void testCommitConfigurationDataDeleteNoData() throws Exception {
302 // assume that data to delete does not exist
303 prepareDataForDelete(false);
305 // try to delete and expect 404 error
307 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
308 fail("Delete operation should fail due to missing data");
309 } catch (final RestconfDocumentedException e) {
310 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
311 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
312 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
317 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
318 * {@code assumeDataExists} parameter.
319 * @param assumeDataExists boolean to assume if data exists
321 private void prepareDataForDelete(final boolean assumeDataExists) {
322 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
323 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
327 public void testRegisterToListenDataChanges() {
328 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
329 NotificationOutputType.XML);
331 @SuppressWarnings("unchecked")
332 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
334 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
335 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
337 this.brokerFacade.registerToListenDataChanges(
338 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
340 verify(this.domDataBroker).registerDataChangeListener(
341 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
343 assertEquals("isListening", true, listener.isListening());
345 this.brokerFacade.registerToListenDataChanges(
346 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
347 verifyNoMoreInteractions(this.domDataBroker);
351 * Create, register, close and remove notification listener.
354 public void testRegisterToListenNotificationChanges() throws Exception {
355 // create test notification listener
356 final String identifier = "create-notification-stream/toaster:toastDone";
357 final SchemaPath path = SchemaPath.create(true,
358 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
359 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
360 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
363 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
364 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
365 .thenReturn(registration);
367 // test to register listener for the first time
368 this.brokerFacade.registerToListenNotification(listener);
369 assertEquals("Registration was not successful", true, listener.isListening());
371 // try to register for the second time
372 this.brokerFacade.registerToListenNotification(listener);
373 assertEquals("Registration was not successful", true, listener.isListening());
375 // registrations should be invoked only once
376 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
378 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
379 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
380 final CheckedFuture<Void, TransactionCommitFailedException> checked = Futures.immediateCheckedFuture(null);
381 when(wTx.submit()).thenReturn(checked);
382 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
383 final TransactionChainHandler transactionChainHandler = new TransactionChainHandler(transactionChain);
384 final SchemaContextHandler schemaHandler = Mockito.mock(SchemaContextHandler.class);
385 final SchemaContext schCtx = TestUtils.loadSchemaContext("/modules");
386 when(schemaHandler.get()).thenReturn(schCtx);
387 listener.setCloseVars(transactionChainHandler, schemaHandler);
388 // close and remove test notification listener
390 Notificator.removeListenerIfNoSubscriberExists(listener);
394 * Test Patch method on the server with no data.
397 @SuppressWarnings("unchecked")
398 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
399 final PatchContext patchContext = mock(PatchContext.class);
400 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
401 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
403 when(patchContext.getData()).thenReturn(Lists.newArrayList());
404 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
407 when(identifierContext.getMountPoint()).thenReturn(null);
409 when(this.rwTransaction.submit()).thenReturn(expFuture);
411 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
414 assertTrue("Patch operation should be successful on server", status.isOk());
418 * Test Patch method on mounted device with no data.
421 @SuppressWarnings("unchecked")
422 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
423 final PatchContext patchContext = mock(PatchContext.class);
424 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
425 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
426 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
427 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
428 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
430 when(patchContext.getData()).thenReturn(Lists.newArrayList());
431 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
433 // return mount point with broker
434 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
435 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
436 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
437 when(transaction.submit()).thenReturn(expFuture);
439 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
442 assertTrue("Patch operation should be successful on mounted device", status.isOk());
446 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
447 * Patch operation should fail with global error.
450 @SuppressWarnings("unchecked")
451 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
452 final PatchContext patchContext = mock(PatchContext.class);
453 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
454 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
455 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
456 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
457 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
459 when(patchContext.getData()).thenReturn(Lists.newArrayList());
460 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
461 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
463 // missing broker on mounted device
464 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
466 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
467 when(transaction.submit()).thenReturn(expFuture);
469 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
471 // assert not successful operation with error
472 assertNotNull(status.getGlobalErrors());
473 assertEquals(1, status.getGlobalErrors().size());
474 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
475 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
477 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());