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.assertNotNull;
13 import static org.junit.Assert.assertSame;
14 import static org.junit.Assert.fail;
15 import static org.mockito.Matchers.any;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Mockito.inOrder;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.times;
20 import static org.mockito.Mockito.verify;
21 import static org.mockito.Mockito.verifyNoMoreInteractions;
22 import static org.mockito.Mockito.when;
24 import com.google.common.base.Optional;
25 import com.google.common.collect.Lists;
26 import com.google.common.util.concurrent.CheckedFuture;
27 import com.google.common.util.concurrent.Futures;
28 import java.util.concurrent.Future;
29 import org.junit.Before;
30 import org.junit.Test;
31 import org.mockito.InOrder;
32 import org.mockito.Mock;
33 import org.mockito.MockitoAnnotations;
34 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
35 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
36 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
37 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
38 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
39 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
40 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
41 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
42 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
43 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
44 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
47 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
48 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
49 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
50 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
51 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
52 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
53 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
54 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
55 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
56 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
57 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
58 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
59 import org.opendaylight.yangtools.concepts.ListenerRegistration;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 * Unit tests for BrokerFacade.
71 * @author Thomas Pantelis
73 public class BrokerFacadeTest {
74 @Mock private DOMDataBroker domDataBroker;
75 @Mock private DOMNotificationService domNotification;
76 @Mock private ConsumerSession context;
77 @Mock private DOMRpcService mockRpcService;
78 @Mock private DOMMountPoint mockMountInstance;
80 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
81 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
82 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
83 wrapDummyNode(dummyNode);
84 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
85 private final SchemaPath type = SchemaPath.create(true, qname);
86 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).build();
88 @Mock private DOMDataReadOnlyTransaction rTransaction;
89 @Mock private DOMDataWriteTransaction wTransaction;
90 @Mock private DOMDataReadWriteTransaction rwTransaction;
93 public void setUp() throws Exception {
94 MockitoAnnotations.initMocks(this);
95 this.brokerFacade.setDomDataBroker(this.domDataBroker);
96 this.brokerFacade.setDomNotificationService(this.domNotification);
97 this.brokerFacade.setRpcService(this.mockRpcService);
98 this.brokerFacade.setContext(this.context);
99 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
100 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
101 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
103 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
106 private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
107 final NormalizedNode<?, ?> dummyNode) {
108 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
111 private CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
112 return Futures.immediateCheckedFuture(exists);
116 * Value of this node shouldn't be important for testing purposes
118 private NormalizedNode<?, ?> createDummyNode(final String namespace, final String date, final String localName) {
119 return Builders.containerBuilder()
120 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
124 public void testReadConfigurationData() {
125 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
126 this.dummyNodeInFuture);
128 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
130 assertSame("readConfigurationData", this.dummyNode, actualNode);
134 public void testReadOperationalData() {
135 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
136 this.dummyNodeInFuture);
138 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
140 assertSame("readOperationalData", this.dummyNode, actualNode);
143 @Test(expected = RestconfDocumentedException.class)
144 public void testReadOperationalDataWithNoDataBroker() {
145 this.brokerFacade.setDomDataBroker(null);
147 this.brokerFacade.readOperationalData(this.instanceID);
151 public void testInvokeRpc() throws Exception {
152 final DOMRpcResult expResult = mock(DOMRpcResult.class);
153 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
154 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
156 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
157 .invokeRpc(this.type, this.dummyNode);
158 assertNotNull("Future is null", actualFuture);
159 final DOMRpcResult actualResult = actualFuture.get();
160 assertSame("invokeRpc", expResult, actualResult);
163 @Test(expected = RestconfDocumentedException.class)
164 public void testInvokeRpcWithNoConsumerSession() {
165 this.brokerFacade.setContext(null);
166 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
170 public void testCommitConfigurationDataPut() throws Exception {
171 @SuppressWarnings("unchecked")
172 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
173 when(this.rwTransaction.submit()).thenReturn(expFuture);
175 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
176 when(optionalMock.get()).thenReturn(null);
178 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
179 .immediateCheckedFuture(optionalMock);
180 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
182 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
183 this.instanceID, this.dummyNode);
185 final Future<Void> actualFuture = result.getFutureOfPutData();
187 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
189 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
190 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
191 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
192 inOrder.verify(this.rwTransaction).submit();
196 public void testCommitConfigurationDataPost() {
197 @SuppressWarnings("unchecked")
198 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
200 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
201 .thenReturn(wrapExistence(false));
203 when(this.rwTransaction.submit()).thenReturn(expFuture);
205 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
206 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode);
208 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
210 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
211 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
212 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
213 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
214 inOrder.verify(this.rwTransaction).submit();
217 @Test(expected = RestconfDocumentedException.class)
218 public void testCommitConfigurationDataPostAlreadyExists() {
219 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
220 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
221 .thenReturn(successFuture);
223 // Schema context is only necessary for ensuring parent structure
224 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode);
225 } catch (final RestconfDocumentedException e) {
226 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
232 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
235 public void testCommitConfigurationDataDelete() throws Exception {
236 // assume that data to delete exists
237 prepareDataForDelete(true);
240 @SuppressWarnings("unchecked")
241 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
242 when(this.rwTransaction.submit()).thenReturn(expFuture);
245 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
246 .commitConfigurationDataDelete(this.instanceID);
248 // verify result and interactions
249 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
251 // check exists, delete, submit
252 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
253 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
254 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
255 inOrder.verify(this.rwTransaction).submit();
259 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
262 public void testCommitConfigurationDataDeleteNoData() throws Exception {
263 // assume that data to delete does not exist
264 prepareDataForDelete(false);
266 // try to delete and expect 404 error
268 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
269 fail("Delete operation should fail due to missing data");
270 } catch (final RestconfDocumentedException e) {
271 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
272 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
273 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
278 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
279 * {@code assumeDataExists} parameter.
280 * @param assumeDataExists
282 private void prepareDataForDelete(final boolean assumeDataExists) {
283 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
284 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
288 public void testRegisterToListenDataChanges() {
289 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream");
291 @SuppressWarnings("unchecked")
292 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
294 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
295 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
297 this.brokerFacade.registerToListenDataChanges(
298 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
300 verify(this.domDataBroker).registerDataChangeListener(
301 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
303 assertEquals("isListening", true, listener.isListening());
305 this.brokerFacade.registerToListenDataChanges(
306 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
307 verifyNoMoreInteractions(this.domDataBroker);
311 * Create, register, close and remove notification listener.
314 public void testRegisterToListenNotificationChanges() {
315 // create test notification listener
316 final String identifier = "create-notification-stream/toaster:toastDone";
317 final SchemaPath path = SchemaPath.create(true,
318 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
319 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
320 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
323 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
324 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
325 .thenReturn(registration);
327 // test to register listener for the first time
328 this.brokerFacade.registerToListenNotification(listener);
329 assertEquals("Registration was not successful", true, listener.isListening());
331 // try to register for the second time
332 this.brokerFacade.registerToListenNotification(listener);
333 assertEquals("Registration was not successful", true, listener.isListening());
335 // registrations should be invoked only once
336 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
338 // close and remove test notification listener
340 Notificator.removeNotificationListenerIfNoSubscriberExists(listener);