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