Update MRI projects for Aluminium
[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.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;
29
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;
82
83 /**
84  * Unit tests for BrokerFacade.
85  *
86  * @author Thomas Pantelis
87  */
88 public class BrokerFacadeTest {
89
90     @Mock
91     private DOMDataBroker domDataBroker;
92     @Mock
93     private DOMNotificationService domNotification;
94     @Mock
95     private DOMRpcService mockRpcService;
96     @Mock
97     private DOMMountPoint mockMountInstance;
98     @Mock
99     private DOMDataTreeReadTransaction readTransaction;
100     @Mock
101     private DOMDataTreeWriteTransaction writeTransaction;
102     @Mock
103     private DOMDataTreeReadWriteTransaction rwTransaction;
104
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;
112
113     @Before
114     public void setUp() throws Exception {
115         MockitoAnnotations.initMocks(this);
116
117         controllerContext = TestRestconfUtils.newControllerContext(
118                 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
119
120         brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
121
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)));
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,
141             final String localName) {
142         return Builders.containerBuilder()
143                 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
144     }
145
146     @Test
147     public void testReadConfigurationData() {
148         when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
149                 this.dummyNodeInFuture);
150
151         final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
152
153         assertSame("readConfigurationData", this.dummyNode, actualNode);
154     }
155
156     @Test
157     public void testReadOperationalData() {
158         when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
159                 this.dummyNodeInFuture);
160
161         final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
162
163         assertSame("readOperationalData", this.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.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));
174         try {
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());
182         }
183     }
184
185     @Test
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);
189
190         final ListenableFuture<? extends DOMRpcResult> actualFuture = this.brokerFacade.invokeRpc(this.type,
191             this.dummyNode);
192         assertNotNull("Future is null", actualFuture);
193         final DOMRpcResult actualResult = actualFuture.get();
194         assertSame("invokeRpc", expResult, actualResult);
195     }
196
197     @Test
198     public void testCommitConfigurationDataPut() throws Exception {
199         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
200
201         doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(this.rwTransaction)
202         .read(LogicalDatastoreType.CONFIGURATION, this.instanceID);
203
204         final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
205                 this.instanceID, this.dummyNode, null, null);
206
207         assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
208
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();
213     }
214
215     @Test
216     public void testCommitConfigurationDataPost() {
217         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
218                 .thenReturn(wrapExistence(false));
219
220         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
221
222         final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
223                 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode, null, null);
224
225         assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
226
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();
232     }
233
234     @Test(expected = RestconfDocumentedException.class)
235     public void testCommitConfigurationDataPostAlreadyExists() {
236         when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
237                 .thenReturn(immediateTrueFluentFuture());
238         try {
239             // Schema context is only necessary for ensuring parent structure
240             this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode, null,
241                     null);
242         } catch (final RestconfDocumentedException e) {
243             assertEquals("getErrorTag", RestconfError.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(this.rwTransaction).commit();
258
259         // test
260         final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
261                 .commitConfigurationDataDelete(this.instanceID);
262
263         // verify result and interactions
264         assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
265
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();
271     }
272
273     /**
274      * Negative test of delete operation when data to delete does not exist. Error 404 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 404 error
282         try {
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());
289         }
290     }
291
292     /**
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
296      */
297     private void prepareDataForDelete(final boolean assumeDataExists) {
298         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
299                 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
300     }
301
302     @Test
303     public void testRegisterToListenDataChanges() {
304         final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
305                 NotificationOutputType.XML, controllerContext);
306
307         @SuppressWarnings("unchecked")
308         final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
309
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);
314
315         this.brokerFacade.registerToListenDataChanges(
316                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
317
318         verify(changeService).registerDataTreeChangeListener(loc, listener);
319
320         assertEquals("isListening", true, listener.isListening());
321
322         this.brokerFacade.registerToListenDataChanges(
323                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
324         verifyNoMoreInteractions(changeService);
325     }
326
327     /**
328      * Create, register, close and remove notification listener.
329      */
330     @Test
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);
338
339         // mock registration
340         final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
341         when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
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, listener.getSchemaPath());
354
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
360         listener.close();
361         Notificator.removeListenerIfNoSubscriberExists(listener);
362     }
363
364     /**
365      * Test Patch method on the server with no data.
366      */
367     @Test
368     public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
369         final PatchContext patchContext = mock(PatchContext.class);
370         final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
371
372         when(patchContext.getData()).thenReturn(new ArrayList<>());
373         doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
374
375         // no mount point
376         when(identifierContext.getMountPoint()).thenReturn(null);
377
378         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
379
380         final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
381
382         // assert success
383         assertTrue("Patch operation should be successful on server", status.isOk());
384     }
385
386     /**
387      * Test Patch method on mounted device with no data.
388      */
389     @Test
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);
396
397         when(patchContext.getData()).thenReturn(new ArrayList<>());
398         doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
399
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();
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         when(patchContext.getData()).thenReturn(new ArrayList<>());
425         doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
426         when(identifierContext.getMountPoint()).thenReturn(mountPoint);
427
428         // missing broker on mounted device
429         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
430
431         when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
432         doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
433
434         final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
435
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());
441
442         assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());
443     }
444 }