2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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);
280 fail("testGetDCAEMSTemplateData failed due to: " + e);
283 logger.debug("testGetDCAEMSTemplateData: exit");
287 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
288 * HttpServletResponse) method test
292 public void testGetModelServiceVersionData() {
294 logger.debug("testGetModelServiceVersionData: enter");
296 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
297 MockHttpServletResponse response = new MockHttpServletResponse();
298 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
301 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
303 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
304 // mock the getReader() call
305 when(request.getReader()).thenReturn(br);
307 List<Object> microServiceModelsData = new ArrayList<Object>();
308 MicroServiceModels testData = new MicroServiceModels();
309 testData.setVersion("1707.4.1.2-Junit");
310 microServiceModelsData.add(testData);
312 // mock the getDataById() call with the same MS model name
313 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
314 controller.getModelServiceVersionData(request, response);
316 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
318 logger.debug("response: " + response.getContentAsString());
320 } catch (Exception e) {
321 logger.error("testGetModelServiceVersionData", e);
322 fail("testGetModelServiceVersionData failed due to: " + e);
325 logger.debug("testGetModelServiceVersionData: exit");
329 * Run the void getDCAEPriorityValuesData(HttpServletRequest,
330 * HttpServletResponse) method test
334 public void testGetDCAEPriorityValuesData() {
336 logger.debug("testGetDCAEPriorityValuesData: enter");
338 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
340 MockHttpServletRequest request = new MockHttpServletRequest();
341 MockHttpServletResponse response = new MockHttpServletResponse();
343 controller.getDCAEPriorityValuesData(request, response);
344 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("priorityDatas"));
345 logger.debug("response: " + response.getContentAsString());
346 } catch (Exception e) {
347 logger.error("testGetDCAEPriorityValuesData", e);
348 fail("testGetDCAEPriorityValuesData failed due to: " + e);
351 logger.debug("testGetDCAEPriorityValuesData: exit");
355 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
356 * PolicyEntity) method test
360 public void testPrePopulateDCAEMSPolicyData() {
362 logger.debug("testPrePopulateDCAEMSPolicyData: enter");
364 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
366 // populate an entity object for testing
367 PolicyEntity entity = new PolicyEntity();
368 ConfigurationDataEntity configData = new ConfigurationDataEntity();
369 configData.setConfigBody(configBodyString);
370 entity.setConfigurationData(configData);
372 JsonNode root = null;
373 ObjectMapper mapper = new ObjectMapper();
374 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
375 PolicyRestAdapter restAdapter = null;
378 root = JsonLoader.fromString(jsonString);
379 restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
380 PolicyType policyType = new PolicyType();
381 TargetType target = new TargetType();
383 // create guard attribute
384 AnyOfType anyOfType = new AnyOfType();
385 AllOfType alltype = new AllOfType();
386 MatchType matchType = new MatchType();
388 AttributeValueType attributeValue1 = new AttributeValueType();
389 attributeValue1.getContent().add("True");
390 matchType.setAttributeValue(attributeValue1);
392 AttributeDesignatorType designator = new AttributeDesignatorType();
393 designator.setAttributeId("guard");
394 matchType.setAttributeDesignator(designator);
395 alltype.getMatch().add(matchType);
397 // add a dummy MatchType object since while (matchList.size()>1 ...)
398 MatchType matchDummy = new MatchType();
400 AttributeValueType dummyValue = new AttributeValueType();
401 dummyValue.getContent().add("dummy");
402 matchDummy.setAttributeValue(dummyValue);
404 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
405 designatorDummy.setAttributeId("dummyId");
406 matchDummy.setAttributeDesignator(designatorDummy);
408 alltype.getMatch().add(matchDummy);
409 anyOfType.getAllOf().add(alltype);
411 target.getAnyOf().add(anyOfType);
413 // create RiskType attribute
414 AnyOfType anyRiskType = new AnyOfType();
415 AllOfType allRiskType = new AllOfType();
416 MatchType matchRiskType = new MatchType();
418 AttributeValueType riskTypeValue = new AttributeValueType();
419 riskTypeValue.getContent().add("test");
420 matchRiskType.setAttributeValue(riskTypeValue);
422 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
423 designatorRiskType.setAttributeId("RiskType");
424 matchRiskType.setAttributeDesignator(designatorRiskType);
425 allRiskType.getMatch().add(matchRiskType);
427 // add a dummy MatchType object since while (matchList.size()>1 ...)
428 MatchType matchDummy1 = new MatchType();
430 AttributeValueType dummy1Value = new AttributeValueType();
431 dummy1Value.getContent().add("dummy");
432 matchDummy1.setAttributeValue(dummy1Value);
434 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
435 designatorDummy1.setAttributeId("dummyId");
436 matchDummy1.setAttributeDesignator(designatorDummy1);
438 allRiskType.getMatch().add(matchDummy1);
440 anyRiskType.getAllOf().add(allRiskType);
442 target.getAnyOf().add(anyRiskType);
444 // create RiskLevel attribute
445 AnyOfType anyRiskLevel = new AnyOfType();
446 AllOfType allRiskLevel = new AllOfType();
447 MatchType matchRiskLevel = new MatchType();
449 AttributeValueType riskLevel = new AttributeValueType();
450 riskLevel.getContent().add("3");
451 matchRiskLevel.setAttributeValue(riskLevel);
453 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
454 designatorRiskLevel.setAttributeId("RiskLevel");
455 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
456 allRiskLevel.getMatch().add(matchRiskLevel);
458 // add a dummy MatchType object since while (matchList.size()>1 ...)
459 MatchType matchDummy2 = new MatchType();
461 AttributeValueType dummy2Value = new AttributeValueType();
462 dummy2Value.getContent().add("dummy");
463 matchDummy2.setAttributeValue(dummy2Value);
465 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
466 designatorDummy2.setAttributeId("dummyId");
467 matchDummy2.setAttributeDesignator(designatorDummy2);
469 allRiskLevel.getMatch().add(matchDummy2);
471 anyRiskLevel.getAllOf().add(allRiskLevel);
472 target.getAnyOf().add(anyRiskLevel);
474 policyType.setTarget(target);
476 restAdapter.setPolicyData(policyType);
478 controller.prePopulateDCAEMSPolicyData(restAdapter, entity);
480 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
481 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
482 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
484 assertEquals("True", restAdapter.getGuard());
485 assertEquals("3", restAdapter.getRiskLevel());
486 assertEquals("test", restAdapter.getRiskType());
488 } catch (Exception e) {
489 logger.error("testPrePopulateDCAEMSPolicyData", e);
490 fail("testPrePopulateDCAEMSPolicyData failed due to: " + e);
493 logger.debug("testPrePopulateDCAEMSPolicyData: exit");
498 * Run the Map<String,String> convert(String, String) method test
502 public void testConvert(){
503 logger.debug("testConvert: enter");
505 String str = "k1=v1,k2=v2,k3=v3";
507 Map<String,String> result = CreateDcaeMicroServiceController.convert(str, split);
508 assertTrue(result != null && result.size() == 3);
510 logger.debug("testConvert: exit");
514 * Run the Map<String,String> convertMap(Map<String,String>,
515 * Map<String,String>) method test
519 public void testConvertMap(){
520 logger.debug("testConvertMap: enter");
522 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
523 Map<String,String> attributesMap = new HashMap<String, String>();
524 Map<String,String> attributesRefMap = new HashMap<String, String>();
525 Map<String,String> attributesListRefMap = controller.getAttributesListRefMap();
526 Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList();
527 LinkedList<String> list = new LinkedList<String>();
529 attributesMap.put("keyOne", "valueOne");
530 attributesMap.put("keyTwo", "valueTwo");
531 attributesMap.put("keyThree", "valueThree");
533 attributesRefMap.put("key4", "value4");
534 attributesRefMap.put("key5", "value5");
535 attributesRefMap.put("key6", "value6");
537 attributesListRefMap.put("key7", "value7");
541 arrayTextList.put("key8", list);
543 Map<String,String> result = controller.convertMap(attributesMap, attributesRefMap);
545 assertTrue(result != null && result.size() == 8);
547 assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]"));
549 logger.debug("testConvertMap: exit");
553 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
557 //Ignore it for now due to Stream ended unexpectedly
560 public void testSetMSModelData() {
562 logger.debug("testSetMSModelData: enter");
564 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
566 MockHttpServletResponse response = new MockHttpServletResponse();
568 HttpServletRequest request = createMock(HttpServletRequest.class);
569 expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
570 expect(request.getMethod()).andReturn("post");
571 expect(request.getHeader("Content-length")).andReturn("7809");
573 expect(request.getContentLength()).andReturn(7809);
576 // value of fileName needs to be matched to your local directory
577 String fileName = "";
579 ClassLoader classLoader = getClass().getClassLoader();
580 fileName = new File(classLoader.getResource("schedulerPolicies1707.xmi").getFile()).getAbsolutePath();
581 } catch (Exception e1) {
582 logger.error("Exception Occured while loading file"+e1);
584 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
585 expect(request.getCharacterEncoding()).andReturn("UTF-8");
586 expect(request.getContentLength()).andReturn(1024);
589 controller.SetMSModelData(request, response);
591 } catch (Exception e) {
592 logger.error("testSetMSModelData" + e);
598 logger.debug("testSetMSModelData: exit");
606 private class MockServletInputStream extends ServletInputStream {
608 InputStream fis = null;
609 public MockServletInputStream(String fileName) {
611 fis = new FileInputStream(fileName);
612 } catch (Exception genExe) {
613 genExe.printStackTrace();
617 public int read() throws IOException {
618 if(fis.available() > 0) {
625 public int read(byte[] bytes, int len, int size) throws IOException {
626 if(fis.available() > 0) {
627 int length = fis.read(bytes, len, size);
633 public boolean isFinished() {
637 public boolean isReady() {
641 public void setReadListener(ReadListener arg0) {