Bug 2594 - PUT method returns wrong status for create resource
[netconf.git] / restconf / sal-rest-connector / 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.assertNotNull;
13 import static org.junit.Assert.assertSame;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.eq;
16 import static org.mockito.Mockito.inOrder;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.times;
19 import static org.mockito.Mockito.verify;
20 import static org.mockito.Mockito.verifyNoMoreInteractions;
21 import static org.mockito.Mockito.when;
22
23 import com.google.common.base.Optional;
24 import com.google.common.collect.Lists;
25 import com.google.common.util.concurrent.CheckedFuture;
26 import com.google.common.util.concurrent.Futures;
27 import java.util.concurrent.Future;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.mockito.InOrder;
31 import org.mockito.Mock;
32 import org.mockito.MockitoAnnotations;
33 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
34 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
35 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
36 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
37 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
38 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
39 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
40 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
41 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
42 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
43 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
44 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
47 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
48 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
49 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
50 import org.opendaylight.netconf.sal.restconf.impl.PutResult;
51 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
52 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
53 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
54 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
55 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
56 import org.opendaylight.yangtools.concepts.ListenerRegistration;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
64
65 /**
66  * Unit tests for BrokerFacade.
67  *
68  * @author Thomas Pantelis
69  */
70 public class BrokerFacadeTest {
71
72     @Mock
73     DOMDataBroker domDataBroker;
74
75     @Mock
76     DOMNotificationService domNotification;
77
78     @Mock
79     ConsumerSession context;
80
81     @Mock
82     DOMRpcService mockRpcService;
83
84     @Mock
85     DOMMountPoint mockMountInstance;
86
87     BrokerFacade brokerFacade = BrokerFacade.getInstance();
88
89     NormalizedNode<?, ?> dummyNode = createDummyNode("test:module", "2014-01-09", "interfaces");
90     CheckedFuture<Optional<NormalizedNode<?, ?>>,ReadFailedException> dummyNodeInFuture = wrapDummyNode(this.dummyNode);
91
92     QName qname = TestUtils.buildQName("interfaces","test:module", "2014-01-09");
93
94     SchemaPath type = SchemaPath.create(true, this.qname);
95
96     YangInstanceIdentifier instanceID = YangInstanceIdentifier.builder().node(this.qname).build();
97
98     @Mock
99     DOMDataReadOnlyTransaction rTransaction;
100
101     @Mock
102     DOMDataWriteTransaction wTransaction;
103
104     @Mock
105     DOMDataReadWriteTransaction rwTransaction;
106
107     @Before
108     public void setUp() throws Exception {
109         MockitoAnnotations.initMocks(this);
110         // TODO it is started before every test method
111         this.brokerFacade.setDomDataBroker(this.domDataBroker);
112         this.brokerFacade.setDomNotificationService(this.domNotification);
113         this.brokerFacade.setRpcService(this.mockRpcService);
114         this.brokerFacade.setContext(this.context);
115         when(this.domDataBroker.newReadOnlyTransaction()).thenReturn(this.rTransaction);
116         when(this.domDataBroker.newWriteOnlyTransaction()).thenReturn(this.wTransaction);
117         when(this.domDataBroker.newReadWriteTransaction()).thenReturn(this.rwTransaction);
118
119         ControllerContext.getInstance().setSchemas(TestUtils.loadSchemaContext("/full-versions/test-module"));
120     }
121
122     private CheckedFuture<Optional<NormalizedNode<?, ?>>,ReadFailedException> wrapDummyNode(
123             final NormalizedNode<?, ?> dummyNode) {
124         return  Futures.immediateCheckedFuture(Optional.<NormalizedNode<?, ?>> of(dummyNode));
125     }
126
127     private CheckedFuture<Boolean,ReadFailedException> wrapExistence(final Boolean exists) {
128         return  Futures.immediateCheckedFuture(exists);
129     }
130
131
132     /**
133      * Value of this node shouldn't be important for testing purposes
134      */
135     private NormalizedNode<?, ?> createDummyNode(final String namespace, final String date, final String localName) {
136         return Builders.containerBuilder()
137                 .withNodeIdentifier(new NodeIdentifier(QName.create(namespace, date, localName))).build();
138     }
139
140     @Test
141     public void testReadConfigurationData() {
142         when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
143                 this.dummyNodeInFuture);
144
145         final NormalizedNode<?, ?> actualNode = this.brokerFacade.readConfigurationData(this.instanceID);
146
147         assertSame("readConfigurationData", this.dummyNode, actualNode);
148     }
149
150     @Test
151     public void testReadOperationalData() {
152         when(this.rTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class))).thenReturn(
153                 this.dummyNodeInFuture);
154
155         final NormalizedNode<?, ?> actualNode = this.brokerFacade.readOperationalData(this.instanceID);
156
157         assertSame("readOperationalData", this.dummyNode, actualNode);
158     }
159
160     @Test(expected = RestconfDocumentedException.class)
161     public void testReadOperationalDataWithNoDataBroker() {
162         this.brokerFacade.setDomDataBroker(null);
163
164         this.brokerFacade.readOperationalData(this.instanceID);
165     }
166
167     @Test
168     public void testInvokeRpc() throws Exception {
169         final DOMRpcResult expResult = mock(DOMRpcResult.class);
170         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
171         when(this.mockRpcService.invokeRpc(this.type, this.dummyNode)).thenReturn(future);
172
173         final CheckedFuture<DOMRpcResult, DOMRpcException> actualFuture = this.brokerFacade.invokeRpc(
174                 this.type, this.dummyNode);
175         assertNotNull("Future is null", actualFuture);
176         final DOMRpcResult actualResult = actualFuture.get();
177         assertSame("invokeRpc", expResult, actualResult);
178     }
179
180     @Test(expected = RestconfDocumentedException.class)
181     public void testInvokeRpcWithNoConsumerSession() {
182         this.brokerFacade.setContext(null);
183         this.brokerFacade.invokeRpc(this.type, this.dummyNode);
184     }
185
186     @Test
187     public void testCommitConfigurationDataPut() throws Exception {
188         @SuppressWarnings("unchecked")
189         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
190         when(this.rwTransaction.submit()).thenReturn(expFuture);
191
192         final Optional<NormalizedNode<?, ?>> optionalMock = mock(Optional.class);
193         when(optionalMock.get()).thenReturn(null);
194         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = Futures
195                 .immediateCheckedFuture(optionalMock);
196         when(this.rwTransaction.read(any(LogicalDatastoreType.class), any(YangInstanceIdentifier.class)))
197                 .thenReturn(readFuture);
198
199         final PutResult result = this.brokerFacade.commitConfigurationDataPut(mock(SchemaContext.class),
200                 this.instanceID, this.dummyNode);
201         final Future<Void> actualFuture = result.getFutureOfPutData();
202
203         assertSame("commitConfigurationDataPut", expFuture, actualFuture);
204
205         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
206         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
207         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
208         inOrder.verify(this.rwTransaction).submit();
209     }
210
211     @Test
212     public void testCommitConfigurationDataPost() {
213         @SuppressWarnings("unchecked")
214         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
215
216         when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class))).thenReturn(
217             wrapExistence(false));
218
219
220         when(this.rwTransaction.submit()).thenReturn(expFuture);
221
222         final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
223                 .commitConfigurationDataPost(mock(SchemaContext.class), this.instanceID, this.dummyNode);
224
225         assertSame("commitConfigurationDataPost", expFuture, actualFuture);
226
227         final InOrder inOrder = inOrder(this.domDataBroker, this.rwTransaction);
228         inOrder.verify(this.domDataBroker).newReadWriteTransaction();
229         inOrder.verify(this.rwTransaction).exists(LogicalDatastoreType.CONFIGURATION, this.instanceID);
230         inOrder.verify(this.rwTransaction).put(LogicalDatastoreType.CONFIGURATION, this.instanceID, this.dummyNode);
231         inOrder.verify(this.rwTransaction).submit();
232     }
233
234     @Test(expected = RestconfDocumentedException.class)
235     public void testCommitConfigurationDataPostAlreadyExists() {
236         final CheckedFuture<Boolean, ReadFailedException> successFuture = Futures.immediateCheckedFuture(Boolean.TRUE);
237         when(this.rwTransaction.exists(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class))).thenReturn(
238                 successFuture);
239         try {
240             // Schema context is only necessary for ensuring parent structure
241             this.brokerFacade.commitConfigurationDataPost((SchemaContext)null, this.instanceID, this.dummyNode);
242         } catch (final RestconfDocumentedException e) {
243             assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
244             throw e;
245         }
246     }
247
248     @Test
249     public void testCommitConfigurationDataDelete() {
250         @SuppressWarnings("unchecked")
251         final CheckedFuture<Void, TransactionCommitFailedException> expFuture = mock(CheckedFuture.class);
252
253         when(this.wTransaction.submit()).thenReturn(expFuture);
254
255         final CheckedFuture<Void, TransactionCommitFailedException> actualFuture = this.brokerFacade
256                 .commitConfigurationDataDelete(this.instanceID);
257
258         assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
259
260         final InOrder inOrder = inOrder(this.domDataBroker, this.wTransaction);
261         inOrder.verify(this.domDataBroker).newWriteOnlyTransaction();
262         inOrder.verify(this.wTransaction).delete(eq(LogicalDatastoreType.CONFIGURATION), any(YangInstanceIdentifier.class));
263         inOrder.verify(this.wTransaction).submit();
264     }
265
266     @SuppressWarnings("unchecked")
267     @Test
268     public void testRegisterToListenDataChanges() {
269         final ListenerAdapter listener = Notificator.createListener(this.instanceID, "stream");
270
271         final ListenerRegistration<DOMDataChangeListener> mockRegistration = mock(ListenerRegistration.class);
272
273         when(this.domDataBroker.registerDataChangeListener(
274                 any(LogicalDatastoreType.class), eq(this.instanceID), eq(listener), eq(DataChangeScope.BASE)))
275                 .thenReturn(mockRegistration);
276
277         this.brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION, DataChangeScope.BASE, listener);
278
279         verify(this.domDataBroker).registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, this.instanceID, listener,
280                 DataChangeScope.BASE);
281
282         assertEquals("isListening", true, listener.isListening());
283
284         this.brokerFacade.registerToListenDataChanges(LogicalDatastoreType.CONFIGURATION,
285                 DataChangeScope.BASE, listener);
286         verifyNoMoreInteractions(this.domDataBroker);
287     }
288
289     /**
290      * Create, register, close and remove notification listener.
291      */
292     @Test
293     public void testRegisterToListenNotificationChanges() {
294         // create test notification listener
295         final String identifier = "create-notification-stream/toaster:toastDone";
296         final SchemaPath path = SchemaPath.create(true,
297                 QName.create("http://netconfcentral.org/ns/toaster", "2009-11-20", "toastDone"));
298         Notificator.createNotificationListener(Lists.newArrayList(path), identifier, "XML");
299         final NotificationListenerAdapter listener = Notificator.getNotificationListenerFor(identifier).get(0);
300
301         // mock registration
302         final ListenerRegistration<NotificationListenerAdapter> registration = mock(ListenerRegistration.class);
303         when(domNotification.registerNotificationListener(listener, listener.getSchemaPath()))
304                 .thenReturn(registration);
305
306         // test to register listener for the first time
307         brokerFacade.registerToListenNotification(listener);
308         assertEquals("Registration was not successful", true, listener.isListening());
309
310         // try to register for the second time
311         brokerFacade.registerToListenNotification(listener);
312         assertEquals("Registration was not successful", true, listener.isListening());
313
314         // registrations should be invoked only once
315         verify(domNotification, times(1)).registerNotificationListener(listener, listener.getSchemaPath());
316
317         // close and remove test notification listener
318         listener.close();
319         Notificator.removeNotificationListenerIfNoSubscriberExists(listener);
320     }
321 }