2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Modifications Copyright (C) 2019 Samsung
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.controller;
25 import static org.easymock.EasyMock.createMock;
26 import static org.easymock.EasyMock.expect;
27 import static org.easymock.EasyMock.replay;
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertTrue;
30 import static org.junit.Assert.fail;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.when;
34 import com.fasterxml.jackson.databind.DeserializationFeature;
35 import com.fasterxml.jackson.databind.JsonNode;
36 import com.fasterxml.jackson.databind.ObjectMapper;
37 import com.github.fge.jackson.JsonLoader;
39 import java.io.BufferedReader;
41 import java.io.FileInputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.StringReader;
45 import java.util.ArrayList;
46 import java.util.List;
48 import javax.servlet.ReadListener;
49 import javax.servlet.ServletInputStream;
50 import javax.servlet.http.HttpServletRequest;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
60 import org.junit.Before;
61 import org.junit.Test;
62 import org.onap.policy.common.logging.flexlogger.FlexLogger;
63 import org.onap.policy.common.logging.flexlogger.Logger;
64 import org.onap.policy.rest.adapter.PolicyRestAdapter;
65 import org.onap.policy.rest.dao.CommonClassDao;
66 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
67 import org.onap.policy.rest.jpa.OptimizationModels;
68 import org.onap.policy.rest.jpa.PolicyEntity;
69 import org.springframework.mock.web.MockHttpServletRequest;
70 import org.springframework.mock.web.MockHttpServletResponse;
73 * The class <code>CreateOptimizationControllerTest</code> contains tests for the class
74 * {@link <code>CreateOptimizationController</code>}*
76 * All JUnits are designed to run in the local development environment where they have write
77 * privileges and can execute time-sensitive tasks.
79 public class CreateOptimizationControllerTest {
81 private static Logger logger = FlexLogger.getLogger(CreateOptimizationControllerTest.class);
82 private static CommonClassDao commonClassDao;
83 private String jsonString = null;
84 private String configBodyString = null;
85 private HttpServletRequest request = null;
88 public void setUp() throws Exception {
90 logger.info("setUp: Entering");
91 commonClassDao = mock(CommonClassDao.class);
92 List<Object> optimizationModelsData = new ArrayList<Object>();
93 OptimizationModels testData = new OptimizationModels();
94 testData.setVersion("OpenOnap-Junit");
95 optimizationModelsData.add(testData);
97 // mock the getDataById() call
98 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test"))
99 .thenReturn(optimizationModelsData);
101 jsonString = "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
102 + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,"
103 + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\","
104 + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false},"
105 + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"},"
106 + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\","
107 + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\","
108 + "\"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\","
109 + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\","
110 + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}},"
111 + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}";
113 configBodyString = "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\","
114 + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\","
115 + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\","
116 + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\","
117 + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\","
118 + "\"target\":\"TEST\"}}";
120 request = mock(HttpServletRequest.class);
121 BufferedReader br = new BufferedReader(new StringReader(jsonString));
122 // mock the getReader() call
123 when(request.getReader()).thenReturn(br);
125 logger.info("setUp: exit");
129 * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test
133 public void testSetDataToPolicyRestAdapter() {
135 logger.debug("testSetDataToPolicyRestAdapter: enter");
137 CreateOptimizationController controller = new CreateOptimizationController();
138 CreateOptimizationController.setCommonClassDao(commonClassDao);
140 JsonNode root = null;
141 ObjectMapper mapper = new ObjectMapper();
142 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
143 PolicyRestAdapter policyData = null;
145 root = JsonLoader.fromString(jsonString);
146 policyData = (PolicyRestAdapter) mapper.readValue(root.get("policyData").get("policy").toString(),
147 PolicyRestAdapter.class);
148 } catch (Exception e) {
149 logger.error("testSetDataToPolicyRestAdapter", e);
152 PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
153 assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
155 logger.debug("result.getJsonBody() : " + result.getJsonBody());
156 logger.debug("testSetDataToPolicyRestAdapter: exit");
160 * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse)
165 public void testGetOptimizationTemplateData() {
167 logger.debug("testGetOptimizationTemplateData: enter");
169 CreateOptimizationController controller = new CreateOptimizationController();
170 MockHttpServletResponse response = new MockHttpServletResponse();
171 String modelJson = "{\"policyData\":\"testPolicyBody\"}";
174 CreateOptimizationController.setCommonClassDao(commonClassDao);
176 BufferedReader br = new BufferedReader(new StringReader(modelJson));
177 // mock the getReader() call
178 when(request.getReader()).thenReturn(br);
180 List<Object> optimizationModelsData = new ArrayList<Object>();
181 OptimizationModels testData = new OptimizationModels();
182 testData.setVersion("1707.4.1.2-Junit");
183 optimizationModelsData.add(testData);
184 // mock the getDataById() call with the same MS model name
185 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody"))
186 .thenReturn(optimizationModelsData);
188 controller.getOptimizationTemplateData(request, response);
190 assertTrue(response.getContentAsString() != null
191 && response.getContentAsString().contains("optimizationModelData"));
193 logger.debug("response: " + response.getContentAsString());
195 } catch (Exception e) {
196 logger.error("testGetOptimizationTemplateData", e);
199 logger.debug("testGetOptimizationTemplateData: exit");
203 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse)
208 public void testGetModelServiceVersionData() {
210 logger.debug("testGetModelServiceVersionData: enter");
212 CreateOptimizationController controller = new CreateOptimizationController();
213 MockHttpServletResponse response = new MockHttpServletResponse();
214 String modelJson = "{\"policyData\":\"TestPolicyBody\"}";
217 CreateOptimizationController.setCommonClassDao(commonClassDao);
219 BufferedReader br = new BufferedReader(new StringReader(modelJson));
220 // mock the getReader() call
221 when(request.getReader()).thenReturn(br);
223 List<Object> optimizationModelsData = new ArrayList<Object>();
224 OptimizationModels testData = new OptimizationModels();
225 testData.setVersion("1707.4.1.2-Junit");
226 optimizationModelsData.add(testData);
228 // mock the getDataById() call with the same MS model name
229 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody"))
230 .thenReturn(optimizationModelsData);
231 controller.getModelServiceVersionData(request, response);
233 assertTrue(response.getContentAsString() != null
234 && response.getContentAsString().contains("1707.4.1.2-Junit"));
236 logger.debug("response: " + response.getContentAsString());
238 } catch (Exception e) {
239 logger.error("testGetModelServiceVersionData", e);
240 fail("testGetModelServiceVersionData failed due to: " + e);
243 logger.debug("testGetModelServiceVersionData: exit");
247 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test
251 public void testPrePopulatePolicyData() {
253 logger.debug("testPrePopulatePolicyData: enter");
255 CreateOptimizationController controller = new CreateOptimizationController();
257 // populate an entity object for testing
258 PolicyEntity entity = new PolicyEntity();
259 ConfigurationDataEntity configData = new ConfigurationDataEntity();
260 configData.setConfigBody(configBodyString);
261 entity.setConfigurationData(configData);
263 JsonNode root = null;
264 ObjectMapper mapper = new ObjectMapper();
265 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
266 PolicyRestAdapter restAdapter = null;
269 root = JsonLoader.fromString(jsonString);
270 restAdapter = (PolicyRestAdapter) mapper.readValue(root.get("policyData").get("policy").toString(),
271 PolicyRestAdapter.class);
272 PolicyType policyType = new PolicyType();
273 TargetType target = new TargetType();
275 // create guard attribute
276 AnyOfType anyOfType = new AnyOfType();
277 AllOfType alltype = new AllOfType();
278 MatchType matchType = new MatchType();
280 AttributeValueType attributeValue1 = new AttributeValueType();
281 attributeValue1.getContent().add("True");
282 matchType.setAttributeValue(attributeValue1);
284 AttributeDesignatorType designator = new AttributeDesignatorType();
285 designator.setAttributeId("guard");
286 matchType.setAttributeDesignator(designator);
287 alltype.getMatch().add(matchType);
289 // add a dummy MatchType object since while (matchList.size()>1 ...)
290 MatchType matchDummy = new MatchType();
292 AttributeValueType dummyValue = new AttributeValueType();
293 dummyValue.getContent().add("dummy");
294 matchDummy.setAttributeValue(dummyValue);
296 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
297 designatorDummy.setAttributeId("dummyId");
298 matchDummy.setAttributeDesignator(designatorDummy);
300 alltype.getMatch().add(matchDummy);
301 anyOfType.getAllOf().add(alltype);
303 target.getAnyOf().add(anyOfType);
305 // create RiskType attribute
306 AnyOfType anyRiskType = new AnyOfType();
307 AllOfType allRiskType = new AllOfType();
308 MatchType matchRiskType = new MatchType();
310 AttributeValueType riskTypeValue = new AttributeValueType();
311 riskTypeValue.getContent().add("test");
312 matchRiskType.setAttributeValue(riskTypeValue);
314 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
315 designatorRiskType.setAttributeId("RiskType");
316 matchRiskType.setAttributeDesignator(designatorRiskType);
317 allRiskType.getMatch().add(matchRiskType);
319 // add a dummy MatchType object since while (matchList.size()>1 ...)
320 MatchType matchDummy1 = new MatchType();
322 AttributeValueType dummy1Value = new AttributeValueType();
323 dummy1Value.getContent().add("dummy");
324 matchDummy1.setAttributeValue(dummy1Value);
326 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
327 designatorDummy1.setAttributeId("dummyId");
328 matchDummy1.setAttributeDesignator(designatorDummy1);
330 allRiskType.getMatch().add(matchDummy1);
332 anyRiskType.getAllOf().add(allRiskType);
334 target.getAnyOf().add(anyRiskType);
336 // create RiskLevel attribute
337 AnyOfType anyRiskLevel = new AnyOfType();
338 AllOfType allRiskLevel = new AllOfType();
339 MatchType matchRiskLevel = new MatchType();
341 AttributeValueType riskLevel = new AttributeValueType();
342 riskLevel.getContent().add("3");
343 matchRiskLevel.setAttributeValue(riskLevel);
345 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
346 designatorRiskLevel.setAttributeId("RiskLevel");
347 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
348 allRiskLevel.getMatch().add(matchRiskLevel);
350 // add a dummy MatchType object since while (matchList.size()>1 ...)
351 MatchType matchDummy2 = new MatchType();
353 AttributeValueType dummy2Value = new AttributeValueType();
354 dummy2Value.getContent().add("dummy");
355 matchDummy2.setAttributeValue(dummy2Value);
357 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
358 designatorDummy2.setAttributeId("dummyId");
359 matchDummy2.setAttributeDesignator(designatorDummy2);
361 allRiskLevel.getMatch().add(matchDummy2);
363 anyRiskLevel.getAllOf().add(allRiskLevel);
364 target.getAnyOf().add(anyRiskLevel);
366 policyType.setTarget(target);
368 restAdapter.setPolicyData(policyType);
370 controller.prePopulatePolicyData(restAdapter, entity);
372 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
373 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
374 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
376 assertEquals("True", restAdapter.getGuard());
377 assertEquals("3", restAdapter.getRiskLevel());
378 assertEquals("test", restAdapter.getRiskType());
380 } catch (Exception e) {
381 logger.error("testPrePopulatePolicyData", e);
382 fail("testPrePopulatePolicyData failed due to: " + e);
385 logger.debug("testPrePopulatePolicyData: exit");
390 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test
394 public void testSetModelData() {
396 logger.debug("testSetModelData: enter");
398 CreateOptimizationController controller = new CreateOptimizationController();
399 HttpServletRequest request = createMock(HttpServletRequest.class);
400 MockHttpServletResponse response = new MockHttpServletResponse();
401 expect(request.getContentType())
402 .andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
403 expect(request.getMethod()).andReturn("post");
404 expect(request.getHeader("Content-length")).andReturn("7809");
406 expect(request.getContentLength()).andReturn(7809);
409 // value of fileName needs to be matched to your local directory
410 String fileName = "";
412 ClassLoader classLoader = getClass().getClassLoader();
413 fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
414 } catch (Exception e1) {
415 logger.error("Exception Occured while loading file" + e1);
417 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
418 expect(request.getCharacterEncoding()).andReturn("UTF-8");
419 expect(request.getContentLength()).andReturn(1024);
421 controller.setModelData(request, response);
423 } catch (Exception e) {
424 logger.error("testSetModelData" + e);
428 logger.debug("testSetModelData: exit");
436 private class MockServletInputStream extends ServletInputStream {
438 InputStream fis = null;
440 public MockServletInputStream(String fileName) {
442 fis = new FileInputStream(fileName);
443 } catch (Exception genExe) {
444 genExe.printStackTrace();
449 public int read() throws IOException {
450 if (fis.available() > 0) {
457 public int read(byte[] bytes, int len, int size) throws IOException {
458 if (fis.available() > 0) {
459 int length = fis.read(bytes, len, size);
466 public boolean isFinished() {
471 public boolean isReady() {
476 public void setReadListener(ReadListener arg0) {