You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestUtil.java 31KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Xerox/PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.testing.util;
  13. import java.io.BufferedReader;
  14. import java.io.ByteArrayOutputStream;
  15. import java.io.DataInputStream;
  16. import java.io.File;
  17. import java.io.FileInputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.PrintStream;
  21. import java.io.PrintWriter;
  22. import java.io.StringReader;
  23. import java.io.StringWriter;
  24. import java.lang.reflect.InvocationTargetException;
  25. import java.lang.reflect.Method;
  26. import java.lang.reflect.Modifier;
  27. import java.net.MalformedURLException;
  28. import java.net.URL;
  29. import java.net.URLClassLoader;
  30. import java.util.*;
  31. import org.aspectj.bridge.IMessageHandler;
  32. import org.aspectj.bridge.MessageUtil;
  33. import org.aspectj.util.FileUtil;
  34. import org.aspectj.util.LangUtil;
  35. import org.aspectj.util.Reflection;
  36. import jdiff.text.FileLine;
  37. import jdiff.util.Diff;
  38. import jdiff.util.DiffNormalOutput;
  39. import junit.framework.Assert;
  40. import junit.framework.AssertionFailedError;
  41. import junit.framework.Test;
  42. import junit.framework.TestCase;
  43. import junit.framework.TestResult;
  44. import junit.framework.TestSuite;
  45. import sun.net.www.ParseUtil;
  46. /**
  47. * Things that junit should perhaps have, but doesn't. Note the file-comparison methods require JDiff to run, but JDiff types are
  48. * not required to resolve this class. Also, the bytecode weaver is required to compare class files, but not to compare other files.
  49. */
  50. public final class TestUtil {
  51. private static final String SANDBOX_NAME = "ajcSandbox";
  52. private static final boolean JAVA_5_VM;
  53. private static final String ASPECTJRT_KEY = "aspectjrt";
  54. private static final String TESTING_CLIENT_KEY = "testing-client";
  55. public static final URL BAD_URL;
  56. private static final File LIB_DIR;
  57. private static final Properties LIB_RPATHS;
  58. private static final Map LIB_ENTRIES;
  59. private static File ASPECTJRT_PATH;
  60. private static File ASPECTJRTJAR_PATH;
  61. static {
  62. {
  63. String[] paths = {
  64. "sp:aspectjrt.path",
  65. "sp:aspectjrt.jar",
  66. "../runtime/target/classes",
  67. "../lib/test/aspectjrt.jar"};
  68. ASPECTJRT_PATH = FileUtil.getBestFile(paths);
  69. ASPECTJRTJAR_PATH = FileUtil.getBestFile(paths, true);
  70. }
  71. {
  72. boolean j5 = false;
  73. try {
  74. Class.forName("java.lang.annotation.Annotation");
  75. j5 = true;
  76. } catch (Throwable t) {
  77. }
  78. JAVA_5_VM = j5;
  79. }
  80. {
  81. URL url = null;
  82. try {
  83. url = new URL("http://eclipse.org/BADURL");
  84. } catch (MalformedURLException e) {
  85. // ignore - hopefully never
  86. }
  87. BAD_URL = url;
  88. }
  89. {
  90. File file = new File("lib");
  91. if (!isLibDir(file)) {
  92. File cur = new File(".").getAbsoluteFile();
  93. File parent = cur.getParentFile();
  94. while (null != parent) {
  95. file = new File(parent, "lib");
  96. if (isLibDir(file)) {
  97. break;
  98. }
  99. parent = parent.getParentFile();
  100. }
  101. if (null == parent) {
  102. file = new File("NOT IN ASPECTJ TREE");
  103. }
  104. }
  105. LIB_DIR = file;
  106. }
  107. LIB_RPATHS = new Properties();
  108. LIB_RPATHS.setProperty(ASPECTJRT_KEY, "tests/aspectjrt.jar");
  109. LIB_RPATHS.setProperty(TESTING_CLIENT_KEY, "tests/testing-client.jar");
  110. // TODO support others loaded dynamically
  111. Map<String,Object> map = new HashMap<>();
  112. for (Object o : LIB_RPATHS.keySet()) {
  113. String key = (String) o;
  114. String path = LIB_RPATHS.getProperty(key);
  115. File file = null;
  116. URL url = null;
  117. try {
  118. file = libFile(path);
  119. url = libURL(path);
  120. } catch (IllegalArgumentException e) {
  121. file = new File(path + " not found");
  122. url = BAD_URL;
  123. } finally {
  124. map.put(key + ".file", file);
  125. map.put(key + ".url", url);
  126. }
  127. }
  128. // TODO support changing entries, etc.
  129. LIB_ENTRIES = Collections.unmodifiableMap(map);
  130. }
  131. private static boolean isLibDir(File lib) {
  132. return new File(lib, "test" + File.separator + "aspectjrt.jar").exists();
  133. }
  134. private TestUtil() {
  135. super();
  136. }
  137. public static boolean is15VMOrGreater() {
  138. return JAVA_5_VM;
  139. }
  140. public static File aspectjrtPath() {
  141. return ASPECTJRT_PATH;
  142. }
  143. // needsJar for module packaged runtime
  144. public static File aspectjrtPath(boolean needsJar) {
  145. if (needsJar) {
  146. return ASPECTJRTJAR_PATH;
  147. } else {
  148. return ASPECTJRT_PATH;
  149. }
  150. }
  151. public static URL fileToURL(File file) {
  152. try {
  153. return file.toURL();
  154. } catch (MalformedURLException e) {
  155. return null;
  156. }
  157. }
  158. public static String filesToPath(File[] entries) {
  159. return toPath(entries);
  160. }
  161. public static String urlsToPath(URL[] entries) {
  162. return toPath(entries);
  163. }
  164. /**
  165. * untyped interface for mixed entries
  166. */
  167. public static String filesOrurlsToPath(Object[] entries) {
  168. return toPath(entries);
  169. }
  170. /**
  171. * This relies on these being File (where toString() == getPath()) or URL (where toString() == toExternalForm()).
  172. *
  173. * @param entries the Object[] of File or URL elements
  174. * @return the String with entries dlimited by the File.pathSeparator
  175. */
  176. private static String toPath(Object[] entries) {
  177. if ((null == entries) || (0 == entries.length)) {
  178. return "";
  179. }
  180. StringBuffer path = new StringBuffer();
  181. boolean started = false;
  182. for (Object entry : entries) {
  183. if (null != entry) {
  184. if (started) {
  185. path.append(File.pathSeparator);
  186. } else {
  187. started = true;
  188. }
  189. path.append(entry.toString());
  190. }
  191. }
  192. return path.toString();
  193. }
  194. public static String aspectjrtClasspath() {
  195. return TestUtil.aspectjrtPath().getPath();
  196. }
  197. /**
  198. * @param input the String to parse for [on|off|true|false]
  199. * @throws IllegalArgumentException if input is bad
  200. **/
  201. public static boolean parseBoolean(String input) {
  202. return parseBoolean(input, true);
  203. }
  204. /**
  205. * @param input the String to parse for [on|off|true|false]
  206. * @param iaxOnError if true and input is bad, throw IllegalArgumentException
  207. * @return true if input is true, false otherwise
  208. * @throws IllegalArgumentException if iaxOnError and input is bad
  209. */
  210. public static boolean parseBoolean(final String input, boolean iaxOnError) {
  211. final String syntax = ": [on|off|true|false]";
  212. if (null == input) {
  213. return false;
  214. }
  215. String lc = input.trim().toLowerCase();
  216. boolean result = false;
  217. boolean valid = false;
  218. switch (lc.length()) {
  219. case 2:
  220. if (valid = "on".equals(lc)) {
  221. result = true;
  222. }
  223. break;
  224. case 3:
  225. valid = "off".equals(lc);
  226. break;
  227. case 4:
  228. if (valid = "true".equals(lc)) {
  229. result = true;
  230. }
  231. break;
  232. case 5:
  233. valid = "false".equals(lc);
  234. break;
  235. }
  236. if (iaxOnError && !valid) {
  237. throw new IllegalArgumentException(input + syntax);
  238. }
  239. return result;
  240. }
  241. public static File aspectjrtJarFile() {
  242. return (File) LIB_ENTRIES.get(ASPECTJRT_KEY + ".file");
  243. }
  244. public static URL aspectjrtJarURL() {
  245. return (URL) LIB_ENTRIES.get(ASPECTJRT_KEY + ".url");
  246. }
  247. public static File testingClientJarFile() {
  248. return (File) LIB_ENTRIES.get(TESTING_CLIENT_KEY + ".file");
  249. }
  250. public static URL testingClientJarURL() {
  251. return (URL) LIB_ENTRIES.get(TESTING_CLIENT_KEY + ".url");
  252. }
  253. /**
  254. *
  255. * @param rpath the String relative path from the library directory to a resource that must exist (may be a directory), using
  256. * forward slashes as a file separator
  257. * @return the File path
  258. * @throws IllegalArgumentException if no such directory or file
  259. */
  260. public static File libFile(String rpath) {
  261. if ((null == rpath) || (0 == rpath.length())) {
  262. throw new IllegalArgumentException("no input");
  263. }
  264. rpath = rpath.replace('/', File.separatorChar);
  265. File result = new File(LIB_DIR, rpath);
  266. if (result.exists()) {
  267. return result;
  268. }
  269. throw new IllegalArgumentException("not in " + LIB_DIR + ": " + rpath);
  270. }
  271. /**
  272. * Like libPath, only it returns a URL.
  273. *
  274. * @return URL or null if it does not exist
  275. * @throws IllegalArgumentException if no such directory or file
  276. */
  277. public static URL libURL(String rpath) {
  278. File file = libFile(rpath);
  279. try {
  280. return file.toURL();
  281. } catch (MalformedURLException e) {
  282. throw new IllegalArgumentException("bad URL from: " + file);
  283. }
  284. }
  285. // ---- arrays
  286. public static void assertArrayEquals(String msg, Object[] expected, Object[] found) {
  287. TestCase.assertEquals(msg, Arrays.asList(expected), Arrays.asList(found));
  288. }
  289. // ---- unordered
  290. public static void assertSetEquals(Collection<?> expected, Collection<?> found) {
  291. assertSetEquals(null, expected, found);
  292. }
  293. public static void assertSetEquals(String msg, Object[] expected, Object[] found) {
  294. assertSetEquals(msg, Arrays.asList(expected), Arrays.asList(found));
  295. }
  296. public static void assertSetEquals(String msg, Collection<?> expected, Collection<?> found) {
  297. msg = (msg == null) ? "" : msg + ": ";
  298. Set<Object> results1 = new HashSet<>(found);
  299. results1.removeAll(expected);
  300. Set<Object> results2 = new HashSet<>(expected);
  301. results2.removeAll(found);
  302. if (results1.isEmpty()) {
  303. TestCase.assertTrue(msg + "Expected but didn't find: " + results2.toString(), results2.isEmpty());
  304. } else if (results2.isEmpty()) {
  305. TestCase.assertTrue(msg + "Didn't expect: " + results1.toString(), results1.isEmpty());
  306. } else {
  307. TestCase.assertTrue(msg + "Expected but didn't find: " + results2.toString() + "\nDidn't expect: "
  308. + results1.toString(), false);
  309. }
  310. }
  311. // ---- objects
  312. public static void assertCommutativeEquals(Object a, Object b, boolean should) {
  313. TestCase.assertEquals(a + " equals " + b, should, a.equals(b));
  314. TestCase.assertEquals(b + " equals " + a, should, b.equals(a));
  315. assertHashEquals(a, b, should);
  316. }
  317. private static void assertHashEquals(Object s, Object t, boolean should) {
  318. if (should) {
  319. TestCase.assertTrue(s + " does not hash to same as " + t, s.hashCode() == t.hashCode());
  320. } else {
  321. if (s.hashCode() == t.hashCode()) {
  322. System.err.println("warning: hash collision with hash = " + t.hashCode());
  323. System.err.println(" for " + s);
  324. System.err.println(" and " + t);
  325. }
  326. }
  327. }
  328. // -- reflective stuff
  329. public static void runMain(String classPath, String className) {
  330. runMethod(classPath, className, "main", new Object[] { new String[0] });
  331. }
  332. public static Object runMethod(String classPath, String className, String methodName, Object[] args) {
  333. classPath += File.pathSeparator + System.getProperty("java.class.path");
  334. ClassLoader loader = new URLClassLoader(pathToURLs(classPath), null);
  335. Class c = null;
  336. try {
  337. c = loader.loadClass(className);
  338. } catch (ClassNotFoundException e) {
  339. Assert.assertTrue("unexpected exception: " + e, false);
  340. }
  341. return Reflection.invokestaticN(c, methodName, args);
  342. }
  343. /**
  344. * @see sun.misc.URLClassPath#pathToURLs(String)
  345. */
  346. public static URL[] pathToURLs(String path) {
  347. StringTokenizer st = new StringTokenizer(path, File.pathSeparator);
  348. URL[] urls = new URL[st.countTokens()];
  349. int count = 0;
  350. while (st.hasMoreTokens()) {
  351. File f = new File(st.nextToken());
  352. try {
  353. f = new File(f.getCanonicalPath());
  354. } catch (IOException x) {
  355. // use the non-canonicalized filename
  356. }
  357. try {
  358. urls[count++] = ParseUtil.fileToEncodedURL(f);
  359. } catch (IOException x) { }
  360. }
  361. if (urls.length != count) {
  362. URL[] tmp = new URL[count];
  363. System.arraycopy(urls, 0, tmp, 0, count);
  364. urls = tmp;
  365. }
  366. return urls;
  367. }
  368. /**
  369. * Checks that two multi-line strings have the same value. Each line is trimmed before comparison.
  370. * Produces an error on the particular line of conflict.
  371. */
  372. public static void assertMultiLineStringEquals(String message, String s1, String s2) {
  373. try {
  374. BufferedReader r1 = new BufferedReader(new StringReader(s1));
  375. BufferedReader r2 = new BufferedReader(new StringReader(s2));
  376. List<String> lines = new ArrayList<>();
  377. String l1, l2;
  378. int index = 1;
  379. while (true) {
  380. l1 = readNonBlankLine(r1);
  381. l2 = readNonBlankLine(r2);
  382. if (l1 == null || l2 == null)
  383. break;
  384. if (l1.equals(l2)) {
  385. lines.add(l1);
  386. } else {
  387. showContext(lines);
  388. Assert.assertEquals(message + "(line " + index + "):\n" + l1 + "\n" + l2, l1, l2);
  389. }
  390. index++;
  391. }
  392. if (l1 != null)
  393. showContext(lines);
  394. Assert.assertTrue(message + ": unexpected " + l1, l1 == null);
  395. if (l2 != null)
  396. showContext(lines);
  397. Assert.assertTrue(message + ": unexpected " + l2, l2 == null);
  398. } catch (IOException ioe) {
  399. Assert.assertTrue(message + ": caught " + ioe.getMessage(), false);
  400. }
  401. }
  402. private static void showContext(List lines) {
  403. int n = lines.size();
  404. for (int i = Math.max(0, n - 8); i < n; i++) {
  405. System.err.println(lines.get(i));
  406. }
  407. }
  408. private static String readNonBlankLine(BufferedReader r) throws IOException {
  409. String l = r.readLine();
  410. if (l == null)
  411. return null;
  412. l = l.trim();
  413. // comment to include comments when reading
  414. int commentLoc = l.indexOf("//");
  415. if (-1 != commentLoc) {
  416. l = l.substring(0, commentLoc).trim();
  417. }
  418. if ("".equals(l))
  419. return readNonBlankLine(r);
  420. return l;
  421. }
  422. /**
  423. * If there is an expected dir, expect each file in its subtree to match a corresponding actual file in the base directory. This
  424. * does NOT check that all actual files have corresponding expected files. This ignores directory paths containing "CVS".
  425. *
  426. * @param handler the IMessageHandler sink for error messages
  427. * @param expectedBaseDir the File path to the directory containing expected files, all of which are compared with any
  428. * corresponding actual files
  429. * @param actualBaseDir the File path to the base directory from which to find any actual files corresponding to expected files.
  430. * @return true if all files in the expectedBaseDir directory tree have matching files in the actualBaseDir directory tree.
  431. */
  432. public static boolean sameDirectoryContents(final IMessageHandler handler, final File expectedBaseDir,
  433. final File actualBaseDir, final boolean fastFail) {
  434. LangUtil.throwIaxIfNull(handler, "handler");
  435. if (!FileUtil.canReadDir(expectedBaseDir)) {
  436. MessageUtil.fail(handler, " expected dir not found: " + expectedBaseDir);
  437. return false;
  438. }
  439. if (!FileUtil.canReadDir(actualBaseDir)) {
  440. MessageUtil.fail(handler, " actual dir not found: " + actualBaseDir);
  441. return false;
  442. }
  443. String[] paths = FileUtil.listFiles(expectedBaseDir);
  444. boolean result = true;
  445. for (String path : paths) {
  446. if (path.contains("CVS")) {
  447. continue;
  448. }
  449. if (!sameFiles(handler, expectedBaseDir, actualBaseDir, path) && result) {
  450. result = false;
  451. if (fastFail) {
  452. break;
  453. }
  454. }
  455. }
  456. return result;
  457. }
  458. // ------------ File-comparison utilities (XXX need their own class...)
  459. /**
  460. * Test interface to compare two files, line by line, and report differences as one FAIL message if a handler is supplied. This
  461. * preprocesses .class files by disassembling.
  462. *
  463. * @param handler the IMessageHandler for any FAIL messages (null to ignore)
  464. * @param expectedFile the File path to the canonical file
  465. * @param actualFile the File path to the actual file, if any
  466. * @return true if the input files are the same, based on per-line comparisons
  467. */
  468. public static boolean sameFiles(IMessageHandler handler, File expectedFile, File actualFile) {
  469. return doSameFile(handler, null, null, expectedFile, actualFile);
  470. }
  471. /**
  472. * Test interface to compare two files, line by line, and report differences as one FAIL message if a handler is supplied. This
  473. * preprocesses .class files by disassembling. This method assumes that the files are at the same offset from two respective
  474. * base directories.
  475. *
  476. * @param handler the IMessageHandler for any FAIL messages (null to ignore)
  477. * @param expectedBaseDir the File path to the canonical file base directory
  478. * @param actualBaseDir the File path to the actual file base directory
  479. * @param path the String path offset from the base directories
  480. * @return true if the input files are the same, based on per-line comparisons
  481. */
  482. public static boolean sameFiles(IMessageHandler handler, File expectedBaseDir, File actualBaseDir, String path) {
  483. File actualFile = new File(actualBaseDir, path);
  484. File expectedFile = new File(expectedBaseDir, path);
  485. return doSameFile(handler, expectedBaseDir, actualBaseDir, expectedFile, actualFile);
  486. }
  487. /**
  488. * This does the work, selecting a lineator subclass and converting public API's to JDiff APIs for comparison. Currently, all
  489. * jdiff interfaces are method-local, so this class will load without it; if we do use it, we can avoid the duplication.
  490. */
  491. private static boolean doSameFile(IMessageHandler handler, File expectedBaseDir, File actualBaseDir, File expectedFile,
  492. File actualFile) {
  493. String path = expectedFile.getPath();
  494. // XXX permit user to specify lineator
  495. ILineator lineator = Lineator.TEXT;
  496. if (path.endsWith(".class")) {
  497. if (ClassLineator.haveDisassembler()) {
  498. lineator = Lineator.CLASS;
  499. } else {
  500. MessageUtil.abort(handler, "skipping - dissassembler not available");
  501. return false;
  502. }
  503. }
  504. CanonicalLine[] actualLines = null;
  505. CanonicalLine[] expectedLines = null;
  506. try {
  507. actualLines = lineator.getLines(handler, actualFile, actualBaseDir);
  508. expectedLines = lineator.getLines(handler, expectedFile, expectedBaseDir);
  509. } catch (IOException e) {
  510. MessageUtil.fail(handler, "rendering lines ", e);
  511. return false;
  512. }
  513. if (!LangUtil.isEmpty(actualLines) && !LangUtil.isEmpty(expectedLines)) {
  514. // here's the transmutation back to jdiff - extract if publishing
  515. // JDiff
  516. CanonicalLine[][] clines = new CanonicalLine[][] { expectedLines, actualLines };
  517. FileLine[][] flines = new FileLine[2][];
  518. for (int i = 0; i < clines.length; i++) {
  519. CanonicalLine[] cline = clines[i];
  520. FileLine[] fline = new FileLine[cline.length];
  521. for (int j = 0; j < fline.length; j++) {
  522. fline[j] = new FileLine(cline[j].canonical, cline[j].line);
  523. }
  524. flines[i] = fline;
  525. }
  526. Diff.change edits = new Diff(flines[0], flines[1]).diff_2(false);
  527. if ((null == edits) || (0 == (edits.inserted + edits.deleted))) {
  528. // XXX confirm with jdiff that null means no edits
  529. return true;
  530. } else {
  531. // String m = render(handler, edits, flines[0], flines[1]);
  532. StringWriter writer = new StringWriter();
  533. DiffNormalOutput out = new DiffNormalOutput(flines[0], flines[1]);
  534. out.setOut(writer);
  535. out.setLineSeparator(LangUtil.EOL);
  536. try {
  537. out.writeScript(edits);
  538. } catch (IOException e) {
  539. MessageUtil.fail(handler, "rendering edits", e);
  540. } finally {
  541. if (null != writer) {
  542. try {
  543. writer.close();
  544. } catch (IOException e) {
  545. MessageUtil.fail(handler, "closing after rendering edits", e);
  546. }
  547. }
  548. }
  549. String message = "diff between " + path + " in expected dir " + expectedBaseDir + " and actual dir "
  550. + actualBaseDir + LangUtil.EOL + writer.toString();
  551. MessageUtil.fail(handler, message);
  552. }
  553. }
  554. return false;
  555. }
  556. public static String cleanTestName(String name) {
  557. name = name.replace(' ', '_');
  558. return name;
  559. }
  560. public static Test skipTest(String tests) {
  561. // could printStackTrace to give more context if needed...
  562. System.err.println("skipping tests " + tests);
  563. return testNamed("skipping tests " + tests);
  564. }
  565. public static Test testNamed(String named) {
  566. final String name = cleanTestName(named);
  567. return new Test() {
  568. public int countTestCases() {
  569. return 1;
  570. }
  571. public void run(TestResult r) {
  572. r.startTest(this);
  573. r.endTest(this);
  574. }
  575. public String toString() {
  576. return name;
  577. }
  578. };
  579. }
  580. /**
  581. * @param sink the TestSuite sink to add result to
  582. * @param sourceName the String fully-qualified name of the class with a suite() method to load
  583. */
  584. public static void loadTestsReflectively(TestSuite sink, String sourceName, boolean ignoreError) {
  585. Throwable thrown = null;
  586. try {
  587. ClassLoader loader = sink.getClass().getClassLoader();
  588. Class sourceClass = loader.loadClass(sourceName);
  589. if (!Modifier.isPublic(sourceClass.getModifiers())) {
  590. errorSuite(sink, sourceName, "not public class");
  591. return;
  592. }
  593. Method suiteMethod = sourceClass.getMethod("suite", new Class[0]);
  594. int mods = suiteMethod.getModifiers();
  595. if (!Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
  596. errorSuite(sink, sourceName, "not static method");
  597. return;
  598. }
  599. if (!Modifier.isPublic(mods)) {
  600. errorSuite(sink, sourceName, "not public method");
  601. return;
  602. }
  603. if (!Test.class.isAssignableFrom(suiteMethod.getReturnType())) {
  604. errorSuite(sink, sourceName, "suite() does not return Test");
  605. return;
  606. }
  607. Object result = suiteMethod.invoke(null, new Object[0]);
  608. Test test = (Test) result;
  609. if (!(test instanceof TestSuite)) {
  610. sink.addTest(test);
  611. } else {
  612. TestSuite source = (TestSuite) test;
  613. Enumeration tests = source.tests();
  614. while (tests.hasMoreElements()) {
  615. sink.addTest((Test) tests.nextElement());
  616. }
  617. }
  618. } catch (ClassNotFoundException e) {
  619. thrown = e;
  620. } catch (SecurityException e) {
  621. thrown = e;
  622. } catch (NoSuchMethodException e) {
  623. thrown = e;
  624. } catch (IllegalArgumentException e) {
  625. thrown = e;
  626. } catch (IllegalAccessException e) {
  627. thrown = e;
  628. } catch (InvocationTargetException e) {
  629. thrown = e;
  630. }
  631. if (null != thrown) {
  632. if (ignoreError) {
  633. System.err.println("Error loading " + sourceName);
  634. thrown.printStackTrace(System.err);
  635. } else {
  636. errorSuite(sink, sourceName, thrown);
  637. }
  638. }
  639. }
  640. private static void errorSuite(TestSuite sink, String sourceName, Throwable thrown) {
  641. sink.addTest(new ErrorTest(sourceName, thrown));
  642. }
  643. private static void errorSuite(TestSuite sink, String sourceName, String err) {
  644. String message = "bad " + sourceName + ": " + err;
  645. sink.addTest(new ErrorTest(message));
  646. }
  647. /**
  648. * Junit test failure, e.g., to report suite initialization errors at test time.
  649. */
  650. public static class ErrorTest implements Test {
  651. private final Throwable thrown;
  652. public ErrorTest(Throwable thrown) {
  653. this.thrown = thrown;
  654. }
  655. public ErrorTest(String message) {
  656. this.thrown = new Error(message);
  657. }
  658. public ErrorTest(String message, Throwable thrown) {
  659. this(new TestError(message, thrown));
  660. }
  661. public int countTestCases() {
  662. return 1;
  663. }
  664. public void run(TestResult result) {
  665. result.startTest(this);
  666. result.addError(this, thrown);
  667. }
  668. }
  669. /**
  670. * Nested exception - remove when using 1.4 or later.
  671. */
  672. public static class TestError extends Error {
  673. private Throwable thrown;
  674. public TestError(String message) {
  675. super(message);
  676. }
  677. public TestError(String message, Throwable thrown) {
  678. super(message);
  679. this.thrown = thrown;
  680. }
  681. public Throwable getCause() {
  682. return thrown;
  683. }
  684. public void printStackTrace() {
  685. printStackTrace(System.err);
  686. }
  687. public void printStackTrace(PrintStream ps) {
  688. printStackTrace(new PrintWriter(ps));
  689. }
  690. public void printStackTrace(PrintWriter pw) {
  691. super.printStackTrace(pw);
  692. if (null != thrown) {
  693. pw.print("Caused by: ");
  694. thrown.printStackTrace(pw);
  695. }
  696. }
  697. }
  698. /** component that reduces file to CanonicalLine[] */
  699. public interface ILineator {
  700. /** Lineator suitable for text files */
  701. ILineator TEXT = new TextLineator();
  702. /** Lineator suitable for class files (disassembles first) */
  703. ILineator CLASS = new ClassLineator();
  704. /**
  705. * Reduce file to CanonicalLine[].
  706. *
  707. * @param handler the IMessageHandler for errors (may be null)
  708. * @param file the File to render
  709. * @param basedir the File for the base directory (may be null)
  710. * @return CanonicalLine[] of lines - not null, but perhaps empty
  711. */
  712. CanonicalLine[] getLines(IMessageHandler handler, File file, File basedir) throws IOException;
  713. }
  714. /** alias for jdiff FileLine to avoid client binding */
  715. public static class CanonicalLine {
  716. public static final CanonicalLine[] NO_LINES = new CanonicalLine[0];
  717. /** canonical variant of line for comparison */
  718. public final String canonical;
  719. /** actual line, for logging */
  720. public final String line;
  721. public CanonicalLine(String canonical, String line) {
  722. this.canonical = canonical;
  723. this.line = line;
  724. }
  725. public String toString() {
  726. return line;
  727. }
  728. }
  729. private abstract static class Lineator implements ILineator {
  730. /**
  731. * Reduce file to CanonicalLine[].
  732. *
  733. * @param handler the IMessageHandler for errors (may be null)
  734. * @param file the File to render
  735. * @param basedir the File for the base directory (may be null)
  736. */
  737. public CanonicalLine[] getLines(IMessageHandler handler, File file, File basedir) throws IOException {
  738. if (!file.canRead() || !file.isFile()) {
  739. MessageUtil.error(handler, "not readable file: " + basedir + " - " + file);
  740. return null;
  741. }
  742. // capture file as FileLine[]
  743. InputStream in = null;
  744. /* String path = */FileUtil.normalizedPath(file, basedir);
  745. LineStream capture = new LineStream();
  746. try {
  747. lineate(capture, handler, basedir, file);
  748. } catch (IOException e) {
  749. MessageUtil.fail(handler, "NormalizedCompareFiles IOException reading " + file, e);
  750. return null;
  751. } finally {
  752. if (null != in) {
  753. try {
  754. in.close();
  755. } catch (IOException e) {
  756. } // ignore
  757. }
  758. capture.flush();
  759. capture.close();
  760. }
  761. String missed = capture.getMissed();
  762. if (!LangUtil.isEmpty(missed)) {
  763. MessageUtil.warn(handler, "NormalizedCompareFiles missed input: " + missed);
  764. return null;
  765. } else {
  766. String[] lines = capture.getLines();
  767. CanonicalLine[] result = new CanonicalLine[lines.length];
  768. for (int i = 0; i < lines.length; i++) {
  769. result[i] = new CanonicalLine(lines[i], lines[i]);
  770. }
  771. return result;
  772. }
  773. }
  774. protected abstract void lineate(PrintStream sink, IMessageHandler handler, File basedir, File file) throws IOException;
  775. }
  776. private static class TextLineator extends Lineator {
  777. protected void lineate(PrintStream sink, IMessageHandler handler, File basedir, File file) throws IOException {
  778. InputStream in = null;
  779. try {
  780. in = new FileInputStream(file);
  781. FileUtil.copyStream(new DataInputStream(in), sink);
  782. } finally {
  783. try {
  784. in.close();
  785. } catch (IOException e) {
  786. } // ignore
  787. }
  788. }
  789. }
  790. public static class ClassLineator extends Lineator {
  791. protected void lineate(PrintStream sink, IMessageHandler handler, File basedir, File file) throws IOException {
  792. String name = FileUtil.fileToClassName(basedir, file);
  793. // XXX re-enable preflight?
  794. // if ((null != basedir) && (path.length()-6 != name.length())) {
  795. // MessageUtil.error(handler, "unexpected class name \""
  796. // + name + "\" for path " + path);
  797. // return null;
  798. // }
  799. disassemble(handler, basedir, name, sink);
  800. }
  801. public static boolean haveDisassembler() {
  802. try {
  803. return (null != Class.forName("org.aspectj.weaver.bcel.LazyClassGen"));
  804. } catch (ClassNotFoundException e) {
  805. // XXX fix
  806. // System.err.println(e.getMessage());
  807. // e.printStackTrace(System.err);
  808. return false;
  809. }
  810. }
  811. /** XXX dependency on bcweaver/bcel */
  812. private static void disassemble(IMessageHandler handler, File basedir, String name, PrintStream out) throws IOException {
  813. // LazyClassGen.disassemble(FileUtil.normalizedPath(basedir), name,
  814. // capture);
  815. Throwable thrown = null;
  816. String basedirPath = FileUtil.normalizedPath(basedir);
  817. // XXX use reflection utilities to invoke dissassembler?
  818. try {
  819. // XXX need test to detect when this is refactored
  820. Class c = Class.forName("org.aspectj.weaver.bcel.LazyClassGen");
  821. Method m = c.getMethod("disassemble", new Class[] { String.class, String.class, PrintStream.class });
  822. m.invoke(null, new Object[] { basedirPath, name, out });
  823. } catch (ClassNotFoundException e) {
  824. thrown = e;
  825. } catch (NoSuchMethodException e) {
  826. thrown = e;
  827. } catch (IllegalAccessException e) {
  828. thrown = e;
  829. } catch (InvocationTargetException e) {
  830. Throwable t = e.getTargetException();
  831. if (t instanceof IOException) {
  832. throw (IOException) t;
  833. }
  834. thrown = t;
  835. }
  836. if (null != thrown) {
  837. MessageUtil.fail(handler, "disassembling " + name + " path: " + basedirPath, thrown);
  838. }
  839. }
  840. }
  841. public static File createEmptySandbox() {
  842. File sandbox;
  843. String os = System.getProperty("os.name");
  844. File tempDir = null;
  845. // AMC - I did this rather than use the JDK default as I hate having to go look
  846. // in c:\documents and settings\......... for the results of a failed test.
  847. if (os.startsWith("Windows")) {
  848. tempDir = new File("N:\\temp");
  849. if (!tempDir.exists()) {
  850. tempDir = new File("C:\\temp");
  851. if (!tempDir.exists()) {
  852. tempDir.mkdir();
  853. }
  854. }
  855. } else {
  856. tempDir = new File("/tmp");
  857. }
  858. File sandboxRoot = new File(tempDir, SANDBOX_NAME);
  859. if (!sandboxRoot.exists()) {
  860. sandboxRoot.mkdir();
  861. }
  862. try {
  863. File workspace = new File(".." + File.separator);
  864. String workspaceName = workspace.getCanonicalPath();
  865. int index = workspaceName.lastIndexOf(File.separator);
  866. workspaceName = workspaceName.substring(index + 1);
  867. File workspaceRoot = new File(sandboxRoot, workspaceName);
  868. if (!workspaceRoot.exists()) {
  869. workspaceRoot.mkdir();
  870. }
  871. FileUtil.deleteContents(workspaceRoot);
  872. sandbox = File.createTempFile("ajcTest", ".tmp", workspaceRoot);
  873. sandbox.delete();
  874. sandbox.mkdir();
  875. } catch (IOException ioEx) {
  876. throw new AssertionFailedError("Unable to create sandbox directory for test");
  877. }
  878. return sandbox;
  879. }
  880. /**
  881. * Capture PrintStream output to String[] (delimiting component String on println()), also showing any missed text.
  882. */
  883. public static class LineStream extends PrintStream {
  884. StringBuffer sb = new StringBuffer();
  885. ByteArrayOutputStream missed;
  886. ArrayList<String> sink;
  887. public LineStream() {
  888. super(new ByteArrayOutputStream());
  889. this.sink = new ArrayList<>();
  890. missed = (ByteArrayOutputStream) out;
  891. }
  892. /** @return any text not captured by our overrides */
  893. public String getMissed() {
  894. return missed.toString();
  895. }
  896. /** clear captured lines (but not missed text) */
  897. public void clear() {
  898. sink.clear();
  899. }
  900. /**
  901. * Get String[] of lines printed, delimited by println(..) calls.
  902. *
  903. * @return lines printed, exclusive of any not yet terminated by newline
  904. */
  905. public String[] getLines() {
  906. return sink.toArray(new String[0]);
  907. }
  908. // ---------- PrintStream overrides
  909. public void println(Object x) {
  910. println(x.toString());
  911. }
  912. public void print(Object obj) {
  913. print(obj.toString());
  914. }
  915. public void println(char c) {
  916. sb.append(c);
  917. println();
  918. }
  919. public void println(char[] c) {
  920. sb.append(c);
  921. println();
  922. }
  923. public void print(char c) {
  924. sb.append(c);
  925. }
  926. public void print(char[] c) {
  927. sb.append(c);
  928. }
  929. public void println(String s) {
  930. print(s);
  931. println();
  932. }
  933. public void print(String s) {
  934. sb.append(s);
  935. }
  936. public void println() {
  937. String line = sb.toString();
  938. sink.add(line);
  939. sb.setLength(0);
  940. }
  941. }
  942. }