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.concurrent.Future;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.mockito.InOrder;
35 import org.mockito.Mock;
36 import org.mockito.Mockito;
37 import org.mockito.MockitoAnnotations;
38 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
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.DOMDataChangeListener;
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.DOMDataWriteTransaction;
47 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
48 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
53 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
54 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
55 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
56 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
57 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
58 import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
59 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
61 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
62 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
63 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
64 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.restconf.handlers.SchemaContextHandler;
68 import org.opendaylight.restconf.handlers.TransactionChainHandler;
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 ConsumerSession context;
95 private DOMRpcService mockRpcService;
97 private DOMMountPoint mockMountInstance;
99 private DOMDataReadOnlyTransaction rTransaction;
101 private DOMDataWriteTransaction wTransaction;
103 private DOMDataReadWriteTransaction rwTransaction;
105 private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
106 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
107 private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
108 wrapDummyNode(this.dummyNode);
109 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
110 private final SchemaPath type = SchemaPath.create(true, this.qname);
111 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
114 public void setUp() throws Exception {
115 MockitoAnnotations.initMocks(this);
116 this.brokerFacade.setDomDataBroker(this.domDataBroker);
117 this.brokerFacade.setDomNotificationService(this.domNotification);
118 this.brokerFacade.setRpcService(this.mockRpcService);
119 this.brokerFacade.setContext(this.context);
120 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
121 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
122 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
124 ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
127 private static CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
128 final NormalizedNode<?, ?> dummyNode) {
129 return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
132 private static CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
133 return Futures.immediateCheckedFuture(exists);
137 * Value of this node shouldn't be important for testing purposes
139 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
140 final String localName) {
141 return Builders.containerBuilder()
142 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
146 public void testReadConfigurationData() {
147 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
148 this.dummyNodeInFuture);
150 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
152 assertSame("readConfigurationData", this.dummyNode, actualNode);
156 public void testReadOperationalData() {
157 when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
158 this.dummyNodeInFuture);
160 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
162 assertSame("readOperationalData", this.dummyNode, actualNode);
165 @Test(expected = RestconfDocumentedException.class)
166 public void testReadOperationalDataWithNoDataBroker() {
167 this.brokerFacade.setDomDataBroker(null);
169 this.brokerFacade.readOperationalData(this.instanceID);
173 public void test503() throws Exception {
174 final RpcError error = RpcResultBuilder.newError(
175 RpcError.ErrorType.TRANSPORT,
176 ErrorTag.RESOURCE_DENIED.getTagValue(),
177 "Master is down. Please try again.");
178 final ReadFailedException exception503 = new ReadFailedException("Read from transaction failed", error);
179 doReturn(Futures.immediateFailedCheckedFuture(exception503))
180 .when(rTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
182 brokerFacade.readConfigurationData(this.instanceID, "explicit");
183 fail("This test should fail.");
184 } catch (final RestconfDocumentedException e) {
185 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
186 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
187 assertEquals("getErrorMessage", "Master is down. Please try again.", e.getErrors().get(0).getErrorMessage());
192 public void testInvokeRpc() throws Exception {
193 final DOMRpcResult expResult = mock(DOMRpcResult.class);
194 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
195 when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
197 final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
198 .invokeRpc(this.type, this.dummyNode);
199 assertNotNull("Future is null", actualFuture);
200 final DOMRpcResult actualResult = actualFuture.get();
201 assertSame("invokeRpc", expResult, actualResult);
204 @Test(expected = RestconfDocumentedException.class)
205 public void testInvokeRpcWithNoConsumerSession() {
206 this.brokerFacade.setContext(null);
207 this.brokerFacade.invokeRpc(this.type, this.dummyNode);
211 public void testCommitConfigurationDataPut() throws Exception {
212 @SuppressWarnings("unchecked")
213 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
214 when(this.rwTransaction.submit()).thenReturn(expFuture);
216 final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
217 when(optionalMock.get()).thenReturn(null);
219 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
220 .immediateCheckedFuture(optionalMock);
221 when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
223 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
224 this.instanceID, this.dummyNode, null, null);
226 final Future<Void> actualFuture = result.getFutureOfPutData();
228 assertSame("commitConfigurationDataPut", expFuture, actualFuture);
230 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
231 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
232 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
233 inOrder.verify(this.rwTransaction).submit();
237 public void testCommitConfigurationDataPost() {
238 @SuppressWarnings("unchecked")
239 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
241 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
242 .thenReturn(wrapExistence(false));
244 when(this.rwTransaction.submit()).thenReturn(expFuture);
246 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
247 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
249 assertSame("commitConfigurationDataPost", expFuture, actualFuture);
251 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
252 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
253 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
254 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
255 inOrder.verify(this.rwTransaction).submit();
258 @Test(expected = RestconfDocumentedException.class)
259 public void testCommitConfigurationDataPostAlreadyExists() {
260 final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
261 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
262 .thenReturn(successFuture);
264 // Schema context is only necessary for ensuring parent structure
265 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
267 } catch (final RestconfDocumentedException e) {
268 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
274 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
277 public void testCommitConfigurationDataDelete() throws Exception {
278 // assume that data to delete exists
279 prepareDataForDelete(true);
282 @SuppressWarnings("unchecked")
283 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
284 when(this.rwTransaction.submit()).thenReturn(expFuture);
287 final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
288 .commitConfigurationDataDelete(this.instanceID);
290 // verify result and interactions
291 assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
293 // check exists, delete, submit
294 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
295 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
296 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
297 inOrder.verify(this.rwTransaction).submit();
301 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
304 public void testCommitConfigurationDataDeleteNoData() throws Exception {
305 // assume that data to delete does not exist
306 prepareDataForDelete(false);
308 // try to delete and expect 404 error
310 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
311 fail("Delete operation should fail due to missing data");
312 } catch (final RestconfDocumentedException e) {
313 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
314 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
315 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
320 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
321 * {@code assumeDataExists} parameter.
322 * @param assumeDataExists
324 private void prepareDataForDelete(final boolean assumeDataExists) {
325 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
326 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
330 public void testRegisterToListenDataChanges() {
331 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
332 NotificationOutputType.XML);
334 @SuppressWarnings("unchecked")
335 final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
337 when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
338 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
340 this.brokerFacade.registerToListenDataChanges(
341 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
343 verify(this.domDataBroker).registerDataChangeListener(
344 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
346 assertEquals("isListening", true, listener.isListening());
348 this.brokerFacade.registerToListenDataChanges(
349 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
350 verifyNoMoreInteractions(this.domDataBroker);
354 * Create, register, close and remove notification listener.
357 public void testRegisterToListenNotificationChanges() throws Exception {
358 // create test notification listener
359 final String identifier = "create-notification-stream/toaster:toastDone";
360 final SchemaPath path = SchemaPath.create(true,
361 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
362 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
363 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
366 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
367 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
368 .thenReturn(registration);
370 // test to register listener for the first time
371 this.brokerFacade.registerToListenNotification(listener);
372 assertEquals("Registration was not successful", true, listener.isListening());
374 // try to register for the second time
375 this.brokerFacade.registerToListenNotification(listener);
376 assertEquals("Registration was not successful", true, listener.isListening());
378 // registrations should be invoked only once
379 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
381 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
382 final DOMDataWriteTransaction wTx = mock(DOMDataWriteTransaction.class);
383 final CheckedFuture checked = Futures.immediateCheckedFuture("");
384 when(wTx.submit()).thenReturn(checked);
385 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
386 final TransactionChainHandler transactionChainHandler = new TransactionChainHandler(transactionChain);
387 final SchemaContextHandler schemaHandler = Mockito.mock(SchemaContextHandler.class);
388 final SchemaContext schCtx = TestUtils.loadSchemaContext("/modules");
389 when(schemaHandler.get()).thenReturn(schCtx);
390 listener.setCloseVars(transactionChainHandler, schemaHandler);
391 // close and remove test notification listener
393 Notificator.removeListenerIfNoSubscriberExists(listener);
397 * Test PATCH method on the server with no data
400 @SuppressWarnings("unchecked")
401 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
402 final PATCHContext patchContext = mock(PATCHContext.class);
403 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
404 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
406 when(patchContext.getData()).thenReturn(Lists.newArrayList());
407 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
410 when(identifierContext.getMountPoint()).thenReturn(null);
412 when(this.rwTransaction.submit()).thenReturn(expFuture);
414 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
417 assertTrue("PATCH operation should be successful on server", status.isOk());
421 * Test PATCH method on mounted device with no data
424 @SuppressWarnings("unchecked")
425 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
426 final PATCHContext patchContext = mock(PATCHContext.class);
427 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
428 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
429 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
430 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
431 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
433 when(patchContext.getData()).thenReturn(Lists.newArrayList());
434 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
436 // return mount point with broker
437 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
438 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
439 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
440 when(transaction.submit()).thenReturn(expFuture);
442 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
445 assertTrue("PATCH operation should be successful on mounted device", status.isOk());
449 * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
450 * PATCH operation should fail with global error.
453 @SuppressWarnings("unchecked")
454 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
455 final PATCHContext patchContext = mock(PATCHContext.class);
456 final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
457 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
458 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
459 final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
460 final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
462 when(patchContext.getData()).thenReturn(Lists.newArrayList());
463 when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
464 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
466 // missing broker on mounted device
467 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
469 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
470 when(transaction.submit()).thenReturn(expFuture);
472 final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
474 // assert not successful operation with error
475 assertNotNull(status.getGlobalErrors());
476 assertEquals(1, status.getGlobalErrors().size());
477 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
478 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
480 assertFalse("PATCH operation should fail on mounted device without Broker", status.isOk());