395f6445103e08a307abdbf3f7ac5077707b192a
[netconf.git] / restconf / restconf-nb-bierman02 / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / BrokerFacadeTest.java
1 /*
2  * Copyright (c) 2014, 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sal.restconf.impl.test;
9
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.assertThrows;
15 import static org.junit.Assert.assertTrue;
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;
29
30 import com.google.common.collect.ImmutableClassToInstanceMap;
31 import com.google.common.util.concurrent.FluentFuture;
32 import com.google.common.util.concurrent.ListenableFuture;
33 import java.util.List;
34 import java.util.Optional;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.junit.runner.RunWith;
38 import org.mockito.InOrder;
39 import org.mockito.Mock;
40 import org.mockito.Mockito;
41 import org.mockito.junit.MockitoJUnitRunner;
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.DOMSchemaService;
57 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
58 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
59 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
60 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
61 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
62 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
64 import org.opendaylight.restconf.common.ErrorTags;
65 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
66 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
67 import org.opendaylight.restconf.common.errors.RestconfError;
68 import org.opendaylight.restconf.common.patch.PatchContext;
69 import org.opendaylight.restconf.common.patch.PatchStatusContext;
70 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
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.ErrorTag;
74 import org.opendaylight.yangtools.yang.common.ErrorType;
75 import org.opendaylight.yangtools.yang.common.QName;
76 import org.opendaylight.yangtools.yang.common.RpcError;
77 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
78 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
81 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
82 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
84 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
85
86 /**
87  * Unit tests for BrokerFacade.
88  *
89  * @author Thomas Pantelis
90  */
91 @RunWith(MockitoJUnitRunner.StrictStubs.class)
92 public class BrokerFacadeTest {
93
94     @Mock
95     private DOMDataBroker domDataBroker;
96     @Mock
97     private DOMNotificationService domNotification;
98     @Mock
99     private DOMRpcService mockRpcService;
100     @Mock
101     private DOMMountPoint mockMountInstance;
102     @Mock
103     private DOMDataTreeReadTransaction readTransaction;
104     @Mock
105     private DOMDataTreeWriteTransaction writeTransaction;
106     @Mock
107     private DOMDataTreeReadWriteTransaction rwTransaction;
108
109     private BrokerFacade brokerFacade;
110     private final NormalizedNode dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
111     private final FluentFuture<Optional<NormalizedNode>> dummyNodeInFuture = wrapDummyNode(dummyNode);
112     private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
113     private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(qname).build();
114     private ControllerContext controllerContext;
115
116     @Before
117     public void setUp() throws Exception {
118         controllerContext = TestRestconfUtils.newControllerContext(
119                 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
120
121         brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
122
123         when(domDataBroker.newReadOnlyTransaction()).thenReturn(readTransaction);
124         when(domDataBroker.newReadWriteTransaction()).thenReturn(rwTransaction);
125         when(domDataBroker.getExtensions()).thenReturn(ImmutableClassToInstanceMap.of(
126             DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class)));
127     }
128
129     private static FluentFuture<Optional<NormalizedNode>> wrapDummyNode(final NormalizedNode dummyNode) {
130         return immediateFluentFuture(Optional.of(dummyNode));
131     }
132
133     private static FluentFuture<Boolean> wrapExistence(final boolean exists) {
134         return immediateBooleanFluentFuture(exists);
135     }
136
137     /**
138      * Value of this node shouldn't be important for testing purposes.
139      */
140     private static NormalizedNode createDummyNode(final String namespace, final String date, final String localName) {
141         return Builders.containerBuilder()
142                 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName)))
143                 .build();
144     }
145
146     @Test
147     public void testReadConfigurationData() {
148         when(readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
149                 dummyNodeInFuture);
150
151         final NormalizedNode actualNode = brokerFacade.readConfigurationData(instanceID);
152
153         assertSame("readConfigurationData", dummyNode, actualNode);
154     }
155
156     @Test
157     public void testReadOperationalData() {
158         when(readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
159                 dummyNodeInFuture);
160
161         final NormalizedNode actualNode = brokerFacade.readOperationalData(instanceID);
162
163         assertSame("readOperationalData", dummyNode, actualNode);
164     }
165
166     @Test
167     public void test503() throws Exception {
168         final RpcError error = RpcResultBuilder.newError(
169                 RpcError.ErrorType.TRANSPORT,
170                 ErrorTag.RESOURCE_DENIED.elementBody(),
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));
174
175         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
176             () -> brokerFacade.readConfigurationData(instanceID, "explicit"));
177         final List<RestconfError> errors = ex.getErrors();
178         assertEquals(1, errors.size());
179         assertEquals("getErrorTag", ErrorTags.RESOURCE_DENIED_TRANSPORT, errors.get(0).getErrorTag());
180         assertEquals("getErrorType", ErrorType.TRANSPORT,errors.get(0).getErrorType());
181         assertEquals("getErrorMessage", "Master is down. Please try again.", errors.get(0).getErrorMessage());
182     }
183
184     @Test
185     public void testInvokeRpc() throws Exception {
186         final DOMRpcResult expResult = mock(DOMRpcResult.class);
187         doReturn(immediateFluentFuture(expResult)).when(mockRpcService).invokeRpc(qname, dummyNode);
188
189         final ListenableFuture<? extends DOMRpcResult> actualFuture = brokerFacade.invokeRpc(qname,
190             dummyNode);
191         assertNotNull("Future is null", actualFuture);
192         final DOMRpcResult actualResult = actualFuture.get();
193         assertSame("invokeRpc", expResult, actualResult);
194     }
195
196     @Test
197     public void testCommitConfigurationDataPut() throws Exception {
198         doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
199
200         doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(rwTransaction)
201         .read(LogicalDatastoreType.CONFIGURATION, instanceID);
202
203         final PutResult result = brokerFacade.commitConfigurationDataPut(mock(EffectiveModelContext.class),
204                 instanceID, dummyNode, null, null);
205
206         assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
207
208         final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
209         inOrder.verify(domDataBroker).newReadWriteTransaction();
210         inOrder.verify(rwTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
211         inOrder.verify(rwTransaction).commit();
212     }
213
214     @Test
215     public void testCommitConfigurationDataPost() {
216         when(rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, instanceID))
217                 .thenReturn(wrapExistence(false));
218
219         doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
220
221         final FluentFuture<? extends CommitInfo> actualFuture = brokerFacade
222                 .commitConfigurationDataPost(mock(EffectiveModelContext.class), instanceID, dummyNode, null,
223                         null);
224
225         assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
226
227         final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
228         inOrder.verify(domDataBroker).newReadWriteTransaction();
229         inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
230         inOrder.verify(rwTransaction).put(LogicalDatastoreType.CONFIGURATION, instanceID, dummyNode);
231         inOrder.verify(rwTransaction).commit();
232     }
233
234     @Test(expected = RestconfDocumentedException.class)
235     public void testCommitConfigurationDataPostAlreadyExists() {
236         when(rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
237                 .thenReturn(immediateTrueFluentFuture());
238         try {
239             // Schema context is only necessary for ensuring parent structure
240             brokerFacade.commitConfigurationDataPost((EffectiveModelContext) null, instanceID, dummyNode,
241                     null, null);
242         } catch (final RestconfDocumentedException e) {
243             assertEquals("getErrorTag", ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
244             throw e;
245         }
246     }
247
248     /**
249      * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
250      */
251     @Test
252     public void testCommitConfigurationDataDelete() throws Exception {
253         // assume that data to delete exists
254         prepareDataForDelete(true);
255
256         // expected result
257         doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
258
259         // test
260         final FluentFuture<? extends CommitInfo> actualFuture = brokerFacade
261                 .commitConfigurationDataDelete(instanceID);
262
263         // verify result and interactions
264         assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
265
266         // check exists, delete, submit
267         final InOrder inOrder = inOrder(domDataBroker, rwTransaction);
268         inOrder.verify(rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, instanceID);
269         inOrder.verify(rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, instanceID);
270         inOrder.verify(rwTransaction).commit();
271     }
272
273     /**
274      * Negative test of delete operation when data to delete does not exist. Error DATA_MISSING should be returned.
275      */
276     @Test
277     public void testCommitConfigurationDataDeleteNoData() throws Exception {
278         // assume that data to delete does not exist
279         prepareDataForDelete(false);
280
281         // try to delete and expect DATA_MISSING error
282         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
283             () -> brokerFacade.commitConfigurationDataDelete(instanceID));
284         final List<RestconfError> errors = ex.getErrors();
285         assertEquals(1, errors.size());
286         assertEquals(ErrorType.PROTOCOL, errors.get(0).getErrorType());
287         assertEquals(ErrorTag.DATA_MISSING, errors.get(0).getErrorTag());
288     }
289
290     /**
291      * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
292      * {@code assumeDataExists} parameter.
293      * @param assumeDataExists boolean to assume if data exists
294      */
295     private void prepareDataForDelete(final boolean assumeDataExists) {
296         when(rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, instanceID))
297                 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
298     }
299
300     @Test
301     public void testRegisterToListenDataChanges() {
302         final ListenerAdapter listener = Notificator.createListener(instanceID, "stream",
303                 NotificationOutputType.XML, controllerContext);
304
305         @SuppressWarnings("unchecked")
306         final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
307
308         DOMDataTreeChangeService changeService = domDataBroker.getExtensions()
309                 .getInstance(DOMDataTreeChangeService.class);
310         DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, instanceID);
311         when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
312
313         brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, Scope.BASE, listener);
314
315         verify(changeService).registerDataTreeChangeListener(loc, listener);
316
317         assertEquals("isListening", true, listener.isListening());
318
319         brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, Scope.BASE, listener);
320         verifyNoMoreInteractions(changeService);
321     }
322
323     /**
324      * Create, register, close and remove notification listener.
325      */
326     @Test
327     public void testRegisterToListenNotificationChanges() throws Exception {
328         // create test notification listener
329         final String identifier = "create-notification-stream/toaster:toastDone";
330         final Absolute path = Absolute.of(
331                 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
332         Notificator.createNotificationListener(List.of(path), identifier, "XML", controllerContext);
333         final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
334
335         // mock registration
336         final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
337         when(domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
338                 .thenReturn(registration);
339
340         // test to register listener for the first time
341         brokerFacade.registerToListenNotification(listener);
342         assertEquals("Registration was not successful", true, listener.isListening());
343
344         // try to register for the second time
345         brokerFacade.registerToListenNotification(listener);
346         assertEquals("Registration was not successful", true, listener.isListening());
347
348         // registrations should be invoked only once
349         verify(domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
350
351         final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
352         final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
353         // close and remove test notification listener
354         listener.close();
355         Notificator.removeListenerIfNoSubscriberExists(listener);
356     }
357
358     /**
359      * Test Patch method on the server with no data.
360      */
361     @Test
362     public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
363         final PatchContext patchContext = mock(PatchContext.class);
364
365         when(patchContext.getData()).thenReturn(List.of());
366         // no mount point
367         doReturn(InstanceIdentifierContext.ofDataSchemaNode(
368             mock(EffectiveModelContext.class), mock(DataSchemaNode.class)))
369                 .when(patchContext).getInstanceIdentifierContext();
370
371         doReturn(CommitInfo.emptyFluentFuture()).when(rwTransaction).commit();
372
373         final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
374
375         // assert success
376         assertTrue("Patch operation should be successful on server", status.isOk());
377     }
378
379     /**
380      * Test Patch method on mounted device with no data.
381      */
382     @Test
383     public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
384         final PatchContext patchContext = mock(PatchContext.class);
385         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
386         final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
387         final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
388
389         when(patchContext.getData()).thenReturn(List.of());
390         // return mount point with broker
391         doReturn(InstanceIdentifierContext.ofDataSchemaNode(
392             mock(EffectiveModelContext.class), mock(DataSchemaNode.class), mountPoint))
393                 .when(patchContext).getInstanceIdentifierContext();
394
395         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
396         when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
397         when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
398         doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
399
400         final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
401
402         // assert success
403         assertTrue("Patch operation should be successful on mounted device", status.isOk());
404     }
405
406     /**
407      * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
408      * Patch operation should fail with global error.
409      */
410     @Test
411     public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
412         final PatchContext patchContext = mock(PatchContext.class);
413         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
414
415         doReturn(InstanceIdentifierContext.ofDataSchemaNode(
416             mock(EffectiveModelContext.class), mock(DataSchemaNode.class), mountPoint))
417                 .when(patchContext).getInstanceIdentifierContext();
418
419         // missing broker on mounted device
420         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
421         when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
422
423         final PatchStatusContext status = brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
424
425         // assert not successful operation with error
426         assertNotNull(status.getGlobalErrors());
427         assertEquals(1, status.getGlobalErrors().size());
428         assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
429         assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
430
431         assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());
432     }
433 }