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 final BrokerFacade brokerFacade = BrokerFacade.getInstance();
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 this.brokerFacade.setDomDataBroker(this.domDataBroker);
120 this.brokerFacade.setDomNotificationService(this.domNotification);
121 this.brokerFacade.setRpcService(this.mockRpcService);
122 this.brokerFacade.setControllerContext(controllerContext);
124 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
125 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
126 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
127 HashMap extensions = new HashMap();
128 extensions.put(DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class));
129 when(this.domDataBroker.getSupportedExtensions()).thenReturn(extensions);
132 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
133 final NormalizedNode<?, ?> dummyNode) {
134 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
137 private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
138 return Futures.immediateCheckedFuture(exists);
142 * Value of this node shouldn't be important for testing purposes.
144 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
145 final String localName) {
146 return Builders.containerBuilder()
147 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
151 public void testReadConfigurationData() {
152 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
153 this.dummyNodeInFuture);
155 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
157 assertSame("readConfigurationData", this.dummyNode, actualNode);
161 public void testReadOperationalData() {
162 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
163 this.dummyNodeInFuture);
165 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
167 assertSame("readOperationalData", this.dummyNode, actualNode);
170 @Test(expected = RestconfDocumentedException.class)
171 public void testReadOperationalDataWithNoDataBroker() {
172 this.brokerFacade.setDomDataBroker(null);
174 this.brokerFacade.readOperationalData(this.instanceID);
178 public void test503() throws Exception {
179 final RpcError error = RpcResultBuilder.newError(
180 RpcError.ErrorType.TRANSPORT,
181 ErrorTag.RESOURCE_DENIED.getTagValue(),
182 "Master is down. Please try again.");
183 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
184 doReturn(Futures.immediateFailedCheckedFuture(exception503))
185 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
187 brokerFacade.readConfigurationData(this.instanceID, "explicit");
188 fail("This test should fail.");
189 } catch (final RestconfDocumentedException e) {
190 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
191 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
192 assertEquals("getErrorMessage", "Master is down. Please try again.",
193 e.getErrors().get(0).getErrorMessage());
198 public void testInvokeRpc() throws Exception {
199 final DOMRpcResult expResult = mock(DOMRpcResult.class);
200 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
201 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
203 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
204 .invokeRpc(this.type, this.dummyNode);
205 assertNotNull("Future is null", actualFuture);
206 final DOMRpcResult actualResult = actualFuture.get();
207 assertSame("invokeRpc", expResult, actualResult);
210 @Test(expected = RestconfDocumentedException.class)
211 public void testInvokeRpcWithNoConsumerSession() {
212 brokerFacade.setDomDataBroker(null);
213 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
217 public void testCommitConfigurationDataPut() throws Exception {
218 @SuppressWarnings("unchecked")
219 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
220 when(this.rwTransaction.submit()).thenReturn(expFuture);
222 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
223 when(optionalMock.get()).thenReturn(null);
225 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
226 .immediateCheckedFuture(optionalMock);
227 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
229 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
230 this.instanceID, this.dummyNode, null, null);
232 final Future<Void> actualFuture = result.getFutureOfPutData();
234 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
236 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
237 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
238 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
239 inOrder.verify(this.rwTransaction).submit();
243 public void testCommitConfigurationDataPost() {
244 @SuppressWarnings("unchecked")
245 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
247 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
248 .thenReturn(wrapExistence(false));
250 when(this.rwTransaction.submit()).thenReturn(expFuture);
252 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
253 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
255 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
257 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
258 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
259 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
260 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
261 inOrder.verify(this.rwTransaction).submit();
264 @Test(expected = RestconfDocumentedException.class)
265 public void testCommitConfigurationDataPostAlreadyExists() {
266 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
267 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
268 .thenReturn(successFuture);
270 // Schema context is only necessary for ensuring parent structure
271 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
273 } catch (final RestconfDocumentedException e) {
274 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
280 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
283 public void testCommitConfigurationDataDelete() throws Exception {
284 // assume that data to delete exists
285 prepareDataForDelete(true);
288 @SuppressWarnings("unchecked")
289 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
290 when(this.rwTransaction.submit()).thenReturn(expFuture);
293 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
294 .commitConfigurationDataDelete(this.instanceID);
296 // verify result and interactions
297 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
299 // check exists, delete, submit
300 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
301 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
302 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
303 inOrder.verify(this.rwTransaction).submit();
307 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
310 public void testCommitConfigurationDataDeleteNoData() throws Exception {
311 // assume that data to delete does not exist
312 prepareDataForDelete(false);
314 // try to delete and expect 404 error
316 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
317 fail("Delete operation should fail due to missing data");
318 } catch (final RestconfDocumentedException e) {
319 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
320 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
321 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
326 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
327 * {@code assumeDataExists} parameter.
328 * @param assumeDataExists boolean to assume if data exists
330 private void prepareDataForDelete(final boolean assumeDataExists) {
331 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
332 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
336 public void testRegisterToListenDataChanges() {
337 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
338 NotificationOutputType.XML, controllerContext);
340 @SuppressWarnings("unchecked")
341 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
343 DOMDataTreeChangeService changeService = (DOMDataTreeChangeService)
344 this.domDataBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
345 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
346 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
348 this.brokerFacade.registerToListenDataChanges(
349 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
351 verify(changeService).registerDataTreeChangeListener(loc, listener);
353 assertEquals("isListening", true, listener.isListening());
355 this.brokerFacade.registerToListenDataChanges(
356 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
357 verifyNoMoreInteractions(changeService);
361 * Create, register, close and remove notification listener.
364 public void testRegisterToListenNotificationChanges() throws Exception {
365 // create test notification listener
366 final String identifier = "create-notification-stream/toaster:toastDone";
367 final SchemaPath path = SchemaPath.create(true,
368 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
369 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
370 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
373 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
374 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
375 .thenReturn(registration);
377 // test to register listener for the first time
378 this.brokerFacade.registerToListenNotification(listener);
379 assertEquals("Registration was not successful", true, listener.isListening());
381 // try to register for the second time
382 this.brokerFacade.registerToListenNotification(listener);
383 assertEquals("Registration was not successful", true, listener.isListening());
385 // registrations should be invoked only once
386 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
388 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
389 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
390 final CheckedFuture<Void, TransactionCommitFailedException> checked = Futures.immediateCheckedFuture(null);
391 when(wTx.submit()).thenReturn(checked);
392 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
393 // close and remove test notification listener
395 Notificator.removeListenerIfNoSubscriberExists(listener);
399 * Test Patch method on the server with no data.
402 @SuppressWarnings("unchecked")
403 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
404 final PatchContext patchContext = mock(PatchContext.class);
405 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
406 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
408 when(patchContext.getData()).thenReturn(Lists.newArrayList());
409 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
412 when(identifierContext.getMountPoint()).thenReturn(null);
414 when(this.rwTransaction.submit()).thenReturn(expFuture);
416 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
419 assertTrue("Patch operation should be successful on server", status.isOk());
423 * Test Patch method on mounted device with no data.
426 @SuppressWarnings("unchecked")
427 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
428 final PatchContext patchContext = mock(PatchContext.class);
429 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
430 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
431 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
432 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
433 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
435 when(patchContext.getData()).thenReturn(Lists.newArrayList());
436 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
438 // return mount point with broker
439 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
440 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
441 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
442 when(transaction.submit()).thenReturn(expFuture);
444 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
447 assertTrue("Patch operation should be successful on mounted device", status.isOk());
451 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
452 * Patch operation should fail with global error.
455 @SuppressWarnings("unchecked")
456 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
457 final PatchContext patchContext = mock(PatchContext.class);
458 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
459 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
460 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
461 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
462 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
464 when(patchContext.getData()).thenReturn(Lists.newArrayList());
465 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
466 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
468 // missing broker on mounted device
469 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
471 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
472 when(transaction.submit()).thenReturn(expFuture);
474 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
476 // assert not successful operation with error
477 assertNotNull(status.getGlobalErrors());
478 assertEquals(1, status.getGlobalErrors().size());
479 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
480 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
482 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());