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