2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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;
26 import static org.easymock.EasyMock.createMock;
27 import static org.easymock.EasyMock.expect;
28 import static org.easymock.EasyMock.replay;
29 import static org.junit.Assert.assertEquals;
30 import static org.junit.Assert.assertTrue;
31 import static org.junit.Assert.fail;
32 import static org.mockito.Mockito.mock;
33 import static org.mockito.Mockito.when;
34 import java.io.BufferedReader;
36 import java.io.FileInputStream;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.StringReader;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.LinkedList;
43 import java.util.List;
45 import javax.servlet.ReadListener;
46 import javax.servlet.ServletInputStream;
47 import javax.servlet.http.HttpServletRequest;
48 import org.junit.Before;
49 import org.junit.Test;
50 import org.onap.policy.common.logging.flexlogger.FlexLogger;
51 import org.onap.policy.common.logging.flexlogger.Logger;
52 import org.onap.policy.rest.adapter.PolicyRestAdapter;
53 import org.onap.policy.rest.dao.CommonClassDao;
54 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
55 import org.onap.policy.rest.jpa.MicroServiceModels;
56 import org.onap.policy.rest.jpa.PolicyEntity;
57 import org.springframework.mock.web.MockHttpServletRequest;
58 import org.springframework.mock.web.MockHttpServletResponse;
59 import com.fasterxml.jackson.databind.DeserializationFeature;
60 import com.fasterxml.jackson.databind.JsonNode;
61 import com.fasterxml.jackson.databind.ObjectMapper;
62 import com.github.fge.jackson.JsonLoader;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
72 * The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests for the class
73 * {@link <code>CreateDcaeMicroServiceController</code>}*
75 * All JUnits are designed to run in the local development environment where they have write
76 * privileges and can execute time-sensitive tasks.
80 public class CreateDcaeMicroServiceControllerTest {
82 private static Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceControllerTest.class);
83 private static CommonClassDao commonClassDao;
84 private String jsonString = null;
85 private String configBodyString = null;
86 private HttpServletRequest request = null;
89 public void setUp() throws Exception {
91 logger.info("setUp: Entering");
92 commonClassDao = mock(CommonClassDao.class);
93 List<Object> microServiceModelsData = new ArrayList<Object>();
94 MicroServiceModels testData = new MicroServiceModels();
95 testData.setVersion("OpenOnap-Junit");
96 microServiceModelsData.add(testData);
98 // mock the getDataById() call
99 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "test"))
100 .thenReturn(microServiceModelsData);
103 "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
104 + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,"
105 + "\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\",\"createdBy\": \"someone\","
106 + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false},"
107 + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"},"
108 + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\","
109 + "\"policyName\": \"may1501\", \"policyDescription\": \"testing input\","
110 + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\","
111 + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\","
112 + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}},"
113 + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}";
116 "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\","
117 + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\","
118 + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\","
119 + "\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\",\"name\":\"test\","
120 + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\","
121 + "\"target\":\"SNIRO\"}}";
123 request = mock(HttpServletRequest.class);
124 BufferedReader br = new BufferedReader(new StringReader(jsonString));
125 // mock the getReader() call
126 when(request.getReader()).thenReturn(br);
128 logger.info("setUp: exit");
132 * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test
136 public void testSetDataToPolicyRestAdapter() {
138 logger.debug("testSetDataToPolicyRestAdapter: enter");
140 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
141 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
143 JsonNode root = null;
144 ObjectMapper mapper = new ObjectMapper();
145 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
146 PolicyRestAdapter policyData = null;
148 root = JsonLoader.fromString(jsonString);
149 policyData = (PolicyRestAdapter) mapper.readValue(
150 root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
151 } catch (Exception e) {
152 logger.error("testSetDataToPolicyRestAdapter", e);
155 PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
157 result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
159 logger.debug("result.getJsonBody() : " + result.getJsonBody());
160 logger.debug("testSetDataToPolicyRestAdapter: exit");
164 * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest, HttpServletResponse) method
169 public void testGetDCAEMSTemplateData() {
171 logger.debug("testGetDCAEMSTemplateData: enter");
173 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
174 MockHttpServletResponse response = new MockHttpServletResponse();
175 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
178 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
180 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
181 // mock the getReader() call
182 when(request.getReader()).thenReturn(br);
184 List<Object> microServiceModelsData = new ArrayList<Object>();
185 MicroServiceModels testData = new MicroServiceModels();
186 testData.setVersion("1707.4.1.2-Junit");
187 microServiceModelsData.add(testData);
188 // mock the getDataById() call with the same MS model name
189 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName",
190 "DkatPolicyBody")).thenReturn(microServiceModelsData);
192 controller.getDCAEMSTemplateData(request, response);
194 assertTrue(response.getContentAsString() != null
195 && response.getContentAsString().contains("dcaeModelData"));
197 logger.debug("response: " + response.getContentAsString());
199 } catch (Exception e) {
200 logger.error("testGetDCAEMSTemplateData", e);
203 logger.debug("testGetDCAEMSTemplateData: exit");
207 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse)
212 public void testGetModelServiceVersionData() {
214 logger.debug("testGetModelServiceVersionData: enter");
216 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
217 MockHttpServletResponse response = new MockHttpServletResponse();
218 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
221 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
223 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
224 // mock the getReader() call
225 when(request.getReader()).thenReturn(br);
227 List<Object> microServiceModelsData = new ArrayList<Object>();
228 MicroServiceModels testData = new MicroServiceModels();
229 testData.setVersion("1707.4.1.2-Junit");
230 microServiceModelsData.add(testData);
232 // mock the getDataById() call with the same MS model name
233 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName",
234 "DkatPolicyBody")).thenReturn(microServiceModelsData);
235 controller.getModelServiceVersionData(request, response);
237 assertTrue(response.getContentAsString() != null
238 && response.getContentAsString().contains("1707.4.1.2-Junit"));
240 logger.debug("response: " + response.getContentAsString());
242 } catch (Exception e) {
243 logger.error("testGetModelServiceVersionData", e);
244 fail("testGetModelServiceVersionData failed due to: " + e);
247 logger.debug("testGetModelServiceVersionData: exit");
251 * Run the void getDCAEPriorityValuesData(HttpServletRequest, HttpServletResponse) method test
255 public void testGetDCAEPriorityValuesData() {
257 logger.debug("testGetDCAEPriorityValuesData: enter");
259 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
261 MockHttpServletRequest request = new MockHttpServletRequest();
262 MockHttpServletResponse response = new MockHttpServletResponse();
264 controller.getDCAEPriorityValuesData(request, response);
265 assertTrue(response.getContentAsString() != null
266 && response.getContentAsString().contains("priorityDatas"));
267 logger.debug("response: " + response.getContentAsString());
268 } catch (Exception e) {
269 logger.error("testGetDCAEPriorityValuesData", e);
270 fail("testGetDCAEPriorityValuesData failed due to: " + e);
273 logger.debug("testGetDCAEPriorityValuesData: exit");
277 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test
281 public void testPrePopulateDCAEMSPolicyData() {
283 logger.debug("testPrePopulateDCAEMSPolicyData: enter");
285 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
287 // populate an entity object for testing
288 PolicyEntity entity = new PolicyEntity();
289 ConfigurationDataEntity configData = new ConfigurationDataEntity();
290 configData.setConfigBody(configBodyString);
291 entity.setConfigurationData(configData);
293 JsonNode root = null;
294 ObjectMapper mapper = new ObjectMapper();
295 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
296 PolicyRestAdapter restAdapter = null;
299 root = JsonLoader.fromString(jsonString);
300 restAdapter = (PolicyRestAdapter) mapper.readValue(
301 root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
302 PolicyType policyType = new PolicyType();
303 TargetType target = new TargetType();
305 // create guard attribute
306 AnyOfType anyOfType = new AnyOfType();
307 AllOfType alltype = new AllOfType();
308 MatchType matchType = new MatchType();
310 AttributeValueType attributeValue1 = new AttributeValueType();
311 attributeValue1.getContent().add("True");
312 matchType.setAttributeValue(attributeValue1);
314 AttributeDesignatorType designator = new AttributeDesignatorType();
315 designator.setAttributeId("guard");
316 matchType.setAttributeDesignator(designator);
317 alltype.getMatch().add(matchType);
319 // add a dummy MatchType object since while (matchList.size()>1 ...)
320 MatchType matchDummy = new MatchType();
322 AttributeValueType dummyValue = new AttributeValueType();
323 dummyValue.getContent().add("dummy");
324 matchDummy.setAttributeValue(dummyValue);
326 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
327 designatorDummy.setAttributeId("dummyId");
328 matchDummy.setAttributeDesignator(designatorDummy);
330 alltype.getMatch().add(matchDummy);
331 anyOfType.getAllOf().add(alltype);
333 target.getAnyOf().add(anyOfType);
335 // create RiskType attribute
336 AnyOfType anyRiskType = new AnyOfType();
337 AllOfType allRiskType = new AllOfType();
338 MatchType matchRiskType = new MatchType();
340 AttributeValueType riskTypeValue = new AttributeValueType();
341 riskTypeValue.getContent().add("test");
342 matchRiskType.setAttributeValue(riskTypeValue);
344 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
345 designatorRiskType.setAttributeId("RiskType");
346 matchRiskType.setAttributeDesignator(designatorRiskType);
347 allRiskType.getMatch().add(matchRiskType);
349 // add a dummy MatchType object since while (matchList.size()>1 ...)
350 MatchType matchDummy1 = new MatchType();
352 AttributeValueType dummy1Value = new AttributeValueType();
353 dummy1Value.getContent().add("dummy");
354 matchDummy1.setAttributeValue(dummy1Value);
356 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
357 designatorDummy1.setAttributeId("dummyId");
358 matchDummy1.setAttributeDesignator(designatorDummy1);
360 allRiskType.getMatch().add(matchDummy1);
362 anyRiskType.getAllOf().add(allRiskType);
364 target.getAnyOf().add(anyRiskType);
366 // create RiskLevel attribute
367 AnyOfType anyRiskLevel = new AnyOfType();
368 AllOfType allRiskLevel = new AllOfType();
369 MatchType matchRiskLevel = new MatchType();
371 AttributeValueType riskLevel = new AttributeValueType();
372 riskLevel.getContent().add("3");
373 matchRiskLevel.setAttributeValue(riskLevel);
375 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
376 designatorRiskLevel.setAttributeId("RiskLevel");
377 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
378 allRiskLevel.getMatch().add(matchRiskLevel);
380 // add a dummy MatchType object since while (matchList.size()>1 ...)
381 MatchType matchDummy2 = new MatchType();
383 AttributeValueType dummy2Value = new AttributeValueType();
384 dummy2Value.getContent().add("dummy");
385 matchDummy2.setAttributeValue(dummy2Value);
387 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
388 designatorDummy2.setAttributeId("dummyId");
389 matchDummy2.setAttributeDesignator(designatorDummy2);
391 allRiskLevel.getMatch().add(matchDummy2);
393 anyRiskLevel.getAllOf().add(allRiskLevel);
394 target.getAnyOf().add(anyRiskLevel);
396 policyType.setTarget(target);
398 restAdapter.setPolicyData(policyType);
400 controller.prePopulateDCAEMSPolicyData(restAdapter, entity);
402 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
403 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
404 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
406 assertEquals("True", restAdapter.getGuard());
407 assertEquals("3", restAdapter.getRiskLevel());
408 assertEquals("test", restAdapter.getRiskType());
410 } catch (Exception e) {
411 logger.error("testPrePopulateDCAEMSPolicyData", e);
412 fail("testPrePopulateDCAEMSPolicyData failed due to: " + e);
415 logger.debug("testPrePopulateDCAEMSPolicyData: exit");
420 * Run the Map<String,String> convert(String, String) method test
424 public void testConvert() {
425 logger.debug("testConvert: enter");
427 String str = "k1=v1,k2=v2,k3=v3";
429 Map<String, String> result = CreateDcaeMicroServiceController.convert(str, split);
430 assertTrue(result != null && result.size() == 3);
432 logger.debug("testConvert: exit");
436 * Run the Map<String,String> convertMap(Map<String,String>, Map<String,String>) method test
440 public void testConvertMap() {
441 logger.debug("testConvertMap: enter");
443 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
444 Map<String, String> attributesMap = new HashMap<String, String>();
445 Map<String, String> attributesRefMap = new HashMap<String, String>();
446 Map<String, String> attributesListRefMap = controller.getAttributesListRefMap();
447 Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList();
448 LinkedList<String> list = new LinkedList<String>();
450 attributesMap.put("keyOne", "valueOne");
451 attributesMap.put("keyTwo", "valueTwo");
452 attributesMap.put("keyThree", "valueThree");
454 attributesRefMap.put("key4", "value4");
455 attributesRefMap.put("key5", "value5");
456 attributesRefMap.put("key6", "value6");
458 attributesListRefMap.put("key7", "value7");
462 arrayTextList.put("key8", list);
464 Map<String, String> result = controller.convertMap(attributesMap, attributesRefMap);
466 assertTrue(result != null && result.size() == 8);
468 assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]"));
470 logger.debug("testConvertMap: exit");
474 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test
479 public void testSetMSModelData() {
481 logger.debug("testSetMSModelData: enter");
483 HttpServletRequest request = createMock(HttpServletRequest.class);
484 expect(request.getContentType())
485 .andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
486 expect(request.getMethod()).andReturn("post");
487 expect(request.getHeader("Content-length")).andReturn("7809");
489 expect(request.getContentLength()).andReturn(7809);
492 // value of fileName needs to be matched to your local directory
493 String fileName = "";
495 ClassLoader classLoader = getClass().getClassLoader();
497 new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile())
499 } catch (Exception e1) {
500 logger.error("Exception Occured while loading file" + e1);
502 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
503 expect(request.getCharacterEncoding()).andReturn("UTF-8");
504 expect(request.getContentLength()).andReturn(1024);
507 } catch (Exception e) {
508 logger.error("testSetMSModelData" + e);
512 logger.debug("testSetMSModelData: exit");
520 private class MockServletInputStream extends ServletInputStream {
522 InputStream fis = null;
524 public MockServletInputStream(String fileName) {
526 fis = new FileInputStream(fileName);
527 } catch (Exception genExe) {
528 genExe.printStackTrace();
533 public int read() throws IOException {
534 if (fis.available() > 0) {
541 public int read(byte[] bytes, int len, int size) throws IOException {
542 if (fis.available() > 0) {
543 int length = fis.read(bytes, len, size);
550 public boolean isFinished() {
555 public boolean isReady() {
560 public void setReadListener(ReadListener arg0) {