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