c39251394b8850ec377ef2957e705eddca87deba
[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.ImmutableList;
32 import com.google.common.collect.Lists;
33 import com.google.common.util.concurrent.FluentFuture;
34 import com.google.common.util.concurrent.ListenableFuture;
35 import java.util.ArrayList;
36 import java.util.Optional;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.junit.runner.RunWith;
40 import org.mockito.InOrder;
41 import org.mockito.Mock;
42 import org.mockito.Mockito;
43 import org.mockito.junit.MockitoJUnitRunner;
44 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
45 import org.opendaylight.mdsal.common.api.CommitInfo;
46 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
47 import org.opendaylight.mdsal.common.api.ReadFailedException;
48 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
49 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
51 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
52 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
53 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
54 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
55 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
56 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
57 import org.opendaylight.mdsal.dom.api.DOMRpcService;
58 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
59 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
60 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
61 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
62 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
63 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
64 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
66 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
67 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
68 import org.opendaylight.restconf.common.errors.RestconfError;
69 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
70 import org.opendaylight.restconf.common.patch.PatchContext;
71 import org.opendaylight.restconf.common.patch.PatchStatusContext;
72 import org.opendaylight.restconf.common.util.DataChangeScope;
73 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
74 import org.opendaylight.yangtools.concepts.ListenerRegistration;
75 import org.opendaylight.yangtools.yang.common.ErrorType;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.RpcError;
78 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
79 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
80 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
81 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
82 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
83 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
84 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
85 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
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(this.dummyNode);
113     private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
114     private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.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(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
125         when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
126         when(this.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(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         doReturn(immediateFailedFluentFuture(new ReadFailedException("Read from transaction failed", error)))
174                 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
175         try {
176             brokerFacade.readConfigurationData(this.instanceID, "explicit");
177             fail("This test should fail.");
178         } catch (final RestconfDocumentedException e) {
179             assertEquals("getErrorTag", ErrorTag.RESOURCE_DENIED_TRANSPORT, e.getErrors().get(0).getErrorTag());
180             assertEquals("getErrorType", ErrorType.TRANSPORT, e.getErrors().get(0).getErrorType());
181             assertEquals("getErrorMessage", "Master is down. Please try again.",
182                     e.getErrors().get(0).getErrorMessage());
183         }
184     }
185
186     @Test
187     public void testInvokeRpc() throws Exception {
188         final DOMRpcResult expResult = mock(DOMRpcResult.class);
189         doReturn(immediateFluentFuture(expResult)).when(this.mockRpcService).invokeRpc(this.qname, this.dummyNode);
190
191         final ListenableFuture<? extends DOMRpcResult> actualFuture = this.brokerFacade.invokeRpc(this.qname,
192             this.dummyNode);
193         assertNotNull("Future is null", actualFuture);
194         final DOMRpcResult actualResult = actualFuture.get();
195         assertSame("invokeRpc", expResult, actualResult);
196     }
197
198     @Test
199     public void testCommitConfigurationDataPut() throws Exception {
200         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
201
202         doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(this.rwTransaction)
203         .read(LogicalDatastoreType.CONFIGURATION, this.instanceID);
204
205         final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(EffectiveModelContext.class),
206                 this.instanceID, this.dummyNode, null, null);
207
208         assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
209
210         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
211         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
212         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
213         inOrder.verify(this.rwTransaction).commit();
214     }
215
216     @Test
217     public void testCommitConfigurationDataPost() {
218         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
219                 .thenReturn(wrapExistence(false));
220
221         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
222
223         final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
224                 .commitConfigurationDataPost(mock(EffectiveModelContext.class), this.instanceID, this.dummyNode, null,
225                         null);
226
227         assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
228
229         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
230         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
231         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
232         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
233         inOrder.verify(this.rwTransaction).commit();
234     }
235
236     @Test(expected = RestconfDocumentedException.class)
237     public void testCommitConfigurationDataPostAlreadyExists() {
238         when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
239                 .thenReturn(immediateTrueFluentFuture());
240         try {
241             // Schema context is only necessary for ensuring parent structure
242             this.brokerFacade.commitConfigurationDataPost((EffectiveModelContext) null, this.instanceID, this.dummyNode,
243                     null, null);
244         } catch (final RestconfDocumentedException e) {
245             assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
246             throw e;
247         }
248     }
249
250     /**
251      * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
252      */
253     @Test
254     public void testCommitConfigurationDataDelete() throws Exception {
255         // assume that data to delete exists
256         prepareDataForDelete(true);
257
258         // expected result
259         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
260
261         // test
262         final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
263                 .commitConfigurationDataDelete(this.instanceID);
264
265         // verify result and interactions
266         assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
267
268         // check exists, delete, submit
269         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
270         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
271         inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
272         inOrder.verify(this.rwTransaction).commit();
273     }
274
275     /**
276      * Negative test of delete operation when data to delete does not exist. Error DATA_MISSING should be returned.
277      */
278     @Test
279     public void testCommitConfigurationDataDeleteNoData() throws Exception {
280         // assume that data to delete does not exist
281         prepareDataForDelete(false);
282
283         // try to delete and expect DATA_MISSING error
284         try {
285             this.brokerFacade.commitConfigurationDataDelete(this.instanceID);
286             fail("Delete operation should fail due to missing data");
287         } catch (final RestconfDocumentedException e) {
288             assertEquals(ErrorType.PROTOCOL, e.getErrors().get(0).getErrorType());
289             assertEquals(ErrorTag.DATA_MISSING, e.getErrors().get(0).getErrorTag());
290         }
291     }
292
293     /**
294      * Prepare conditions to test delete operation. Data to delete exists or does not exist according to value of
295      * {@code assumeDataExists} parameter.
296      * @param assumeDataExists boolean to assume if data exists
297      */
298     private void prepareDataForDelete(final boolean assumeDataExists) {
299         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
300                 .thenReturn(immediateBooleanFluentFuture(assumeDataExists));
301     }
302
303     @Test
304     public void testRegisterToListenDataChanges() {
305         final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream",
306                 NotificationOutputType.XML, controllerContext);
307
308         @SuppressWarnings("unchecked")
309         final ListenerRegistration<ListenerAdapter> mockRegistration = mock(ListenerRegistration.class);
310
311         DOMDataTreeChangeService changeService = this.domDataBroker.getExtensions()
312                 .getInstance(DOMDataTreeChangeService.class);
313         DOMDataTreeIdentifier loc = new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, this.instanceID);
314         when(changeService.registerDataTreeChangeListener(eq(loc), eq(listener))).thenReturn(mockRegistration);
315
316         this.brokerFacade.registerToListenDataChanges(
317                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
318
319         verify(changeService).registerDataTreeChangeListener(loc, listener);
320
321         assertEquals("isListening", true, listener.isListening());
322
323         this.brokerFacade.registerToListenDataChanges(
324                 LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
325         verifyNoMoreInteractions(changeService);
326     }
327
328     /**
329      * Create, register, close and remove notification listener.
330      */
331     @Test
332     public void testRegisterToListenNotificationChanges() throws Exception {
333         // create test notification listener
334         final String identifier = "create-notification-stream/toaster:toastDone";
335         final SchemaPath path = SchemaPath.create(true,
336                 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
337         Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML", controllerContext);
338         final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
339
340         // mock registration
341         final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
342         when(this.domNotification.registerNotificationListener(listener,
343             Absolute.of(ImmutableList.copyOf(listener.getSchemaPath().getPathFromRoot()))))
344                 .thenReturn(registration);
345
346         // test to register listener for the first time
347         this.brokerFacade.registerToListenNotification(listener);
348         assertEquals("Registration was not successful", true, listener.isListening());
349
350         // try to register for the second time
351         this.brokerFacade.registerToListenNotification(listener);
352         assertEquals("Registration was not successful", true, listener.isListening());
353
354         // registrations should be invoked only once
355         verify(this.domNotification, times(1)).registerNotificationListener(listener,
356             Absolute.of(ImmutableList.copyOf(listener.getSchemaPath().getPathFromRoot())));
357
358         final DOMTransactionChain transactionChain = mock(DOMTransactionChain.class);
359         final DOMDataTreeWriteTransaction wTx = mock(DOMDataTreeWriteTransaction.class);
360         // close and remove test notification listener
361         listener.close();
362         Notificator.removeListenerIfNoSubscriberExists(listener);
363     }
364
365     /**
366      * Test Patch method on the server with no data.
367      */
368     @Test
369     public void testPatchConfigurationDataWithinTransactionServer() throws Exception {
370         final PatchContext patchContext = mock(PatchContext.class);
371         final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
372
373         when(patchContext.getData()).thenReturn(new ArrayList<>());
374         doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
375
376         // no mount point
377         when(identifierContext.getMountPoint()).thenReturn(null);
378
379         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
380
381         final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
382
383         // assert success
384         assertTrue("Patch operation should be successful on server", status.isOk());
385     }
386
387     /**
388      * Test Patch method on mounted device with no data.
389      */
390     @Test
391     public void testPatchConfigurationDataWithinTransactionMount() throws Exception {
392         final PatchContext patchContext = mock(PatchContext.class);
393         final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
394         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
395         final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
396         final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
397
398         when(patchContext.getData()).thenReturn(new ArrayList<>());
399         doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
400
401         // return mount point with broker
402         when(identifierContext.getMountPoint()).thenReturn(mountPoint);
403         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.of(mountDataBroker));
404         when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
405         when(mountDataBroker.newReadWriteTransaction()).thenReturn(transaction);
406         doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit();
407
408         final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
409
410         // assert success
411         assertTrue("Patch operation should be successful on mounted device", status.isOk());
412     }
413
414     /**
415      * Negative test for Patch operation when mounted device does not support {@link DOMDataBroker service.}
416      * Patch operation should fail with global error.
417      */
418     @Test
419     public void testPatchConfigurationDataWithinTransactionMountFail() throws Exception {
420         final PatchContext patchContext = mock(PatchContext.class);
421         final InstanceIdentifierContext<?> identifierContext = mock(InstanceIdentifierContext.class);
422         final DOMMountPoint mountPoint = mock(DOMMountPoint.class);
423         final DOMDataBroker mountDataBroker = mock(DOMDataBroker.class);
424         final DOMDataTreeReadWriteTransaction transaction = mock(DOMDataTreeReadWriteTransaction.class);
425
426         doReturn(identifierContext).when(patchContext).getInstanceIdentifierContext();
427         when(identifierContext.getMountPoint()).thenReturn(mountPoint);
428
429         // missing broker on mounted device
430         when(mountPoint.getService(DOMDataBroker.class)).thenReturn(Optional.empty());
431         when(mountPoint.getService(DOMSchemaService.class)).thenReturn(Optional.empty());
432
433
434         final PatchStatusContext status = this.brokerFacade.patchConfigurationDataWithinTransaction(patchContext);
435
436         // assert not successful operation with error
437         assertNotNull(status.getGlobalErrors());
438         assertEquals(1, status.getGlobalErrors().size());
439         assertEquals(ErrorType.APPLICATION, status.getGlobalErrors().get(0).getErrorType());
440         assertEquals(ErrorTag.OPERATION_FAILED, status.getGlobalErrors().get(0).getErrorTag());
441
442         assertFalse("Patch operation should fail on mounted device without Broker", status.isOk());
443     }
444 }