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 com.google.common.util.concurrent.ListenableFuture;
34 import java.util.ArrayList;
35 import java.util.Optional;
36 import org.junit.Before;
37 import org.junit.Test;
38 import org.mockito.InOrder;
39 import org.mockito.Mock;
40 import org.mockito.Mockito;
41 import org.mockito.MockitoAnnotations;
42 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
43 import org.opendaylight.mdsal.common.api.CommitInfo;
44 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
45 import org.opendaylight.mdsal.common.api.ReadFailedException;
46 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
47 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
48 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
49 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
51 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
52 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
53 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
54 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
55 import org.opendaylight.mdsal.dom.api.DOMRpcService;
56 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
57 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
58 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
59 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
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.restconf.common.context.InstanceIdentifierContext;
64 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
65 import org.opendaylight.restconf.common.errors.RestconfError;
66 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
67 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
68 import org.opendaylight.restconf.common.patch.PatchContext;
69 import org.opendaylight.restconf.common.patch.PatchStatusContext;
70 import org.opendaylight.restconf.common.util.DataChangeScope;
71 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
72 import org.opendaylight.yangtools.concepts.ListenerRegistration;
73 import org.opendaylight.yangtools.yang.common.QName;
74 import org.opendaylight.yangtools.yang.common.RpcError;
75 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
76 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
80 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
81 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
84 * Unit tests for BrokerFacade.
86 * @author Thomas Pantelis
88 public class BrokerFacadeTest {
91 private DOMDataBroker domDataBroker;
93 private DOMNotificationService domNotification;
95 private DOMRpcService mockRpcService;
97 private DOMMountPoint mockMountInstance;
99 private DOMDataTreeReadTransaction readTransaction;
101 private DOMDataTreeWriteTransaction writeTransaction;
103 private DOMDataTreeReadWriteTransaction rwTransaction;
105 private BrokerFacade brokerFacade;
106 private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
107 private final FluentFuture<Optional<NormalizedNode<?, ?>>> dummyNodeInFuture = wrapDummyNode(this.dummyNode);
108 private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
109 private final SchemaPath type = SchemaPath.create(true, this.qname);
110 private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
111 private ControllerContext controllerContext;
114 public void setUp() throws Exception {
115 MockitoAnnotations.initMocks(this);
117 controllerContext = TestRestconfUtils.newControllerContext(
118 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
120 brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
122 when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
123 when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.writeTransaction);
124 when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
125 when(this.domDataBroker.getExtensions()).thenReturn(ImmutableClassToInstanceMap.of(
126 DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class)));
129 private static FluentFuture<Optional<NormalizedNode<?, ?>>> wrapDummyNode(final NormalizedNode<?, ?> dummyNode) {
130 return immediateFluentFuture(Optional.of(dummyNode));
133 private static FluentFuture<Boolean> wrapExistence(final boolean exists) {
134 return immediateBooleanFluentFuture(exists);
138 * Value of this node shouldn't be important for testing purposes.
140 private static NormalizedNode<?, ?> createDummyNode(final String namespace, final String date,
141 final String localName) {
142 return Builders.containerBuilder()
143 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
147 public void testReadConfigurationData() {
148 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
149 this.dummyNodeInFuture);
151 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
153 assertSame("readConfigurationData", this.dummyNode, actualNode);
157 public void testReadOperationalData() {
158 when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
159 this.dummyNodeInFuture);
161 final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
163 assertSame("readOperationalData", this.dummyNode, actualNode);
167 public void test503() throws Exception {
168 final RpcError error = RpcResultBuilder.newError(
169 RpcError.ErrorType.TRANSPORT,
170 ErrorTag.RESOURCE_DENIED.getTagValue(),
171 "Master is down. Please try again.");
172 doReturn(immediateFailedFluentFuture(new ReadFailedException("Read from transaction failed", error)))
173 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
175 brokerFacade.readConfigurationData(this.instanceID, "explicit");
176 fail("This test should fail.");
177 } catch (final RestconfDocumentedException e) {
178 assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
179 assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
180 assertEquals("getErrorMessage", "Master is down. Please try again.",
181 e.getErrors().get(0).getErrorMessage());
186 public void testInvokeRpc() throws Exception {
187 final DOMRpcResult expResult = mock(DOMRpcResult.class);
188 doReturn(immediateFluentFuture(expResult)).when(this.mockRpcService).invokeRpc(this.type, this.dummyNode);
190 final ListenableFuture<? extends DOMRpcResult> actualFuture = this.brokerFacade.invokeRpc(this.type,
192 assertNotNull("Future is null", actualFuture);
193 final DOMRpcResult actualResult = actualFuture.get();
194 assertSame("invokeRpc", expResult, actualResult);
198 public void testCommitConfigurationDataPut() throws Exception {
199 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
201 doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(this.rwTransaction)
202 .read(LogicalDatastoreType.CONFIGURATION, this.instanceID);
204 final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
205 this.instanceID, this.dummyNode, null, null);
207 assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
209 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
210 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
211 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
212 inOrder.verify(this.rwTransaction).commit();
216 public void testCommitConfigurationDataPost() {
217 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
218 .thenReturn(wrapExistence(false));
220 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
222 final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
223 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
225 assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
227 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
228 inOrder.verify(this.domDataBroker).newReadWriteTransaction();
229 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
230 inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
231 inOrder.verify(this.rwTransaction).commit();
234 @Test(expected = RestconfDocumentedException.class)
235 public void testCommitConfigurationDataPostAlreadyExists() {
236 when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
237 .thenReturn(immediateTrueFluentFuture());
239 // Schema context is only necessary for ensuring parent structure
240 this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
242 } catch (final RestconfDocumentedException e) {
243 assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
249 * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
252 public void testCommitConfigurationDataDelete() throws Exception {
253 // assume that data to delete exists
254 prepareDataForDelete(true);
257 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
260 final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
261 .commitConfigurationDataDelete(this.instanceID);
263 // verify result and interactions
264 assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
266 // check exists, delete, submit
267 final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
268 inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
269 inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
270 inOrder.verify(this.rwTransaction).commit();
274 * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
277 public void testCommitConfigurationDataDeleteNoData() throws Exception {
278 // assume that data to delete does not exist
279 prepareDataForDelete(false);
281 // try to delete and expect 404 error
283 this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
284 fail("Delete operation should fail due to missing data");
285 } catch (final RestconfDocumentedException e) {
286 assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
287 assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
288 assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
293 * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
294 * {@code assumeDataExists} parameter.
295 * @param assumeDataExists boolean to assume if data exists
297 private void prepareDataForDelete(final boolean assumeDataExists) {
298 when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
299 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
303 public void testRegisterToListenDataChanges() {
304 final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
305 NotificationOutputType.XML, controllerContext);
307 @SuppressWarnings("unchecked")
308 final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
310 DOMDataTreeChangeService changeService = this.domDataBroker.getExtensions()
311 .getInstance(DOMDataTreeChangeService.class);
312 DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
313 when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
315 this.brokerFacade.registerToListenDataChanges(
316 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
318 verify(changeService).registerDataTreeChangeListener(loc, listener);
320 assertEquals("isListening", true, listener.isListening());
322 this.brokerFacade.registerToListenDataChanges(
323 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
324 verifyNoMoreInteractions(changeService);
328 * Create, register, close and remove notification listener.
331 public void testRegisterToListenNotificationChanges() throws Exception {
332 // create test notification listener
333 final String identifier = "create-notification-stream/toaster:toastDone";
334 final SchemaPath path = SchemaPath.create(true,
335 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
336 Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
337 final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
340 final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
341 when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
342 .thenReturn(registration);
344 // test to register listener for the first time
345 this.brokerFacade.registerToListenNotification(listener);
346 assertEquals("Registration was not successful", true, listener.isListening());
348 // try to register for the second time
349 this.brokerFacade.registerToListenNotification(listener);
350 assertEquals("Registration was not successful", true, listener.isListening());
352 // registrations should be invoked only once
353 verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
355 final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
356 final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
357 doReturn(CommitInfo.emptyFluentFuture()).when(wTx).commit();
358 when(transactionChain.newWriteOnlyTransaction()).thenReturn(wTx);
359 // close and remove test notification listener
361 Notificator.removeListenerIfNoSubscriberExists(listener);
365 * Test Patch method on the server with no data.
368 public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
369 final PatchContext patchContext = mock(PatchContext.class);
370 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
372 when(patchContext.getData()).thenReturn(new ArrayList<>());
373 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
376 when(identifierContext.getMountPoint()).thenReturn(null);
378 doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
380 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
383 assertTrue("Patch operation should be successful on server", status.isOk());
387 * Test Patch method on mounted device with no data.
390 public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
391 final PatchContext patchContext = mock(PatchContext.class);
392 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
393 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
394 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
395 final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
397 when(patchContext.getData()).thenReturn(new ArrayList<>());
398 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
400 // return mount point with broker
401 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
402 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
403 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
404 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
406 final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
409 assertTrue("Patch operation should be successful on mounted device", status.isOk());
413 * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
414 * Patch operation should fail with global error.
417 public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
418 final PatchContext patchContext = mock(PatchContext.class);
419 final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
420 final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
421 final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
422 final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
424 when(patchContext.getData()).thenReturn(new ArrayList<>());
425 doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
426 when(identifierContext.getMountPoint()).thenReturn(mountPoint);
428 // missing broker on mounted device
429 when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
431 when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
432 doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
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());