Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

TestUtil.java 30KB

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