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.inOrder;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.times;
22 import static org.mockito.Mockito.verify;
23 import static org.mockito.Mockito.verifyNoMoreInteractions;
24 import static org.mockito.Mockito.when;
25 import com.google.common.base.Optional;
26 import com.google.common.collect.Lists;
27 import com.google.common.util.concurrent.CheckedFuture;
28 import com.google.common.util.concurrent.Futures;
29 import java.util.concurrent.Future;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.mockito.InOrder;
33 import org.mockito.Mock;
34 import org.mockito.MockitoAnnotations;
35 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
39 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
40 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
41 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
42 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
43 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
44 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
45 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
47 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
49 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
50 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
51 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
52 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
53 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
54 import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
55 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
56 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
57 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
58 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
60 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
61 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
62 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
63 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
64 import org.opendaylight.yangtools.concepts.ListenerRegistration;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
74 * Unit tests for BrokerFacade.
76 * @author Thomas Pantelis
78 public class BrokerFacadeTest {
81 private DOMDataBroker domDataBroker;
83 private DOMNotificationService domNotification;
85 private ConsumerSession context;
87 private DOMRpcService mockRpcService;
89 private DOMMountPoint mockMountInstance;
91 private DOMDataReadOnlyTransaction rTransaction;
93 private DOMDataWriteTransaction wTransaction;
95 private DOMDataReadWriteTransaction rwTransaction;
97 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
98 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
99 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
100 wrapDummyNode(this.dummyNode);
101 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
102 private final SchemaPath type = SchemaPath.create(true, this.qname);
103 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
106 public void setUp() throws Exception {
107 MockitoAnnotations.initMocks(this);
108 this.brokerFacade.setDomDataBroker(this.domDataBroker);
109 this.brokerFacade.setDomNotificationService(this.domNotification);
110 this.brokerFacade.setRpcService(this.mockRpcService);
111 this.brokerFacade.setContext(this.context);
112 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
113 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
114 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
116 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
119 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
120 final NormalizedNode<?, ?> dummyNode) {
121 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
124 private CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
125 return Futures.immediateCheckedFuture(exists);
129 * Value of this node shouldn't be important for testing purposes
131 private NormalizedNode<?, ?> createDummyNode(final String namespace, final String date, final String localName) {
132 return Builders.containerBuilder()
133 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
137 public void testReadConfigurationData() {
138 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
139 this.dummyNodeInFuture);
141 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
143 assertSame("readConfigurationData", this.dummyNode, actualNode);
147 public void testReadOperationalData() {
148 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
149 this.dummyNodeInFuture);
151 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
153 assertSame("readOperationalData", this.dummyNode, actualNode);
156 @Test(expected = RestconfDocumentedException.class)
157 public void testReadOperationalDataWithNoDataBroker() {
158 this.brokerFacade.setDomDataBroker(null);
160 this.brokerFacade.readOperationalData(this.instanceID);
164 public void testInvokeRpc() throws Exception {
165 final DOMRpcResult expResult = mock(DOMRpcResult.class);
166 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
167 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
169 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
170 .invokeRpc(this.type, this.dummyNode);
171 assertNotNull("Future is null", actualFuture);
172 final DOMRpcResult actualResult = actualFuture.get();
173 assertSame("invokeRpc", expResult, actualResult);
176 @Test(expected = RestconfDocumentedException.class)
177 public void testInvokeRpcWithNoConsumerSession() {
178 this.brokerFacade.setContext(null);
179 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
183 public void testCommitConfigurationDataPut() throws Exception {
184 @SuppressWarnings("unchecked")
185 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
186 when(this.rwTransaction.submit()).thenReturn(expFuture);
188 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
189 when(optionalMock.get()).thenReturn(null);
191 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
192 .immediateCheckedFuture(optionalMock);
193 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
195 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
196 this.instanceID, this.dummyNode, null, null);
198 final Future<Void> actualFuture = result.getFutureOfPutData();
200 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
202 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
203 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
204 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
205 inOrder.verify(this.rwTransaction).submit();
209 public void testCommitConfigurationDataPost() {
210 @SuppressWarnings("unchecked")
211 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
213 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
214 .thenReturn(wrapExistence(false));
216 when(this.rwTransaction.submit()).thenReturn(expFuture);
218 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
219 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
221 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
223 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
224 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
225 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
226 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
227 inOrder.verify(this.rwTransaction).submit();
230 @Test(expected = RestconfDocumentedException.class)
231 public void testCommitConfigurationDataPostAlreadyExists() {
232 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
233 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
234 .thenReturn(successFuture);
236 // Schema context is only necessary for ensuring parent structure
237 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
239 } catch (final RestconfDocumentedException e) {
240 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
246 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
249 public void testCommitConfigurationDataDelete() throws Exception {
250 // assume that data to delete exists
251 prepareDataForDelete(true);
254 @SuppressWarnings("unchecked")
255 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
256 when(this.rwTransaction.submit()).thenReturn(expFuture);
259 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
260 .commitConfigurationDataDelete(this.instanceID);
262 // verify result and interactions
263 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
265 // check exists, delete, submit
266 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
267 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
268 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
269 inOrder.verify(this.rwTransaction).submit();
273 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
276 public void testCommitConfigurationDataDeleteNoData() throws Exception {
277 // assume that data to delete does not exist
278 prepareDataForDelete(false);
280 // try to delete and expect 404 error
282 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
283 fail("Delete operation should fail due to missing data");
284 } catch (final RestconfDocumentedException e) {
285 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
286 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
287 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
292 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
293 * {@code assumeDataExists} parameter.
294 * @param assumeDataExists
296 private void prepareDataForDelete(final boolean assumeDataExists) {
297 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
298 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
302 public void testRegisterToListenDataChanges() {
303 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
304 NotificationOutputType.XML);
306 @SuppressWarnings("unchecked")
307 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
309 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
310 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
312 this.brokerFacade.registerToListenDataChanges(
313 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
315 verify(this.domDataBroker).registerDataChangeListener(
316 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
318 assertEquals("isListening", true, listener.isListening());
320 this.brokerFacade.registerToListenDataChanges(
321 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
322 verifyNoMoreInteractions(this.domDataBroker);
326 * Create, register, close and remove notification listener.
329 public void testRegisterToListenNotificationChanges() {
330 // create test notification listener
331 final String identifier = "create-notification-stream/toaster:toastDone";
332 final SchemaPath path = SchemaPath.create(true,
333 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
334 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
335 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
338 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
339 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
340 .thenReturn(registration);
342 // test to register listener for the first time
343 this.brokerFacade.registerToListenNotification(listener);
344 assertEquals("Registration was not successful", true, listener.isListening());
346 // try to register for the second time
347 this.brokerFacade.registerToListenNotification(listener);
348 assertEquals("Registration was not successful", true, listener.isListening());
350 // registrations should be invoked only once
351 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
353 // close and remove test notification listener
355 Notificator.removeNotificationListenerIfNoSubscriberExists(listener);
359 * Test PATCH method on the server with no data
362 @SuppressWarnings("unchecked")
363 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
364 final PATCHContext patchContext = mock(PATCHContext.class);
365 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
366 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
368 when(patchContext.getData()).thenReturn(Lists.newArrayList());
369 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
372 when(identifierContext.getMountPoint()).thenReturn(null);
374 when(this.rwTransaction.submit()).thenReturn(expFuture);
376 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
379 assertTrue("PATCH operation should be successful on server", status.isOk());
383 * Test PATCH method on mounted device with no data
386 @SuppressWarnings("unchecked")
387 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
388 final PATCHContext patchContext = mock(PATCHContext.class);
389 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
390 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
391 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
392 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
393 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
395 when(patchContext.getData()).thenReturn(Lists.newArrayList());
396 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
398 // return mount point with broker
399 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
400 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
401 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
402 when(transaction.submit()).thenReturn(expFuture);
404 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
407 assertTrue("PATCH operation should be successful on mounted device", status.isOk());
411 * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
412 * PATCH operation should fail with global error.
415 @SuppressWarnings("unchecked")
416 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
417 final PATCHContext patchContext = mock(PATCHContext.class);
418 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
419 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
420 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
421 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
422 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
424 when(patchContext.getData()).thenReturn(Lists.newArrayList());
425 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
426 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
428 // missing broker on mounted device
429 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
431 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
432 when(transaction.submit()).thenReturn(expFuture);
434 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
436 // assert not successful operation with error
437 assertNotNull(status.getGlobalErrors());
438 assertEquals(1, status.getGlobalErrors().size());
439 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
440 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
442 assertFalse("PATCH operation should fail on mounted device without Broker", status.isOk());