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

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