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
8 package org.opendaylight.controller.sal.restconf.impl.test;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertSame;
14 import static org.junit.Assert.assertTrue;
15 import static org.junit.Assert.fail;
16 import static org.mockito.ArgumentMatchers.any;
17 import static org.mockito.ArgumentMatchers.eq;
18 import static org.mockito.Mockito.doReturn;
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 static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateBooleanFluentFuture;
26 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
27 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
28 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateTrueFluentFuture;
30 import com.google.common.collect.ImmutableClassToInstanceMap;
31 import com.google.common.collect.Lists;
32 import com.google.common.util.concurrent.FluentFuture;
33 import java.util.Optional;
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.rest.common.TestRestconfUtils;
41 import org.opendaylight.mdsal.common.api.CommitInfo;
42 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
43 import org.opendaylight.mdsal.common.api.ReadFailedException;
44 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
46 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
47 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
48 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
49 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
50 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
51 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
52 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
53 import org.opendaylight.mdsal.dom.api.DOMRpcService;
54 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
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 DOMDataTreeReadTransaction readTransaction;
99 private DOMDataTreeWriteTransaction writeTransaction;
101 private DOMDataTreeReadWriteTransaction rwTransaction;
103 private BrokerFacade brokerFacade;
104 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
105 private final FluentFuture<Optional<NormalizedNode<?, ?>>> dummyNodeInFuture = wrapDummyNode(this.dummyNode);
106 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
107 private final SchemaPath type = SchemaPath.create(true, this.qname);
108 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
109 private ControllerContext controllerContext;
112 public void setUp() throws Exception {
113 MockitoAnnotations.initMocks(this);
115 controllerContext = TestRestconfUtils.newControllerContext(
116 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
118 brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
120 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
121 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
122 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
123 when(this.domDataBroker.getExtensions()).thenReturn(ImmutableClassToInstanceMap.of(
124 DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class)));
127 private static FluentFuture<Optional<NormalizedNode<?, ?>>> wrapDummyNode(final NormalizedNode<?, ?> dummyNode) {
128 return immediateFluentFuture(Optional.of(dummyNode));
131 private static FluentFuture<Boolean> wrapExistence(final boolean exists) {
132 return immediateBooleanFluentFuture(exists);
136 * Value of this node shouldn't be important for testing purposes.
138 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
139 final String localName) {
140 return Builders.containerBuilder()
141 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
145 public void testReadConfigurationData() {
146 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
147 this.dummyNodeInFuture);
149 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
151 assertSame("readConfigurationData", this.dummyNode, actualNode);
155 public void testReadOperationalData() {
156 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
157 this.dummyNodeInFuture);
159 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
161 assertSame("readOperationalData", this.dummyNode, actualNode);
165 public void test503() throws Exception {
166 final RpcError error = RpcResultBuilder.newError(
167 RpcError.ErrorType.TRANSPORT,
168 ErrorTag.RESOURCE_DENIED.getTagValue(),
169 "Master is down. Please try again.");
170 doReturn(immediateFailedFluentFuture(new ReadFailedException("Read from transaction failed", error)))
171 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
173 brokerFacade.readConfigurationData(this.instanceID, "explicit");
174 fail("This test should fail.");
175 } catch (final RestconfDocumentedException e) {
176 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
177 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
178 assertEquals("getErrorMessage", "Master is down. Please try again.",
179 e.getErrors().get(0).getErrorMessage());
184 public void testInvokeRpc() throws Exception {
185 final DOMRpcResult expResult = mock(DOMRpcResult.class);
186 doReturn(immediateFluentFuture(expResult)).when(this.mockRpcService).invokeRpc(this.type, this.dummyNode);
188 final FluentFuture<DOMRpcResult> actualFuture = this.brokerFacade.invokeRpc(this.type, this.dummyNode);
189 assertNotNull("Future is null", actualFuture);
190 final DOMRpcResult actualResult = actualFuture.get();
191 assertSame("invokeRpc", expResult, actualResult);
195 public void testCommitConfigurationDataPut() throws Exception {
196 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
198 doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(this.rwTransaction)
199 .read(LogicalDatastoreType.CONFIGURATION, this.instanceID);
201 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
202 this.instanceID, this.dummyNode, null, null);
204 assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
206 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
207 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
208 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
209 inOrder.verify(this.rwTransaction).commit();
213 public void testCommitConfigurationDataPost() {
214 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
215 .thenReturn(wrapExistence(false));
217 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
219 final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
220 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
222 assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
224 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
225 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
226 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
227 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
228 inOrder.verify(this.rwTransaction).commit();
231 @Test(expected = RestconfDocumentedException.class)
232 public void testCommitConfigurationDataPostAlreadyExists() {
233 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
234 .thenReturn(immediateTrueFluentFuture());
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 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
257 final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
258 .commitConfigurationDataDelete(this.instanceID);
260 // verify result and interactions
261 assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
263 // check exists, delete, submit
264 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
265 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
266 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
267 inOrder.verify(this.rwTransaction).commit();
271 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
274 public void testCommitConfigurationDataDeleteNoData() throws Exception {
275 // assume that data to delete does not exist
276 prepareDataForDelete(false);
278 // try to delete and expect 404 error
280 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
281 fail("Delete operation should fail due to missing data");
282 } catch (final RestconfDocumentedException e) {
283 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
284 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
285 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
290 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
291 * {@code assumeDataExists} parameter.
292 * @param assumeDataExists boolean to assume if data exists
294 private void prepareDataForDelete(final boolean assumeDataExists) {
295 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
296 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
300 public void testRegisterToListenDataChanges() {
301 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
302 NotificationOutputType.XML, controllerContext);
304 @SuppressWarnings("unchecked")
305 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
307 DOMDataTreeChangeService changeService = this.domDataBroker.getExtensions()
308 .getInstance(DOMDataTreeChangeService.class);
309 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
310 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
312 this.brokerFacade.registerToListenDataChanges(
313 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
315 verify(changeService).registerDataTreeChangeListener(loc, listener);
317 assertEquals("isListening", true, listener.isListening());
319 this.brokerFacade.registerToListenDataChanges(
320 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
321 verifyNoMoreInteractions(changeService);
325 * Create, register, close and remove notification listener.
328 public void testRegisterToListenNotificationChanges() throws Exception {
329 // create test notification listener
330 final String identifier = "create-notification-stream/toaster:toastDone";
331 final SchemaPath path = SchemaPath.create(true,
332 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
333 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
334 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
337 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
338 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
339 .thenReturn(registration);
341 // test to register listener for the first time
342 this.brokerFacade.registerToListenNotification(listener);
343 assertEquals("Registration was not successful", true, listener.isListening());
345 // try to register for the second time
346 this.brokerFacade.registerToListenNotification(listener);
347 assertEquals("Registration was not successful", true, listener.isListening());
349 // registrations should be invoked only once
350 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
352 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
353 final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
354 doReturn(CommitInfo.emptyFluentFuture()).when(wTx).commit();
355 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
356 // close and remove test notification listener
358 Notificator.removeListenerIfNoSubscriberExists(listener);
362 * Test Patch method on the server with no data.
365 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
366 final PatchContext patchContext = mock(PatchContext.class);
367 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
369 when(patchContext.getData()).thenReturn(Lists.newArrayList());
370 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
373 when(identifierContext.getMountPoint()).thenReturn(null);
375 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
377 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
380 assertTrue("Patch operation should be successful on server", status.isOk());
384 * Test Patch method on mounted device with no data.
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 DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
394 when(patchContext.getData()).thenReturn(Lists.newArrayList());
395 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
397 // return mount point with broker
398 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
399 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
400 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
401 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
403 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
406 assertTrue("Patch operation should be successful on mounted device", status.isOk());
410 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
411 * Patch operation should fail with global error.
414 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
415 final PatchContext patchContext = mock(PatchContext.class);
416 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
417 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
418 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
419 final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
421 when(patchContext.getData()).thenReturn(Lists.newArrayList());
422 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
423 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
425 // missing broker on mounted device
426 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
428 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
429 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
431 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
433 // assert not successful operation with error
434 assertNotNull(status.getGlobalErrors());
435 assertEquals(1, status.getGlobalErrors().size());
436 assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
437 assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
439 assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());