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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.