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.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.DOMDataReadOnlyTransaction;
44 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
45 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
46 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
47 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
48 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
49 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
53 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
54 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
55 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
56 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
57 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
58 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
59 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
60 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
61 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
62 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
63 import org.opendaylight.restconf.common.errors.RestconfError;
64 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
65 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
66 import org.opendaylight.restconf.common.patch.PatchContext;
67 import org.opendaylight.restconf.common.patch.PatchStatusContext;
68 import org.opendaylight.restconf.common.util.DataChangeScope;
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 BrokerFacade brokerFacade;
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 brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
121 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
122 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
123 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
124 HashMap extensions = new HashMap();
125 extensions.put(DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class));
126 when(this.domDataBroker.getSupportedExtensions()).thenReturn(extensions);
129 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
130 final NormalizedNode<?, ?> dummyNode) {
131 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>>of(dummyNode));
134 private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
135 return Futures.immediateCheckedFuture(exists);
139 * Value of this node shouldn't be important for testing purposes.
141 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
142 final String localName) {
143 return Builders.containerBuilder()
144 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
148 public void testReadConfigurationData() {
149 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
150 this.dummyNodeInFuture);
152 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
154 assertSame("readConfigurationData", this.dummyNode, actualNode);
158 public void testReadOperationalData() {
159 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
160 this.dummyNodeInFuture);
162 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
164 assertSame("readOperationalData", this.dummyNode, actualNode);
168 public void test503() throws Exception {
169 final RpcError error = RpcResultBuilder.newError(
170 RpcError.ErrorType.TRANSPORT,
171 ErrorTag.RESOURCE_DENIED.getTagValue(),
172 "Master is down. Please try again.");
173 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
174 doReturn(Futures.immediateFailedCheckedFuture(exception503))
175 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
177 brokerFacade.readConfigurationData(this.instanceID, "explicit");
178 fail("This test should fail.");
179 } catch (final RestconfDocumentedException e) {
180 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
181 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
182 assertEquals("getErrorMessage", "Master is down. Please try again.",
183 e.getErrors().get(0).getErrorMessage());
188 public void testInvokeRpc() throws Exception {
189 final DOMRpcResult expResult = mock(DOMRpcResult.class);
190 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
191 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
193 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
194 .invokeRpc(this.type, this.dummyNode);
195 assertNotNull("Future is null", actualFuture);
196 final DOMRpcResult actualResult = actualFuture.get();
197 assertSame("invokeRpc", expResult, actualResult);
201 public void testCommitConfigurationDataPut() throws Exception {
202 @SuppressWarnings("unchecked")
203 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
204 when(this.rwTransaction.submit()).thenReturn(expFuture);
206 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
207 when(optionalMock.get()).thenReturn(null);
209 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
210 .immediateCheckedFuture(optionalMock);
211 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
213 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
214 this.instanceID, this.dummyNode, null, null);
216 final Future<Void> actualFuture = result.getFutureOfPutData();
218 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
220 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
221 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
222 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
223 inOrder.verify(this.rwTransaction).submit();
227 public void testCommitConfigurationDataPost() {
228 @SuppressWarnings("unchecked")
229 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
231 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
232 .thenReturn(wrapExistence(false));
234 when(this.rwTransaction.submit()).thenReturn(expFuture);
236 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
237 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
239 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
241 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
242 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
243 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
244 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
245 inOrder.verify(this.rwTransaction).submit();
248 @Test(expected = RestconfDocumentedException.class)
249 public void testCommitConfigurationDataPostAlreadyExists() {
250 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
251 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
252 .thenReturn(successFuture);
254 // Schema context is only necessary for ensuring parent structure
255 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
257 } catch (final RestconfDocumentedException e) {
258 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
264 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
267 public void testCommitConfigurationDataDelete() throws Exception {
268 // assume that data to delete exists
269 prepareDataForDelete(true);
272 @SuppressWarnings("unchecked")
273 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
274 when(this.rwTransaction.submit()).thenReturn(expFuture);
277 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
278 .commitConfigurationDataDelete(this.instanceID);
280 // verify result and interactions
281 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
283 // check exists, delete, submit
284 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
285 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
286 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
287 inOrder.verify(this.rwTransaction).submit();
291 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
294 public void testCommitConfigurationDataDeleteNoData() throws Exception {
295 // assume that data to delete does not exist
296 prepareDataForDelete(false);
298 // try to delete and expect 404 error
300 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
301 fail("Delete operation should fail due to missing data");
302 } catch (final RestconfDocumentedException e) {
303 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
304 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
305 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
310 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
311 * {@code assumeDataExists} parameter.
312 * @param assumeDataExists boolean to assume if data exists
314 private void prepareDataForDelete(final boolean assumeDataExists) {
315 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
316 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
320 public void testRegisterToListenDataChanges() {
321 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
322 NotificationOutputType.XML, controllerContext);
324 @SuppressWarnings("unchecked")
325 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
327 DOMDataTreeChangeService changeService = (DOMDataTreeChangeService)
328 this.domDataBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
329 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
330 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
332 this.brokerFacade.registerToListenDataChanges(
333 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
335 verify(changeService).registerDataTreeChangeListener(loc, listener);
337 assertEquals("isListening", true, listener.isListening());
339 this.brokerFacade.registerToListenDataChanges(
340 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
341 verifyNoMoreInteractions(changeService);
345 * Create, register, close and remove notification listener.
348 public void testRegisterToListenNotificationChanges() throws Exception {
349 // create test notification listener
350 final String identifier = "create-notification-stream/toaster:toastDone";
351 final SchemaPath path = SchemaPath.create(true,
352 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
353 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
354 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
357 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
358 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
359 .thenReturn(registration);
361 // test to register listener for the first time
362 this.brokerFacade.registerToListenNotification(listener);
363 assertEquals("Registration was not successful", true, listener.isListening());
365 // try to register for the second time
366 this.brokerFacade.registerToListenNotification(listener);
367 assertEquals("Registration was not successful", true, listener.isListening());
369 // registrations should be invoked only once
370 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
372 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
373 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
374 final CheckedFuture<Void, TransactionCommitFailedException> checked = Futures.immediateCheckedFuture(null);
375 when(wTx.submit()).thenReturn(checked);
376 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
377 // close and remove test notification listener
379 Notificator.removeListenerIfNoSubscriberExists(listener);
383 * Test Patch method on the server with no data.
386 @SuppressWarnings("unchecked")
387 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
388 final PatchContext patchContext = mock(PatchContext.class);
389 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
390 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
392 when(patchContext.getData()).thenReturn(Lists.newArrayList());
393 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
396 when(identifierContext.getMountPoint()).thenReturn(null);
398 when(this.rwTransaction.submit()).thenReturn(expFuture);
400 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
403 assertTrue("Patch operation should be successful on server", status.isOk());
407 * Test Patch method on mounted device with no data.
410 @SuppressWarnings("unchecked")
411 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
412 final PatchContext patchContext = mock(PatchContext.class);
413 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
414 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
415 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
416 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
417 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
419 when(patchContext.getData()).thenReturn(Lists.newArrayList());
420 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
422 // return mount point with broker
423 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
424 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
425 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
426 when(transaction.submit()).thenReturn(expFuture);
428 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
431 assertTrue("Patch operation should be successful on mounted device", status.isOk());
435 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
436 * Patch operation should fail with global error.
439 @SuppressWarnings("unchecked")
440 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
441 final PatchContext patchContext = mock(PatchContext.class);
442 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
443 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
444 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
445 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
446 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
448 when(patchContext.getData()).thenReturn(Lists.newArrayList());
449 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
450 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
452 // missing broker on mounted device
453 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
455 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
456 when(transaction.submit()).thenReturn(expFuture);
458 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
460 // assert not successful operation with error
461 assertNotNull(status.getGlobalErrors());
462 assertEquals(1, status.getGlobalErrors().size());
463 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
464 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
466 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());