New Optimization Policy
[policy/engine.git] / POLICY-SDK-APP / src / test / java / org / onap / policy / controller / CreateOptimizationControllerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 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.List;
41
42 import javax.servlet.ReadListener;
43 import javax.servlet.ServletInputStream;
44 import javax.servlet.http.HttpServletRequest;
45
46 import org.junit.Before;
47 import org.junit.Test;
48 import org.onap.policy.common.logging.flexlogger.FlexLogger;
49 import org.onap.policy.common.logging.flexlogger.Logger;
50 import org.onap.policy.rest.adapter.PolicyRestAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
53 import org.onap.policy.rest.jpa.OptimizationModels;
54 import org.onap.policy.rest.jpa.PolicyEntity;
55 import org.springframework.mock.web.MockHttpServletRequest;
56 import org.springframework.mock.web.MockHttpServletResponse;
57
58 import com.fasterxml.jackson.databind.DeserializationFeature;
59 import com.fasterxml.jackson.databind.JsonNode;
60 import com.fasterxml.jackson.databind.ObjectMapper;
61 import com.github.fge.jackson.JsonLoader;
62
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
70
71 /**
72  * The class <code>CreateOptimizationControllerTest</code> contains tests
73  * for the class {@link <code>CreateOptimizationController</code>}*
74  *
75  * All JUnits are designed to run in the local development environment
76  * where they have write privileges and can execute time-sensitive
77  * tasks.
78  */
79 public class CreateOptimizationControllerTest {
80         
81         private static Logger logger = FlexLogger.getLogger(CreateOptimizationControllerTest.class);
82         private static CommonClassDao commonClassDao;
83         private String jsonString = null;
84         private String configBodyString = null;
85         private HttpServletRequest request = null;
86         
87         @Before
88         public void setUp() throws Exception {
89
90                 logger.info("setUp: Entering");
91         commonClassDao = mock(CommonClassDao.class);
92         List<Object> optimizationModelsData = new ArrayList<Object>();
93         OptimizationModels testData = new OptimizationModels();
94         testData.setVersion("OpenOnap-Junit");        
95         optimizationModelsData.add(testData);
96
97         // mock the getDataById() call
98         when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test")).thenReturn(optimizationModelsData);
99         
100                 jsonString = "{\"policyData\": {\"error\": \"\",        \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
101                                 + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
102                                 + " \"version\": \"\",\"createdBy\": \"someone\",       \"modifiedBy\": \"someone\",    \"content\": \"\",\"recursive\": false},"
103                                 + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"    },"
104                                 + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\",\"policyName\": \"testPolicy\", "
105                                 + "     \"policyDescription\": \"testing input\", \"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
106                                 + "     \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
107                                 + "     \"policyJSON\": {\"pmTableName\": \"test\",     \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
108
109                 configBodyString = "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\","
110                                 + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\","
111                                 + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"TEST\"}}";
112
113                 request = mock(HttpServletRequest.class);        
114         BufferedReader br = new BufferedReader(new StringReader(jsonString));
115         // mock the getReader() call
116         when(request.getReader()).thenReturn(br);   
117         
118         logger.info("setUp: exit");
119         }
120                 
121         
122         /**
123          * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter,
124          * JsonNode) method test
125          */
126         
127         @Test
128         public void testSetDataToPolicyRestAdapter() {
129                 
130                 logger.debug("testSetDataToPolicyRestAdapter: enter");
131                 
132                 CreateOptimizationController controller = new CreateOptimizationController();
133                 CreateOptimizationController.setCommonClassDao(commonClassDao);
134         
135                 JsonNode root = null;
136                 ObjectMapper mapper = new ObjectMapper();
137                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
138                 PolicyRestAdapter policyData = null;
139                 try {
140                         root = JsonLoader.fromString(jsonString);
141                         policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
142                 } catch (Exception e) {
143                         logger.error("testSetDataToPolicyRestAdapter", e);                      
144                 } 
145                 
146                 PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData,    root);
147                 assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
148         
149                 logger.debug("result.getJsonBody() : " + result.getJsonBody());
150                 logger.debug("testSetDataToPolicyRestAdapter: exit");
151         }
152         
153
154         /**
155          * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest,
156          * HttpServletResponse) method test
157          */
158         
159          @Test
160         public void testGetOptimizationTemplateData() {
161                 
162                 logger.debug("testGetOptimizationTemplateData: enter");
163                 
164                 CreateOptimizationController controller = new CreateOptimizationController();
165                 MockHttpServletResponse response =  new MockHttpServletResponse();
166                 String modelJson = "{\"policyData\":\"testPolicyBody\"}";
167                 try {   
168                         
169                         CreateOptimizationController.setCommonClassDao(commonClassDao);
170                 
171                 BufferedReader br = new BufferedReader(new StringReader(modelJson));
172                 // mock the getReader() call
173                 when(request.getReader()).thenReturn(br); 
174                 
175                 List<Object> optimizationModelsData = new ArrayList<Object>();
176                 OptimizationModels testData = new OptimizationModels();
177                 testData.setVersion("1707.4.1.2-Junit");        
178                 optimizationModelsData.add(testData);
179                 // mock the getDataById() call with the same MS model name 
180                 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody")).thenReturn(optimizationModelsData);   
181                 
182                         controller.getOptimizationTemplateData(request, response);
183                         
184                         assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("optimizationModelData"));
185                         
186                         logger.debug("response: "  + response.getContentAsString());
187                         
188                 } catch (Exception e) {
189                         logger.error("testGetOptimizationTemplateData", e);
190                 }               
191         
192                 logger.debug("testGetOptimizationTemplateData: exit");
193         }
194
195         /**
196          * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
197          * HttpServletResponse) method test
198          */
199         
200         @Test
201         public void testGetModelServiceVersionData() {
202                 
203                 logger.debug("testGetModelServiceVersionData: enter");
204                 
205                 CreateOptimizationController controller = new CreateOptimizationController();
206                 MockHttpServletResponse response =  new MockHttpServletResponse();
207                 String modelJson = "{\"policyData\":\"TestPolicyBody\"}";
208                 try {
209                         
210                         CreateOptimizationController.setCommonClassDao(commonClassDao);
211                 
212                 BufferedReader br = new BufferedReader(new StringReader(modelJson));
213                 // mock the getReader() call
214                 when(request.getReader()).thenReturn(br);   
215                 
216                 List<Object> optimizationModelsData = new ArrayList<Object>();
217                 OptimizationModels testData = new OptimizationModels();
218                 testData.setVersion("1707.4.1.2-Junit");        
219                 optimizationModelsData.add(testData);
220
221                 // mock the getDataById() call with the same MS model name 
222                 when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody")).thenReturn(optimizationModelsData);
223                         controller.getModelServiceVersionData(request, response);       
224                                                 
225                         assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
226                         
227                         logger.debug("response: "  + response.getContentAsString());
228                         
229                 } catch (Exception e) {
230                         logger.error("testGetModelServiceVersionData", e);
231                         fail("testGetModelServiceVersionData failed due to: " + e);
232                 }
233
234                 logger.debug("testGetModelServiceVersionData: exit");
235         }
236
237         /**
238          * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
239          * PolicyEntity) method test
240          */
241         
242         @Test
243         public void testPrePopulatePolicyData() {
244                 
245                 logger.debug("testPrePopulatePolicyData: enter");
246                 
247                 CreateOptimizationController controller = new CreateOptimizationController();
248             
249             // populate an entity object for testing
250                 PolicyEntity entity = new PolicyEntity();
251                 ConfigurationDataEntity configData = new ConfigurationDataEntity();
252                 configData.setConfigBody(configBodyString);             
253                 entity.setConfigurationData(configData);
254                 
255                 JsonNode root = null;
256                 ObjectMapper mapper = new ObjectMapper();
257                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
258                 PolicyRestAdapter restAdapter = null;
259
260                 try {
261                         root = JsonLoader.fromString(jsonString);
262                         restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
263                         PolicyType policyType = new PolicyType();
264                         TargetType target = new TargetType(); 
265                         
266                         // create guard attribute 
267                         AnyOfType anyOfType = new AnyOfType();                  
268                         AllOfType alltype = new AllOfType();
269                         MatchType matchType = new MatchType();
270                         // set value
271                         AttributeValueType attributeValue1 = new AttributeValueType();
272                         attributeValue1.getContent().add("True");
273                         matchType.setAttributeValue(attributeValue1);
274             // set Id
275                         AttributeDesignatorType designator = new AttributeDesignatorType();
276                         designator.setAttributeId("guard");
277                         matchType.setAttributeDesignator(designator);
278                         alltype.getMatch().add(matchType);      
279                         
280                         // add a dummy MatchType object since while (matchList.size()>1 ...)
281                         MatchType matchDummy = new MatchType();
282                         // set value
283                         AttributeValueType dummyValue = new AttributeValueType();
284                         dummyValue.getContent().add("dummy");
285                         matchDummy.setAttributeValue(dummyValue);
286             // set Id
287                         AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
288                         designatorDummy.setAttributeId("dummyId");
289                         matchDummy.setAttributeDesignator(designatorDummy);
290                         
291                         alltype.getMatch().add(matchDummy);
292                         anyOfType.getAllOf().add(alltype);
293                         
294                         target.getAnyOf().add(anyOfType);
295                         
296                         // create RiskType attribute 
297                         AnyOfType anyRiskType = new AnyOfType();                        
298                         AllOfType allRiskType = new AllOfType();
299                         MatchType matchRiskType = new MatchType();
300                         // set value
301                         AttributeValueType riskTypeValue = new AttributeValueType();
302                         riskTypeValue.getContent().add("test");
303                         matchRiskType.setAttributeValue(riskTypeValue);
304             // set Id
305                         AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
306                         designatorRiskType.setAttributeId("RiskType");
307                         matchRiskType.setAttributeDesignator(designatorRiskType);
308                         allRiskType.getMatch().add(matchRiskType);      
309                         
310                         // add a dummy MatchType object since while (matchList.size()>1 ...)
311                         MatchType matchDummy1 = new MatchType();
312                         // set value
313                         AttributeValueType dummy1Value = new AttributeValueType();
314                         dummy1Value.getContent().add("dummy");
315                         matchDummy1.setAttributeValue(dummy1Value);
316             // set Id
317                         AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
318                         designatorDummy1.setAttributeId("dummyId");
319                         matchDummy1.setAttributeDesignator(designatorDummy1);
320                         
321                         allRiskType.getMatch().add(matchDummy1);
322                         
323                         anyRiskType.getAllOf().add(allRiskType);
324                         
325                         target.getAnyOf().add(anyRiskType);
326                         
327                         // create RiskLevel attribute 
328                         AnyOfType anyRiskLevel = new AnyOfType();                       
329                         AllOfType allRiskLevel = new AllOfType();
330                         MatchType matchRiskLevel = new MatchType();
331                         // set value
332                         AttributeValueType riskLevel = new AttributeValueType();
333                         riskLevel.getContent().add("3");
334                         matchRiskLevel.setAttributeValue(riskLevel);
335             // set Id
336                         AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
337                         designatorRiskLevel.setAttributeId("RiskLevel");
338                         matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
339                         allRiskLevel.getMatch().add(matchRiskLevel);
340                         
341                         // add a dummy MatchType object since while (matchList.size()>1 ...)
342                         MatchType matchDummy2 = new MatchType();
343                         // set value
344                         AttributeValueType dummy2Value = new AttributeValueType();
345                         dummy2Value.getContent().add("dummy");
346                         matchDummy2.setAttributeValue(dummy2Value);
347             // set Id
348                         AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
349                         designatorDummy2.setAttributeId("dummyId");
350                         matchDummy2.setAttributeDesignator(designatorDummy2);
351                         
352                         allRiskLevel.getMatch().add(matchDummy2);
353                         
354                         anyRiskLevel.getAllOf().add(allRiskLevel);
355                         target.getAnyOf().add(anyRiskLevel);
356                         
357                         policyType.setTarget(target);
358                         
359                         restAdapter.setPolicyData(policyType);
360                         
361                         controller.prePopulatePolicyData(restAdapter, entity);
362                         
363                         logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
364                         logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
365                         logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
366                         
367                         assertEquals("True", restAdapter.getGuard());
368                         assertEquals("3", restAdapter.getRiskLevel());
369                         assertEquals("test", restAdapter.getRiskType());
370                         
371                 } catch (Exception e) {
372                         logger.error("testPrePopulatePolicyData", e);
373                         fail("testPrePopulatePolicyData failed due to: " + e);
374                 } 
375                 
376                 logger.debug("testPrePopulatePolicyData: exit");
377                 
378         }
379         
380         /**
381          * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
382          * method test
383          */
384         
385         @Test
386         public void testSetModelData() {                
387                 
388                 logger.debug("testSetModelData: enter");
389
390             HttpServletRequest request = createMock(HttpServletRequest.class);
391             expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
392             expect(request.getMethod()).andReturn("post");
393             expect(request.getHeader("Content-length")).andReturn("7809");
394             
395             expect(request.getContentLength()).andReturn(7809);
396
397             try {
398                 // value of fileName needs to be matched to your local directory
399                 String fileName = "";
400                 try {
401                                 ClassLoader classLoader = getClass().getClassLoader();
402                                 fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath();
403                         } catch (Exception e1) {
404                                 logger.error("Exception Occured while loading file"+e1);
405                         }
406                         expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));           
407                     expect(request.getCharacterEncoding()).andReturn("UTF-8");
408                     expect(request.getContentLength()).andReturn(1024);
409                     replay(request);
410                         
411                 } catch (Exception e) {
412                         logger.error("testSetModelData" + e);
413                         e.printStackTrace();
414                 }
415                         
416                 logger.debug("testSetModelData: exit");
417         }
418
419         /**
420          * 
421          * @ Get File Stream
422          *
423          */
424         private class MockServletInputStream extends ServletInputStream {
425
426                 InputStream fis = null;
427                 public MockServletInputStream(String fileName) {
428                         try {
429                                 fis = new FileInputStream(fileName);
430                         } catch (Exception genExe) {
431                                 genExe.printStackTrace();
432                         }
433                 }
434                 @Override
435                 public int read() throws IOException {
436                         if(fis.available() > 0) {
437                                 return fis.read();
438                         }
439                         return 0;
440                 }
441
442                 @Override
443                 public int read(byte[] bytes, int len, int size) throws IOException {
444                         if(fis.available() > 0) {
445                                 int length = fis.read(bytes, len, size);
446                                 return length;
447                         }
448                         return -1;
449                 }
450                 @Override
451                 public boolean isFinished() {
452                         return false;
453                 }
454                 @Override
455                 public boolean isReady() {
456                         return false;
457                 }
458                 @Override
459                 public void setReadListener(ReadListener arg0) {
460
461                 }
462         }       
463         
464 }