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 30KB

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