Debian Codegraph @

test/main/RulesTest.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2017.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 or
6 * version 2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13 package main;
14
15 import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
16 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.AND;
17 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.EXISTS;
18 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.FUNCTION;
19 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.GTE;
20 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.NOT;
21 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.NOT_EQUALS;
22 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.NOT_EXISTS;
23 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.OR;
24 import static uk.me.parabola.mkgmap.osmstyle.eval.NodeType.VALUE;
25
26 import java.io.BufferedWriter;
27 import java.io.ByteArrayOutputStream;
28 import java.io.File;
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.io.OutputStream;
32 import java.io.PrintStream;
33 import java.io.StringReader;
34 import java.io.UnsupportedEncodingException;
35 import java.math.BigInteger;
36 import java.nio.file.Files;
37 import java.nio.file.Paths;
38 import java.security.MessageDigest;
39 import java.security.NoSuchAlgorithmException;
40 import java.text.SimpleDateFormat;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Date;
44 import java.util.EnumSet;
45 import java.util.List;
46 import java.util.Objects;
47 import java.util.Random;
48 import java.util.concurrent.ExecutionException;
49 import java.util.concurrent.ExecutorService;
50 import java.util.concurrent.Executors;
51 import java.util.concurrent.Future;
52 import java.util.concurrent.TimeUnit;
53 import java.util.concurrent.TimeoutException;
54 import java.util.function.BiFunction;
55
56 import uk.me.parabola.imgfmt.app.Coord;
57 import uk.me.parabola.mkgmap.main.StyleTester;
58 import uk.me.parabola.mkgmap.osmstyle.ExpressionArranger;
59 import uk.me.parabola.mkgmap.osmstyle.eval.AndOp;
60 import uk.me.parabola.mkgmap.osmstyle.eval.BinaryOp;
61 import uk.me.parabola.mkgmap.osmstyle.eval.EqualsOp;
62 import uk.me.parabola.mkgmap.osmstyle.eval.ExistsOp;
63 import uk.me.parabola.mkgmap.osmstyle.eval.ExpressionReader;
64 import uk.me.parabola.mkgmap.osmstyle.eval.GTEOp;
65 import uk.me.parabola.mkgmap.osmstyle.eval.LTOp;
66 import uk.me.parabola.mkgmap.osmstyle.eval.NodeType;
67 import uk.me.parabola.mkgmap.osmstyle.eval.NotEqualOp;
68 import uk.me.parabola.mkgmap.osmstyle.eval.NotExistsOp;
69 import uk.me.parabola.mkgmap.osmstyle.eval.NotOp;
70 import uk.me.parabola.mkgmap.osmstyle.eval.Op;
71 import uk.me.parabola.mkgmap.osmstyle.eval.OrOp;
72 import uk.me.parabola.mkgmap.osmstyle.eval.RegexOp;
73 import uk.me.parabola.mkgmap.osmstyle.eval.ValueOp;
74 import uk.me.parabola.mkgmap.osmstyle.function.FunctionFactory;
75 import uk.me.parabola.mkgmap.osmstyle.function.GetTagFunction;
76 import uk.me.parabola.mkgmap.reader.osm.FeatureKind;
77 import uk.me.parabola.mkgmap.reader.osm.Way;
78 import uk.me.parabola.mkgmap.scan.SyntaxException;
79 import uk.me.parabola.mkgmap.scan.TokenScanner;
80
81 public class RulesTest {
82 private static final Random rand = new Random();
83
84 private static final EnumSet<NodeType> INVALID_TOP = EnumSet.of(NOT, NOT_EXISTS, NOT_EQUALS);
85 private static final EnumSet<NodeType> USEFUL_NODES;
86
87 private static final String TEST_FILE_NAME = "tmp.test";
88 private static final int TEST_TIMEOUT = 500; // In Milli seconds
89
90 static {
91 USEFUL_NODES = EnumSet.allOf(NodeType.class);
92 USEFUL_NODES.removeAll(INVALID_TOP);
93 USEFUL_NODES.removeAll(EnumSet.of(OR, AND, VALUE));
94 }
95
96 private static boolean onlyErrors;
97 private static int maxErrors = Integer.MAX_VALUE;
98 private static int maxRules = 1000;
99 private static long seed = 8799543;
100 private static boolean debug;
101 private static boolean saveErrors;
102 private static boolean stopOnFail;
103
104
105 private final String[] values = {
106 "1", "2"
107 };
108 private final String[] names = {
109 "a", "b"
110 };
111
112 private int syntaxErrors;
113
114 private final ExecutorService executor = Executors.newSingleThreadExecutor();
115
116 private static ExpressionArranger arranger;
117
118 private final List<Way> testWays = new ArrayList<>();
119
120 private static void processOptions(String... args) {
121 for (int i = 0, argsLength = args.length; i < argsLength; i++) {
122 String s = args[i];
123 if (s.startsWith("--err")) {
124 onlyErrors = true;
125 } else if (s.startsWith("--save")) {
126 saveErrors = true;
127 } else if (s.startsWith("--max-e")) {
128 maxErrors = Integer.parseInt(args[++i]);
129 } else if (s.startsWith("--max-r")) {
130 maxRules = Integer.parseInt(args[++i]);
131 } else if (s.startsWith("--arr")) {
132 arranger = new ExpressionArranger();
133 } else if (s.startsWith("--stop")) {
134 stopOnFail = true;
135 } else if (s.startsWith("--use-len")) {
136 System.out.println("The --use-length option is no longer needed");
137 } else if (s.startsWith("--seed")) {
138 seed = Long.parseLong(args[++i]);
139 } else if (s.startsWith("--rand")) {
140 seed = System.currentTimeMillis();
141 } else if (s.startsWith("--debug")) {
142 debug = true;
143 } else {
144 System.out.println("Usage:\n" +
145 "--arrange-test use the ExpressionArranger instead of style tester\n" +
146 "--max-errors stop after this many errors\n" +
147 "--max-rules run this number of random rules\n" +
148 "--errors only show errors\n" +
149 "--stop-on-fail stop on test failures\n" +
150 "--seed N set the random number seed to reproduce a previous run\n" +
151 "--rand set the random seed to the current time, so a different set of rules" +
152 " are generated.\n" +
153 "--save-errors save errors as style tester files\n" +
154 "\n" +
155 "Any error displayed is a bug in mkgmap.\n")
156 ;
157 System.exit(2);
158 }
159
160 }
161 }
162
163 public static void main(String... args) {
164 processOptions(args);
165 rand.setSeed(seed);
166
167 RulesTest srt = new RulesTest();
168 srt.run();
169 }
170
171 private void run() {
172 initTestWays();
173
174 int errors = 0;
175
176 int count;
177 for (count = 0; count < maxRules && errors < maxErrors; ) {
178
179 Op expr = generateExpr(true);
180
181 boolean invalid = checkEmpty(expr);
182 if (!invalid) {
183 count++;
184 String rule = expr + String.format(" {name 'n%d'} [0x2]", count);
185 boolean ok = testRule(rule, count);
186 if (!ok)
187 errors++;
188 }
189 }
190
191 executor.shutdownNow();
192 System.out.printf("Tests: %s, errors=%d (%d non-syntax failures), passed=%d. ",
193 count, errors, errors-syntaxErrors, count-errors);
194 System.out.printf("Seed was %d\n", seed);
195 }
196
197 private void initTestWays() {
198 for (int a = 0; a < 3; a++) {
199 for (int b = 0; b < 3; b++) {
200
201 Way w = makeWay();
202 if (a > 0)
203 w.addTag("a", String.valueOf(a));
204 if (b > 0)
205 w.addTag("b", String.valueOf(b));
206 testWays.add(w);
207 }
208 }
209 }
210
211 /**
212 * Test the rule by writing a style-tester file and letting it run it.
213 */
214 private boolean testRule(String rule, int id) {
215 if (arranger != null) {
216 return testCradle(rule, id, this::runArrangeTest);
217 } else {
218 return testCradle(rule, id, this::runStyleTester);
219 }
220 }
221
222 private boolean runStyleTester(String rule, int id) {
223 OutputStream buf = new ByteArrayOutputStream();
224 StyleTester.setOut(new PrintStream(buf));
225
226 try (BufferedWriter fw = new BufferedWriter(new FileWriter(TEST_FILE_NAME))) {
227
228 fw.write(String.format("#\n# Rule: %s\n# Id: %d\n# Seed: %d\n# Date: %s\n#\n",
229 rule, id, seed, SimpleDateFormat.getDateInstance().format(new Date())));
230
231 writeWayDefs(fw);
232 fw.write("<<<lines>>>\n");
233 fw.write(rule);
234 fw.newLine();
235
236 } catch (IOException e) {
237 e.printStackTrace();
238 System.exit(2);
239 }
240
241 StyleTester.runSimpleTest(TEST_FILE_NAME);
242
243 String output = buf.toString();
244 if (output.contains("ERROR")) {
245 System.out.println("ERROR: FAILED test: " + rule);
246 System.out.println(output);
247
248 // On error save the test file.
249 saveFile(TEST_FILE_NAME, rule, id);
250 checkStopOnFail();
251 return false;
252 } else {
253 if (!onlyErrors)
254 System.out.println("OK: " + rule);
255
256 // remove since ok
257 new File(TEST_FILE_NAME).delete();
258 return true;
259 }
260 }
261
262 private boolean runArrangeTest(String rule, int id) {
263 TokenScanner scanner = new TokenScanner("test.file", new StringReader(rule));
264 ExpressionReader er = new ExpressionReader(scanner, FeatureKind.POLYLINE);
265 Op op = er.readConditions();
266
267 boolean[] orig = evalWays(op);
268 Op result = arranger.arrange(op);
269
270 boolean[] after = evalWays(result);
271 boolean ok = Arrays.equals(after, orig);
272 if (ok) {
273 if (!onlyErrors)
274 System.out.println("OK: " + rule);
275 } else {
276 System.out.println("ERROR: FAILED test: " + rule);
277 System.out.println(" new expr: " + op);
278
279 for (int i = 0; i < orig.length; i++) {
280 if (orig[i] != after[i]) {
281 System.out.println(" way " + testWays.get(i) + ", orig=" + orig[i] + ", arranged=" + after[i]);
282 }
283 }
284 checkStopOnFail();
285 }
286 return ok;
287 }
288
289 private boolean[] evalWays(Op op) {
290 boolean[] result = new boolean[testWays.size()];
291 int count = 0;
292 for (Way w : testWays) {
293 result[count++] = op.eval(w);
294 }
295 return result;
296 }
297
298 /**
299 * Call a test method in a timeout protected wrapper.
300 *
301 * @param rule The rule to be tested.
302 * @param id The id of the rule in this run.
303 * @param call The test method to call.
304 * @return True if the test passed, false if it failed, or there was an exception.
305 */
306 private boolean testCradle(String rule, int id, BiFunction<String, Integer, Boolean> call) {
307 Future<Boolean> future = executor.submit(() -> call.apply(rule, id));
308 try {
309 Boolean result = future.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
310 if (result != null)
311 return result;
312 } catch (InterruptedException | TimeoutException e) {
313 future.cancel(true);
314
315 System.out.println("ERROR: Timeout - took too long: " + rule);
316 System.out.println(" Message: " + e);
317
318 // On error save the test file.
319 saveFile(TEST_FILE_NAME, rule, id);
320 checkStopOnFail();
321 } catch (ExecutionException e) {
322 future.cancel(true);
323
324 Throwable ne = e.getCause();
325 if (ne instanceof SyntaxException) {
326 System.out.println("ERROR: Syntax: " + rule);
327 syntaxErrors++;
328 } else {
329 System.out.println("ERROR: Failed with exception: " + rule);
330 System.out.println(" exception: " + ne);
331 }
332 checkStopOnFail();
333 System.out.println(" Message: " + ne.getMessage());
334
335 // On error save the test file.
336 saveFile(TEST_FILE_NAME, rule, id);
337 }
338
339 return false;
340 }
341
342 private void checkStopOnFail() {
343 if (stopOnFail) {
344 System.out.println("Stopping after first failure");
345 executor.shutdownNow();
346 System.exit(1);
347 }
348 }
349
350 private void saveFile(String fromName, String rule, int id) {
351 if (!saveErrors || fromName == null)
352 return;
353
354 String fileName;
355 try {
356 MessageDigest md5 = MessageDigest.getInstance("md5");
357 byte[] digest = md5.digest(rule.getBytes("utf-8"));
358 String s = String.format("%032x", new BigInteger(1, digest)).substring(0, 8);
359 fileName = String.format("t-%s.test", s);
360 } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
361 fileName = String.format("t-%06d.test", id);
362 }
363
364 try {
365 Files.move(Paths.get(fromName), Paths.get(fileName), REPLACE_EXISTING);
366 } catch (IOException e) {
367 e.printStackTrace();
368 }
369 }
370
371 /**
372 * Create ways for all combinations of the used variables and values.
373 * @param fw Write to here
374 */
375 private void writeWayDefs(BufferedWriter fw) {
376 int count = 1;
377 for (int a = 0; a < 3; a++) {
378 for (int b = 0; b < 3; b++) {
379
380 try {
381 fw.write(String.format("WAY %d\n", count));
382 if (a > 0)
383 fw.write(String.format("a=%d\n", a));
384 if (b > 0)
385 fw.write(String.format("b=%d\n", b));
386 fw.newLine();
387 } catch (IOException e) {
388 e.printStackTrace();
389 }
390 count++;
391 }
392 }
393 }
394
395 /**
396 * Check if this rule would match an empty way.
397 *
398 * Such rules are not allowed.
399 *
400 * The problem case is length(). The length of the test way is 3.3 and we always make
401 * sure that length is only used in expressions with GTE and values of 1 or 2 so they
402 * are always true. However if there is a NOT in front if it it will then be false and
403 * so the simple test of of an empty way returning true could miss this case.
404 *
405 * So we also check with a way of length zero.
406 *
407 * Then there is still the problem that we do not detect an expression such as (length()>=2 & !(length()>=2))
408 *
409 * So reject any rule that has length() beneath a not.
410 */
411 private static boolean checkEmpty(Op expr) {
412 Way way = makeWay();
413
414 boolean invalid = expr.eval(way);
415
416 Way way1 = new Way(2);
417 way1.addPoint(new Coord(1, 1));
418 if (expr.eval(way1))
419 invalid = true;
420
421 // So if there is a length() anywhere beneath a NOT then throw this rule out.
422 if (checkNotLength(expr, expr.isType(NOT)))
423 invalid = true;
424
425 return invalid;
426 }
427
428 public static boolean checkNotLength(Op expr, boolean hasNot) {
429 if (expr == null)
430 return false;
431
432 Op f = expr.getFirst();
433 if (hasNot && f != null && f.isType(FUNCTION) && Objects.equals(f.toString(), "length()"))
434 return true;
435
436 boolean invalid = false;
437 NodeType t = expr.getType();
438 if (expr instanceof BinaryOp) {
439 if (checkNotLength(expr.getFirst(), hasNot))
440 invalid = true;
441
442 if (checkNotLength(expr.getSecond(), hasNot))
443 invalid = true;
444
445 } else if (t == NOT) {
446 if (checkNotLength(expr.getFirst(), true))
447 invalid = true;
448 }
449 return invalid;
450 }
451
452 private static Way makeWay() {
453 Way way = new Way(1);
454 way.addPoint(new Coord(1, 1));
455 way.addPoint(new Coord(2, 2));
456 return way;
457 }
458
459 /**
460 * Generate a random expression.
461 */
462 private Op generateExpr() {
463 return generateExpr(false);
464 }
465
466 /**
467 * Generate a random expression.
468 *
469 * Picks a random operation from a hopefully representative list of possibilities.
470 * It is called recursively to fill in AND and OR subtrees.
471 *
472 * @param interesting Only return OR / AND for use as the starting term. Otherwise
473 * you get a lot of uninteresting a=2 type expressions.
474 */
475 private Op generateExpr(boolean interesting) {
476 int t = rand.nextInt(interesting ? 3: 10);
477 switch (t) {
478 case 0:
479 return fillOp(new AndOp());
480 case 1:
481 return fillOp(new OrOp());
482 case 2:
483 return fillOp(new NotOp());
484 case 3:
485 return fillNameValue(new LTOp());
486 case 4:
487 return fillNameValue(new GTEOp());
488 case 5:
489 return fillNameValue(new RegexOp());
490 case 6:
491 return fillNameValue(new NotEqualOp());
492 case 7:
493 return new ExistsOp().setFirst(genNameOp(EXISTS));
494 case 8:
495 return new NotExistsOp().setFirst(genNameOp(NOT_EXISTS));
496 default:
497 return fillNameValue(new EqualsOp());
498 }
499 }
500
501 /**
502 * Fill the slots on a container operation eg AND, OR
503 */
504 private Op fillOp(Op op) {
505 op.setFirst(generateExpr());
506 if (op instanceof BinaryOp)
507 op.setSecond(generateExpr());
508 return op;
509 }
510
511 /**
512 * Fill with an name and a value.
513 *
514 * There are a limited number of names and values available.
515 */
516 private Op fillNameValue(BinaryOp op) {
517 op.setFirst(genNameOp(op.getType()));
518 op.setSecond(valueOp());
519 return op;
520 }
521
522 private Op genNameOp(NodeType type) {
523 if (type == GTE && rand.nextInt(4) == 0) {
524 return FunctionFactory.createFunction("length");
525 }
526
527 String name = names[rand.nextInt(names.length)];
528 return new GetTagFunction(name);
529 }
530
531 private Op valueOp() {
532 return new ValueOp(values[rand.nextInt(values.length)]);
533 }
534 }