PageRenderTime 66ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/test/tools/launcher/TestHelper.java

https://github.com/ikeji/openjdk7-jdk
Java | 385 lines | 300 code | 30 blank | 55 comment | 47 complexity | 772d01ac8a4908dd00f0607dc9119318 MD5 | raw file
  1. /*
  2. * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation.
  8. *
  9. * This code is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. * version 2 for more details (a copy is included in the LICENSE file that
  13. * accompanied this code).
  14. *
  15. * You should have received a copy of the GNU General Public License version
  16. * 2 along with this work; if not, write to the Free Software Foundation,
  17. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18. *
  19. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20. * or visit www.oracle.com if you need additional information or have any
  21. * questions.
  22. */
  23. import java.nio.file.attribute.BasicFileAttributes;
  24. import java.nio.file.FileVisitResult;
  25. import java.nio.file.SimpleFileVisitor;
  26. import javax.tools.ToolProvider;
  27. import java.io.BufferedReader;
  28. import java.io.File;
  29. import java.io.FileNotFoundException;
  30. import java.io.FileOutputStream;
  31. import java.io.IOException;
  32. import java.io.InputStreamReader;
  33. import java.io.PrintStream;
  34. import java.nio.file.Files;
  35. import java.nio.file.Path;
  36. import java.util.ArrayList;
  37. import java.util.List;
  38. import java.util.Map;
  39. import javax.tools.JavaCompiler;
  40. import static java.nio.file.StandardCopyOption.*;
  41. /**
  42. * This class provides some common utilities for the launcher tests.
  43. */
  44. public enum TestHelper {
  45. INSTANCE;
  46. static final String JAVAHOME = System.getProperty("java.home");
  47. static final boolean isSDK = JAVAHOME.endsWith("jre");
  48. static final String javaCmd;
  49. static final String java64Cmd;
  50. static final String javacCmd;
  51. static final JavaCompiler compiler;
  52. static final boolean debug = Boolean.getBoolean("TestHelper.Debug");
  53. static final boolean isWindows =
  54. System.getProperty("os.name", "unknown").startsWith("Windows");
  55. static final boolean is64Bit =
  56. System.getProperty("sun.arch.data.model").equals("64");
  57. static final boolean is32Bit =
  58. System.getProperty("sun.arch.data.model").equals("32");
  59. static final boolean isSolaris =
  60. System.getProperty("os.name", "unknown").startsWith("SunOS");
  61. static final boolean isLinux =
  62. System.getProperty("os.name", "unknown").startsWith("Linux");
  63. static final boolean isDualMode = isSolaris;
  64. static final boolean isSparc = System.getProperty("os.arch").startsWith("sparc");
  65. static int testExitValue = 0;
  66. static {
  67. if (is64Bit && is32Bit) {
  68. throw new RuntimeException("arch model cannot be both 32 and 64 bit");
  69. }
  70. if (!is64Bit && !is32Bit) {
  71. throw new RuntimeException("arch model is not 32 or 64 bit ?");
  72. }
  73. compiler = ToolProvider.getSystemJavaCompiler();
  74. File binDir = (isSDK) ? new File((new File(JAVAHOME)).getParentFile(), "bin")
  75. : new File(JAVAHOME, "bin");
  76. File javaCmdFile = (isWindows)
  77. ? new File(binDir, "java.exe")
  78. : new File(binDir, "java");
  79. javaCmd = javaCmdFile.getAbsolutePath();
  80. if (!javaCmdFile.canExecute()) {
  81. throw new RuntimeException("java <" + TestHelper.javaCmd + "> must exist");
  82. }
  83. File javacCmdFile = (isWindows)
  84. ? new File(binDir, "javac.exe")
  85. : new File(binDir, "javac");
  86. javacCmd = javacCmdFile.getAbsolutePath();
  87. if (!javacCmdFile.canExecute()) {
  88. throw new RuntimeException("java <" + javacCmd + "> must exist");
  89. }
  90. if (isSolaris) {
  91. File sparc64BinDir = new File(binDir,isSparc ? "sparcv9" : "amd64");
  92. File java64CmdFile= new File(sparc64BinDir, "java");
  93. if (java64CmdFile.exists() && java64CmdFile.canExecute()) {
  94. java64Cmd = java64CmdFile.getAbsolutePath();
  95. } else {
  96. java64Cmd = null;
  97. }
  98. } else {
  99. java64Cmd = null;
  100. }
  101. }
  102. /*
  103. * is a dual mode available in the test jdk
  104. */
  105. static boolean dualModePresent() {
  106. return isDualMode && java64Cmd != null;
  107. }
  108. /*
  109. * usually the jre/lib/arch-name is the same as os.arch, except for x86.
  110. */
  111. static String getJreArch() {
  112. String arch = System.getProperty("os.arch");
  113. return arch.equals("x86") ? "i386" : arch;
  114. }
  115. /*
  116. * get the complementary jre arch ie. if sparc then return sparcv9 and
  117. * vice-versa.
  118. */
  119. static String getComplementaryJreArch() {
  120. String arch = System.getProperty("os.arch");
  121. if (arch != null) {
  122. switch (arch) {
  123. case "sparc":
  124. return "sparcv9";
  125. case "sparcv9":
  126. return "sparc";
  127. case "x86":
  128. return "amd64";
  129. case "amd64":
  130. return "i386";
  131. }
  132. }
  133. return null;
  134. }
  135. /*
  136. * A convenience method to create a jar with jar file name and defs
  137. */
  138. static void createJar(File jarName, String... mainDefs)
  139. throws FileNotFoundException{
  140. createJar(null, jarName, new File("Foo"), mainDefs);
  141. }
  142. /*
  143. * A convenience method to create a java file, compile and jar it up, using
  144. * the sole class file name in the jar, as the Main-Class attribute value.
  145. */
  146. static void createJar(File jarName, File mainClass, String... mainDefs)
  147. throws FileNotFoundException {
  148. createJar(null, jarName, mainClass, mainDefs);
  149. }
  150. /*
  151. * A generic jar file creator to create a java file, compile it
  152. * and jar it up, a specific Main-Class entry name in the
  153. * manifest can be specified or a null to use the sole class file name
  154. * as the Main-Class attribute value.
  155. */
  156. static void createJar(String mEntry, File jarName, File mainClass,
  157. String... mainDefs) throws FileNotFoundException {
  158. if (jarName.exists()) {
  159. jarName.delete();
  160. }
  161. PrintStream ps = new PrintStream(new FileOutputStream(mainClass + ".java"));
  162. ps.println("public class Foo {");
  163. if (mainDefs != null) {
  164. for (String x : mainDefs) {
  165. ps.println(x);
  166. }
  167. }
  168. ps.println("}");
  169. ps.close();
  170. String compileArgs[] = {
  171. mainClass + ".java"
  172. };
  173. if (compiler.run(null, null, null, compileArgs) != 0) {
  174. throw new RuntimeException("compilation failed " + mainClass + ".java");
  175. }
  176. if (mEntry == null) {
  177. mEntry = mainClass.getName();
  178. }
  179. String jarArgs[] = {
  180. (debug) ? "cvfe" : "cfe",
  181. jarName.getAbsolutePath(),
  182. mEntry,
  183. mainClass.getName() + ".class"
  184. };
  185. sun.tools.jar.Main jarTool =
  186. new sun.tools.jar.Main(System.out, System.err, "JarCreator");
  187. if (!jarTool.run(jarArgs)) {
  188. throw new RuntimeException("jar creation failed " + jarName);
  189. }
  190. }
  191. static void copyFile(File src, File dst) throws IOException {
  192. Path parent = dst.toPath().getParent();
  193. if (parent != null) {
  194. Files.createDirectories(parent);
  195. }
  196. Files.copy(src.toPath(), dst.toPath(), COPY_ATTRIBUTES, REPLACE_EXISTING);
  197. }
  198. static void recursiveDelete(File target) throws IOException {
  199. if (!target.exists()) {
  200. return;
  201. }
  202. Files.walkFileTree(target.toPath(), new SimpleFileVisitor<Path>() {
  203. @Override
  204. public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
  205. try {
  206. Files.deleteIfExists(dir);
  207. } catch (IOException ex) {
  208. System.out.println("Error: could not delete: " + dir.toString());
  209. System.out.println(ex.getMessage());
  210. return FileVisitResult.TERMINATE;
  211. }
  212. return FileVisitResult.CONTINUE;
  213. }
  214. @Override
  215. public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
  216. try {
  217. Files.deleteIfExists(file);
  218. } catch (IOException ex) {
  219. System.out.println("Error: could not delete: " + file.toString());
  220. System.out.println(ex.getMessage());
  221. return FileVisitResult.TERMINATE;
  222. }
  223. return FileVisitResult.CONTINUE;
  224. }
  225. });
  226. }
  227. static TestResult doExec(String...cmds) {
  228. return doExec(null, cmds);
  229. }
  230. /*
  231. * A method which executes a java cmd and returns the results in a container
  232. */
  233. static TestResult doExec(Map<String, String> envToSet, String...cmds) {
  234. String cmdStr = "";
  235. for (String x : cmds) {
  236. cmdStr = cmdStr.concat(x + " ");
  237. }
  238. ProcessBuilder pb = new ProcessBuilder(cmds);
  239. Map<String, String> env = pb.environment();
  240. if (envToSet != null) {
  241. env.putAll(envToSet);
  242. }
  243. BufferedReader rdr = null;
  244. try {
  245. List<String> outputList = new ArrayList<>();
  246. pb.redirectErrorStream(true);
  247. Process p = pb.start();
  248. rdr = new BufferedReader(new InputStreamReader(p.getInputStream()));
  249. String in = rdr.readLine();
  250. while (in != null) {
  251. outputList.add(in);
  252. in = rdr.readLine();
  253. }
  254. p.waitFor();
  255. p.destroy();
  256. return new TestHelper.TestResult(cmdStr, p.exitValue(), outputList,
  257. env, new Throwable("current stack of the test"));
  258. } catch (Exception ex) {
  259. ex.printStackTrace();
  260. throw new RuntimeException(ex.getMessage());
  261. }
  262. }
  263. /*
  264. * A class to encapsulate the test results and stuff, with some ease
  265. * of use methods to check the test results.
  266. */
  267. static class TestResult {
  268. StringBuilder status;
  269. int exitValue;
  270. List<String> testOutput;
  271. Map<String, String> env;
  272. Throwable t;
  273. public TestResult(String str, int rv, List<String> oList,
  274. Map<String, String> env, Throwable t) {
  275. status = new StringBuilder("Executed command: " + str + "\n");
  276. exitValue = rv;
  277. testOutput = oList;
  278. this.env = env;
  279. this.t = t;
  280. }
  281. void appendStatus(String x) {
  282. status = status.append(" " + x + "\n");
  283. }
  284. void checkNegative() {
  285. if (exitValue == 0) {
  286. appendStatus("Error: test must not return 0 exit value");
  287. testExitValue++;
  288. }
  289. }
  290. void checkPositive() {
  291. if (exitValue != 0) {
  292. appendStatus("Error: test did not return 0 exit value");
  293. testExitValue++;
  294. }
  295. }
  296. boolean isOK() {
  297. return exitValue == 0;
  298. }
  299. boolean isZeroOutput() {
  300. if (!testOutput.isEmpty()) {
  301. appendStatus("Error: No message from cmd please");
  302. testExitValue++;
  303. return false;
  304. }
  305. return true;
  306. }
  307. boolean isNotZeroOutput() {
  308. if (testOutput.isEmpty()) {
  309. appendStatus("Error: Missing message");
  310. testExitValue++;
  311. return false;
  312. }
  313. return true;
  314. }
  315. @Override
  316. public String toString() {
  317. status.append("++++Begin Test Info++++\n");
  318. status.append("++++Test Environment++++\n");
  319. for (String x : env.keySet()) {
  320. status.append(x).append("=").append(env.get(x)).append("\n");
  321. }
  322. status.append("++++Test Output++++\n");
  323. for (String x : testOutput) {
  324. appendStatus(x);
  325. }
  326. status.append("++++Test Stack Trace++++\n");
  327. status.append(t.toString());
  328. for (StackTraceElement e : t.getStackTrace()) {
  329. status.append(e.toString());
  330. }
  331. status.append("++++End of Test Info++++\n");
  332. return status.toString();
  333. }
  334. boolean contains(String str) {
  335. for (String x : testOutput) {
  336. if (x.contains(str)) {
  337. return true;
  338. }
  339. }
  340. appendStatus("Error: string <" + str + "> not found");
  341. testExitValue++;
  342. return false;
  343. }
  344. boolean matches(String stringToMatch) {
  345. for (String x : testOutput) {
  346. if (x.matches(stringToMatch)) {
  347. return true;
  348. }
  349. }
  350. appendStatus("Error: string <" + stringToMatch + "> not found");
  351. testExitValue++;
  352. return false;
  353. }
  354. }
  355. }