Bug 2834: Fix Restconf POST to wait for completion
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / RestPostOperationTest.java
1 /*
2  * Copyright (c) 2014 Cisco 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.mockito.Matchers.any;
12 import static org.mockito.Mockito.doReturn;
13 import static org.mockito.Mockito.doThrow;
14 import static org.mockito.Mockito.mock;
15 import static org.mockito.Mockito.times;
16 import static org.mockito.Mockito.verify;
17 import static org.mockito.Mockito.when;
18 import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUtils.XML;
19 import com.google.common.base.Optional;
20 import com.google.common.collect.ImmutableList;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.Futures;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.UnsupportedEncodingException;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.text.ParseException;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.Set;
34 import javax.ws.rs.client.Entity;
35 import javax.ws.rs.core.Application;
36 import javax.ws.rs.core.MediaType;
37 import org.glassfish.jersey.server.ResourceConfig;
38 import org.glassfish.jersey.test.JerseyTest;
39 import org.junit.BeforeClass;
40 import org.junit.Ignore;
41 import org.junit.Test;
42 import org.mockito.ArgumentCaptor;
43 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
44 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
45 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
46 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
47 import org.opendaylight.controller.sal.rest.api.Draft02;
48 import org.opendaylight.controller.sal.rest.impl.JsonNormalizedNodeBodyReader;
49 import org.opendaylight.controller.sal.rest.impl.NormalizedNodeJsonBodyWriter;
50 import org.opendaylight.controller.sal.rest.impl.NormalizedNodeXmlBodyWriter;
51 import org.opendaylight.controller.sal.rest.impl.RestconfDocumentedExceptionMapper;
52 import org.opendaylight.controller.sal.rest.impl.XmlNormalizedNodeBodyReader;
53 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
54 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
55 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
56 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
58 import org.opendaylight.yangtools.yang.common.RpcError;
59 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
60 import org.opendaylight.yangtools.yang.common.RpcResult;
61 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
62 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.model.api.Module;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67
68 public class RestPostOperationTest extends JerseyTest {
69
70     private static String xmlDataAbsolutePath;
71     private static String xmlDataInterfaceAbsolutePath;
72     private static String xmlDataRpcInput;
73     private static String xmlBlockData;
74     private static String xmlTestInterface;
75     private static CompositeNodeWrapper cnSnDataOutput;
76     private static String xmlData3;
77     private static String xmlData4;
78
79     private static BrokerFacade brokerFacade;
80     private static RestconfImpl restconfImpl;
81     private static SchemaContext schemaContextYangsIetf;
82     private static SchemaContext schemaContextTestModule;
83     private static SchemaContext schemaContext;
84
85     private static DOMMountPointService mountService;
86
87     @BeforeClass
88     public static void init() throws URISyntaxException, IOException {
89         schemaContextYangsIetf = TestUtils.loadSchemaContext("/full-versions/yangs");
90         schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
91         brokerFacade = mock(BrokerFacade.class);
92         restconfImpl = RestconfImpl.getInstance();
93         restconfImpl.setBroker(brokerFacade);
94
95         final Set<Module> modules = TestUtils.loadModulesFrom("/test-config-data/yang1");
96         schemaContext = TestUtils.loadSchemaContext(modules);
97
98         loadData();
99     }
100
101     @Override
102     protected Application configure() {
103         /* enable/disable Jersey logs to console */
104         // enable(TestProperties.LOG_TRAFFIC);
105         // enable(TestProperties.DUMP_ENTITY);
106         // enable(TestProperties.RECORD_LOG_LEVEL);
107         // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
108         ResourceConfig resourceConfig = new ResourceConfig();
109         resourceConfig = resourceConfig.registerInstances(restconfImpl, new XmlNormalizedNodeBodyReader(),
110                 new NormalizedNodeXmlBodyWriter(), new JsonNormalizedNodeBodyReader(), new NormalizedNodeJsonBodyWriter());
111         resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
112         return resourceConfig;
113     }
114
115     private void setSchemaControllerContext(final SchemaContext schema) {
116         final ControllerContext context = ControllerContext.getInstance();
117         context.setSchemas(schema);
118         restconfImpl.setControllerContext(context);
119     }
120
121 //    @Test
122 //    public void postRpcNoPayload() throws Exception {
123 //        setSchemaControllerContext(schemaContextTestModule);
124 //        final String uri = "/operations/test-module:no-payload-rpc-test";
125 //        final String mediaType = MediaType.APPLICATION_XML;
126 //        final Response response = target(uri).request(mediaType).post(Entity.entity("", mediaType));
127 //        assertNotNull(response);
128 //
129 //    }
130
131     @Test
132     @Ignore //FIXME we don't wish to mock CompositeNode as result
133     public void postOperationsStatusCodes() throws IOException {
134         setSchemaControllerContext(schemaContextTestModule);
135         mockInvokeRpc(cnSnDataOutput, true);
136         String uri = "/operations/test-module:rpc-test";
137         assertEquals(200, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
138
139         mockInvokeRpc(null, true);
140         assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
141
142         mockInvokeRpc(null, false);
143         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
144
145         final List<RpcError> rpcErrors = new ArrayList<>();
146         rpcErrors.add(RpcResultBuilder.newError(ErrorType.RPC, "tag1", "message1", "applicationTag1", "info1", null));
147         rpcErrors.add(RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "tag2", "message2", "applicationTag2", "info2",
148                 null));
149         mockInvokeRpc(null, false, rpcErrors);
150         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
151
152         uri = "/operations/test-module:rpc-wrongtest";
153         assertEquals(400, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
154     }
155
156     @Test
157     @Ignore // TODO RestconfDocumentedExceptionMapper needs be fixed before
158     public void postConfigOnlyStatusCodes() throws UnsupportedEncodingException {
159         setSchemaControllerContext(schemaContextYangsIetf);
160         final String uri = "/config";
161         mockCommitConfigurationDataPostMethod(true);
162         assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath));
163
164         mockCommitConfigurationDataPostMethod(false);
165         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath));
166
167         assertEquals(400, post(uri, MediaType.APPLICATION_XML, ""));
168     }
169
170     @Test
171     @Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
172     public void postConfigStatusCodes() throws UnsupportedEncodingException {
173         setSchemaControllerContext(schemaContextYangsIetf);
174         final String uri = "/config/ietf-interfaces:interfaces";
175
176         mockCommitConfigurationDataPostMethod(true);
177         assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
178
179         mockCommitConfigurationDataPostMethod(false);
180         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
181
182         // FIXME : empty json input post value return NullPointerException by parsing -> err. code 500
183 //        assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
184     }
185
186     @Test
187     @Ignore /// xmlData* need netconf-yang
188     public void postDataViaUrlMountPoint() throws UnsupportedEncodingException {
189         setSchemaControllerContext(schemaContextYangsIetf);
190         when(
191                 brokerFacade.commitConfigurationDataPost(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
192                         any(NormalizedNode.class))).thenReturn(mock(CheckedFuture.class));
193
194         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
195         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
196         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
197         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
198
199         ControllerContext.getInstance().setMountService(mockMountService);
200
201         String uri = "/config/ietf-interfaces:interfaces/interface/0/";
202         assertEquals(204, post(uri, Draft02.MediaTypes.DATA + XML, xmlData4));
203         uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
204         assertEquals(204, post(uri, Draft02.MediaTypes.DATA + XML, xmlData3));
205
206         assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
207     }
208
209     private void mockInvokeRpc(final CompositeNode result, final boolean sucessful, final Collection<RpcError> errors) {
210
211         final DummyRpcResult.Builder<CompositeNode> builder = new DummyRpcResult.Builder<CompositeNode>().result(result)
212                 .isSuccessful(sucessful);
213         if (!errors.isEmpty()) {
214             builder.errors(errors);
215         }
216         final RpcResult<CompositeNode> rpcResult = builder.build();
217 //        when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
218 //                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
219     }
220
221     /**
222      * @deprecated has to be removed for lithium release
223      */
224     @Deprecated
225     private void mockInvokeRpc(final CompositeNode result, final boolean sucessful) {
226         mockInvokeRpc(result, sucessful, Collections.<RpcError> emptyList());
227     }
228
229     private void mockCommitConfigurationDataPostMethod(final boolean succesfulComit) {
230         if (succesfulComit) {
231             doReturn(mock(CheckedFuture.class)).when(brokerFacade).commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class));
232         } else {
233             doThrow(RestconfDocumentedException.class).when(brokerFacade).commitConfigurationDataPost(
234                     any(YangInstanceIdentifier.class), any(NormalizedNode.class));
235         }
236     }
237
238     @Test
239     @Ignore //jenkins has problem with JerseyTest - we expecting problems with singletons ControllerContext as schemaContext holder
240     public void createConfigurationDataTest() throws UnsupportedEncodingException, ParseException {
241         initMocking();
242         final RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(
243                 TransactionStatus.COMMITED).build();
244
245         when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
246                 .thenReturn(mock(CheckedFuture.class));
247
248         final ArgumentCaptor<YangInstanceIdentifier> instanceIdCaptor = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
249         final ArgumentCaptor<NormalizedNode> compNodeCaptor = ArgumentCaptor.forClass(NormalizedNode.class);
250
251
252         // FIXME : identify who is set the schemaContext
253 //        final String URI_1 = "/config";
254 //        assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface));
255 //        verify(brokerFacade).commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
256         final String identifier = "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces]";
257 //        assertEquals(identifier, ImmutableList.copyOf(instanceIdCaptor.getValue().getPathArguments()).toString());
258
259         final String URI_2 = "/config/test-interface:interfaces";
260         assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData));
261         // FIXME : NEVER test a nr. of call some service in complex test suite
262 //        verify(brokerFacade, times(2))
263         verify(brokerFacade, times(1))
264                 .commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
265 //        identifier = "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces, (urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)block]";
266         assertEquals(identifier, ImmutableList.copyOf(instanceIdCaptor.getValue().getPathArguments()).toString());
267     }
268
269     @Test
270     public void createConfigurationDataNullTest() throws UnsupportedEncodingException {
271         initMocking();
272
273         when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class),any(NormalizedNode.class)))
274                 .thenReturn(Futures.<Void, TransactionCommitFailedException>immediateCheckedFuture(null));
275
276         //FIXME : find who is set schemaContext
277 //        final String URI_1 = "/config";
278 //        assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface));
279
280         final String URI_2 = "/config/test-interface:interfaces";
281         assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData));
282     }
283
284     private static void initMocking() {
285         final ControllerContext controllerContext = ControllerContext.getInstance();
286         controllerContext.setSchemas(schemaContext);
287         mountService = mock(DOMMountPointService.class);
288         controllerContext.setMountService(mountService);
289         brokerFacade = mock(BrokerFacade.class);
290         restconfImpl = RestconfImpl.getInstance();
291         restconfImpl.setBroker(brokerFacade);
292         restconfImpl.setControllerContext(controllerContext);
293     }
294
295     private int post(final String uri, final String mediaType, final String data) {
296         return target(uri).request(mediaType).post(Entity.entity(data, mediaType)).getStatus();
297     }
298
299     private static void loadData() throws IOException, URISyntaxException {
300         InputStream xmlStream = RestconfImplTest.class
301                 .getResourceAsStream("/parts/ietf-interfaces_interfaces_absolute_path.xml");
302         xmlDataAbsolutePath = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
303         xmlStream = RestconfImplTest.class
304                 .getResourceAsStream("/parts/ietf-interfaces_interfaces_interface_absolute_path.xml");
305         xmlDataInterfaceAbsolutePath = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
306         final String xmlPathRpcInput = RestconfImplTest.class.getResource("/full-versions/test-data2/data-rpc-input.xml")
307                 .getPath();
308         xmlDataRpcInput = TestUtils.loadTextFile(xmlPathRpcInput);
309         final String xmlPathBlockData = RestconfImplTest.class.getResource("/test-config-data/xml/block-data.xml").getPath();
310         xmlBlockData = TestUtils.loadTextFile(xmlPathBlockData);
311         final String xmlPathTestInterface = RestconfImplTest.class.getResource("/test-config-data/xml/test-interface.xml")
312                 .getPath();
313         xmlTestInterface = TestUtils.loadTextFile(xmlPathTestInterface);
314         cnSnDataOutput = prepareCnSnRpcOutput();
315         final String data3Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data3.xml").getPath();
316         xmlData3 = TestUtils.loadTextFile(data3Input);
317         final String data4Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data7.xml").getPath();
318         xmlData4 = TestUtils.loadTextFile(data4Input);
319     }
320
321     private static CompositeNodeWrapper prepareCnSnRpcOutput() throws URISyntaxException {
322         final CompositeNodeWrapper cnSnDataOutput = new CompositeNodeWrapper(new URI("test:module"), "output");
323         final CompositeNodeWrapper cont = new CompositeNodeWrapper(new URI("test:module"), "cont-output");
324         cnSnDataOutput.addValue(cont);
325         cnSnDataOutput.unwrap();
326         return cnSnDataOutput;
327     }
328 }