6685c12ba9340b8c725f51e2e564556e32378645
[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     @Ignore //FIXME we don't wish to mock CompositeNode as result
129     public void postOperationsStatusCodes() throws IOException {
130         setSchemaControllerContext(schemaContextTestModule);
131         mockInvokeRpc(cnSnDataOutput, true);
132         String uri = "/operations/test-module:rpc-test";
133         assertEquals(200, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
134
135         mockInvokeRpc(null, true);
136         assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
137
138         mockInvokeRpc(null, false);
139         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
140
141         final List<RpcError> rpcErrors = new ArrayList<>();
142         rpcErrors.add(RpcResultBuilder.newError(ErrorType.RPC, "tag1", "message1", "applicationTag1", "info1", null));
143         rpcErrors.add(RpcResultBuilder.newWarning(ErrorType.PROTOCOL, "tag2", "message2", "applicationTag2", "info2",
144                 null));
145         mockInvokeRpc(null, false, rpcErrors);
146         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
147
148         uri = "/operations/test-module:rpc-wrongtest";
149         assertEquals(400, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
150     }
151
152     @Test
153     @Ignore // TODO RestconfDocumentedExceptionMapper needs be fixed before
154     public void postConfigOnlyStatusCodes() throws UnsupportedEncodingException {
155         setSchemaControllerContext(schemaContextYangsIetf);
156         final String uri = "/config";
157         mockCommitConfigurationDataPostMethod(true);
158         assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath));
159
160         mockCommitConfigurationDataPostMethod(false);
161         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataAbsolutePath));
162
163         assertEquals(400, post(uri, MediaType.APPLICATION_XML, ""));
164     }
165
166     @Test
167     public void postConfigStatusCodes() throws UnsupportedEncodingException {
168         setSchemaControllerContext(schemaContextYangsIetf);
169         final String uri = "/config/ietf-interfaces:interfaces";
170
171         mockCommitConfigurationDataPostMethod(true);
172         assertEquals(204, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
173
174         mockCommitConfigurationDataPostMethod(false);
175         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataInterfaceAbsolutePath));
176
177         // FIXME : empty json input post value return NullPointerException by parsing -> err. code 500
178 //        assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
179     }
180
181     @Test
182     @Ignore /// xmlData* need netconf-yang
183     public void postDataViaUrlMountPoint() throws UnsupportedEncodingException {
184         setSchemaControllerContext(schemaContextYangsIetf);
185         when(
186                 brokerFacade.commitConfigurationDataPost(any(DOMMountPoint.class), any(YangInstanceIdentifier.class),
187                         any(NormalizedNode.class))).thenReturn(mock(CheckedFuture.class));
188
189         final DOMMountPoint mountInstance = mock(DOMMountPoint.class);
190         when(mountInstance.getSchemaContext()).thenReturn(schemaContextTestModule);
191         final DOMMountPointService mockMountService = mock(DOMMountPointService.class);
192         when(mockMountService.getMountPoint(any(YangInstanceIdentifier.class))).thenReturn(Optional.of(mountInstance));
193
194         ControllerContext.getInstance().setMountService(mockMountService);
195
196         String uri = "/config/ietf-interfaces:interfaces/interface/0/";
197         assertEquals(204, post(uri, Draft02.MediaTypes.DATA + XML, xmlData4));
198         uri = "/config/ietf-interfaces:interfaces/interface/0/yang-ext:mount/test-module:cont";
199         assertEquals(204, post(uri, Draft02.MediaTypes.DATA + XML, xmlData3));
200
201         assertEquals(400, post(uri, MediaType.APPLICATION_JSON, ""));
202     }
203
204     private void mockInvokeRpc(final CompositeNode result, final boolean sucessful, final Collection<RpcError> errors) {
205
206         final DummyRpcResult.Builder<CompositeNode> builder = new DummyRpcResult.Builder<CompositeNode>().result(result)
207                 .isSuccessful(sucessful);
208         if (!errors.isEmpty()) {
209             builder.errors(errors);
210         }
211         final RpcResult<CompositeNode> rpcResult = builder.build();
212         when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
213                 Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
214     }
215
216     /**
217      * @deprecated has to be removed for lithium release
218      */
219     @Deprecated
220     private void mockInvokeRpc(final CompositeNode result, final boolean sucessful) {
221         mockInvokeRpc(result, sucessful, Collections.<RpcError> emptyList());
222     }
223
224     private void mockCommitConfigurationDataPostMethod(final boolean succesfulComit) {
225         if (succesfulComit) {
226             doReturn(mock(CheckedFuture.class)).when(brokerFacade).commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class));
227         } else {
228             doThrow(RestconfDocumentedException.class).when(brokerFacade).commitConfigurationDataPost(
229                     any(YangInstanceIdentifier.class), any(NormalizedNode.class));
230         }
231     }
232
233     @Test
234     public void createConfigurationDataTest() throws UnsupportedEncodingException, ParseException {
235         initMocking();
236         final RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(
237                 TransactionStatus.COMMITED).build();
238
239         when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
240                 .thenReturn(mock(CheckedFuture.class));
241
242         final ArgumentCaptor<YangInstanceIdentifier> instanceIdCaptor = ArgumentCaptor.forClass(YangInstanceIdentifier.class);
243         final ArgumentCaptor<NormalizedNode> compNodeCaptor = ArgumentCaptor.forClass(NormalizedNode.class);
244
245
246         // FIXME : identify who is set the schemaContext
247 //        final String URI_1 = "/config";
248 //        assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface));
249 //        verify(brokerFacade).commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
250         final String identifier = "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces]";
251 //        assertEquals(identifier, ImmutableList.copyOf(instanceIdCaptor.getValue().getPathArguments()).toString());
252
253         final String URI_2 = "/config/test-interface:interfaces";
254         assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData));
255         // FIXME : NEVER test a nr. of call some service in complex test suite
256 //        verify(brokerFacade, times(2))
257         verify(brokerFacade, times(1))
258                 .commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
259         // FIXME : identifier flow to interface only, why we want to see block too ?
260 //        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]";
261         assertEquals(identifier, ImmutableList.copyOf(instanceIdCaptor.getValue().getPathArguments()).toString());
262     }
263
264     @Test
265     public void createConfigurationDataNullTest() throws UnsupportedEncodingException {
266         initMocking();
267
268         when(brokerFacade.commitConfigurationDataPost(any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
269                 .thenReturn(null);
270
271         //FIXME : find who is set schemaContext
272 //        final String URI_1 = "/config";
273 //        assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface));
274
275         final String URI_2 = "/config/test-interface:interfaces";
276         assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData));
277     }
278
279     private static void initMocking() {
280         final ControllerContext controllerContext = ControllerContext.getInstance();
281         controllerContext.setSchemas(schemaContext);
282         mountService = mock(DOMMountPointService.class);
283         controllerContext.setMountService(mountService);
284         brokerFacade = mock(BrokerFacade.class);
285         restconfImpl = RestconfImpl.getInstance();
286         restconfImpl.setBroker(brokerFacade);
287         restconfImpl.setControllerContext(controllerContext);
288     }
289
290     private int post(final String uri, final String mediaType, final String data) {
291         return target(uri).request(mediaType).post(Entity.entity(data, mediaType)).getStatus();
292     }
293
294     private static void loadData() throws IOException, URISyntaxException {
295         InputStream xmlStream = RestconfImplTest.class
296                 .getResourceAsStream("/parts/ietf-interfaces_interfaces_absolute_path.xml");
297         xmlDataAbsolutePath = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
298         xmlStream = RestconfImplTest.class
299                 .getResourceAsStream("/parts/ietf-interfaces_interfaces_interface_absolute_path.xml");
300         xmlDataInterfaceAbsolutePath = TestUtils.getDocumentInPrintableForm(TestUtils.loadDocumentFrom(xmlStream));
301         final String xmlPathRpcInput = RestconfImplTest.class.getResource("/full-versions/test-data2/data-rpc-input.xml")
302                 .getPath();
303         xmlDataRpcInput = TestUtils.loadTextFile(xmlPathRpcInput);
304         final String xmlPathBlockData = RestconfImplTest.class.getResource("/test-config-data/xml/block-data.xml").getPath();
305         xmlBlockData = TestUtils.loadTextFile(xmlPathBlockData);
306         final String xmlPathTestInterface = RestconfImplTest.class.getResource("/test-config-data/xml/test-interface.xml")
307                 .getPath();
308         xmlTestInterface = TestUtils.loadTextFile(xmlPathTestInterface);
309         cnSnDataOutput = prepareCnSnRpcOutput();
310         final String data3Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data3.xml").getPath();
311         xmlData3 = TestUtils.loadTextFile(data3Input);
312         final String data4Input = RestconfImplTest.class.getResource("/full-versions/test-data2/data7.xml").getPath();
313         xmlData4 = TestUtils.loadTextFile(data4Input);
314     }
315
316     private static CompositeNodeWrapper prepareCnSnRpcOutput() throws URISyntaxException {
317         final CompositeNodeWrapper cnSnDataOutput = new CompositeNodeWrapper(new URI("test:module"), "output");
318         final CompositeNodeWrapper cont = new CompositeNodeWrapper(new URI("test:module"), "cont-output");
319         cnSnDataOutput.addValue(cont);
320         cnSnDataOutput.unwrap();
321         return cnSnDataOutput;
322     }
323 }