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;
32 import java.util.HashMap;
33 import java.util.concurrent.Future;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.mockito.InOrder;
37 import org.mockito.Mock;
38 import org.mockito.Mockito;
39 import org.mockito.MockitoAnnotations;
40 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
43 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
44 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
45 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
46 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
47 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
48 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
49 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
50 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
51 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
55 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
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();
112 public void setUp() throws Exception {
113 MockitoAnnotations.initMocks(this);
114 this.brokerFacade.setDomDataBroker(this.domDataBroker);
115 this.brokerFacade.setDomNotificationService(this.domNotification);
116 this.brokerFacade.setRpcService(this.mockRpcService);
117 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
118 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
119 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
120 HashMap extensions = new HashMap();
121 extensions.put(DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class));
122 when(this.domDataBroker.getSupportedExtensions()).thenReturn(extensions);
124 ControllerContext.getInstance()
125 .setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
128 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
129 final NormalizedNode<?, ?> dummyNode) {
130 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
133 private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
134 return Futures.immediateCheckedFuture(exists);
138 * Value of this node shouldn't be important for testing purposes.
140 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
141 final String localName) {
142 return Builders.containerBuilder()
143 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
147 public void testReadConfigurationData() {
148 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
149 this.dummyNodeInFuture);
151 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
153 assertSame("readConfigurationData", this.dummyNode, actualNode);
157 public void testReadOperationalData() {
158 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
159 this.dummyNodeInFuture);
161 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
163 assertSame("readOperationalData", this.dummyNode, actualNode);
166 @Test(expected = RestconfDocumentedException.class)
167 public void testReadOperationalDataWithNoDataBroker() {
168 this.brokerFacade.setDomDataBroker(null);
170 this.brokerFacade.readOperationalData(this.instanceID);
174 public void test503() throws Exception {
175 final RpcError error = RpcResultBuilder.newError(
176 RpcError.ErrorType.TRANSPORT,
177 ErrorTag.RESOURCE_DENIED.getTagValue(),
178 "Master is down. Please try again.");
179 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
180 doReturn(Futures.immediateFailedCheckedFuture(exception503))
181 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
183 brokerFacade.readConfigurationData(this.instanceID, "explicit");
184 fail("This test should fail.");
185 } catch (final RestconfDocumentedException e) {
186 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
187 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
188 assertEquals("getErrorMessage", "Master is down. Please try again.",
189 e.getErrors().get(0).getErrorMessage());
194 public void testInvokeRpc() throws Exception {
195 final DOMRpcResult expResult = mock(DOMRpcResult.class);
196 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
197 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
199 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
200 .invokeRpc(this.type, this.dummyNode);
201 assertNotNull("Future is null", actualFuture);
202 final DOMRpcResult actualResult = actualFuture.get();
203 assertSame("invokeRpc", expResult, actualResult);
206 @Test(expected = RestconfDocumentedException.class)
207 public void testInvokeRpcWithNoConsumerSession() {
208 brokerFacade.setDomDataBroker(null);
209 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
213 public void testCommitConfigurationDataPut() throws Exception {
214 @SuppressWarnings("unchecked")
215 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
216 when(this.rwTransaction.submit()).thenReturn(expFuture);
218 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
219 when(optionalMock.get()).thenReturn(null);
221 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
222 .immediateCheckedFuture(optionalMock);
223 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
225 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
226 this.instanceID, this.dummyNode, null, null);
228 final Future<Void> actualFuture = result.getFutureOfPutData();
230 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
232 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
233 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
234 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
235 inOrder.verify(this.rwTransaction).submit();
239 public void testCommitConfigurationDataPost() {
240 @SuppressWarnings("unchecked")
241 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
243 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
244 .thenReturn(wrapExistence(false));
246 when(this.rwTransaction.submit()).thenReturn(expFuture);
248 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
249 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
251 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
253 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
254 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
255 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
256 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
257 inOrder.verify(this.rwTransaction).submit();
260 @Test(expected = RestconfDocumentedException.class)
261 public void testCommitConfigurationDataPostAlreadyExists() {
262 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
263 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
264 .thenReturn(successFuture);
266 // Schema context is only necessary for ensuring parent structure
267 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
269 } catch (final RestconfDocumentedException e) {
270 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
276 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
279 public void testCommitConfigurationDataDelete() throws Exception {
280 // assume that data to delete exists
281 prepareDataForDelete(true);
284 @SuppressWarnings("unchecked")
285 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
286 when(this.rwTransaction.submit()).thenReturn(expFuture);
289 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
290 .commitConfigurationDataDelete(this.instanceID);
292 // verify result and interactions
293 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
295 // check exists, delete, submit
296 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
297 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
298 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
299 inOrder.verify(this.rwTransaction).submit();
303 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
306 public void testCommitConfigurationDataDeleteNoData() throws Exception {
307 // assume that data to delete does not exist
308 prepareDataForDelete(false);
310 // try to delete and expect 404 error
312 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
313 fail("Delete operation should fail due to missing data");
314 } catch (final RestconfDocumentedException e) {
315 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
316 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
317 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
322 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
323 * {@code assumeDataExists} parameter.
324 * @param assumeDataExists boolean to assume if data exists
326 private void prepareDataForDelete(final boolean assumeDataExists) {
327 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
328 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
332 public void testRegisterToListenDataChanges() {
333 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
334 NotificationOutputType.XML);
336 @SuppressWarnings("unchecked")
337 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
339 DOMDataTreeChangeService changeService = (DOMDataTreeChangeService)
340 this.domDataBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
341 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
342 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
344 this.brokerFacade.registerToListenDataChanges(
345 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
347 verify(changeService).registerDataTreeChangeListener(loc, listener);
349 assertEquals("isListening", true, listener.isListening());
351 this.brokerFacade.registerToListenDataChanges(
352 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
353 verifyNoMoreInteractions(changeService);
357 * Create, register, close and remove notification listener.
360 public void testRegisterToListenNotificationChanges() throws Exception {
361 // create test notification listener
362 final String identifier = "create-notification-stream/toaster:toastDone";
363 final SchemaPath path = SchemaPath.create(true,
364 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
365 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
366 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
369 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
370 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
371 .thenReturn(registration);
373 // test to register listener for the first time
374 this.brokerFacade.registerToListenNotification(listener);
375 assertEquals("Registration was not successful", true, listener.isListening());
377 // try to register for the second time
378 this.brokerFacade.registerToListenNotification(listener);
379 assertEquals("Registration was not successful", true, listener.isListening());
381 // registrations should be invoked only once
382 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
384 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
385 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
386 final CheckedFuture<Void, TransactionCommitFailedException> checked = Futures.immediateCheckedFuture(null);
387 when(wTx.submit()).thenReturn(checked);
388 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
389 // close and remove test notification listener
391 Notificator.removeListenerIfNoSubscriberExists(listener);
395 * Test Patch method on the server with no data.
398 @SuppressWarnings("unchecked")
399 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
400 final PatchContext patchContext = mock(PatchContext.class);
401 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
402 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
404 when(patchContext.getData()).thenReturn(Lists.newArrayList());
405 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
408 when(identifierContext.getMountPoint()).thenReturn(null);
410 when(this.rwTransaction.submit()).thenReturn(expFuture);
412 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
415 assertTrue("Patch operation should be successful on server", status.isOk());
419 * Test Patch method on mounted device with no data.
422 @SuppressWarnings("unchecked")
423 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
424 final PatchContext patchContext = mock(PatchContext.class);
425 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
426 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
427 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
428 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
429 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
431 when(patchContext.getData()).thenReturn(Lists.newArrayList());
432 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
434 // return mount point with broker
435 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
436 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
437 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
438 when(transaction.submit()).thenReturn(expFuture);
440 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
443 assertTrue("Patch operation should be successful on mounted device", status.isOk());
447 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
448 * Patch operation should fail with global error.
451 @SuppressWarnings("unchecked")
452 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
453 final PatchContext patchContext = mock(PatchContext.class);
454 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
455 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
456 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
457 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
458 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
460 when(patchContext.getData()).thenReturn(Lists.newArrayList());
461 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
462 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
464 // missing broker on mounted device
465 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
467 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
468 when(transaction.submit()).thenReturn(expFuture);
470 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
472 // assert not successful operation with error
473 assertNotNull(status.getGlobalErrors());
474 assertEquals(1, status.getGlobalErrors().size());
475 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
476 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
478 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());