Merge "Disable syslog in heat-translator for functest integration"
[parser.git] / verigraph / src / it / polito / verigraph / test / Tester.java
1 /*******************************************************************************
2  * Copyright (c) 2017 Politecnico di Torino and others.
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Apache License, Version 2.0
6  * which accompanies this distribution, and is available at
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *******************************************************************************/
9 package it.polito.verigraph.test;
10
11 import java.io.BufferedReader;
12 import java.io.File;
13 import java.io.FilenameFilter;
14 import java.io.IOException;
15 import java.io.InputStreamReader;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19
20 import javax.ws.rs.client.Client;
21 import javax.ws.rs.client.ClientBuilder;
22 import javax.ws.rs.client.ResponseProcessingException;
23 import javax.ws.rs.client.WebTarget;
24 import javax.ws.rs.core.Response;
25
26 import com.fasterxml.jackson.core.JsonParseException;
27 import com.fasterxml.jackson.databind.JsonMappingException;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30 import com.github.fge.jsonschema.core.exceptions.ProcessingException;
31 import com.github.fge.jsonschema.main.JsonSchema;
32
33 import it.polito.verigraph.client.VerifyClient;
34 import it.polito.verigraph.client.VerifyClientException;
35 import it.polito.verigraph.model.Graph;
36 import it.polito.verigraph.model.Verification;
37 import it.polito.verigraph.service.ValidationUtils;
38
39 public class Tester {
40
41     private File schema;
42
43     private List<File> testFiles= new ArrayList<File>();
44
45     private List<TestCase> testCases= new ArrayList<TestCase>();
46
47     private String target;
48
49     private VerifyClient verifyClient;
50
51     public Tester(String target, File schema, File folder)throws JsonParseException, JsonMappingException, IOException,
52     Exception {
53         init(target, schema, folder);
54     }
55
56     private void init(String target, File schema, File folder)throws JsonParseException, JsonMappingException,
57     IOException, Exception {
58         this.target = target;
59         this.verifyClient = new VerifyClient(this.target);
60         this.schema = schema;
61         this.testFiles = getTests(folder);
62         this.testCases = getTestCases(this.testFiles);
63     }
64
65     public List<File> getTests(File folder) {
66         List<File> filesList = new ArrayList<File>();
67
68         System.out.println("Test folder set to '" + folder.getAbsolutePath() + "'");
69
70         File[] files = folder.listFiles(new FilenameFilter() {
71
72             @Override
73             public boolean accept(File dir, String name) {
74                 return name.endsWith(".json");
75             }
76         });
77
78         for (File f : files) {
79             filesList.add(f);
80             System.out.println("File '" + f.getName() + "' added to test files");
81         }
82
83         return filesList;
84     }
85
86     public List<TestCase> getTestCases(List<File> files)throws JsonParseException, JsonMappingException, IOException,
87     Exception {
88         List<TestCase> testCases = new ArrayList<TestCase>();
89
90         for (File file : files) {
91             validateTestFile(file);
92             try {
93                 TestCase tc = new ObjectMapper().readValue(file, TestCase.class);
94                 testCases.add(tc);
95             }
96             catch (Exception e) {
97                 throw e;
98             }
99         }
100
101         return testCases;
102     }
103
104     private void runTestCases() throws VerifyClientException, TestExecutionException {
105         int counter = 0;
106         for (TestCase tc : this.testCases) {
107             List<String> results = runTestCase(tc);
108             Iterator<String> iter = tc.getResults().iterator();
109             for(String result : results){
110                 if (iter.hasNext()){
111                     if( !result.equals(iter.next()))
112                         throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()
113                                 + "'. Test returned '" + result + "' instead of '" + tc.getResults() + "'.");
114                     else
115                         System.out.println("Test given in file '"+ this.testFiles.get(counter).getName() + "' returned '"
116                                 + result + "' as expected");
117                 } else throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()
118                         + "'. Test returned '" + result + "' instead of '" + tc.getResults() + "'.");
119             }
120             counter++;
121         }
122         System.out.println("All tests PASSED");
123     }
124
125     private List<String> runTestCase(TestCase tc) throws VerifyClientException, TestExecutionException{
126         Client client = ClientBuilder.newClient();
127
128         List<String> results = new ArrayList<String>();
129
130         Graph graph = tc.getGraph();
131         Response response = null;
132         try{
133             response = this.verifyClient.createGraph(graph);
134         }
135         catch(ResponseProcessingException e){
136             throw new TestExecutionException("Response processing has failed: " + e.getResponse().readEntity(String.class));
137         }
138         catch(javax.ws.rs.ProcessingException e){
139             throw new TestExecutionException("HTTP request failed");
140         }
141         Graph createdGraph = response.readEntity(Graph.class);
142         for (String urlParams : tc.getPolicyUrlParameters()){
143             WebTarget target = client.target(this.target + "/graphs/" + createdGraph.getId() + "/policy" + urlParams);
144
145             response = target.request().get();
146             Verification verification = response.readEntity(Verification.class);
147             results.add(verification.getResult());
148         }
149         return results;
150     }
151
152     public void validateTestFile(File testFile) throws Exception {
153         JsonSchema schemaNode = null;
154         try {
155             schemaNode = ValidationUtils.getSchemaNode(schema);
156         }
157         catch (IOException e) {
158             throw new Exception("Unable to load '" + schema.getAbsolutePath() + "' schema file");
159         }
160         catch (ProcessingException e) {
161             throw new Exception("Unable to resolve '" + schema.getAbsolutePath() + "' schema file as a schema node");
162         }
163
164         JsonNode jsonNode;
165         try {
166             jsonNode = ValidationUtils.getJsonNode(testFile);
167         }
168         catch (IOException e) {
169             throw new Exception("Unable to load '" + testFile.getAbsolutePath() + "' as a json node");
170         }
171
172         try {
173             ValidationUtils.validateJson(schemaNode, jsonNode);
174         }
175         catch (ProcessingException e) {
176             throw new Exception("There were errors in the validation of file '"+ testFile.getAbsolutePath()
177             + "' against the json schema '" + schema.getAbsolutePath() + "': " + e.getMessage());
178
179         }
180     }
181
182     public static void main(String[] args)throws JsonParseException, JsonMappingException, IOException,
183     VerifyClientException, Exception {
184         String folderName = System.getProperty("user.dir") + "/tester/testcases";
185         File folder = new File(folderName);
186         if (!folder.exists()) {
187             BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
188             String s;
189             do{
190                 System.out.println("Please enter the testcases folder path: ");
191                 s = in.readLine();
192                 if (isValidpath(s)){
193                     folder = new File(s);
194                     break;
195                 }
196             }while (s != null && s.length() != 0);
197             if(s == null)
198                 System.exit(0);
199         }
200         String schemaName = System.getProperty("user.dir") + "/tester/testcase_schema.json";
201         File schema = new File(schemaName);
202         if (!schema.exists()) {
203             BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
204             String s;
205             do{
206                 System.out.println("Please enter the full path of 'testcase_schema.json': ");
207                 s = in.readLine();
208                 if (isValidpath(s)){
209                     folder = new File(s);
210                     break;
211                 }
212             }while (s != null && s.length() != 0);
213             if(s == null)
214                 System.exit(0);
215         }
216
217         Tester tester = new Tester("http://localhost:8080/verigraph/api", schema, folder);
218
219         tester.runTestCases();
220
221     }
222
223     private static boolean isValidpath(String s) {
224         if (s==null)
225             return false;
226         File file = new File(s);
227         return file.exists();
228     }
229
230 }