New Optimization Policy
[policy/engine.git] / POLICY-SDK-APP / src / test / java / org / onap / policy / controller / CreateDcaeMicroServiceControllerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.controller;
22
23
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;
32
33 import java.io.BufferedReader;
34 import java.io.File;
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;
43 import java.util.Map;
44
45 import javax.servlet.ReadListener;
46 import javax.servlet.ServletInputStream;
47 import javax.servlet.http.HttpServletRequest;
48
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;
60
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;
65
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;
73
74 /**
75  * The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests
76  * for the class {@link <code>CreateDcaeMicroServiceController</code>}*
77  *
78  * All JUnits are designed to run in the local development environment
79  * where they have write privileges and can execute time-sensitive
80  * tasks.
81  *
82  * 
83  *
84  */
85
86 public class CreateDcaeMicroServiceControllerTest {
87         
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;
93         
94         @Before
95         public void setUp() throws Exception {
96
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);
103
104         // mock the getDataById() call
105         when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "test")).thenReturn(microServiceModelsData);
106         
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\"} }";
115
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\"}}";
119
120                 request = mock(HttpServletRequest.class);        
121         BufferedReader br = new BufferedReader(new StringReader(jsonString));
122         // mock the getReader() call
123         when(request.getReader()).thenReturn(br);   
124         
125         logger.info("setUp: exit");
126         }
127                 
128         
129         /**
130          * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter,
131          * JsonNode) method test
132          */
133         
134         @Test
135         public void testSetDataToPolicyRestAdapter() {
136                 
137                 logger.debug("testSetDataToPolicyRestAdapter: enter");
138                 
139                 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
140                 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
141         
142                 JsonNode root = null;
143                 ObjectMapper mapper = new ObjectMapper();
144                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
145                 PolicyRestAdapter policyData = null;
146                 try {
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);                      
151                 } 
152                 
153                 PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData,    root);
154                 assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
155         
156                 logger.debug("result.getJsonBody() : " + result.getJsonBody());
157                 logger.debug("testSetDataToPolicyRestAdapter: exit");
158         }
159
160         /**
161          * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest,
162          * HttpServletResponse) method test
163          */
164         
165          @Test
166         public void testGetDCAEMSTemplateData() {
167                 
168                 logger.debug("testGetDCAEMSTemplateData: enter");
169                 
170                 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();   
171                 MockHttpServletResponse response =  new MockHttpServletResponse();
172                 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
173                 try {   
174                         
175                 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
176                 
177                 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
178                 // mock the getReader() call
179                 when(request.getReader()).thenReturn(br); 
180                 
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);   
187                 
188                         controller.getDCAEMSTemplateData(request, response);
189                         
190                         assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeModelData"));
191                         
192                         logger.debug("response: "  + response.getContentAsString());
193                         
194                 } catch (Exception e) {
195                         logger.error("testGetDCAEMSTemplateData", e);
196                 }               
197         
198                 logger.debug("testGetDCAEMSTemplateData: exit");
199         }
200
201         /**
202          * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
203          * HttpServletResponse) method test
204          */
205         
206         @Test
207         public void testGetModelServiceVersionData() {
208                 
209                 logger.debug("testGetModelServiceVersionData: enter");
210                 
211                 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
212                 MockHttpServletResponse response =  new MockHttpServletResponse();
213                 String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
214                 try {
215                         
216                 CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
217                 
218                 BufferedReader br = new BufferedReader(new StringReader(msModelJson));
219                 // mock the getReader() call
220                 when(request.getReader()).thenReturn(br);   
221                 
222                 List<Object> microServiceModelsData = new ArrayList<Object>();
223                 MicroServiceModels testData = new MicroServiceModels();
224                 testData.setVersion("1707.4.1.2-Junit");        
225                 microServiceModelsData.add(testData);
226
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);       
230                                                 
231                         assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
232                         
233                         logger.debug("response: "  + response.getContentAsString());
234                         
235                 } catch (Exception e) {
236                         logger.error("testGetModelServiceVersionData", e);
237                         fail("testGetModelServiceVersionData failed due to: " + e);
238                 }
239
240                 logger.debug("testGetModelServiceVersionData: exit");
241         }
242
243         /**
244          * Run the void getDCAEPriorityValuesData(HttpServletRequest,
245          * HttpServletResponse) method test
246          */
247         
248         @Test
249         public void testGetDCAEPriorityValuesData() {
250                 
251                 logger.debug("testGetDCAEPriorityValuesData: enter");
252                 
253                 CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
254                 
255             MockHttpServletRequest request = new MockHttpServletRequest();
256             MockHttpServletResponse response = new MockHttpServletResponse();
257         try{
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);
264                 }
265                 
266                 logger.debug("testGetDCAEPriorityValuesData: exit");
267         }
268
269         /**
270          * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
271          * PolicyEntity) method test
272          */
273         
274         @Test
275         public void testPrePopulateDCAEMSPolicyData() {
276                 
277                 logger.debug("testPrePopulateDCAEMSPolicyData: enter");
278                 
279             CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
280             
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);
286                 
287                 JsonNode root = null;
288                 ObjectMapper mapper = new ObjectMapper();
289                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
290                 PolicyRestAdapter restAdapter = null;
291
292                 try {
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(); 
297                         
298                         // create guard attribute 
299                         AnyOfType anyOfType = new AnyOfType();                  
300                         AllOfType alltype = new AllOfType();
301                         MatchType matchType = new MatchType();
302                         // set value
303                         AttributeValueType attributeValue1 = new AttributeValueType();
304                         attributeValue1.getContent().add("True");
305                         matchType.setAttributeValue(attributeValue1);
306             // set Id
307                         AttributeDesignatorType designator = new AttributeDesignatorType();
308                         designator.setAttributeId("guard");
309                         matchType.setAttributeDesignator(designator);
310                         alltype.getMatch().add(matchType);      
311                         
312                         // add a dummy MatchType object since while (matchList.size()>1 ...)
313                         MatchType matchDummy = new MatchType();
314                         // set value
315                         AttributeValueType dummyValue = new AttributeValueType();
316                         dummyValue.getContent().add("dummy");
317                         matchDummy.setAttributeValue(dummyValue);
318             // set Id
319                         AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
320                         designatorDummy.setAttributeId("dummyId");
321                         matchDummy.setAttributeDesignator(designatorDummy);
322                         
323                         alltype.getMatch().add(matchDummy);
324                         anyOfType.getAllOf().add(alltype);
325                         
326                         target.getAnyOf().add(anyOfType);
327                         
328                         // create RiskType attribute 
329                         AnyOfType anyRiskType = new AnyOfType();                        
330                         AllOfType allRiskType = new AllOfType();
331                         MatchType matchRiskType = new MatchType();
332                         // set value
333                         AttributeValueType riskTypeValue = new AttributeValueType();
334                         riskTypeValue.getContent().add("test");
335                         matchRiskType.setAttributeValue(riskTypeValue);
336             // set Id
337                         AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
338                         designatorRiskType.setAttributeId("RiskType");
339                         matchRiskType.setAttributeDesignator(designatorRiskType);
340                         allRiskType.getMatch().add(matchRiskType);      
341                         
342                         // add a dummy MatchType object since while (matchList.size()>1 ...)
343                         MatchType matchDummy1 = new MatchType();
344                         // set value
345                         AttributeValueType dummy1Value = new AttributeValueType();
346                         dummy1Value.getContent().add("dummy");
347                         matchDummy1.setAttributeValue(dummy1Value);
348             // set Id
349                         AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
350                         designatorDummy1.setAttributeId("dummyId");
351                         matchDummy1.setAttributeDesignator(designatorDummy1);
352                         
353                         allRiskType.getMatch().add(matchDummy1);
354                         
355                         anyRiskType.getAllOf().add(allRiskType);
356                         
357                         target.getAnyOf().add(anyRiskType);
358                         
359                         // create RiskLevel attribute 
360                         AnyOfType anyRiskLevel = new AnyOfType();                       
361                         AllOfType allRiskLevel = new AllOfType();
362                         MatchType matchRiskLevel = new MatchType();
363                         // set value
364                         AttributeValueType riskLevel = new AttributeValueType();
365                         riskLevel.getContent().add("3");
366                         matchRiskLevel.setAttributeValue(riskLevel);
367             // set Id
368                         AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
369                         designatorRiskLevel.setAttributeId("RiskLevel");
370                         matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
371                         allRiskLevel.getMatch().add(matchRiskLevel);
372                         
373                         // add a dummy MatchType object since while (matchList.size()>1 ...)
374                         MatchType matchDummy2 = new MatchType();
375                         // set value
376                         AttributeValueType dummy2Value = new AttributeValueType();
377                         dummy2Value.getContent().add("dummy");
378                         matchDummy2.setAttributeValue(dummy2Value);
379             // set Id
380                         AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
381                         designatorDummy2.setAttributeId("dummyId");
382                         matchDummy2.setAttributeDesignator(designatorDummy2);
383                         
384                         allRiskLevel.getMatch().add(matchDummy2);
385                         
386                         anyRiskLevel.getAllOf().add(allRiskLevel);
387                         target.getAnyOf().add(anyRiskLevel);
388                         
389                         policyType.setTarget(target);
390                         
391                         restAdapter.setPolicyData(policyType);
392                         
393                         controller.prePopulateDCAEMSPolicyData(restAdapter, entity);
394                         
395                         logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
396                         logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
397                         logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
398                         
399                         assertEquals("True", restAdapter.getGuard());
400                         assertEquals("3", restAdapter.getRiskLevel());
401                         assertEquals("test", restAdapter.getRiskType());
402                         
403                 } catch (Exception e) {
404                         logger.error("testPrePopulateDCAEMSPolicyData", e);
405                         fail("testPrePopulateDCAEMSPolicyData failed due to: " + e);
406                 } 
407                 
408                 logger.debug("testPrePopulateDCAEMSPolicyData: exit");
409                 
410         }
411
412         /**
413          * Run the Map<String,String> convert(String, String) method test
414          */
415         
416         @Test
417         public void testConvert(){
418                 logger.debug("testConvert: enter");
419                 
420             String str = "k1=v1,k2=v2,k3=v3";
421                 String split = ",";
422                 Map<String,String> result = CreateDcaeMicroServiceController.convert(str, split);               
423                 assertTrue(result != null && result.size() == 3);
424                 
425                 logger.debug("testConvert: exit");
426         }
427         
428         /**
429          * Run the Map<String,String> convertMap(Map<String,String>,
430          * Map<String,String>) method test
431          */
432         
433         @Test
434         public void testConvertMap(){
435                 logger.debug("testConvertMap: enter");
436                 
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>();
443                  
444                 attributesMap.put("keyOne", "valueOne");
445                 attributesMap.put("keyTwo", "valueTwo");
446                 attributesMap.put("keyThree", "valueThree");
447                 
448                 attributesRefMap.put("key4", "value4");
449                 attributesRefMap.put("key5", "value5");
450                 attributesRefMap.put("key6", "value6");
451                 
452                 attributesListRefMap.put("key7", "value7");
453                 
454                 list.add("l1");
455                 list.add("l2");
456                 arrayTextList.put("key8", list);
457                 
458                 Map<String,String> result = controller.convertMap(attributesMap, attributesRefMap);
459                 
460                 assertTrue(result != null && result.size() == 8);
461                 
462                 assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]"));
463                 
464                 logger.debug("testConvertMap: exit");
465         }
466         
467         /**
468          * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
469          * method test
470          */
471         
472         //@Ignore
473         @Test
474         public void testSetMSModelData() {              
475                 
476                 logger.debug("testSetMSModelData: enter");
477
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");
482             
483             expect(request.getContentLength()).andReturn(7809);
484
485             try {
486                 // value of fileName needs to be matched to your local directory
487                 String fileName = "";
488                 try {
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);
493                         }
494                         expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));           
495                     expect(request.getCharacterEncoding()).andReturn("UTF-8");
496                     expect(request.getContentLength()).andReturn(1024);
497                     replay(request);
498                         
499                 } catch (Exception e) {
500                         logger.error("testSetMSModelData" + e);
501                         e.printStackTrace();
502                 }
503                         
504                 logger.debug("testSetMSModelData: exit");
505         }
506
507         /**
508          * 
509          * @ Get File Stream
510          *
511          */
512         private class MockServletInputStream extends ServletInputStream {
513
514                 InputStream fis = null;
515                 public MockServletInputStream(String fileName) {
516                         try {
517                                 fis = new FileInputStream(fileName);
518                         } catch (Exception genExe) {
519                                 genExe.printStackTrace();
520                         }
521                 }
522                 @Override
523                 public int read() throws IOException {
524                         if(fis.available() > 0) {
525                                 return fis.read();
526                         }
527                         return 0;
528                 }
529
530                 @Override
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);
534                                 return length;
535                         }
536                         return -1;
537                 }
538                 @Override
539                 public boolean isFinished() {
540                         return false;
541                 }
542                 @Override
543                 public boolean isReady() {
544                         return false;
545                 }
546                 @Override
547                 public void setReadListener(ReadListener arg0) {
548
549                 }
550         }       
551         
552 }