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