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.MockHttpServletResponse;
72 * The class <code>CreateOptimizationControllerTest</code> contains tests for the class
74 * <p/>All JUnits are designed to run in the local development environment where they have write
75 * privileges and can execute time-sensitive tasks.
77 public class CreateOptimizationControllerTest {
79 private static Logger logger = FlexLogger.getLogger(CreateOptimizationControllerTest.class);
80 private static CommonClassDao commonClassDao;
81 private String jsonString = null;
82 private String configBodyString = null;
83 private HttpServletRequest request = null;
86 public void setUp() throws Exception {
88 logger.info("setUp: Entering");
89 commonClassDao = mock(CommonClassDao.class);
90 List<Object> optimizationModelsData = new ArrayList<Object>();
91 OptimizationModels testData = new OptimizationModels();
92 testData.setVersion("OpenOnap-Junit");
93 optimizationModelsData.add(testData);
95 // mock the getDataById() call
96 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test"))
97 .thenReturn(optimizationModelsData);
99 jsonString = "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
100 + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,"
101 + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\","
102 + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false},"
103 + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"},"
104 + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\","
105 + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\","
106 + "\"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\","
107 + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\","
108 + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}},"
109 + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}";
111 configBodyString = "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\","
112 + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\","
113 + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\","
114 + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\","
115 + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\","
116 + "\"target\":\"TEST\"}}";
118 request = mock(HttpServletRequest.class);
119 BufferedReader br = new BufferedReader(new StringReader(jsonString));
120 // mock the getReader() call
121 when(request.getReader()).thenReturn(br);
123 logger.info("setUp: exit");
127 * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test.
131 public void testSetDataToPolicyRestAdapter() {
133 logger.debug("testSetDataToPolicyRestAdapter: enter");
135 CreateOptimizationController controller = new CreateOptimizationController();
136 CreateOptimizationController.setCommonClassDao(commonClassDao);
138 JsonNode root = null;
139 ObjectMapper mapper = new ObjectMapper();
140 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
141 PolicyRestAdapter policyData = null;
143 root = JsonLoader.fromString(jsonString);
144 policyData = mapper.readValue(root.get("policyData").get("policy").toString(),
145 PolicyRestAdapter.class);
146 } catch (Exception e) {
147 logger.error("testSetDataToPolicyRestAdapter", e);
150 PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
151 assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
153 logger.debug("result.getJsonBody() : " + result.getJsonBody());
154 logger.debug("testSetDataToPolicyRestAdapter: exit");
158 * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse)
163 public void testGetOptimizationTemplateData() {
165 logger.debug("testGetOptimizationTemplateData: enter");
167 CreateOptimizationController controller = new CreateOptimizationController();
168 MockHttpServletResponse response = new MockHttpServletResponse();
169 String modelJson = "{\"policyData\":\"testPolicyBody\"}";
172 CreateOptimizationController.setCommonClassDao(commonClassDao);
174 BufferedReader br = new BufferedReader(new StringReader(modelJson));
175 // mock the getReader() call
176 when(request.getReader()).thenReturn(br);
178 List<Object> optimizationModelsData = new ArrayList<Object>();
179 OptimizationModels testData = new OptimizationModels();
180 testData.setVersion("1707.4.1.2-Junit");
181 optimizationModelsData.add(testData);
182 // mock the getDataById() call with the same MS model name
183 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody"))
184 .thenReturn(optimizationModelsData);
186 controller.getOptimizationTemplateData(request, response);
188 assertTrue(response.getContentAsString() != null
189 && response.getContentAsString().contains("optimizationModelData"));
191 logger.debug("response: " + response.getContentAsString());
193 } catch (Exception e) {
194 logger.error("testGetOptimizationTemplateData", e);
197 logger.debug("testGetOptimizationTemplateData: exit");
201 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse)
206 public void testGetModelServiceVersionData() {
208 logger.debug("testGetModelServiceVersionData: enter");
210 CreateOptimizationController controller = new CreateOptimizationController();
211 MockHttpServletResponse response = new MockHttpServletResponse();
212 String modelJson = "{\"policyData\":\"TestPolicyBody\"}";
215 CreateOptimizationController.setCommonClassDao(commonClassDao);
217 BufferedReader br = new BufferedReader(new StringReader(modelJson));
218 // mock the getReader() call
219 when(request.getReader()).thenReturn(br);
221 List<Object> optimizationModelsData = new ArrayList<Object>();
222 OptimizationModels testData = new OptimizationModels();
223 testData.setVersion("1707.4.1.2-Junit");
224 optimizationModelsData.add(testData);
226 // mock the getDataById() call with the same MS model name
227 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody"))
228 .thenReturn(optimizationModelsData);
229 controller.getModelServiceVersionData(request, response);
231 assertTrue(response.getContentAsString() != null
232 && response.getContentAsString().contains("1707.4.1.2-Junit"));
234 logger.debug("response: " + response.getContentAsString());
236 } catch (Exception e) {
237 logger.error("testGetModelServiceVersionData", e);
238 fail("testGetModelServiceVersionData failed due to: " + e);
241 logger.debug("testGetModelServiceVersionData: exit");
245 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test.
249 public void testPrePopulatePolicyData() {
251 logger.debug("testPrePopulatePolicyData: enter");
253 CreateOptimizationController controller = new CreateOptimizationController();
255 // populate an entity object for testing
256 PolicyEntity entity = new PolicyEntity();
257 ConfigurationDataEntity configData = new ConfigurationDataEntity();
258 configData.setConfigBody(configBodyString);
259 entity.setConfigurationData(configData);
261 JsonNode root = null;
262 ObjectMapper mapper = new ObjectMapper();
263 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
264 PolicyRestAdapter restAdapter = null;
267 root = JsonLoader.fromString(jsonString);
268 restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(),
269 PolicyRestAdapter.class);
270 PolicyType policyType = new PolicyType();
271 TargetType target = new TargetType();
273 // create guard attribute
274 AnyOfType anyOfType = new AnyOfType();
275 AllOfType alltype = new AllOfType();
276 MatchType matchType = new MatchType();
278 AttributeValueType attributeValue1 = new AttributeValueType();
279 attributeValue1.getContent().add("True");
280 matchType.setAttributeValue(attributeValue1);
282 AttributeDesignatorType designator = new AttributeDesignatorType();
283 designator.setAttributeId("guard");
284 matchType.setAttributeDesignator(designator);
285 alltype.getMatch().add(matchType);
287 // add a dummy MatchType object since while (matchList.size()>1 ...)
288 MatchType matchDummy = new MatchType();
290 AttributeValueType dummyValue = new AttributeValueType();
291 dummyValue.getContent().add("dummy");
292 matchDummy.setAttributeValue(dummyValue);
294 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
295 designatorDummy.setAttributeId("dummyId");
296 matchDummy.setAttributeDesignator(designatorDummy);
298 alltype.getMatch().add(matchDummy);
299 anyOfType.getAllOf().add(alltype);
301 target.getAnyOf().add(anyOfType);
303 // create RiskType attribute
304 AnyOfType anyRiskType = new AnyOfType();
305 AllOfType allRiskType = new AllOfType();
306 MatchType matchRiskType = new MatchType();
308 AttributeValueType riskTypeValue = new AttributeValueType();
309 riskTypeValue.getContent().add("test");
310 matchRiskType.setAttributeValue(riskTypeValue);
312 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
313 designatorRiskType.setAttributeId("RiskType");
314 matchRiskType.setAttributeDesignator(designatorRiskType);
315 allRiskType.getMatch().add(matchRiskType);
317 // add a dummy MatchType object since while (matchList.size()>1 ...)
318 MatchType matchDummy1 = new MatchType();
320 AttributeValueType dummy1Value = new AttributeValueType();
321 dummy1Value.getContent().add("dummy");
322 matchDummy1.setAttributeValue(dummy1Value);
324 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
325 designatorDummy1.setAttributeId("dummyId");
326 matchDummy1.setAttributeDesignator(designatorDummy1);
328 allRiskType.getMatch().add(matchDummy1);
330 anyRiskType.getAllOf().add(allRiskType);
332 target.getAnyOf().add(anyRiskType);
334 // create RiskLevel attribute
335 AnyOfType anyRiskLevel = new AnyOfType();
336 AllOfType allRiskLevel = new AllOfType();
337 MatchType matchRiskLevel = new MatchType();
339 AttributeValueType riskLevel = new AttributeValueType();
340 riskLevel.getContent().add("3");
341 matchRiskLevel.setAttributeValue(riskLevel);
343 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
344 designatorRiskLevel.setAttributeId("RiskLevel");
345 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
346 allRiskLevel.getMatch().add(matchRiskLevel);
348 // add a dummy MatchType object since while (matchList.size()>1 ...)
349 MatchType matchDummy2 = new MatchType();
351 AttributeValueType dummy2Value = new AttributeValueType();
352 dummy2Value.getContent().add("dummy");
353 matchDummy2.setAttributeValue(dummy2Value);
355 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
356 designatorDummy2.setAttributeId("dummyId");
357 matchDummy2.setAttributeDesignator(designatorDummy2);
359 allRiskLevel.getMatch().add(matchDummy2);
361 anyRiskLevel.getAllOf().add(allRiskLevel);
362 target.getAnyOf().add(anyRiskLevel);
364 policyType.setTarget(target);
366 restAdapter.setPolicyData(policyType);
368 controller.prePopulatePolicyData(restAdapter, entity);
370 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
371 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
372 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
374 assertEquals("True", restAdapter.getGuard());
375 assertEquals("3", restAdapter.getRiskLevel());
376 assertEquals("test", restAdapter.getRiskType());
378 } catch (Exception e) {
379 logger.error("testPrePopulatePolicyData", e);
380 fail("testPrePopulatePolicyData failed due to: " + e);
383 logger.debug("testPrePopulatePolicyData: exit");
388 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test.
392 public void testSetModelData() {
394 logger.debug("testSetModelData: enter");
396 CreateOptimizationController controller = new CreateOptimizationController();
397 HttpServletRequest request = createMock(HttpServletRequest.class);
398 MockHttpServletResponse response = new MockHttpServletResponse();
399 expect(request.getContentType())
400 .andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
401 expect(request.getMethod()).andReturn("post");
402 expect(request.getHeader("Content-length")).andReturn("7809");
404 expect(request.getContentLength()).andReturn(7809);
407 // value of fileName needs to be matched to your local directory
408 String fileName = "";
410 ClassLoader classLoader = getClass().getClassLoader();
411 fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
412 } catch (Exception e1) {
413 logger.error("Exception Occured while loading file" + e1);
415 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
416 expect(request.getCharacterEncoding()).andReturn("UTF-8");
417 expect(request.getContentLength()).andReturn(1024);
419 controller.setModelData(request, response);
421 } catch (Exception e) {
422 logger.error("testSetModelData" + e);
426 logger.debug("testSetModelData: exit");
432 private class MockServletInputStream extends ServletInputStream {
434 InputStream fis = null;
436 public MockServletInputStream(String fileName) {
438 fis = new FileInputStream(fileName);
439 } catch (Exception genExe) {
440 genExe.printStackTrace();
445 public int read() throws IOException {
446 if (fis.available() > 0) {
453 public int read(byte[] bytes, int len, int size) throws IOException {
454 if (fis.available() > 0) {
455 int length = fis.read(bytes, len, size);
462 public boolean isFinished() {
467 public boolean isReady() {
472 public void setReadListener(ReadListener arg0) {