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