Remove RestconfError.ErrorTag
[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.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.List;
37 import java.util.Optional;
38 import org.junit.Before;
39 import org.junit.Test;
40 import org.junit.runner.RunWith;
41 import org.mockito.InOrder;
42 import org.mockito.Mock;
43 import org.mockito.Mockito;
44 import org.mockito.junit.MockitoJUnitRunner;
45 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
46 import org.opendaylight.mdsal.common.api.CommitInfo;
47 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
48 import org.opendaylight.mdsal.common.api.ReadFailedException;
49 import org.opendaylight.mdsal.dom.api.DOMDataBroker;
50 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
51 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
52 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
53 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
54 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
55 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
56 import org.opendaylight.mdsal.dom.api.DOMNotificationService;
57 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
58 import org.opendaylight.mdsal.dom.api.DOMRpcService;
59 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
60 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
61 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
62 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
63 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
64 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
65 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
66 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
67 import org.opendaylight.restconf.common.ErrorTags;
68 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
69 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
70 import org.opendaylight.restconf.common.errors.RestconfError;
71 import org.opendaylight.restconf.common.patch.PatchContext;
72 import org.opendaylight.restconf.common.patch.PatchStatusContext;
73 import org.opendaylight.restconf.common.util.DataChangeScope;
74 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
75 import org.opendaylight.yangtools.concepts.ListenerRegistration;
76 import org.opendaylight.yangtools.yang.common.ErrorTag;
77 import org.opendaylight.yangtools.yang.common.ErrorType;
78 import org.opendaylight.yangtools.yang.common.QName;
79 import org.opendaylight.yangtools.yang.common.RpcError;
80 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
81 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
82 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
83 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
84 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
85 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
86 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
87 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
88
89 /**
90  * Unit tests for BrokerFacade.
91  *
92  * @author Thomas Pantelis
93  */
94 @RunWith(MockitoJUnitRunner.StrictStubs.class)
95 public class BrokerFacadeTest {
96
97     @Mock
98     private DOMDataBroker domDataBroker;
99     @Mock
100     private DOMNotificationService domNotification;
101     @Mock
102     private DOMRpcService mockRpcService;
103     @Mock
104     private DOMMountPoint mockMountInstance;
105     @Mock
106     private DOMDataTreeReadTransaction readTransaction;
107     @Mock
108     private DOMDataTreeWriteTransaction writeTransaction;
109     @Mock
110     private DOMDataTreeReadWriteTransaction rwTransaction;
111
112     private BrokerFacade brokerFacade;
113     private final NormalizedNode dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
114     private final FluentFuture<Optional<NormalizedNode>> dummyNodeInFuture = wrapDummyNode(this.dummyNode);
115     private final QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
116     private final YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
117     private ControllerContext controllerContext;
118
119     @Before
120     public void setUp() throws Exception {
121         controllerContext = TestRestconfUtils.newControllerContext(
122                 TestUtils.loadSchemaContext("/full-versions/test-module", "/modules"));
123
124         brokerFacade = BrokerFacade.newInstance(mockRpcService, domDataBroker, domNotification, controllerContext);
125
126         when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.readTransaction);
127         when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
128         when(this.domDataBroker.getExtensions()).thenReturn(ImmutableClassToInstanceMap.of(
129             DOMDataTreeChangeService.class, Mockito.mock(DOMDataTreeChangeService.class)));
130     }
131
132     private static FluentFuture<Optional<NormalizedNode>> wrapDummyNode(final NormalizedNode dummyNode) {
133         return immediateFluentFuture(Optional.of(dummyNode));
134     }
135
136     private static FluentFuture<Boolean> wrapExistence(final boolean exists) {
137         return immediateBooleanFluentFuture(exists);
138     }
139
140     /**
141      * Value of this node shouldn't be important for testing purposes.
142      */
143     private static NormalizedNode createDummyNode(final String namespace, final String date, final String localName) {
144         return Builders.containerBuilder()
145                 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName)))
146                 .build();
147     }
148
149     @Test
150     public void testReadConfigurationData() {
151         when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
152                 this.dummyNodeInFuture);
153
154         final NormalizedNode actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
155
156         assertSame("readConfigurationData", this.dummyNode, actualNode);
157     }
158
159     @Test
160     public void testReadOperationalData() {
161         when(this.readTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
162                 this.dummyNodeInFuture);
163
164         final NormalizedNode actualNode = this.brokerFacade.readOperationalData(this.instanceID);
165
166         assertSame("readOperationalData", this.dummyNode, actualNode);
167     }
168
169     @Test
170     public void test503() throws Exception {
171         final RpcError error = RpcResultBuilder.newError(
172                 RpcError.ErrorType.TRANSPORT,
173                 ErrorTag.RESOURCE_DENIED.elementBody(),
174                 "Master is down. Please try again.");
175         doReturn(immediateFailedFluentFuture(new ReadFailedException("Read from transaction failed", error)))
176                 .when(readTransaction).read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class));
177
178         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
179             () -> brokerFacade.readConfigurationData(this.instanceID, "explicit"));
180         final List<RestconfError> errors = ex.getErrors();
181         assertEquals(1, errors.size());
182         assertEquals("getErrorTag", ErrorTags.RESOURCE_DENIED_TRANSPORT, errors.get(0).getErrorTag());
183         assertEquals("getErrorType", ErrorType.TRANSPORT,errors.get(0).getErrorType());
184         assertEquals("getErrorMessage", "Master is down. Please try again.", errors.get(0).getErrorMessage());
185     }
186
187     @Test
188     public void testInvokeRpc() throws Exception {
189         final DOMRpcResult expResult = mock(DOMRpcResult.class);
190         doReturn(immediateFluentFuture(expResult)).when(this.mockRpcService).invokeRpc(this.qname, this.dummyNode);
191
192         final ListenableFuture<? extends DOMRpcResult> actualFuture = this.brokerFacade.invokeRpc(this.qname,
193             this.dummyNode);
194         assertNotNull("Future is null", actualFuture);
195         final DOMRpcResult actualResult = actualFuture.get();
196         assertSame("invokeRpc", expResult, actualResult);
197     }
198
199     @Test
200     public void testCommitConfigurationDataPut() throws Exception {
201         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
202
203         doReturn(immediateFluentFuture(Optional.of(mock(NormalizedNode.class)))).when(this.rwTransaction)
204         .read(LogicalDatastoreType.CONFIGURATION, this.instanceID);
205
206         final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(EffectiveModelContext.class),
207                 this.instanceID, this.dummyNode, null, null);
208
209         assertSame("commitConfigurationDataPut", CommitInfo.emptyFluentFuture(), result.getFutureOfPutData());
210
211         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
212         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
213         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
214         inOrder.verify(this.rwTransaction).commit();
215     }
216
217     @Test
218     public void testCommitConfigurationDataPost() {
219         when(this.rwTransaction.exists(LogicalDatastoreType.CONFIGURATION, this.instanceID))
220                 .thenReturn(wrapExistence(false));
221
222         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
223
224         final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
225                 .commitConfigurationDataPost(mock(EffectiveModelContext.class), this.instanceID, this.dummyNode, null,
226                         null);
227
228         assertSame("commitConfigurationDataPost", CommitInfo.emptyFluentFuture(), actualFuture);
229
230         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
231         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
232         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
233         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
234         inOrder.verify(this.rwTransaction).commit();
235     }
236
237     @Test(expected = RestconfDocumentedException.class)
238     public void testCommitConfigurationDataPostAlreadyExists() {
239         when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class)))
240                 .thenReturn(immediateTrueFluentFuture());
241         try {
242             // Schema context is only necessary for ensuring parent structure
243             this.brokerFacade.commitConfigurationDataPost((EffectiveModelContext) null, this.instanceID, this.dummyNode,
244                     null, null);
245         } catch (final RestconfDocumentedException e) {
246             assertEquals("getErrorTag", ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
247             throw e;
248         }
249     }
250
251     /**
252      * Positive test of delete operation when data to delete exits. Returned value and order of steps are validated.
253      */
254     @Test
255     public void testCommitConfigurationDataDelete() throws Exception {
256         // assume that data to delete exists
257         prepareDataForDelete(true);
258
259         // expected result
260         doReturn(CommitInfo.emptyFluentFuture()).when(this.rwTransaction).commit();
261
262         // test
263         final FluentFuture<? extends CommitInfo> actualFuture = this.brokerFacade
264                 .commitConfigurationDataDelete(this.instanceID);
265
266         // verify result and interactions
267         assertSame("commitConfigurationDataDelete", CommitInfo.emptyFluentFuture(), actualFuture);
268
269         // check exists, delete, submit
270         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
271         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
272         inOrder.verify(this.rwTransaction).delete(LogicalDatastoreType.CONFIGURATION, this.instanceID);
273         inOrder.verify(this.rwTransaction).commit();
274     }
275
276     /**
277      * Negative test of delete operation when data to delete does not exist. Error DATA_MISSING should be returned.
278      */
279     @Test
280     public void testCommitConfigurationDataDeleteNoData() throws Exception {
281         // assume that data to delete does not exist
282         prepareDataForDelete(false);
283
284         // try to delete and expect DATA_MISSING error
285         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
286             () -> brokerFacade.commitConfigurationDataDelete(this.instanceID));
287         final List<RestconfError> errors = ex.getErrors();
288         assertEquals(1, errors.size());
289         assertEquals(ErrorType.PROTOCOL, errors.get(0).getErrorType());
290         assertEquals(ErrorTag.DATA_MISSING, errors.get(0).getErrorTag());
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 }