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.openecomp.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.openecomp.policy.common.logging.flexlogger.FlexLogger;
52 import org.openecomp.policy.common.logging.flexlogger.Logger;
53 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
54 import org.openecomp.policy.rest.dao.CommonClassDao;
55 import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
56 import org.openecomp.policy.rest.jpa.MicroServiceModels;
57 import org.openecomp.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("OpenEcomp-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\", \"ecompName\": \"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";
173 assertEquals(1, controllerA.stringBetweenDots(str));
175 //expect: uniqueKeys should not contain a string value
176 str = "testing\byWrongtWay.\\OfDATA";
177 CreateDcaeMicroServiceController controllerB = new CreateDcaeMicroServiceController();
178 assertEquals(0, controllerB.stringBetweenDots(str));
180 logger.debug("testStringBetweenDots: exit");
184 * Run the Map<String,String> load(String) method test
188 public void testLoad() {
190 logger.debug("testLoad: enter");
192 boolean isLocalTesting = true;
193 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
194 String fileName = null;
195 Map<String,String> result = null;
197 ClassLoader classLoader = getClass().getClassLoader();
198 fileName = new File(classLoader.getResource("policy_tosca_tca_v1707.yml").getFile()).getAbsolutePath();
199 } catch (Exception e1) {
200 logger.error("Exception Occured while loading file"+e1);
204 result = controller.load(fileName);
205 } catch (IOException e) {
206 logger.error("testLoad", e);
210 assertTrue(result != null && !result.isEmpty());
211 logger.debug("result : " + result);
214 logger.debug("testLoad: exit");
218 * Run the void parseTosca(String) method test
222 public void testParseTosca() {
224 logger.debug("testParseTosca: enter");
225 boolean isLocalTesting = true;
226 String fileName = null;
228 ClassLoader classLoader = getClass().getClassLoader();
229 fileName = new File(classLoader.getResource("policy_tosca_tca_v1707.yml").getFile()).getAbsolutePath();
230 } catch (Exception e1) {
231 logger.error("Exception Occured while loading file"+e1);
234 CreateDcaeMicroServiceController contoller = new CreateDcaeMicroServiceController();
237 contoller.parseTosca(fileName);
238 }catch (Exception e) {
239 fail("parseTosca caused error: " + e);
242 logger.debug("testParseTosca: exit");
246 * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest,
247 * HttpServletResponse) method test
251 public void testGetDCAEMSTemplateData() {
253 logger.debug("testGetDCAEMSTemplateData: enter");
255 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
256 MockHttpServletResponse response = new MockHttpServletResponse();
257 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
260 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
262 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
263 // mock the getReader() call
264 when(request.getReader()).thenReturn(br);
266 List<Object> microServiceModelsData = new ArrayList<Object>();
267 MicroServiceModels testData = new MicroServiceModels();
268 testData.setVersion("1707.4.1.2-Junit");
269 microServiceModelsData.add(testData);
270 // mock the getDataById() call with the same MS model name
271 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
273 controller.getDCAEMSTemplateData(request, response);
275 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeModelData"));
277 logger.debug("response: " + response.getContentAsString());
279 } catch (Exception e) {
280 logger.error("testGetDCAEMSTemplateData", e);
281 fail("testGetDCAEMSTemplateData failed due to: " + e);
284 logger.debug("testGetDCAEMSTemplateData: exit");
288 * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
289 * HttpServletResponse) method test
293 public void testGetModelServiceVersionData() {
295 logger.debug("testGetModelServiceVersionData: enter");
297 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
298 MockHttpServletResponse response = new MockHttpServletResponse();
299 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
302 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
304 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
305 // mock the getReader() call
306 when(request.getReader()).thenReturn(br);
308 List<Object> microServiceModelsData = new ArrayList<Object>();
309 MicroServiceModels testData = new MicroServiceModels();
310 testData.setVersion("1707.4.1.2-Junit");
311 microServiceModelsData.add(testData);
313 // mock the getDataById() call with the same MS model name
314 when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
315 controller.getModelServiceVersionData(request, response);
317 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
319 logger.debug("response: " + response.getContentAsString());
321 } catch (Exception e) {
322 logger.error("testGetModelServiceVersionData", e);
323 fail("testGetModelServiceVersionData failed due to: " + e);
326 logger.debug("testGetModelServiceVersionData: exit");
330 * Run the void getDCAEPriorityValuesData(HttpServletRequest,
331 * HttpServletResponse) method test
335 public void testGetDCAEPriorityValuesData() {
337 logger.debug("testGetDCAEPriorityValuesData: enter");
339 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
341 MockHttpServletRequest request = new MockHttpServletRequest();
342 MockHttpServletResponse response = new MockHttpServletResponse();
344 controller.getDCAEPriorityValuesData(request, response);
345 assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("priorityDatas"));
346 logger.debug("response: " + response.getContentAsString());
347 } catch (Exception e) {
348 logger.error("testGetDCAEPriorityValuesData", e);
349 fail("testGetDCAEPriorityValuesData failed due to: " + e);
352 logger.debug("testGetDCAEPriorityValuesData: exit");
356 * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
357 * PolicyEntity) method test
361 public void testPrePopulateDCAEMSPolicyData() {
363 logger.debug("testPrePopulateDCAEMSPolicyData: enter");
365 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
367 // populate an entity object for testing
368 PolicyEntity entity = new PolicyEntity();
369 ConfigurationDataEntity configData = new ConfigurationDataEntity();
370 configData.setConfigBody(configBodyString);
371 entity.setConfigurationData(configData);
373 JsonNode root = null;
374 ObjectMapper mapper = new ObjectMapper();
375 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
376 PolicyRestAdapter restAdapter = null;
379 root = JsonLoader.fromString(jsonString);
380 restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
381 PolicyType policyType = new PolicyType();
382 TargetType target = new TargetType();
384 // create guard attribute
385 AnyOfType anyOfType = new AnyOfType();
386 AllOfType alltype = new AllOfType();
387 MatchType matchType = new MatchType();
389 AttributeValueType attributeValue1 = new AttributeValueType();
390 attributeValue1.getContent().add("True");
391 matchType.setAttributeValue(attributeValue1);
393 AttributeDesignatorType designator = new AttributeDesignatorType();
394 designator.setAttributeId("guard");
395 matchType.setAttributeDesignator(designator);
396 alltype.getMatch().add(matchType);
398 // add a dummy MatchType object since while (matchList.size()>1 ...)
399 MatchType matchDummy = new MatchType();
401 AttributeValueType dummyValue = new AttributeValueType();
402 dummyValue.getContent().add("dummy");
403 matchDummy.setAttributeValue(dummyValue);
405 AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
406 designatorDummy.setAttributeId("dummyId");
407 matchDummy.setAttributeDesignator(designatorDummy);
409 alltype.getMatch().add(matchDummy);
410 anyOfType.getAllOf().add(alltype);
412 target.getAnyOf().add(anyOfType);
414 // create RiskType attribute
415 AnyOfType anyRiskType = new AnyOfType();
416 AllOfType allRiskType = new AllOfType();
417 MatchType matchRiskType = new MatchType();
419 AttributeValueType riskTypeValue = new AttributeValueType();
420 riskTypeValue.getContent().add("test");
421 matchRiskType.setAttributeValue(riskTypeValue);
423 AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
424 designatorRiskType.setAttributeId("RiskType");
425 matchRiskType.setAttributeDesignator(designatorRiskType);
426 allRiskType.getMatch().add(matchRiskType);
428 // add a dummy MatchType object since while (matchList.size()>1 ...)
429 MatchType matchDummy1 = new MatchType();
431 AttributeValueType dummy1Value = new AttributeValueType();
432 dummy1Value.getContent().add("dummy");
433 matchDummy1.setAttributeValue(dummy1Value);
435 AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
436 designatorDummy1.setAttributeId("dummyId");
437 matchDummy1.setAttributeDesignator(designatorDummy1);
439 allRiskType.getMatch().add(matchDummy1);
441 anyRiskType.getAllOf().add(allRiskType);
443 target.getAnyOf().add(anyRiskType);
445 // create RiskLevel attribute
446 AnyOfType anyRiskLevel = new AnyOfType();
447 AllOfType allRiskLevel = new AllOfType();
448 MatchType matchRiskLevel = new MatchType();
450 AttributeValueType riskLevel = new AttributeValueType();
451 riskLevel.getContent().add("3");
452 matchRiskLevel.setAttributeValue(riskLevel);
454 AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
455 designatorRiskLevel.setAttributeId("RiskLevel");
456 matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
457 allRiskLevel.getMatch().add(matchRiskLevel);
459 // add a dummy MatchType object since while (matchList.size()>1 ...)
460 MatchType matchDummy2 = new MatchType();
462 AttributeValueType dummy2Value = new AttributeValueType();
463 dummy2Value.getContent().add("dummy");
464 matchDummy2.setAttributeValue(dummy2Value);
466 AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
467 designatorDummy2.setAttributeId("dummyId");
468 matchDummy2.setAttributeDesignator(designatorDummy2);
470 allRiskLevel.getMatch().add(matchDummy2);
472 anyRiskLevel.getAllOf().add(allRiskLevel);
473 target.getAnyOf().add(anyRiskLevel);
475 policyType.setTarget(target);
477 restAdapter.setPolicyData(policyType);
479 controller.prePopulateDCAEMSPolicyData(restAdapter, entity);
481 logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
482 logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
483 logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
485 assertEquals("True", restAdapter.getGuard());
486 assertEquals("3", restAdapter.getRiskLevel());
487 assertEquals("test", restAdapter.getRiskType());
489 } catch (Exception e) {
490 logger.error("testPrePopulateDCAEMSPolicyData", e);
491 fail("testPrePopulateDCAEMSPolicyData failed due to: " + e);
494 logger.debug("testPrePopulateDCAEMSPolicyData: exit");
499 * Run the Map<String,String> convert(String, String) method test
503 public void testConvert(){
504 logger.debug("testConvert: enter");
506 String str = "k1=v1,k2=v2,k3=v3";
508 Map<String,String> result = CreateDcaeMicroServiceController.convert(str, split);
509 assertTrue(result != null && result.size() == 3);
511 logger.debug("testConvert: exit");
515 * Run the Map<String,String> convertMap(Map<String,String>,
516 * Map<String,String>) method test
520 public void testConvertMap(){
521 logger.debug("testConvertMap: enter");
523 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
524 Map<String,String> attributesMap = new HashMap<String, String>();
525 Map<String,String> attributesRefMap = new HashMap<String, String>();
526 Map<String,String> attributesListRefMap = controller.getAttributesListRefMap();
527 Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList();
528 LinkedList<String> list = new LinkedList<String>();
530 attributesMap.put("keyOne", "valueOne");
531 attributesMap.put("keyTwo", "valueTwo");
532 attributesMap.put("keyThree", "valueThree");
534 attributesRefMap.put("key4", "value4");
535 attributesRefMap.put("key5", "value5");
536 attributesRefMap.put("key6", "value6");
538 attributesListRefMap.put("key7", "value7");
542 arrayTextList.put("key8", list);
544 Map<String,String> result = controller.convertMap(attributesMap, attributesRefMap);
546 assertTrue(result != null && result.size() == 8);
548 assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]"));
550 logger.debug("testConvertMap: exit");
554 * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
558 //Ignore it for now due to Stream ended unexpectedly
561 public void testSetMSModelData() {
563 logger.debug("testSetMSModelData: enter");
565 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
567 MockHttpServletResponse response = new MockHttpServletResponse();
569 HttpServletRequest request = createMock(HttpServletRequest.class);
570 expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
571 expect(request.getMethod()).andReturn("post");
572 expect(request.getHeader("Content-length")).andReturn("7809");
574 expect(request.getContentLength()).andReturn(7809);
577 // value of fileName needs to be matched to your local directory
578 String fileName = "";
580 ClassLoader classLoader = getClass().getClassLoader();
581 fileName = new File(classLoader.getResource("schedulerPolicies1707.xmi").getFile()).getAbsolutePath();
582 } catch (Exception e1) {
583 logger.error("Exception Occured while loading file"+e1);
585 expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
586 expect(request.getCharacterEncoding()).andReturn("UTF-8");
587 expect(request.getContentLength()).andReturn(1024);
590 controller.SetMSModelData(request, response);
592 } catch (Exception e) {
593 logger.error("testSetMSModelData" + e);
599 logger.debug("testSetMSModelData: exit");
607 private class MockServletInputStream extends ServletInputStream {
609 InputStream fis = null;
610 public MockServletInputStream(String fileName) {
612 fis = new FileInputStream(fileName);
613 } catch (Exception genExe) {
614 genExe.printStackTrace();
618 public int read() throws IOException {
619 if(fis.available() > 0) {
626 public int read(byte[] bytes, int len, int size) throws IOException {
627 if(fis.available() > 0) {
628 int length = fis.read(bytes, len, size);
634 public boolean isFinished() {
638 public boolean isReady() {
642 public void setReadListener(ReadListener arg0) {