update verigraph
[parser.git] / verigraph / src / it / polito / verigraph / grpc / test / ReachabilityTest.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.grpc.test;
10
11 import java.io.File;
12 import java.io.IOException;
13 import java.util.ArrayList;
14 import java.util.Iterator;
15 import java.util.List;
16 import java.util.Map;
17
18 import org.junit.After;
19 import org.junit.Before;
20 import org.junit.FixMethodOrder;
21 import org.junit.Test;
22 import org.junit.runner.RunWith;
23 import org.junit.runners.JUnit4;
24 import org.junit.runners.MethodSorters;
25
26 import static org.junit.Assert.assertEquals;
27
28 import java.io.BufferedReader;
29 import java.io.FilenameFilter;
30 import java.io.InputStreamReader;
31
32 import com.fasterxml.jackson.core.JsonParseException;
33 import com.fasterxml.jackson.databind.JsonMappingException;
34 import com.fasterxml.jackson.databind.JsonNode;
35 import com.fasterxml.jackson.databind.ObjectMapper;
36 import com.github.fge.jsonschema.core.exceptions.ProcessingException;
37 import com.github.fge.jsonschema.main.JsonSchema;
38
39 import it.polito.verigraph.grpc.GraphGrpc;
40 import it.polito.verigraph.grpc.NewGraph;
41 import it.polito.verigraph.grpc.Policy;
42 import it.polito.verigraph.grpc.VerificationGrpc;
43 import it.polito.verigraph.client.VerifyClientException;
44 import it.polito.verigraph.grpc.client.Client;
45 import it.polito.verigraph.grpc.server.GrpcUtils;
46 import it.polito.verigraph.grpc.server.Service;
47 import it.polito.verigraph.service.ValidationUtils;
48 import it.polito.verigraph.test.TestCase;
49 import it.polito.verigraph.test.TestExecutionException;
50
51 @RunWith(JUnit4.class)
52 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
53 public class ReachabilityTest {
54     private File schema;
55     private List<File>testFiles= new ArrayList<File>();
56     private List<TestCase>testCases= new ArrayList<TestCase>();
57     private Client client;
58     private Service server;
59
60     @Before
61     public void setUpBeforeClass() throws Exception {
62         client = new Client("localhost" , 50051);
63         server = new Service(50051);
64         server.start();
65
66         String folderName = System.getProperty("user.dir") + "/tester/testcases";
67         File folder = new File(folderName);
68         if (!folder.exists()) {
69             BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
70             String s;
71             do{
72                 System.out.println("Please enter the testcases folder path: ");
73                 s = in.readLine();
74                 if (isValidpath(s)){
75                     folder = new File(s);
76                     break;
77                 }
78             }while (s != null && s.length() != 0);
79             if(s == null)
80                 System.exit(0);
81         }
82         String schemaName = System.getProperty("user.dir") + "/tester/testcase_schema.json";
83         File schema = new File(schemaName);
84         if (!schema.exists()) {
85             BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
86             String s;
87             do{
88                 System.out.println("Please enter the full path of 'testcase_schema.json': ");
89                 s = in.readLine();
90                 if (isValidpath(s)){
91                     folder = new File(s);
92                     break;
93                 }
94             }while (s != null && s.length() != 0);
95             if(s == null)
96                 System.exit(0);
97         }
98
99         this.schema = schema;
100         this.testFiles = getTests(folder);
101         this.testCases = getTestCases(this.testFiles);
102     }
103
104     @After
105     public void tearDown() throws Exception {
106         server.stop();
107         client.shutdown();
108     }
109
110     @Test
111     public final void wrongReachability() {
112         System.out.println("[DEBUG] wrongReachability starts");
113         System.out.println("DEBUG: starting testWrongReachability");
114
115         VerificationGrpc nullVer = VerificationGrpc.newBuilder()
116                 .setErrorMessage("There is no Graph whose Id is '52'").build();
117         //verification on uncreated graph
118         if(client.getGraph(52) != null){
119             client.deleteGraph(52);
120         }
121         Policy policyToVerify = Client.createPolicy("Node1", "Node4", "reachability", null, 52);
122         VerificationGrpc ver = client.verify(policyToVerify);
123         assertEquals(ver, nullVer);
124
125         //verification on uncreated nodes
126         GraphGrpc graph = GraphGrpc.newBuilder().build();
127         graph = client.createGraph(graph).getGraph();
128         nullVer = VerificationGrpc.newBuilder()
129                 .setErrorMessage("The \'source\' parameter \'Node5\' is not valid, please insert the name of an existing node").build();
130         policyToVerify = Client.createPolicy("Node5", "Node4", "reachability", null, graph.getId());
131         ver = client.verify(policyToVerify);
132         assertEquals(ver, nullVer);
133
134         //verification on uncreated nodes
135         nullVer = VerificationGrpc.newBuilder()
136                 .setErrorMessage("The \'source\' parameter \'Node1\' is not valid, please insert the name of an existing node").build();
137
138         policyToVerify = Client.createPolicy("Node1", "Node10", "reachability", null, graph.getId());
139         ver = client.verify(policyToVerify);
140         assertEquals(ver, nullVer);
141
142     }
143
144     public List<File> getTests(File folder) {
145         List<File> filesList = new ArrayList<File>();
146
147         System.out.println("Test folder set to '" + folder.getAbsolutePath() + "'");
148
149         File[] files = folder.listFiles(new FilenameFilter() {
150
151             @Override
152             public boolean accept(File dir, String name) {
153                 return name.endsWith(".json");
154             }
155         });
156
157         for (File f : files) {
158             filesList.add(f);
159             System.out.println("File '" + f.getName() + "' added to test files");
160         }
161
162         return filesList;
163     }
164
165     public List<TestCase> getTestCases(List<File> files)throws JsonParseException, JsonMappingException, IOException,
166     Exception {
167         List<TestCase> testCases = new ArrayList<TestCase>();
168
169         for (File file : files) {
170             validateTestFile(file);
171             try {
172                 TestCase tc = new ObjectMapper().readValue(file, TestCase.class);
173                 testCases.add(tc);
174             }
175             catch (Exception e) {
176                 throw e;
177             }
178         }
179
180         return testCases;
181     }
182
183     @Test
184     public void runTestCases() throws VerifyClientException, TestExecutionException {
185         System.out.println("[DEBUG] runTestCases starts");
186         int counter = 0;
187         for (TestCase tc : this.testCases) {
188             List<String> results = runTestCase(tc);
189             Iterator<String> iter = tc.getResults().iterator();
190
191             if(results.isEmpty()){
192                 throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()+ "'.");
193             }
194
195             for(String result : results){
196                 if (iter.hasNext()){
197                     if( !result.equals(iter.next()))
198                         throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()
199                                 + "'. Test returned '" + result + "' instead of '" + tc.getResults() + "'.");
200                     else
201                         System.out.println("Test given in file '"+ this.testFiles.get(counter).getName() + "' returned '"
202                                 + result + "' as expected");
203                 } else throw new TestExecutionException("Error running test given in file '"+ this.testFiles.get(counter).getName()
204                         + "'. Test returned '" + result + "' instead of '" + tc.getResults() + "'.");
205             }
206             counter++;
207
208         }
209         System.out.println("All tests PASSED");
210     }
211
212     private List<String> runTestCase(TestCase tc) throws VerifyClientException, TestExecutionException{
213         GraphGrpc graph = GrpcUtils.obtainGraph(tc.getGraph());
214         ArrayList<String> results = new ArrayList<String>();
215
216         NewGraph newGraph = this.client.createGraph(graph);
217         if(newGraph.getSuccess() == false)
218             throw new VerifyClientException("gRPC request failed");
219         GraphGrpc createdGraph = newGraph.getGraph();
220
221         GraphGrpc addedgraph = client.getGraph(createdGraph.getId());
222         System.out.println(addedgraph);
223
224         for(String url : tc.getPolicyUrlParameters()){
225             final Map<String, String> map = GrpcUtils.getParamGivenString(url);
226             Policy policy = Client.createPolicy(map.get("source"),
227                     map.get("destination"),
228                     map.get("type"),
229                     map.get("middlebox"),
230                     createdGraph.getId());
231             VerificationGrpc verification = this.client.verify(policy);
232             results.add(verification.getResult());
233         }
234         return results;
235     }
236
237     public void validateTestFile(File testFile) throws Exception {
238         JsonSchema schemaNode = null;
239         try {
240             schemaNode = ValidationUtils.getSchemaNode(schema);
241         }
242         catch (IOException e) {
243             throw new Exception("Unable to load '" + schema.getAbsolutePath() + "' schema file");
244         }
245         catch (ProcessingException e) {
246             throw new Exception("Unable to resolve '" + schema.getAbsolutePath() + "' schema file as a schema node");
247         }
248
249         JsonNode jsonNode;
250         try {
251             jsonNode = ValidationUtils.getJsonNode(testFile);
252         }
253         catch (IOException e) {
254             throw new Exception("Unable to load '" + testFile.getAbsolutePath() + "' as a json node");
255         }
256
257         try {
258             ValidationUtils.validateJson(schemaNode, jsonNode);
259         }
260         catch (ProcessingException e) {
261             throw new Exception("There were errors in the validation of file '"+ testFile.getAbsolutePath()
262             + "' against the json schema '" + schema.getAbsolutePath() + "': " + e.getMessage());
263
264         }
265     }
266
267     private static boolean isValidpath(String s) {
268         if (s==null)
269             return false;
270         File file = new File(s);
271         return file.exists();
272     }
273
274 }