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