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