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