Fixes for sonar critical issues
[policy/engine.git] / PolicyEngineClient / src / test / java / org / onap / policyengine / GeneralTestClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineClient
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
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 /*
22  *                        AT&T - PROPRIETARY
23  *          THIS FILE CONTAINS PROPRIETARY INFORMATION OF
24  *        AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN
25  *             ACCORDANCE WITH APPLICABLE AGREEMENTS.
26  *
27  *          Copyright (c) 2014 AT&T Knowledge Ventures
28  *              Unpublished and Not for Publication
29  *                     All Rights Reserved
30  */
31 package org.onap.policyengine;
32
33 import java.io.FileNotFoundException;
34 import java.io.FileReader;
35 import java.io.IOException;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.Map;
44
45 import org.json.simple.JSONArray;
46 import org.json.simple.JSONObject;
47 import org.json.simple.parser.JSONParser;
48 import org.onap.policy.api.PolicyEngine;
49 import org.onap.policy.api.PolicyEngineException;
50 import org.onap.policy.common.logging.flexlogger.FlexLogger;
51 import org.onap.policy.common.logging.flexlogger.Logger;
52
53 /**
54  * Class reads from .testCases file and run the test cases available in the file
55  * and generates output for each test cases specifing whether is passed or fail
56  * and reason why it fails.
57  * 
58  * 
59  * @version 1.0
60  *
61  */
62 public class GeneralTestClient {
63         
64         private static final Logger LOGGER      = FlexLogger.getLogger(GeneralTestClient.class);
65         
66         static int totalTC = 0, passTC = 0, failTC = 0;
67
68         public static void main(String[] args) {
69                 Path file;
70                 /* command line arguments */
71                 if (args.length != 0) {
72                         for (int index = 0; index < args.length; index++) {
73                                 // System.out.println(args[index]);
74                                 file = Paths.get(args[index]);
75                                 runTestClientOnConfigFile(file);
76                         }
77                 } else {
78                         /* default file */
79                         file = Paths.get("input.testCases");
80                         runTestClientOnConfigFile(file);
81                 }
82                 System.out
83                 .println("###############################################################################################");
84                 System.out.println("\n\t SUMMARY: TOTAL: " + totalTC + ",\tPASS: "
85                                 + passTC + ",\tFAIL: " + failTC + "\n");
86                 System.out
87                 .println("###############################################################################################");
88
89                 System.out.println("Enter a any key to exit");
90                 try {
91                         System.in.read();
92                 } catch (IOException e) {
93                         //
94                 }
95
96         }
97
98         /**
99          * This function reads the files passed as arguments and runs the test cases
100          * in the file
101          *
102          * @param file
103          */
104         private static void runTestClientOnConfigFile(Path file) {
105                 String resultReturned, onapComponentName;
106                 int totalTCforFile = 0, passTCforFile = 0, failTCforFile = 0;
107                 System.out
108                 .println("\n###############################################################################################");
109                 System.out.println("\tRuning test Client on Config file: " + file);
110                 System.out
111                 .println("###############################################################################################\n");
112
113                 if (Files.notExists(file)) {
114                         System.out.println("file doesnot exist");
115                         // throw new
116                         // PolicyEngineException("File doesn't exist in the specified Path "
117                         // + file.toString());
118                 } else if (file.toString().endsWith(".testCases")) {
119                         try {
120                                 // read the json file
121                                 FileReader reader = new FileReader(file.toString());
122
123                                 JSONParser jsonParser = new JSONParser();
124                                 JSONArray jsonObjectArray = (JSONArray) jsonParser
125                                                 .parse(reader);
126                                 for (Object jsonObject : jsonObjectArray) {
127                                         totalTC++;
128                                         totalTCforFile++;
129                                         ArrayList<String> expectedResult = new ArrayList<>();
130                                         ArrayList<String> resultReceived = new ArrayList<>();
131                                         JSONObject testCase = (JSONObject) jsonObject;
132                                         // get a String from the JSON object
133                                         long id = (long) testCase.get("id");
134                                         String testFor = (String) testCase.get("testFor");
135                                         String testCaseDescription = (String) testCase
136                                                         .get("testCaseDescription");
137                                         JSONArray expectedResultJson = (JSONArray) testCase
138                                                         .get("expectedResult");
139                                         @SuppressWarnings("rawtypes")
140                                         Iterator i = expectedResultJson.iterator();
141                                         while (i.hasNext()) {
142                                                 expectedResult.add((String) i.next());
143                                         }
144                                         String pdp_urlConfigFile = (String) testCase
145                                                         .get("PDP_URLConfigFile");
146                                         // System.out.println(pdp_urlConfigFile);
147                                         PolicyEngine policyEngine;
148                                         try {
149                                                 policyEngine = new PolicyEngine(pdp_urlConfigFile);
150
151                                                 switch (testFor) {
152
153                                                 case "getConfig":
154                                                         onapComponentName = (String) testCase
155                                                         .get("ONAPName");
156                                                         String configName = (String) testCase
157                                                                         .get("ConfigName");
158                                                         Map<String, String> configAttributes = new HashMap<>();
159                                                         configAttributes.put("key", "value");
160                                                         JSONArray configAttributesJSON = (JSONArray) testCase
161                                                                         .get("configAttributes");
162                                                         if(configAttributesJSON!=null){
163                                                         i = configAttributesJSON.iterator();
164                                                         while (i.hasNext()) {
165                                                                 JSONObject innerObj = (JSONObject) i.next();
166                                                                 configAttributes.put(
167                                                                                 (String) innerObj.get("key"),
168                                                                                 (String) innerObj.get("value"));
169
170                                                         }
171                                                         }else{
172                                                                 configAttributes = null;
173                                                         }
174                                                         resultReceived = PolicyEngineTestClient.getConfig(
175                                                                         policyEngine, onapComponentName,
176                                                                         configName, configAttributes);
177                                                         Collections.sort(expectedResult);
178                                                         Collections.sort(resultReceived);
179                                                         resultReturned = compareResults(expectedResult,resultReceived);
180                                                         if (resultReturned.equals("PASSED")) {
181                                                                 printResult(id, testFor, testCaseDescription,
182                                                                                 "PASSED");
183                                                                 passTCforFile++;
184                                                                 passTC++;
185                                                         } else {
186                                                                 printResult(id, testFor, testCaseDescription,
187                                                                                 "FAILED", resultReturned);
188                                                                 failTCforFile++;
189                                                                 failTC++;
190                                                         }
191                                                         break;
192
193                                                 case "getAction":
194                                                         Map<String, String> eventAttributes = new HashMap<>();
195                                                         eventAttributes.put("Key", "Value");
196                                                         JSONArray eventAttributesJSON = (JSONArray) testCase
197                                                                         .get("eventAttributes");
198                                                         if(eventAttributesJSON != null){
199                                                         i = eventAttributesJSON.iterator();
200                                                         while (i.hasNext()) {
201                                                                 JSONObject innerObj = (JSONObject) i.next();
202                                                                 eventAttributes.put(
203                                                                                 (String) innerObj.get("key"),
204                                                                                 (String) innerObj.get("value"));
205                                                         }
206                                                         }else{
207                                                                 eventAttributes=null;
208                                                         }
209                                                         resultReceived = PolicyEngineTestClient.getAction(
210                                                                         policyEngine, eventAttributes);
211                                                         Collections.sort(expectedResult);
212                                                         Collections.sort(resultReceived);
213                                                         resultReturned = compareResults(expectedResult,
214                                                                         resultReceived);
215                                                         if (resultReturned.equals("PASSED")) {
216                                                                 printResult(id, testFor, testCaseDescription,
217                                                                                 "PASSED");
218                                                                 passTCforFile++;
219                                                                 passTC++;
220                                                         } else {
221                                                                 printResult(id, testFor, testCaseDescription,
222                                                                                 "FAILED", resultReturned);
223                                                                 failTCforFile++;
224                                                                 failTC++;
225                                                         }
226                                                         break;
227
228                                                 case "getDecision":
229                                                         onapComponentName = (String) testCase
230                                                         .get("ONAPName");
231                                                         Map<String, String> decisionAttributes = new HashMap<>();
232                                                         decisionAttributes.put("Key", "Value");
233                                                         JSONArray decisionAttributesJSON = (JSONArray) testCase
234                                                                         .get("decisionAttributes");
235                                                         i = decisionAttributesJSON.iterator();
236                                                         while (i.hasNext()) {
237                                                                 JSONObject innerObj = (JSONObject) i.next();
238                                                                 decisionAttributes.put(
239                                                                                 (String) innerObj.get("key"),
240                                                                                 (String) innerObj.get("value"));
241
242                                                         }
243                                                         
244                                                         resultReceived = PolicyEngineTestClient
245                                                                         .getDecision(policyEngine,
246                                                                                         onapComponentName,
247                                                                                         decisionAttributes);
248                                                         Collections.sort(expectedResult);
249                                                         Collections.sort(resultReceived);
250                                                         resultReturned = compareResults(expectedResult,
251                                                                         resultReceived);
252                                                         if (resultReturned.equals("PASSED")) {
253                                                                 printResult(id, testFor, testCaseDescription,
254                                                                                 "PASSED");
255                                                                 passTCforFile++;
256                                                                 passTC++;
257                                                         } else {
258                                                                 printResult(id, testFor, testCaseDescription,
259                                                                                 "FAILED", resultReturned);
260                                                                 failTCforFile++;
261                                                                 failTC++;
262                                                         }
263                                                         break;
264
265                                                         // case "getManualNotification":
266                                                         // PolicyEngineTestClient
267                                                         // .getManualNotifications(org.onap.policyEngine);
268                                                         // break;
269                                                         // case "getAutoNotification":
270                                                         // PolicyEngineTestClient
271                                                         // .getAutoNotifications(org.onap.policyEngine);
272                                                         // break;
273
274                                                 default:
275                                                         printResult(id, testFor, testCaseDescription,
276                                                                         "FAILED", "\tINVAILD TEST CASE.");
277                                                         failTCforFile++;
278                                                         failTC++;
279                                                         break;
280
281                                                 }
282                                         } catch (PolicyEngineException e) {
283                                                 printResult(id, testFor, testCaseDescription, "FAILED");
284                                                 failTCforFile++;
285                                                 failTC++;
286                                                 LOGGER.error("Exception Occured"+e);
287                                         } catch (Exception e) {
288                                                 printResult(id, testFor, testCaseDescription, "FAILED");
289                                                 failTCforFile++;
290                                                 failTC++;
291                                                 LOGGER.error("Exception Occured"+e);
292                                         }
293                                 }
294
295                         } catch (FileNotFoundException ex) {
296                                 LOGGER.error("Exception Occured due to File not found"+ex);
297                         } catch (IOException ex) {
298                                 LOGGER.error("Exception Occured"+ex);
299                         } catch (NullPointerException ex) {
300                                 LOGGER.error("Exception Occured due to Null Pointer"+ex);
301                         } catch (org.json.simple.parser.ParseException e) {
302                                 LOGGER.error("Exception Occured while Parsing"+e);
303                         }
304                 }
305                 System.out.println("\n\n\t Summary for the file: TOTAL: "
306                                 + totalTCforFile + ",\tPASS: " + passTCforFile + ",\tFAIL: "
307                                 + failTCforFile + "\n");
308         }
309
310         /**
311          * This function prints the reason if test fails.
312          * 
313          * @param id
314          * @param testFor
315          * @param testCaseDescription
316          * @param passFail
317          * @param resultReturned
318          */
319         private static void printResult(long id, String testFor,
320                         String testCaseDescription, String passFail, String resultReturned) {
321                 // TODO Auto-generated method stub
322                 printResult(id, testFor, testCaseDescription, passFail);
323                 System.out.println(resultReturned);
324
325         }
326
327         /**
328          * This function prints in output in required format.
329          * 
330          * @param id
331          * @param testFor
332          * @param testCaseDescription
333          * @param result
334          */
335         private static void printResult(long id, String testFor,
336                         String testCaseDescription, String result) {
337                 System.out.println(result + " - Test Case " + id + " - Test type: "
338                                 + testFor + " - " + testCaseDescription);
339         }
340
341         /**
342          * This function compares the required expected output and received output
343          * and returns PASS if expected output and received output matches
344          * 
345          * @param expectedResult
346          * @param resultReceived
347          * @return
348          */
349         private static String compareResults(ArrayList<String> expectedResult,
350                         ArrayList<String> resultReceived) {
351                 // TODO Auto-generated method stub
352                 String returnString = "";
353                 int index;
354 //              System.out.println(expectedResult.size());
355 //              System.out.println(resultReceived.size());
356                 for (index = 0; index < expectedResult.size()
357                                 || index < resultReceived.size(); index++) {
358                         if (index < expectedResult.size() && index < resultReceived.size()) {
359                                 if (!expectedResult.get(index)
360                                                 .equals(resultReceived.get(index))) {
361                                         //returnString = "FAILED";
362                                         returnString += "\tExpected Output: "
363                                                         + expectedResult.get(index)
364                                                         + ",\n\tOutput Received: "
365                                                         + resultReceived.get(index)+"\n";
366 //                              
367                                         //System.out.println(resultReceived.get(index));
368                                 } 
369
370                         } else {
371                                 if (index >= expectedResult.size()) {
372                                         returnString += "\tExpected Size of output: "
373                                                         + expectedResult.size()
374                                                         + ", Size of output received: "
375                                                         + resultReceived.size()
376                                                         + "\n\tExpected Output: none,\n\tOutput Received: "
377                                                         + resultReceived.get(index)+"\n";
378
379                                 } else {
380                                         if (index >= resultReceived.size()) {
381                                                 returnString += "\tExpected Size of output: "
382                                                                 + expectedResult.size()
383                                                                 + ", Size of output received: "
384                                                                 + resultReceived.size()
385                                                                 + "\n\tExpected Output: "
386                                                                 + expectedResult.get(index)
387                                                                 + ",\n\tOutput Received: none\n";
388
389                                         }
390                                 }
391                         }
392
393                 }
394                 if(index==expectedResult.size() && index==resultReceived.size() && returnString.equals("")){
395                         returnString="PASSED";
396                 }
397                 return returnString;
398
399         }
400 }