Bug 6995 - Change event notification subscription usability PART1
[netconf.git] / restconf / sal-rest-connector / 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
9 package org.opendaylight.controller.sal.restconf.impl.test;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.assertNotNull;
14 import static org.junit.Assert.assertSame;
15 import static org.junit.Assert.assertTrue;
16 import static org.junit.Assert.fail;
17 import static org.mockito.Matchers.any;
18 import static org.mockito.Matchers.eq;
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 com.google.common.base.Optional;
26 import com.google.common.collect.Lists;
27 import com.google.common.util.concurrent.CheckedFuture;
28 import com.google.common.util.concurrent.Futures;
29 import java.util.concurrent.Future;
30 import org.junit.Before;
31 import org.junit.Test;
32 import org.mockito.InOrder;
33 import org.mockito.Mock;
34 import org.mockito.MockitoAnnotations;
35 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
39 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
40 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
41 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
42 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
43 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
44 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
45 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
47 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
49 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
50 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
51 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
52 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
53 import org.opendaylight.netconf.sal.restconf.impl.PATCHContext;
54 import org.opendaylight.netconf.sal.restconf.impl.PATCHStatusContext;
55 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
56 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
57 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
58 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
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.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
64 import org.opendaylight.yangtools.concepts.ListenerRegistration;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
72
73 /**
74  * Unit tests for BrokerFacade.
75  *
76  * @author Thomas Pantelis
77  */
78 public class BrokerFacadeTest {
79
80     @Mock
81     private DOMDataBroker domDataBroker;
82     @Mock
83     private DOMNotificationService domNotification;
84     @Mock
85     private ConsumerSession context;
86     @Mock
87     private DOMRpcService mockRpcService;
88     @Mock
89     private DOMMountPoint mockMountInstance;
90     @Mock
91     private DOMDataReadOnlyTransaction rTransaction;
92     @Mock
93     private DOMDataWriteTransaction wTransaction;
94     @Mock
95     private DOMDataReadWriteTransaction rwTransaction;
96
97     private final BrokerFacade brokerFacade = BrokerFacade.getInstance();
98     private final NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
99     private final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> dummyNodeInFuture =
100             wrapDummyNode(this.dummyNode);
101     private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
102     private final SchemaPath type = SchemaPath.create(true, this.qname);
103     private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
104
105     @Before
106     public void setUp() throws Exception {
107         MockitoAnnotations.initMocks(this);
108         this.brokerFacade.setDomDataBroker(this.domDataBroker);
109         this.brokerFacade.setDomNotificationService(this.domNotification);
110         this.brokerFacade.setRpcService(this.mockRpcService);
111         this.brokerFacade.setContext(this.context);
112         when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
113         when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
114         when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
115
116         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
117     }
118
119     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> wrapDummyNode(
120             final NormalizedNode<?, ?> dummyNode) {
121         return Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
122     }
123
124     private CheckedFuture<Boolean, ReadFailedException> wrapExistence(final Boolean exists) {
125         return Futures.immediateCheckedFuture(exists);
126     }
127
128     /**
129      * Value of this node shouldn't be important for testing purposes
130      */
131     private NormalizedNode<?, ?> createDummyNode(final String namespace, final String date, final String localName) {
132         return Builders.containerBuilder()
133                 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
134     }
135
136     @Test
137     public void testReadConfigurationData() {
138         when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
139                 this.dummyNodeInFuture);
140
141         final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
142
143         assertSame("readConfigurationData", this.dummyNode, actualNode);
144     }
145
146     @Test
147     public void testReadOperationalData() {
148         when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
149                 this.dummyNodeInFuture);
150
151         final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
152
153         assertSame("readOperationalData", this.dummyNode, actualNode);
154     }
155
156     @Test(expected = RestconfDocumentedException.class)
157     public void testReadOperationalDataWithNoDataBroker() {
158         this.brokerFacade.setDomDataBroker(null);
159
160         this.brokerFacade.readOperationalData(this.instanceID);
161     }
162
163     @Test
164     public void testInvokeRpc() throws Exception {
165         final DOMRpcResult expResult = mock(DOMRpcResult.class);
166         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
167         when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
168
169         final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade
170                 .invokeRpc(this.type, this.dummyNode);
171         assertNotNull("Future is null", actualFuture);
172         final DOMRpcResult actualResult = actualFuture.get();
173         assertSame("invokeRpc", expResult, actualResult);
174     }
175
176     @Test(expected = RestconfDocumentedException.class)
177     public void testInvokeRpcWithNoConsumerSession() {
178         this.brokerFacade.setContext(null);
179         this.brokerFacade.invokeRpc(this.type, this.dummyNode);
180     }
181
182     @Test
183     public void testCommitConfigurationDataPut() throws Exception {
184         @SuppressWarnings("unchecked")
185         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
186         when(this.rwTransaction.submit()).thenReturn(expFuture);
187
188         final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
189         when(optionalMock.get()).thenReturn(null);
190
191         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
192                 .immediateCheckedFuture(optionalMock);
193         when(this.rwTransaction.read(LogicalDatastoreType.CONFIGURATION, this.instanceID)).thenReturn(readFuture);
194
195         final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
196                 this.instanceID, this.dummyNode);
197
198         final Future<Void> actualFuture = result.getFutureOfPutData();
199
200         assertSame("commitConfigurationDataPut", expFuture, actualFuture);
201
202         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
203         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
204         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
205         inOrder.verify(this.rwTransaction).submit();
206     }
207
208     @Test
209     public void testCommitConfigurationDataPost() {
210         @SuppressWarnings("unchecked")
211         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
212
213         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
214                 .thenReturn(wrapExistence(false));
215
216         when(this.rwTransaction.submit()).thenReturn(expFuture);
217
218         final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
219                 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode);
220
221         assertSame("commitConfigurationDataPost", expFuture, actualFuture);
222
223         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
224         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
225         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
226         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
227         inOrder.verify(this.rwTransaction).submit();
228     }
229
230     @Test(expected = RestconfDocumentedException.class)
231     public void testCommitConfigurationDataPostAlreadyExists() {
232         final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
233         when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
234                 .thenReturn(successFuture);
235         try {
236             // Schema context is only necessary for ensuring parent structure
237             this.brokerFacade.commitConfigurationDataPost((SchemaContext) null, this.instanceID, this.dummyNode);
238         } catch (final RestconfDocumentedException e) {
239             assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
240             throw e;
241         }
242     }
243
244     /**
245      * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
246      */
247     @Test
248     public void testCommitConfigurationDataDelete() throws Exception {
249         // assume that data to delete exists
250         prepareDataForDelete(true);
251
252         // expected result
253         @SuppressWarnings("unchecked")
254         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
255         when(this.rwTransaction.submit()).thenReturn(expFuture);
256
257         // test
258         final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
259                 .commitConfigurationDataDelete(this.instanceID);
260
261         // verify result and interactions
262         assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
263
264         // check exists, delete, submit
265         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
266         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
267         inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
268         inOrder.verify(this.rwTransaction).submit();
269     }
270
271     /**
272      * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
273      */
274     @Test
275     public void testCommitConfigurationDataDeleteNoData() throws Exception {
276         // assume that data to delete does not exist
277         prepareDataForDelete(false);
278
279         // try to delete and expect 404 error
280         try {
281             this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
282             fail("Delete operation should fail due to missing data");
283         } catch (final RestconfDocumentedException e) {
284             assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
285             assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
286             assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
287         }
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
294      */
295     private void prepareDataForDelete(final boolean assumeDataExists) {
296         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
297                 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
298     }
299
300     @Test
301     public void testRegisterToListenDataChanges() {
302         final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
303                 NotificationOutputType.XML);
304
305         @SuppressWarnings("unchecked")
306         final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
307
308         when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
309                 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
310
311         this.brokerFacade.registerToListenDataChanges(
312                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
313
314         verify(this.domDataBroker).registerDataChangeListener(
315                 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
316
317         assertEquals("isListening", true, listener.isListening());
318
319         this.brokerFacade.registerToListenDataChanges(
320                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
321         verifyNoMoreInteractions(this.domDataBroker);
322     }
323
324     /**
325      * Create, register, close and remove notification listener.
326      */
327     @Test
328     public void testRegisterToListenNotificationChanges() {
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");
334         final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
335
336         // mock registration
337         final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
338         when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
339                 .thenReturn(registration);
340
341         // test to register listener for the first time
342         this.brokerFacade.registerToListenNotification(listener);
343         assertEquals("Registration was not successful", true, listener.isListening());
344
345         // try to register for the second time
346         this.brokerFacade.registerToListenNotification(listener);
347         assertEquals("Registration was not successful", true, listener.isListening());
348
349         // registrations should be invoked only once
350         verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
351
352         // close and remove test notification listener
353         listener.close();
354         Notificator.removeNotificationListenerIfNoSubscriberExists(listener);
355     }
356
357     /**
358      * Test PATCH method on the server with no data
359      */
360     @Test
361     @SuppressWarnings("unchecked")
362     public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
363         final PATCHContext patchContext = mock(PATCHContext.class);
364         final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
365         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
366
367         when(patchContext.getData()).thenReturn(Lists.newArrayList());
368         when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
369
370         // no mount point
371         when(identifierContext.getMountPoint()).thenReturn(null);
372
373         when(this.rwTransaction.submit()).thenReturn(expFuture);
374
375         final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
376
377         // assert success
378         assertTrue("PATCH operation should be successful on server", status.isOk());
379     }
380
381     /**
382      * Test PATCH method on mounted device with no data
383      */
384     @Test
385     @SuppressWarnings("unchecked")
386     public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
387         final PATCHContext patchContext = mock(PATCHContext.class);
388         final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
389         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
390         final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
391         final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
392         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
393
394         when(patchContext.getData()).thenReturn(Lists.newArrayList());
395         when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
396
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         when(transaction.submit()).thenReturn(expFuture);
402
403         final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
404
405         // assert success
406         assertTrue("PATCH operation should be successful on mounted device", status.isOk());
407     }
408
409     /**
410      * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
411      * PATCH operation should fail with global error.
412      */
413     @Test
414     @SuppressWarnings("unchecked")
415     public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
416         final PATCHContext patchContext = mock(PATCHContext.class);
417         final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
418         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
419         final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
420         final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
421         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
422
423         when(patchContext.getData()).thenReturn(Lists.newArrayList());
424         when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
425         when(identifierContext.getMountPoint()).thenReturn(mountPoint);
426
427         // missing broker on mounted device
428         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
429
430         when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
431         when(transaction.submit()).thenReturn(expFuture);
432
433         final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
434
435         // assert not successful operation with error
436         assertNotNull(status.getGlobalErrors());
437         assertEquals(1, status.getGlobalErrors().size());
438         assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
439         assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
440
441         assertFalse("PATCH operation should fail on mounted device without Broker", status.isOk());
442     }
443 }