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