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