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 void stringBetweenDots(String, String) method test
165 public void testStringBetweenDots() {
167 logger.debug("testStringBetweenDots: enter");
169 //expect: uniqueKeys should contain a string value
170 CreateDcaeMicroServiceController controllerA = new CreateDcaeMicroServiceController();
171 String str = "testing\\.byCorrectWay\\.OfDATA";
172 assertEquals(1, controllerA.stringBetweenDots(str));
174 //expect: uniqueKeys should not contain a string value
175 str = "testing\byWrongtWay.\\OfDATA";
176 CreateDcaeMicroServiceController controllerB = new CreateDcaeMicroServiceController();
177 assertEquals(0, controllerB.stringBetweenDots(str));
179 logger.debug("testStringBetweenDots: exit");
183 * Run the Map<String,String> load(String) method test
187 public void testLoad() {
189 logger.debug("testLoad: enter");
191 boolean isLocalTesting = true;
192 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
193 String fileName = null;
194 Map<String,String> result = null;
196 ClassLoader classLoader = getClass().getClassLoader();
197 fileName = new File(classLoader.getResource("policy_tosca_tca_v1707.yml").getFile()).getAbsolutePath();
198 } catch (Exception e1) {
199 logger.error("Exception Occured while loading file"+e1);
203 result = controller.load(fileName);
204 } catch (IOException e) {
205 logger.error("testLoad", e);
209 assertTrue(result != null && !result.isEmpty());
210 logger.debug("result : " + result);
213 logger.debug("testLoad: exit");
217 * Run the void parseTosca(String) method test
221 public void testParseTosca() {
223 logger.debug("testParseTosca: enter");
224 boolean isLocalTesting = true;
225 String fileName = null;
227 ClassLoader classLoader = getClass().getClassLoader();
228 fileName = new File(classLoader.getResource("policy_tosca_tca_v1707.yml").getFile()).getAbsolutePath();
229 } catch (Exception e1) {
230 logger.error("Exception Occured while loading file"+e1);
233 CreateDcaeMicroServiceController contoller = new CreateDcaeMicroServiceController();
236 contoller.parseTosca(fileName);
237 }catch (Exception e) {
238 fail("parseTosca caused error: " + e);
241 logger.debug("testParseTosca: exit");
245 * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest,
246 * HttpServletResponse) method test
250 public void testGetDCAEMSTemplateData() {
252 logger.debug("testGetDCAEMSTemplateData: enter");
254 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
255 MockHttpServletResponse response = new MockHttpServletResponse();
256 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
259 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
261 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
262 // mock the getReader() call
263 when(request.getReader()).thenReturn(br);
265 List<Object> microServiceModelsData = new ArrayList<Object>();
266 MicroServiceModels testData = new MicroServiceModels();
267 testData.setVersion("1707.4.1.2-Junit");
268 microServiceModelsData.add(testData);
269 // mock the getDataById() call with the same MS model name
270 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
272 controller.getDCAEMSTemplateData(request, response);
274 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeModelData"));
276 logger.debug("response: " + response.getContentAsString());
278 } catch (Exception e) {
279 logger.error("testGetDCAEMSTemplateData", e);
282 logger.debug("testGetDCAEMSTemplateData: exit");
286 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
287 * HttpServletResponse) method test
291 public void testGetModelServiceVersionData() {
293 logger.debug("testGetModelServiceVersionData: enter");
295 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
296 MockHttpServletResponse response = new MockHttpServletResponse();
297 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
300 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
302 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
303 // mock the getReader() call
304 when(request.getReader()).thenReturn(br);
306 List<Object> microServiceModelsData = new ArrayList<Object>();
307 MicroServiceModels testData = new MicroServiceModels();
308 testData.setVersion("1707.4.1.2-Junit");
309 microServiceModelsData.add(testData);
311 // mock the getDataById() call with the same MS model name
312 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
313 controller.getModelServiceVersionData(request, response);
315 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
317 logger.debug("response: " + response.getContentAsString());
319 } catch (Exception e) {
320 logger.error("testGetModelServiceVersionData", e);
321 fail("testGetModelServiceVersionData failed due to: " + e);
324 logger.debug("testGetModelServiceVersionData: exit");
328 * Run the void getDCAEPriorityValuesData(HttpServletRequest,
329 * HttpServletResponse) method test
333 public void testGetDCAEPriorityValuesData() {
335 logger.debug("testGetDCAEPriorityValuesData: enter");
337 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
339 MockHttpServletRequest request = new MockHttpServletRequest();
340 MockHttpServletResponse response = new MockHttpServletResponse();
342 controller.getDCAEPriorityValuesData(request, response);
343 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("priorityDatas"));
344 logger.debug("response: " + response.getContentAsString());
345 } catch (Exception e) {
346 logger.error("testGetDCAEPriorityValuesData", e);
347 fail("testGetDCAEPriorityValuesData failed due to: " + e);
350 logger.debug("testGetDCAEPriorityValuesData: exit");
354 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
355 * PolicyEntity) method test
359 public void testPrePopulateDCAEMSPolicyData() {
361 logger.debug("testPrePopulateDCAEMSPolicyData: enter");
363 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
365 // populate an entity object for testing
366 PolicyEntity entity = new PolicyEntity();
367 ConfigurationDataEntity configData = new ConfigurationDataEntity();
368 configData.setConfigBody(configBodyString);
369 entity.setConfigurationData(configData);
371 JsonNode root = null;
372 ObjectMapper mapper = new ObjectMapper();
373 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
374 PolicyRestAdapter restAdapter = null;
377 root = JsonLoader.fromString(jsonString);
378 restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
379 PolicyType policyType = new PolicyType();
380 TargetType target = new TargetType();
382 // create guard attribute
383 AnyOfType anyOfType = new AnyOfType();
384 AllOfType alltype = new AllOfType();
385 MatchType matchType = new MatchType();
387 AttributeValueType attributeValue1 = new AttributeValueType();
388 attributeValue1.getContent().add("True");
389 matchType.setAttributeValue(attributeValue1);
391 AttributeDesignatorType designator = new AttributeDesignatorType();
392 designator.setAttributeId("guard");
393 matchType.setAttributeDesignator(designator);
394 alltype.getMatch().add(matchType);
396 // add a dummy MatchType object since while (matchList.size()>1 ...)
397 MatchType matchDummy = new MatchType();
399 AttributeValueType dummyValue = new AttributeValueType();
400 dummyValue.getContent().add("dummy");
401 matchDummy.setAttributeValue(dummyValue);
403 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
404 designatorDummy.setAttributeId("dummyId");
405 matchDummy.setAttributeDesignator(designatorDummy);
407 alltype.getMatch().add(matchDummy);
408 anyOfType.getAllOf().add(alltype);
410 target.getAnyOf().add(anyOfType);
412 // create RiskType attribute
413 AnyOfType anyRiskType = new AnyOfType();
414 AllOfType allRiskType = new AllOfType();
415 MatchType matchRiskType = new MatchType();
417 AttributeValueType riskTypeValue = new AttributeValueType();
418 riskTypeValue.getContent().add("test");
419 matchRiskType.setAttributeValue(riskTypeValue);
421 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
422 designatorRiskType.setAttributeId("RiskType");
423 matchRiskType.setAttributeDesignator(designatorRiskType);
424 allRiskType.getMatch().add(matchRiskType);
426 // add a dummy MatchType object since while (matchList.size()>1 ...)
427 MatchType matchDummy1 = new MatchType();
429 AttributeValueType dummy1Value = new AttributeValueType();
430 dummy1Value.getContent().add("dummy");
431 matchDummy1.setAttributeValue(dummy1Value);
433 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
434 designatorDummy1.setAttributeId("dummyId");
435 matchDummy1.setAttributeDesignator(designatorDummy1);
437 allRiskType.getMatch().add(matchDummy1);
439 anyRiskType.getAllOf().add(allRiskType);
441 target.getAnyOf().add(anyRiskType);
443 // create RiskLevel attribute
444 AnyOfType anyRiskLevel = new AnyOfType();
445 AllOfType allRiskLevel = new AllOfType();
446 MatchType matchRiskLevel = new MatchType();
448 AttributeValueType riskLevel = new AttributeValueType();
449 riskLevel.getContent().add("3");
450 matchRiskLevel.setAttributeValue(riskLevel);
452 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
453 designatorRiskLevel.setAttributeId("RiskLevel");
454 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
455 allRiskLevel.getMatch().add(matchRiskLevel);
457 // add a dummy MatchType object since while (matchList.size()>1 ...)
458 MatchType matchDummy2 = new MatchType();
460 AttributeValueType dummy2Value = new AttributeValueType();
461 dummy2Value.getContent().add("dummy");
462 matchDummy2.setAttributeValue(dummy2Value);
464 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
465 designatorDummy2.setAttributeId("dummyId");
466 matchDummy2.setAttributeDesignator(designatorDummy2);
468 allRiskLevel.getMatch().add(matchDummy2);
470 anyRiskLevel.getAllOf().add(allRiskLevel);
471 target.getAnyOf().add(anyRiskLevel);
473 policyType.setTarget(target);
475 restAdapter.setPolicyData(policyType);
477 controller.prePopulateDCAEMSPolicyData(restAdapter, entity);
479 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
480 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
481 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
483 assertEquals("True", restAdapter.getGuard());
484 assertEquals("3", restAdapter.getRiskLevel());
485 assertEquals("test", restAdapter.getRiskType());
487 } catch (Exception e) {
488 logger.error("testPrePopulateDCAEMSPolicyData", e);
489 fail("testPrePopulateDCAEMSPolicyData failed due to: " + e);
492 logger.debug("testPrePopulateDCAEMSPolicyData: exit");
497 * Run the Map<String,String> convert(String, String) method test
501 public void testConvert(){
502 logger.debug("testConvert: enter");
504 String str = "k1=v1,k2=v2,k3=v3";
506 Map<String,String> result = CreateDcaeMicroServiceController.convert(str, split);
507 assertTrue(result != null && result.size() == 3);
509 logger.debug("testConvert: exit");
513 * Run the Map<String,String> convertMap(Map<String,String>,
514 * Map<String,String>) method test
518 public void testConvertMap(){
519 logger.debug("testConvertMap: enter");
521 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
522 Map<String,String> attributesMap = new HashMap<String, String>();
523 Map<String,String> attributesRefMap = new HashMap<String, String>();
524 Map<String,String> attributesListRefMap = controller.getAttributesListRefMap();
525 Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList();
526 LinkedList<String> list = new LinkedList<String>();
528 attributesMap.put("keyOne", "valueOne");
529 attributesMap.put("keyTwo", "valueTwo");
530 attributesMap.put("keyThree", "valueThree");
532 attributesRefMap.put("key4", "value4");
533 attributesRefMap.put("key5", "value5");
534 attributesRefMap.put("key6", "value6");
536 attributesListRefMap.put("key7", "value7");
540 arrayTextList.put("key8", list);
542 Map<String,String> result = controller.convertMap(attributesMap, attributesRefMap);
544 assertTrue(result != null && result.size() == 8);
546 assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]"));
548 logger.debug("testConvertMap: exit");
552 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
558 public void testSetMSModelData() {
560 logger.debug("testSetMSModelData: enter");
562 HttpServletRequest request = createMock(HttpServletRequest.class);
563 expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
564 expect(request.getMethod()).andReturn("post");
565 expect(request.getHeader("Content-length")).andReturn("7809");
567 expect(request.getContentLength()).andReturn(7809);
570 // value of fileName needs to be matched to your local directory
571 String fileName = "";
573 ClassLoader classLoader = getClass().getClassLoader();
574 fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
575 } catch (Exception e1) {
576 logger.error("Exception Occured while loading file"+e1);
578 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
579 expect(request.getCharacterEncoding()).andReturn("UTF-8");
580 expect(request.getContentLength()).andReturn(1024);
583 } catch (Exception e) {
584 logger.error("testSetMSModelData" + e);
590 logger.debug("testSetMSModelData: exit");
598 private class MockServletInputStream extends ServletInputStream {
600 InputStream fis = null;
601 public MockServletInputStream(String fileName) {
603 fis = new FileInputStream(fileName);
604 } catch (Exception genExe) {
605 genExe.printStackTrace();
609 public int read() throws IOException {
610 if(fis.available() > 0) {
617 public int read(byte[] bytes, int len, int size) throws IOException {
618 if(fis.available() > 0) {
619 int length = fis.read(bytes, len, size);
625 public boolean isFinished() {
629 public boolean isReady() {
633 public void setReadListener(ReadListener arg0) {