Bug 6947 / Bug 6948 - implement point and insert query params
[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, null, null);
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, null, null);
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, null,
238                     null);
239         } catch (final RestconfDocumentedException e) {
240             assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
241             throw e;
242         }
243     }
244
245     /**
246      * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
247      */
248     @Test
249     public void testCommitConfigurationDataDelete() throws Exception {
250         // assume that data to delete exists
251         prepareDataForDelete(true);
252
253         // expected result
254         @SuppressWarnings("unchecked")
255         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
256         when(this.rwTransaction.submit()).thenReturn(expFuture);
257
258         // test
259         final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
260                 .commitConfigurationDataDelete(this.instanceID);
261
262         // verify result and interactions
263         assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
264
265         // check exists, delete, submit
266         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
267         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
268         inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
269         inOrder.verify(this.rwTransaction).submit();
270     }
271
272     /**
273      * Negative test of delete operation when data to delete does not exist. Error 404 should be returned.
274      */
275     @Test
276     public void testCommitConfigurationDataDeleteNoData() throws Exception {
277         // assume that data to delete does not exist
278         prepareDataForDelete(false);
279
280         // try to delete and expect 404 error
281         try {
282             this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
283             fail("Delete operation should fail due to missing data");
284         } catch (final RestconfDocumentedException e) {
285             assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
286             assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
287             assertEquals(404, e.getErrors().get(0).getErrorTag().getStatusCode());
288         }
289     }
290
291     /**
292      * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
293      * {@code assumeDataExists} parameter.
294      * @param assumeDataExists
295      */
296     private void prepareDataForDelete(final boolean assumeDataExists) {
297         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
298                 .thenReturn(Futures.immediateCheckedFuture(new Boolean(assumeDataExists)));
299     }
300
301     @Test
302     public void testRegisterToListenDataChanges() {
303         final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
304                 NotificationOutputType.XML);
305
306         @SuppressWarnings("unchecked")
307         final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
308
309         when(this.domDataBroker.registerDataChangeListener(any(LogicalDatastoreType.class), eq(this.instanceID),
310                 eq(listener), eq(DataChangeScope.BASE))).thenReturn(mockRegistration);
311
312         this.brokerFacade.registerToListenDataChanges(
313                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
314
315         verify(this.domDataBroker).registerDataChangeListener(
316                 LogicalDatastoreType.CONFIGURATION, this.instanceID, listener, DataChangeScope.BASE);
317
318         assertEquals("isListening", true, listener.isListening());
319
320         this.brokerFacade.registerToListenDataChanges(
321                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
322         verifyNoMoreInteractions(this.domDataBroker);
323     }
324
325     /**
326      * Create, register, close and remove notification listener.
327      */
328     @Test
329     public void testRegisterToListenNotificationChanges() {
330         // create test notification listener
331         final String identifier = "create-notification-stream/toaster:toastDone";
332         final SchemaPath path = SchemaPath.create(true,
333                 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
334         Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
335         final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
336
337         // mock registration
338         final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
339         when(this.domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
340                 .thenReturn(registration);
341
342         // test to register listener for the first time
343         this.brokerFacade.registerToListenNotification(listener);
344         assertEquals("Registration was not successful", true, listener.isListening());
345
346         // try to register for the second time
347         this.brokerFacade.registerToListenNotification(listener);
348         assertEquals("Registration was not successful", true, listener.isListening());
349
350         // registrations should be invoked only once
351         verify(this.domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
352
353         // close and remove test notification listener
354         listener.close();
355         Notificator.removeNotificationListenerIfNoSubscriberExists(listener);
356     }
357
358     /**
359      * Test PATCH method on the server with no data
360      */
361     @Test
362     @SuppressWarnings("unchecked")
363     public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
364         final PATCHContext patchContext = mock(PATCHContext.class);
365         final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
366         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
367
368         when(patchContext.getData()).thenReturn(Lists.newArrayList());
369         when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
370
371         // no mount point
372         when(identifierContext.getMountPoint()).thenReturn(null);
373
374         when(this.rwTransaction.submit()).thenReturn(expFuture);
375
376         final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
377
378         // assert success
379         assertTrue("PATCH operation should be successful on server", status.isOk());
380     }
381
382     /**
383      * Test PATCH method on mounted device with no data
384      */
385     @Test
386     @SuppressWarnings("unchecked")
387     public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
388         final PATCHContext patchContext = mock(PATCHContext.class);
389         final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
390         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
391         final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
392         final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
393         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
394
395         when(patchContext.getData()).thenReturn(Lists.newArrayList());
396         when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
397
398         // return mount point with broker
399         when(identifierContext.getMountPoint()).thenReturn(mountPoint);
400         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
401         when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
402         when(transaction.submit()).thenReturn(expFuture);
403
404         final PATCHStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
405
406         // assert success
407         assertTrue("PATCH operation should be successful on mounted device", status.isOk());
408     }
409
410     /**
411      * Negative test for PATCH operation when mounted device does not support {@link DOMDataBroker service.
412      * PATCH operation should fail with global error.
413      */
414     @Test
415     @SuppressWarnings("unchecked")
416     public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
417         final PATCHContext patchContext = mock(PATCHContext.class);
418         final InstanceIdentifierContext identifierContext = mock(InstanceIdentifierContext.class);
419         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
420         final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
421         final DOMDataReadWriteTransaction transaction = mock(DOMDataReadWriteTransaction.class);
422         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = Futures.immediateCheckedFuture(null);
423
424         when(patchContext.getData()).thenReturn(Lists.newArrayList());
425         when(patchContext.getInstanceIdentifierContext()).thenReturn(identifierContext);
426         when(identifierContext.getMountPoint()).thenReturn(mountPoint);
427
428         // missing broker on mounted device
429         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.absent());
430
431         when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
432         when(transaction.submit()).thenReturn(expFuture);
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 }