1 package test.failures;
2 
3 import org.testng.Assert;
4 import org.testng.TestNG;
5 import org.testng.reporters.FailedReporter;
6 
7 import java.io.BufferedReader;
8 import java.io.File;
9 import java.io.FileNotFoundException;
10 import java.io.FileReader;
11 import java.io.IOException;
12 import java.util.regex.Pattern;
13 
14 public class BaseFailuresTest {
15 
16 //  protected TestNG run(Class[] classes, String outputDir) {
17 //    return run(new TestNG(), classes, outputDir);
18 //  }
19 
getSuiteName()20   protected String getSuiteName() {
21     return "TmpSuite";
22   }
23 
run(TestNG result, Class[] classes, String outputDir)24   protected TestNG run(TestNG result, Class[] classes, String outputDir) {
25      result.setVerbose(0);
26      result.setOutputDirectory(outputDir);
27      result.setTestClasses(classes);
28      result.run();
29 
30      return result;
31   }
32 
33   /**
34    * @param f
35    * @param regexps
36    * @return true if the file contains at least one occurrence of each regexp
37    */
containsRegularExpressions(File f, String[] strRegexps)38   protected boolean containsRegularExpressions(File f, String[] strRegexps) {
39     Pattern[] matchers = new Pattern[strRegexps.length];
40     boolean[] results = new boolean[strRegexps.length];
41     for (int i = 0; i < strRegexps.length; i++) {
42       matchers[i] = Pattern.compile(".*" + strRegexps[i] + ".*");
43       results[i] = false;
44     }
45 
46     try {
47       FileReader fr = new FileReader(f);
48       BufferedReader br = new BufferedReader(fr);
49       String line = br.readLine();
50       while (line != null) {
51         for (int i = 0; i < strRegexps.length; i++) {
52           if (matchers[i].matcher(line).matches()) {
53             results[i] = true;
54           }
55         }
56         line = br.readLine();
57       }
58       fr.close();
59       br.close();
60     }
61     catch (FileNotFoundException e) {
62       e.printStackTrace();
63       return false;
64     }
65     catch (IOException e) {
66       e.printStackTrace();
67       return false;
68     }
69 
70     for (int i = 0; i < results.length; i++) {
71       boolean result = results[i];
72       if (! result) {
73         throw new AssertionError("Couldn't find " + strRegexps[i]);
74       }
75     }
76 
77     return true;
78   }
79 
verify(String outputDir, String[] expected)80   protected void verify(String outputDir, String[] expected) {
81     File f = new File(outputDir +
82         File.separatorChar + getSuiteName() +
83         File.separator + FailedReporter.TESTNG_FAILED_XML);
84      boolean passed = containsRegularExpressions(f, expected);
85      Assert.assertTrue(passed);
86 
87      File tmpDir = new File(outputDir);
88      tmpDir.delete();
89   }
90 
91 }
92