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.controller.sal.core.api.Broker.ConsumerSession;
54 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
55 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
56 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
57 import org.opendaylight.netconf.sal.restconf.impl.PatchContext;
58 import org.opendaylight.netconf.sal.restconf.impl.PatchStatusContext;
59 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
61 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
62 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
63 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
64 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.restconf.handlers.SchemaContextHandler;
68 import org.opendaylight.restconf.handlers.TransactionChainHandler;
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 ConsumerSession context;
95 private DOMRpcService mockRpcService;
97 private DOMMountPoint mockMountInstance;
99 private DOMDataReadOnlyTransaction readTransaction;
101 private DOMDataWriteTransaction writeTransaction;
103 private DOMDataReadWriteTransaction rwTransaction;
105 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
106 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
107 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
108 wrapDummyNode(this.dummyNode);
109 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
110 private final SchemaPath type = SchemaPath.create(true, this.qname);
111 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
114 public void setUp() throws Exception {
115 MockitoAnnotations.initMocks(this);
116 this.brokerFacade.setDomDataBroker(this.domDataBroker);
117 this.brokerFacade.setDomNotificationService(this.domNotification);
118 this.brokerFacade.setRpcService(this.mockRpcService);
119 this.brokerFacade.setContext(this.context);
120 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
121 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
122 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
124 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
127 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
128 final NormalizedNode<?, ?> dummyNode) {
129 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
132 private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
133 return Futures.immediateCheckedFuture(exists);
137 * Value of this node shouldn't be important for testing purposes.
139 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
140 final String localName) {
141 return Builders.containerBuilder()
142 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
146 public void testReadConfigurationData() {
147 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
148 this.dummyNodeInFuture);
150 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
152 assertSame("readConfigurationData", this.dummyNode, actualNode);
156 public void testReadOperationalData() {
157 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
158 this.dummyNodeInFuture);
160 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
162 assertSame("readOperationalData", this.dummyNode, actualNode);
165 @Test(expected = RestconfDocumentedException.class)
166 public void testReadOperationalDataWithNoDataBroker() {
167 this.brokerFacade.setDomDataBroker(null);
169 this.brokerFacade.readOperationalData(this.instanceID);
173 public void test503() throws Exception {
174 final RpcError error = RpcResultBuilder.newError(
175 RpcError.ErrorType.TRANSPORT,
176 ErrorTag.RESOURCE_DENIED.getTagValue(),
177 "Master is down. Please try again.");
178 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
179 doReturn(Futures.immediateFailedCheckedFuture(exception503))
180 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
182 brokerFacade.readConfigurationData(this.instanceID, "explicit");
183 fail("This test should fail.");
184 } catch (final RestconfDocumentedException e) {
185 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
186 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
187 assertEquals("getErrorMessage", "Master is down. Please try again.",
188 e.getErrors().get(0).getErrorMessage());
193 public void testInvokeRpc() throws Exception {
194 final DOMRpcResult expResult = mock(DOMRpcResult.class);
195 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
196 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
198 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
199 .invokeRpc(this.type, this.dummyNode);
200 assertNotNull("Future is null", actualFuture);
201 final DOMRpcResult actualResult = actualFuture.get();
202 assertSame("invokeRpc", expResult, actualResult);
205 @Test(expected = RestconfDocumentedException.class)
206 public void testInvokeRpcWithNoConsumerSession() {
207 this.brokerFacade.setContext(null);
208 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
212 public void testCommitConfigurationDataPut() throws Exception {
213 @SuppressWarnings("unchecked")
214 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
215 when(this.rwTransaction.submit()).thenReturn(expFuture);
217 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
218 when(optionalMock.get()).thenReturn(null);
220 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
221 .immediateCheckedFuture(optionalMock);
222 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
224 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
225 this.instanceID, this.dummyNode, null, null);
227 final Future<Void> actualFuture = result.getFutureOfPutData();
229 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
231 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
232 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
233 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
234 inOrder.verify(this.rwTransaction).submit();
238 public void testCommitConfigurationDataPost() {
239 @SuppressWarnings("unchecked")
240 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
242 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
243 .thenReturn(wrapExistence(false));
245 when(this.rwTransaction.submit()).thenReturn(expFuture);
247 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
248 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
250 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
252 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
253 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
254 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
255 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
256 inOrder.verify(this.rwTransaction).submit();
259 @Test(expected = RestconfDocumentedException.class)
260 public void testCommitConfigurationDataPostAlreadyExists() {
261 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
262 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
263 .thenReturn(successFuture);
265 // Schema context is only necessary for ensuring parent structure
266 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
268 } catch (final RestconfDocumentedException e) {
269 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
275 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
278 public void testCommitConfigurationDataDelete() throws Exception {
279 // assume that data to delete exists
280 prepareDataForDelete(true);
283 @SuppressWarnings("unchecked")
284 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
285 when(this.rwTransaction.submit()).thenReturn(expFuture);
288 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
289 .commitConfigurationDataDelete(this.instanceID);
291 // verify result and interactions
292 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
294 // check exists, delete, submit
295 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
296 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
297 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
298 inOrder.verify(this.rwTransaction).submit();
302 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
305 public void testCommitConfigurationDataDeleteNoData() throws Exception {
306 // assume that data to delete does not exist
307 prepareDataForDelete(false);
309 // try to delete and expect 404 error
311 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
312 fail("Delete operation should fail due to missing data");
313 } catch (final RestconfDocumentedException e) {
314 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
315 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
316 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
321 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
322 * {@code assumeDataExists} parameter.
323 * @param assumeDataExists boolean to assume if data exists
325 private void prepareDataForDelete(final boolean assumeDataExists) {
326 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
327 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
331 public void testRegisterToListenDataChanges() {
332 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
333 NotificationOutputType.XML);
335 @SuppressWarnings("unchecked")
336 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
338 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
339 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
341 this.brokerFacade.registerToListenDataChanges(
342 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
344 verify(this.domDataBroker).registerDataChangeListener(
345 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
347 assertEquals("isListening", true, listener.isListening());
349 this.brokerFacade.registerToListenDataChanges(
350 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
351 verifyNoMoreInteractions(this.domDataBroker);
355 * Create, register, close and remove notification listener.
358 public void testRegisterToListenNotificationChanges() throws Exception {
359 // create test notification listener
360 final String identifier = "create-notification-stream/toaster:toastDone";
361 final SchemaPath path = SchemaPath.create(true,
362 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
363 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
364 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
367 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
368 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
369 .thenReturn(registration);
371 // test to register listener for the first time
372 this.brokerFacade.registerToListenNotification(listener);
373 assertEquals("Registration was not successful", true, listener.isListening());
375 // try to register for the second time
376 this.brokerFacade.registerToListenNotification(listener);
377 assertEquals("Registration was not successful", true, listener.isListening());
379 // registrations should be invoked only once
380 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
382 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
383 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
384 final CheckedFuture<Void, TransactionCommitFailedException> checked = Futures.immediateCheckedFuture(null);
385 when(wTx.submit()).thenReturn(checked);
386 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
387 final TransactionChainHandler transactionChainHandler = new TransactionChainHandler(transactionChain);
388 final SchemaContextHandler schemaHandler = Mockito.mock(SchemaContextHandler.class);
389 final SchemaContext schCtx = TestUtils.loadSchemaContext("/modules");
390 when(schemaHandler.get()).thenReturn(schCtx);
391 listener.setCloseVars(transactionChainHandler, schemaHandler);
392 // close and remove test notification listener
394 Notificator.removeListenerIfNoSubscriberExists(listener);
398 * Test Patch method on the server with no data.
401 @SuppressWarnings("unchecked")
402 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
403 final PatchContext patchContext = mock(PatchContext.class);
404 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
405 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
407 when(patchContext.getData()).thenReturn(Lists.newArrayList());
408 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
411 when(identifierContext.getMountPoint()).thenReturn(null);
413 when(this.rwTransaction.submit()).thenReturn(expFuture);
415 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
418 assertTrue("Patch operation should be successful on server", status.isOk());
422 * Test Patch method on mounted device with no data.
425 @SuppressWarnings("unchecked")
426 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
427 final PatchContext patchContext = mock(PatchContext.class);
428 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
429 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
430 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
431 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
432 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
434 when(patchContext.getData()).thenReturn(Lists.newArrayList());
435 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
437 // return mount point with broker
438 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
439 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
440 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
441 when(transaction.submit()).thenReturn(expFuture);
443 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
446 assertTrue("Patch operation should be successful on mounted device", status.isOk());
450 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
451 * Patch operation should fail with global error.
454 @SuppressWarnings("unchecked")
455 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
456 final PatchContext patchContext = mock(PatchContext.class);
457 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
458 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
459 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
460 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
461 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
463 when(patchContext.getData()).thenReturn(Lists.newArrayList());
464 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
465 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
467 // missing broker on mounted device
468 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
470 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
471 when(transaction.submit()).thenReturn(expFuture);
473 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
475 // assert not successful operation with error
476 assertNotNull(status.getGlobalErrors());
477 assertEquals(1, status.getGlobalErrors().size());
478 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
479 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
481 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());