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