2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.controller;
24 import static org.easymock.EasyMock.createMock;
25 import static org.easymock.EasyMock.expect;
26 import static org.easymock.EasyMock.replay;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertTrue;
29 import static org.junit.Assert.fail;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.when;
33 import java.io.BufferedReader;
35 import java.io.FileInputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.StringReader;
39 import java.util.ArrayList;
40 import java.util.HashMap;
41 import java.util.LinkedList;
42 import java.util.List;
45 import javax.servlet.ReadListener;
46 import javax.servlet.ServletInputStream;
47 import javax.servlet.http.HttpServletRequest;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.onap.policy.common.logging.flexlogger.FlexLogger;
52 import org.onap.policy.common.logging.flexlogger.Logger;
53 import org.onap.policy.rest.adapter.PolicyRestAdapter;
54 import org.onap.policy.rest.dao.CommonClassDao;
55 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
56 import org.onap.policy.rest.jpa.MicroServiceModels;
57 import org.onap.policy.rest.jpa.PolicyEntity;
58 import org.springframework.mock.web.MockHttpServletRequest;
59 import org.springframework.mock.web.MockHttpServletResponse;
61 import com.fasterxml.jackson.databind.DeserializationFeature;
62 import com.fasterxml.jackson.databind.JsonNode;
63 import com.fasterxml.jackson.databind.ObjectMapper;
64 import com.github.fge.jackson.JsonLoader;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
75 * The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests
76 * for the class {@link <code>CreateDcaeMicroServiceController</code>}*
78 * All JUnits are designed to run in the local development environment
79 * where they have write privileges and can execute time-sensitive
86 public class CreateDcaeMicroServiceControllerTest {
88 private static Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceControllerTest.class);
89 private static CommonClassDao commonClassDao;
90 private String jsonString = null;
91 private String configBodyString = null;
92 private HttpServletRequest request = null;
95 public void setUp() throws Exception {
97 logger.info("setUp: Entering");
98 commonClassDao = mock(CommonClassDao.class);
99 List<Object> microServiceModelsData = new ArrayList<Object>();
100 MicroServiceModels testData = new MicroServiceModels();
101 testData.setVersion("OpenOnap-Junit");
102 microServiceModelsData.add(testData);
104 // mock the getDataById() call
105 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "test")).thenReturn(microServiceModelsData);
107 jsonString = "{\"policyData\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
108 + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
109 + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
110 + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
111 + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
112 + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
113 + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
114 + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
116 configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\","
117 + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\","
118 + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"SNIRO\"}}";
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");
130 * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter,
131 * JsonNode) method test
135 public void testSetDataToPolicyRestAdapter() {
137 logger.debug("testSetDataToPolicyRestAdapter: enter");
139 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
140 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
142 JsonNode root = null;
143 ObjectMapper mapper = new ObjectMapper();
144 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
145 PolicyRestAdapter policyData = null;
147 root = JsonLoader.fromString(jsonString);
148 policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
149 } catch (Exception e) {
150 logger.error("testSetDataToPolicyRestAdapter", e);
153 PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
154 assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
156 logger.debug("result.getJsonBody() : " + result.getJsonBody());
157 logger.debug("testSetDataToPolicyRestAdapter: exit");
161 * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest,
162 * HttpServletResponse) method test
166 public void testGetDCAEMSTemplateData() {
168 logger.debug("testGetDCAEMSTemplateData: enter");
170 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
171 MockHttpServletResponse response = new MockHttpServletResponse();
172 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
175 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
177 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
178 // mock the getReader() call
179 when(request.getReader()).thenReturn(br);
181 List<Object> microServiceModelsData = new ArrayList<Object>();
182 MicroServiceModels testData = new MicroServiceModels();
183 testData.setVersion("1707.4.1.2-Junit");
184 microServiceModelsData.add(testData);
185 // mock the getDataById() call with the same MS model name
186 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
188 controller.getDCAEMSTemplateData(request, response);
190 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeModelData"));
192 logger.debug("response: " + response.getContentAsString());
194 } catch (Exception e) {
195 logger.error("testGetDCAEMSTemplateData", e);
198 logger.debug("testGetDCAEMSTemplateData: exit");
202 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
203 * HttpServletResponse) method test
207 public void testGetModelServiceVersionData() {
209 logger.debug("testGetModelServiceVersionData: enter");
211 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
212 MockHttpServletResponse response = new MockHttpServletResponse();
213 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
216 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
218 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
219 // mock the getReader() call
220 when(request.getReader()).thenReturn(br);
222 List<Object> microServiceModelsData = new ArrayList<Object>();
223 MicroServiceModels testData = new MicroServiceModels();
224 testData.setVersion("1707.4.1.2-Junit");
225 microServiceModelsData.add(testData);
227 // mock the getDataById() call with the same MS model name
228 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
229 controller.getModelServiceVersionData(request, response);
231 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
233 logger.debug("response: " + response.getContentAsString());
235 } catch (Exception e) {
236 logger.error("testGetModelServiceVersionData", e);
237 fail("testGetModelServiceVersionData failed due to: " + e);
240 logger.debug("testGetModelServiceVersionData: exit");
244 * Run the void getDCAEPriorityValuesData(HttpServletRequest,
245 * HttpServletResponse) method test
249 public void testGetDCAEPriorityValuesData() {
251 logger.debug("testGetDCAEPriorityValuesData: enter");
253 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
255 MockHttpServletRequest request = new MockHttpServletRequest();
256 MockHttpServletResponse response = new MockHttpServletResponse();
258 controller.getDCAEPriorityValuesData(request, response);
259 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("priorityDatas"));
260 logger.debug("response: " + response.getContentAsString());
261 } catch (Exception e) {
262 logger.error("testGetDCAEPriorityValuesData", e);
263 fail("testGetDCAEPriorityValuesData failed due to: " + e);
266 logger.debug("testGetDCAEPriorityValuesData: exit");
270 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
271 * PolicyEntity) method test
275 public void testPrePopulateDCAEMSPolicyData() {
277 logger.debug("testPrePopulateDCAEMSPolicyData: enter");
279 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
281 // populate an entity object for testing
282 PolicyEntity entity = new PolicyEntity();
283 ConfigurationDataEntity configData = new ConfigurationDataEntity();
284 configData.setConfigBody(configBodyString);
285 entity.setConfigurationData(configData);
287 JsonNode root = null;
288 ObjectMapper mapper = new ObjectMapper();
289 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
290 PolicyRestAdapter restAdapter = null;
293 root = JsonLoader.fromString(jsonString);
294 restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
295 PolicyType policyType = new PolicyType();
296 TargetType target = new TargetType();
298 // create guard attribute
299 AnyOfType anyOfType = new AnyOfType();
300 AllOfType alltype = new AllOfType();
301 MatchType matchType = new MatchType();
303 AttributeValueType attributeValue1 = new AttributeValueType();
304 attributeValue1.getContent().add("True");
305 matchType.setAttributeValue(attributeValue1);
307 AttributeDesignatorType designator = new AttributeDesignatorType();
308 designator.setAttributeId("guard");
309 matchType.setAttributeDesignator(designator);
310 alltype.getMatch().add(matchType);
312 // add a dummy MatchType object since while (matchList.size()>1 ...)
313 MatchType matchDummy = new MatchType();
315 AttributeValueType dummyValue = new AttributeValueType();
316 dummyValue.getContent().add("dummy");
317 matchDummy.setAttributeValue(dummyValue);
319 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
320 designatorDummy.setAttributeId("dummyId");
321 matchDummy.setAttributeDesignator(designatorDummy);
323 alltype.getMatch().add(matchDummy);
324 anyOfType.getAllOf().add(alltype);
326 target.getAnyOf().add(anyOfType);
328 // create RiskType attribute
329 AnyOfType anyRiskType = new AnyOfType();
330 AllOfType allRiskType = new AllOfType();
331 MatchType matchRiskType = new MatchType();
333 AttributeValueType riskTypeValue = new AttributeValueType();
334 riskTypeValue.getContent().add("test");
335 matchRiskType.setAttributeValue(riskTypeValue);
337 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
338 designatorRiskType.setAttributeId("RiskType");
339 matchRiskType.setAttributeDesignator(designatorRiskType);
340 allRiskType.getMatch().add(matchRiskType);
342 // add a dummy MatchType object since while (matchList.size()>1 ...)
343 MatchType matchDummy1 = new MatchType();
345 AttributeValueType dummy1Value = new AttributeValueType();
346 dummy1Value.getContent().add("dummy");
347 matchDummy1.setAttributeValue(dummy1Value);
349 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
350 designatorDummy1.setAttributeId("dummyId");
351 matchDummy1.setAttributeDesignator(designatorDummy1);
353 allRiskType.getMatch().add(matchDummy1);
355 anyRiskType.getAllOf().add(allRiskType);
357 target.getAnyOf().add(anyRiskType);
359 // create RiskLevel attribute
360 AnyOfType anyRiskLevel = new AnyOfType();
361 AllOfType allRiskLevel = new AllOfType();
362 MatchType matchRiskLevel = new MatchType();
364 AttributeValueType riskLevel = new AttributeValueType();
365 riskLevel.getContent().add("3");
366 matchRiskLevel.setAttributeValue(riskLevel);
368 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
369 designatorRiskLevel.setAttributeId("RiskLevel");
370 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
371 allRiskLevel.getMatch().add(matchRiskLevel);
373 // add a dummy MatchType object since while (matchList.size()>1 ...)
374 MatchType matchDummy2 = new MatchType();
376 AttributeValueType dummy2Value = new AttributeValueType();
377 dummy2Value.getContent().add("dummy");
378 matchDummy2.setAttributeValue(dummy2Value);
380 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
381 designatorDummy2.setAttributeId("dummyId");
382 matchDummy2.setAttributeDesignator(designatorDummy2);
384 allRiskLevel.getMatch().add(matchDummy2);
386 anyRiskLevel.getAllOf().add(allRiskLevel);
387 target.getAnyOf().add(anyRiskLevel);
389 policyType.setTarget(target);
391 restAdapter.setPolicyData(policyType);
393 controller.prePopulateDCAEMSPolicyData(restAdapter, entity);
395 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
396 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
397 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
399 assertEquals("True", restAdapter.getGuard());
400 assertEquals("3", restAdapter.getRiskLevel());
401 assertEquals("test", restAdapter.getRiskType());
403 } catch (Exception e) {
404 logger.error("testPrePopulateDCAEMSPolicyData", e);
405 fail("testPrePopulateDCAEMSPolicyData failed due to: " + e);
408 logger.debug("testPrePopulateDCAEMSPolicyData: exit");
413 * Run the Map<String,String> convert(String, String) method test
417 public void testConvert(){
418 logger.debug("testConvert: enter");
420 String str = "k1=v1,k2=v2,k3=v3";
422 Map<String,String> result = CreateDcaeMicroServiceController.convert(str, split);
423 assertTrue(result != null && result.size() == 3);
425 logger.debug("testConvert: exit");
429 * Run the Map<String,String> convertMap(Map<String,String>,
430 * Map<String,String>) method test
434 public void testConvertMap(){
435 logger.debug("testConvertMap: enter");
437 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
438 Map<String,String> attributesMap = new HashMap<String, String>();
439 Map<String,String> attributesRefMap = new HashMap<String, String>();
440 Map<String,String> attributesListRefMap = controller.getAttributesListRefMap();
441 Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList();
442 LinkedList<String> list = new LinkedList<String>();
444 attributesMap.put("keyOne", "valueOne");
445 attributesMap.put("keyTwo", "valueTwo");
446 attributesMap.put("keyThree", "valueThree");
448 attributesRefMap.put("key4", "value4");
449 attributesRefMap.put("key5", "value5");
450 attributesRefMap.put("key6", "value6");
452 attributesListRefMap.put("key7", "value7");
456 arrayTextList.put("key8", list);
458 Map<String,String> result = controller.convertMap(attributesMap, attributesRefMap);
460 assertTrue(result != null && result.size() == 8);
462 assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]"));
464 logger.debug("testConvertMap: exit");
468 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
474 public void testSetMSModelData() {
476 logger.debug("testSetMSModelData: enter");
478 HttpServletRequest request = createMock(HttpServletRequest.class);
479 expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
480 expect(request.getMethod()).andReturn("post");
481 expect(request.getHeader("Content-length")).andReturn("7809");
483 expect(request.getContentLength()).andReturn(7809);
486 // value of fileName needs to be matched to your local directory
487 String fileName = "";
489 ClassLoader classLoader = getClass().getClassLoader();
490 fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
491 } catch (Exception e1) {
492 logger.error("Exception Occured while loading file"+e1);
494 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
495 expect(request.getCharacterEncoding()).andReturn("UTF-8");
496 expect(request.getContentLength()).andReturn(1024);
499 } catch (Exception e) {
500 logger.error("testSetMSModelData" + e);
504 logger.debug("testSetMSModelData: exit");
512 private class MockServletInputStream extends ServletInputStream {
514 InputStream fis = null;
515 public MockServletInputStream(String fileName) {
517 fis = new FileInputStream(fileName);
518 } catch (Exception genExe) {
519 genExe.printStackTrace();
523 public int read() throws IOException {
524 if(fis.available() > 0) {
531 public int read(byte[] bytes, int len, int size) throws IOException {
532 if(fis.available() > 0) {
533 int length = fis.read(bytes, len, size);
539 public boolean isFinished() {
543 public boolean isReady() {
547 public void setReadListener(ReadListener arg0) {