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