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.

AjcTaskTest.java 34KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  1. /* *******************************************************************
  2. * Copyright (c) 1999-2001 Xerox Corporation,
  3. * 2002 Palo Alto Research Center, Incorporated (PARC)
  4. * 2003 Contributors.
  5. * 2005 Contributors
  6. * All rights reserved.
  7. * This program and the accompanying materials are made available
  8. * under the terms of the Eclipse Public License v1.0
  9. * which accompanies this distribution and is available at
  10. * http://www.eclipse.org/legal/epl-v10.html
  11. *
  12. * Contributors:
  13. * Xerox/PARC initial implementation
  14. * IBM ongoing maintenance
  15. * ******************************************************************/
  16. package org.aspectj.tools.ant.taskdefs;
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.FileFilter;
  20. import java.io.FileReader;
  21. import java.io.IOException;
  22. import java.io.PrintStream;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.jar.JarEntry;
  26. import java.util.jar.JarFile;
  27. import junit.framework.TestCase;
  28. import org.apache.tools.ant.BuildEvent;
  29. import org.apache.tools.ant.BuildException;
  30. import org.apache.tools.ant.BuildListener;
  31. import org.apache.tools.ant.Location;
  32. import org.apache.tools.ant.Project;
  33. import org.apache.tools.ant.types.Path;
  34. import org.apache.tools.ant.types.selectors.FilenameSelector;
  35. import org.aspectj.bridge.IMessage;
  36. import org.aspectj.bridge.IMessageHolder;
  37. import org.aspectj.bridge.MessageHandler;
  38. import org.aspectj.bridge.MessageUtil;
  39. import org.aspectj.util.FileUtil;
  40. import org.aspectj.util.LangUtil;
  41. /**
  42. * AjcTask test cases.
  43. * Please put new ones with others between ------- comments.
  44. *
  45. * Some API tests, but mostly functional tests driving
  46. * the task execute using data in ../taskdefs/testdata.
  47. * This will re-run in forked mode for any nonfailing
  48. * compile if aspectjtools-dist is built into
  49. * ../aj-build/dist/tools/lib/aspectjtools.jar.
  50. */
  51. public class AjcTaskTest extends TestCase {
  52. private static final Class NO_EXCEPTION = null;
  53. private static final String NOFILE = "NOFILE";
  54. private static final File tempDir;
  55. private static final String aspectjtoolsJar;
  56. private static final String testdataDir;
  57. private static final StringBuffer MESSAGES = new StringBuffer();
  58. /** accept writable .class files */
  59. private static FileFilter PICK_CLASS_FILES;
  60. static {
  61. tempDir = new File("IncrementalAjcTaskTest-temp");
  62. String toolsPath = "../aj-build/dist/tools/lib/aspectjtools.jar";
  63. File toolsjar = new File(toolsPath);
  64. if (toolsjar.canRead()) {
  65. aspectjtoolsJar = toolsjar.getAbsolutePath();
  66. } else {
  67. aspectjtoolsJar = null;
  68. String s =
  69. "AjcTaskTest not forking - build aspectjtools-dist to get "
  70. + toolsPath;
  71. System.out.println(s);
  72. }
  73. File dir = new File("../taskdefs/testdata");
  74. if (dir.canRead() && dir.isDirectory()) {
  75. testdataDir = dir.getAbsolutePath();
  76. } else {
  77. testdataDir = null;
  78. }
  79. PICK_CLASS_FILES = new FileFilter() {
  80. public boolean accept(File file) {
  81. return (
  82. (null != file)
  83. && file.isFile()
  84. && file.canWrite()
  85. && file.getPath().endsWith(".class"));
  86. }
  87. };
  88. }
  89. /**
  90. * Check that aspectjtools are found on the classpath,
  91. * reporting any errors to System.err.
  92. *
  93. * Run multiple times with different classpaths.
  94. * This should find variants
  95. * aspectjtools.jar,
  96. * aspectj-tools.jar,
  97. * aspectj-tools-1.1.jar, and
  98. * aspectjtools-1.0.6.jar
  99. * but not
  100. * aspectjrt.jar or
  101. * aspectj/tools.jar.
  102. * XXX use testing aspect to stub out
  103. * <code>System.getProperty("java.class.path")</code>
  104. * @param args a String[], first is expected path, if any
  105. */
  106. public static void main(String[] args) {
  107. java.io.File toolsjar = AjcTask.findAspectjtoolsJar();
  108. if ((null == args) || (0 == args.length)) {
  109. if (null != toolsjar) {
  110. System.err.println("FAIL - not expected: " + toolsjar);
  111. }
  112. } else if ("-help".equals(args[0])) {
  113. System.out.println(
  114. "java "
  115. + AjcTaskTest.class.getName()
  116. + " <expectedPathToAspectjtoolsJar>");
  117. } else if (null == toolsjar) {
  118. System.err.println("FAIL - expected: " + args[0]);
  119. } else {
  120. String path = toolsjar.getAbsolutePath();
  121. if (!path.equals(args[0])) {
  122. System.err.println(
  123. "FAIL - expected: " + args[0] + " actual: " + path);
  124. }
  125. }
  126. }
  127. public static void collectMessage(String s) {
  128. MESSAGES.append(s);
  129. }
  130. private static void deleteTempDir() {
  131. if ((null != tempDir) && tempDir.exists()) {
  132. FileUtil.deleteContents(tempDir);
  133. tempDir.delete();
  134. // when tempDir not used...
  135. if (null != testdataDir) {
  136. File dataDir = new File(testdataDir);
  137. if (dataDir.canRead()) {
  138. FileUtil.deleteContents(dataDir, PICK_CLASS_FILES, false);
  139. }
  140. }
  141. }
  142. }
  143. private static final File getTempDir() {
  144. return tempDir;
  145. }
  146. public AjcTaskTest(String name) {
  147. super(name);
  148. }
  149. public void tearDown() {
  150. deleteTempDir();
  151. MESSAGES.setLength(0);
  152. }
  153. private void checkRun(AjcTask task, String exceptionString) {
  154. try {
  155. task.execute();
  156. assertTrue(null == exceptionString);
  157. } catch (BuildException e) {
  158. if (null == exceptionString) {
  159. assertTrue("unexpected " + e.getMessage(), false);
  160. } else {
  161. String m = e.getMessage();
  162. if (null == m) {
  163. assertTrue("not " + exceptionString, false);
  164. } else if (-1 == m.indexOf(exceptionString)) {
  165. assertEquals(exceptionString, e.getMessage());
  166. }
  167. }
  168. }
  169. }
  170. private void checkContains(String[] cmd, String option, boolean contains) {
  171. for (int i = 0; i < cmd.length; i++) {
  172. if (option.equals(cmd[i])) {
  173. if (contains) {
  174. return;
  175. } else {
  176. assertTrue(
  177. "not expecting " + option + " in " + Arrays.asList(cmd),
  178. false);
  179. }
  180. }
  181. }
  182. if (contains) {
  183. assertTrue(
  184. "expecting " + option + " in " + Arrays.asList(cmd),
  185. false);
  186. }
  187. }
  188. protected AjcTask getTask(String input) {
  189. return getTask(input, getTempDir());
  190. }
  191. protected AjcTask getTask(String input, File destDir) {
  192. AjcTask task = new AjcTask();
  193. Project p = new Project();
  194. task.setProject(p);
  195. if (null != destDir) {
  196. task.setDestdir(destDir);
  197. }
  198. if (NOFILE.equals(input)) {
  199. // add nothing
  200. } else if (input.endsWith(".lst")) {
  201. if (-1 != input.indexOf(",")) {
  202. throw new IllegalArgumentException(
  203. "lists not supported: " + input);
  204. } else if (null == testdataDir) {
  205. throw new Error("testdata not found - run in ../taskdefs");
  206. } else {
  207. String path = testdataDir + File.separator + input;
  208. task.setArgfiles(new Path(task.getProject(), path));
  209. }
  210. } else if ((input.endsWith(".java") || input.endsWith(".aj"))) {
  211. FilenameSelector fns = new FilenameSelector();
  212. fns.setName(input);
  213. task.addFilename(fns);
  214. } else {
  215. String path = testdataDir + File.separator + input;
  216. task.setSourceRoots(new Path(task.getProject(), path));
  217. }
  218. task.setClasspath(new Path(p, "../lib/test/aspectjrt.jar"));
  219. return task;
  220. }
  221. /** used in testMessageHolderClassName */
  222. public static class InfoHolder extends MessageHandler {
  223. public InfoHolder() {
  224. }
  225. public boolean handleMessage(IMessage message) {
  226. if (0 == IMessage.INFO.compareTo(message.getKind())) {
  227. AjcTaskTest.collectMessage(message.getMessage());
  228. }
  229. return true;
  230. }
  231. }
  232. /** used in testMessageHolderClassName */
  233. public static class Holder extends MessageHandler {
  234. public Holder() {
  235. }
  236. public boolean handleMessage(IMessage message) {
  237. IMessage.Kind kind = message.getKind();
  238. if (IMessage.ERROR.isSameOrLessThan(kind)) {
  239. String m = kind.toString();
  240. AjcTaskTest.collectMessage(m.substring(0, 1));
  241. }
  242. return true;
  243. }
  244. }
  245. // ------------------------------------------------------
  246. // ------------------------------------------------------
  247. // ------------------------------------------------------
  248. // ------------------------------------------------------
  249. // ------------------------------------------------------
  250. // ------------------------------------------------------
  251. // Start of test cases
  252. public void testNullDestDir() {
  253. AjcTask task = getTask(NOFILE, null);
  254. String[] cmd = task.makeCommand();
  255. for (int i = 0; i < cmd.length; i++) {
  256. assertTrue(!"-d".equals(cmd[i]));
  257. }
  258. }
  259. public void testOutputRequirement() {
  260. AjcTask task = getTask("default.lst");
  261. checkRun(task, null);
  262. // copyInJars now just emits warning b/c unused
  263. task = getTask("default.lst", null);
  264. task.setCopyInjars(true);
  265. checkRun(task, null);
  266. // sourceRootCopyFilter requires destDir
  267. task = getTask("default.lst", null);
  268. task.setSourceRootCopyFilter("**/*.java");
  269. checkRun(task, "sourceRoot");
  270. }
  271. public void testSourceRootCopyFilter() {
  272. // sourceRootCopyFilter works..
  273. File destDir = getTempDir();
  274. assertTrue(
  275. "unable to create " + destDir,
  276. destDir.canRead() || destDir.mkdirs());
  277. AjcTask task = getTask("sourceroot", destDir);
  278. task.setSourceRootCopyFilter("doNotCopy,**/*.txt");
  279. File file = new File(destDir, "Default.java").getAbsoluteFile();
  280. assertTrue(file + ".canRead() prematurely", !file.canRead());
  281. checkRun(task, null);
  282. // got expected resources
  283. assertTrue(file + ".canRead() failed", file.canRead());
  284. File pack = new File(destDir, "pack");
  285. file = new File(pack, "Pack.java").getAbsoluteFile();
  286. assertTrue(file + ".canRead() failed", file.canRead());
  287. file = new File(pack, "includeme").getAbsoluteFile();
  288. assertTrue(file + ".canRead() failed", file.canRead());
  289. // didn't get unexpected resources
  290. file = new File(pack, "something.txt");
  291. assertTrue(file + ".canRead() passed", !file.canRead());
  292. file = new File(destDir, "doNotCopy");
  293. assertTrue(file + ".canRead() passed", !file.canRead());
  294. file = new File(destDir, "skipTxtFiles.txt");
  295. assertTrue(file + ".canRead() passed", !file.canRead());
  296. }
  297. public void testInpathDirCopyFilter() {
  298. // inpathDirCopyFilter works with output directory
  299. File destDir = getTempDir();
  300. assertTrue(
  301. "unable to create " + destDir,
  302. destDir.canRead() || destDir.mkdirs());
  303. AjcTask task = getTask(NOFILE, destDir);
  304. Project p = task.getProject();
  305. Path indirs = new Path(p);
  306. File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile();
  307. indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath()));
  308. indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath()));
  309. task.setInpath(indirs);
  310. task.setInpathDirCopyFilter("doNotCopy,**/*.txt");
  311. File file = new File(destDir, "Default.java").getAbsoluteFile();
  312. assertTrue(file + ".canRead() prematurely", !file.canRead());
  313. checkRun(task, null);
  314. // got expected resources
  315. File pack = new File(destDir, "pack");
  316. file = new File(pack, "includeme").getAbsoluteFile();
  317. assertTrue(file + ".canRead() failed", file.canRead());
  318. file = new File(pack, "Pack.class").getAbsoluteFile();
  319. assertTrue(file + ".canRead() failed", file.canRead());
  320. file = new File(destDir, "copyMe.htm").getAbsoluteFile();
  321. assertTrue(file + ".canRead() failed", file.canRead());
  322. file = new File(destDir, "Default.class").getAbsoluteFile();
  323. assertTrue(file + ".canRead() failed", file.canRead());
  324. // didn't get unexpected resources
  325. file = new File(pack, "something.txt");
  326. assertTrue(file + ".canRead() passed", !file.canRead());
  327. file = new File(destDir, "doNotCopy");
  328. assertTrue(file + ".canRead() passed", !file.canRead());
  329. file = new File(destDir, "skipTxtFiles.txt");
  330. assertTrue(file + ".canRead() passed", !file.canRead());
  331. }
  332. public void testInpathDirCopyFilterWithJar() throws IOException {
  333. checkInpathCopy("testInpathDirCopyFilterWithJar-out.jar");
  334. }
  335. // test resource copying for oddball jar files that don't end in .jar
  336. public void testInpathDirCopyFilterWithOddjar() throws IOException {
  337. checkInpathCopy("testInpathDirCopyFilterWithJar-outJarFile");
  338. }
  339. private void checkInpathCopy(String outjarFileStr) throws IOException {
  340. // inpathDirCopyFilter works with output jar
  341. File destDir = getTempDir();
  342. assertTrue(
  343. "unable to create " + destDir,
  344. destDir.canRead() || destDir.mkdirs());
  345. AjcTask task = getTask(NOFILE, null);
  346. File destJar = new File(destDir, outjarFileStr);
  347. task.setOutjar(destJar);
  348. Project p = task.getProject();
  349. Path indirs = new Path(p);
  350. File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile();
  351. indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath()));
  352. indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath()));
  353. task.setInpath(indirs);
  354. task.setInpathDirCopyFilter("doNotCopy,**/*.txt,**/*.class");
  355. checkRun(task, null);
  356. JarFile jarFile = new JarFile(destJar);
  357. String[] expected = {"copyMe.htm", "pack/includeme",
  358. "pack/Pack.class", "Default.class"};
  359. String[] unexpected = {"doNotCopy", "skipTxtFiles.txt", "pack/something.txt"};
  360. for (int i = 0; i < expected.length; i++) {
  361. JarEntry entry = jarFile.getJarEntry(expected[i]);
  362. assertTrue(expected[i] + " not found", null != entry);
  363. }
  364. for (int i = 0; i < unexpected.length; i++) {
  365. JarEntry entry = jarFile.getJarEntry(unexpected[i]);
  366. assertTrue(unexpected[i] + " found", null == entry);
  367. }
  368. }
  369. public void testInpathDirCopyFilterError() {
  370. // inpathDirCopyFilter fails with no output directory or jar iff specified
  371. AjcTask task = getTask(NOFILE, null);
  372. Project p = task.getProject();
  373. Path indirs = new Path(p);
  374. File dir = new File(testdataDir, "inpathDirs").getAbsoluteFile();
  375. indirs.addExisting(new Path(p, new File(dir, "inpathDirOne").getAbsolutePath()));
  376. indirs.addExisting(new Path(p, new File(dir, "inpathDirTwo").getAbsolutePath()));
  377. task.setInpath(indirs);
  378. task.setInpathDirCopyFilter("doNotCopy,**/*.txt,**/*.class");
  379. // expecting error
  380. checkRun(task, "inpathDirCopyFilter");
  381. }
  382. // this test method submitted by patch from Andrew Huff (IBM)
  383. // verifies that the log attribute of AjcTask writes output to the given log file
  384. public void testLoggingMode() {
  385. AjcTask task = getTask("default.lst");
  386. task.setFailonerror(false);
  387. File logFile = new File("testLogFile1.txt");
  388. String s = logFile.getAbsolutePath();
  389. logFile.delete();
  390. long initialLength = logFile.length();
  391. task.setLog(logFile);
  392. runTest(task,null,MessageHolderChecker.INFOS);
  393. long newLength = logFile.length();
  394. assertTrue(newLength > initialLength);
  395. logFile.delete();
  396. }
  397. public void testCommandEditor() {
  398. String className = VerboseCommandEditor.class.getName();
  399. System.setProperty(AjcTask.COMMAND_EDITOR_NAME, className);
  400. assertEquals(
  401. className,
  402. System.getProperty(AjcTask.COMMAND_EDITOR_NAME));
  403. AjcTask task = getTask(NOFILE);
  404. task.setCommandEditor(new VerboseCommandEditor());
  405. String[] cmd = task.makeCommand();
  406. assertEquals(VerboseCommandEditor.VERBOSE, cmd[0]);
  407. task = getTask(NOFILE);
  408. task.setCommandEditorClass(VerboseCommandEditor.class.getName());
  409. cmd = task.makeCommand();
  410. assertEquals(VerboseCommandEditor.VERBOSE, cmd[0]);
  411. }
  412. // public void testStaticCommandEditor() {
  413. // // XXX need to test COMMAND_EDITOR, but can't require property when run
  414. // }
  415. public void testLimitTo() {
  416. int numArgs = 100;
  417. String arg = "123456789";
  418. String[] args = new String[numArgs];
  419. for (int i = 0; i < args.length; i++) {
  420. args[i] = arg;
  421. }
  422. // no limit
  423. int max = numArgs * (arg.length() + 1);
  424. Location location = new Location("AjcTaskTest.java");
  425. String[] newArgs = AjcTask.GuardedCommand.limitTo(args, max, location);
  426. assertTrue("same", args == newArgs);
  427. // limited - read file and verify arguments
  428. max--;
  429. newArgs = AjcTask.GuardedCommand.limitTo(args, max, location);
  430. assertTrue("not same", args != newArgs);
  431. assertTrue("not null", null != newArgs);
  432. String label = "newArgs " + Arrays.asList(newArgs);
  433. assertTrue("size 2" + label, 2 == newArgs.length);
  434. assertEquals("-argfile", newArgs[0]);
  435. File file = new File(newArgs[1]);
  436. assertTrue("readable newArgs[1]" + label, file.canRead());
  437. FileReader fin = null;
  438. try {
  439. fin = new FileReader(file);
  440. BufferedReader reader = new BufferedReader(fin);
  441. String line;
  442. int i = 0;
  443. while (null != (line = reader.readLine())) {
  444. assertEquals(i + ": ", args[i++], line);
  445. }
  446. assertEquals("num entries", i, args.length);
  447. } catch (IOException e) {
  448. assertTrue("IOException " + e.getMessage(), false);
  449. } finally {
  450. if (null != fin) {
  451. try {
  452. fin.close();
  453. } catch (IOException e) {
  454. // ignore
  455. }
  456. }
  457. file.delete();
  458. }
  459. }
  460. public void testFindAspectjtoolsJar() {
  461. File toolsJar = AjcTask.findAspectjtoolsJar();
  462. if (null != toolsJar) {
  463. assertNull("tools jar found?: " + toolsJar, toolsJar);
  464. }
  465. // not found when unit testing b/c not on system classpath
  466. // so just checking for exceptions.
  467. // XXX need aspect to stub out System.getProperty(..)
  468. }
  469. public void testMessageHolderClassName() {
  470. AjcTask task = getTask("compileError.lst");
  471. task.setFailonerror(false);
  472. MESSAGES.setLength(0);
  473. runTest(
  474. task,
  475. null,
  476. MessageHolderChecker.ONE_ERROR,
  477. Holder.class.getName());
  478. String result = MESSAGES.toString();
  479. MESSAGES.setLength(0);
  480. assertEquals("messages", "e", result);
  481. }
  482. // TODO skipped test - works locally but not on build machine?
  483. public void skip_testMessageHolderClassWithDoneSignal() {
  484. AjcTask task = getTask("default.lst");
  485. task.setFailonerror(false);
  486. String DONE = "This is a unique message, not confused with others.";
  487. task.setXDoneSignal(DONE);
  488. MESSAGES.setLength(0);
  489. runTest(
  490. task,
  491. null,
  492. MessageHolderChecker.INFOS,
  493. InfoHolder.class.getName());
  494. final String result = MESSAGES.toString();
  495. String temp = new String(result);
  496. MESSAGES.setLength(0);
  497. if (!temp.endsWith(DONE)) {
  498. if (temp.length() > 20) {
  499. temp = "..." + temp.substring(temp.length()-20, temp.length());
  500. }
  501. assertTrue(DONE + " is not suffix of \"" + temp + "\"", false);
  502. }
  503. // exactly one such message
  504. temp = new String(result);
  505. temp = temp.substring(0, temp.length()-DONE.length());
  506. if (temp.endsWith(DONE)) {
  507. temp = new String(result);
  508. if (temp.length() > 20) {
  509. temp = "..." + temp.substring(temp.length()-20, temp.length());
  510. }
  511. assertTrue(DONE + " signalled twice: \"" + temp + "\"", false);
  512. }
  513. }
  514. public void testDefaultListForkedNoTools() {
  515. AjcTask task = getTask("default.lst");
  516. task.setFork(true);
  517. boolean passed = false;
  518. try {
  519. runTest(task, BuildException.class, MessageHolderChecker.NONE);
  520. passed = true;
  521. } finally {
  522. if (!passed) {
  523. String m =
  524. "AjcTaskTest.testDefaultListForkedNoTools()"
  525. + " fails if aspectjtools.jar is on the classpath";
  526. System.err.println(m);
  527. }
  528. }
  529. }
  530. public void testDefaultListForkedIncremental() {
  531. AjcTask task = getTask("default.lst");
  532. task.setFork(true);
  533. task.setIncremental(true);
  534. runTest(task, BuildException.class, MessageHolderChecker.NONE);
  535. }
  536. /** failonerror should default to true, unlike other booleans */
  537. public void testCompileErrorFailOnErrorDefault() {
  538. AjcTask task = getTask("compileError.lst");
  539. final PrintStream serr = System.err;
  540. try {
  541. System.setErr(new PrintStream(new java.io.ByteArrayOutputStream()));
  542. runTest(task, BuildException.class, MessageHolderChecker.ONE_ERROR);
  543. } finally {
  544. System.setErr(serr);
  545. }
  546. }
  547. public void testCompileErrorListDefaultHolder() {
  548. AjcTask task = getTask("compileError.lst");
  549. final PrintStream serr = System.err;
  550. try {
  551. System.setErr(new PrintStream(new java.io.ByteArrayOutputStream()));
  552. task.execute();
  553. fail("expected BuildException from failed compile by default");
  554. } catch (BuildException t) {
  555. // ok
  556. } finally {
  557. System.setErr(serr);
  558. deleteTempDir();
  559. }
  560. }
  561. public void testDefaultList() {
  562. AjcTask task = getTask("default.lst");
  563. runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  564. }
  565. public void testCompileErrorList() {
  566. AjcTask task = getTask("compileError.lst");
  567. task.setFailonerror(false);
  568. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR);
  569. }
  570. public void testShowWeaveInfo() {
  571. AjcTask task = getTask("showweaveinfo.lst");
  572. task.setShowWeaveInfo(true);
  573. MessageHandler mh = new MessageHandler(false);
  574. mh.dontIgnore(IMessage.WEAVEINFO);
  575. MessageHolderChecker mhc = new MessageHolderChecker(0,0,0,0,MessageHolderChecker.IGNORE);
  576. mhc.weaveinfos = 2; // Expect 2 weaving messages
  577. runTest(task,NO_EXCEPTION,mhc);
  578. mhc.weaveinfos = MessageHolderChecker.IGNORE;
  579. }
  580. public void testCompileWarningList() {
  581. AjcTask task = getTask("compileWarning.lst");
  582. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING);
  583. }
  584. public void testNoSuchFileList() {
  585. AjcTask task = getTask("NoSuchFile.lst");
  586. task.setFailonerror(false);
  587. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
  588. }
  589. public void testVersions() {
  590. String[] inputs = AjcTask.TARGET_INPUTS;
  591. for (int i = 0; i < inputs.length; i++) {
  592. AjcTask task = getTask(NOFILE);
  593. task.setTarget(inputs[i]);
  594. String[] cmd = task.makeCommand();
  595. checkContains(cmd, "-target", true);
  596. checkContains(cmd, inputs[i], true);
  597. }
  598. inputs = AjcTask.SOURCE_INPUTS;
  599. for (int i = 0; i < inputs.length; i++) {
  600. AjcTask task = getTask(NOFILE);
  601. task.setSource(inputs[i]);
  602. String[] cmd = task.makeCommand();
  603. checkContains(cmd, "-source", true);
  604. checkContains(cmd, inputs[i], true);
  605. }
  606. inputs = AjcTask.COMPLIANCE_INPUTS;
  607. for (int i = 0; i < inputs.length; i++) {
  608. AjcTask task = getTask(NOFILE);
  609. task.setCompliance(inputs[i]);
  610. String[] cmd = task.makeCommand();
  611. checkContains(cmd, inputs[i], true);
  612. }
  613. }
  614. public void testClasspath() {
  615. AjcTask task = getTask(NOFILE);
  616. String[] cmd = task.makeCommand();
  617. checkContains(cmd, "-bootclasspath", false);
  618. String classpath = null;
  619. for (int i = 0; i < cmd.length; i++) {
  620. if ("-classpath".equals(cmd[i])) {
  621. classpath = cmd[i + 1];
  622. break;
  623. }
  624. }
  625. assertTrue(
  626. "expecting aspectj in classpath",
  627. (-1 != classpath.indexOf("aspectjrt.jar")));
  628. }
  629. // ---------------------------------------- sourcefile
  630. // XXX need to figure out how to specify files directly programmatically
  631. // public void testDefaultFile() {
  632. // AjcTask task = getTask("testdata/Default.java");
  633. // runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  634. // }
  635. public void testNoFile() {
  636. AjcTask task = getTask(NOFILE);
  637. task.setFailonerror(false);
  638. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
  639. }
  640. public void testCompileErrorFile() {
  641. AjcTask task = getTask("compileError.lst");
  642. task.setFailonerror(false);
  643. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR);
  644. }
  645. public void testCompileWarningFile() {
  646. AjcTask task = getTask("compileWarning.lst");
  647. task.setFailonerror(false);
  648. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING);
  649. }
  650. public void testNoSuchFile() {
  651. AjcTask task = getTask("NoSuchFile.lst");
  652. task.setFailonerror(false);
  653. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
  654. }
  655. public void testDefaultFileComplete() {
  656. AjcTask task = getTask("default.lst");
  657. defaultSettings(task);
  658. runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  659. }
  660. private void defaultSettings(AjcTask task) {
  661. task.setDebugLevel("none");
  662. task.setDeprecation(true);
  663. task.setFailonerror(false);
  664. task.setNoExit(true); // ok to override Ant?
  665. task.setNoImportError(true);
  666. task.setNowarn(true);
  667. task.setXTerminateAfterCompilation(true);
  668. task.setPreserveAllLocals(true);
  669. task.setProceedOnError(true);
  670. task.setReferenceInfo(true);
  671. task.setSource("1.3");
  672. task.setTarget("1.1");
  673. task.setTime(true);
  674. task.setVerbose(true);
  675. task.setXlint("info");
  676. }
  677. public void testLogCommand() {
  678. final String DEFAULT = "default.lst";
  679. AjcTask task = getTask(DEFAULT);
  680. defaultSettings(task);
  681. task.setVerbose(false);
  682. task.setLogCommand(true);
  683. LogListener listener = new LogListener(Project.MSG_INFO);
  684. task.getProject().addBuildListener(listener);
  685. runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  686. String[] results = listener.getResults();
  687. boolean matched = false;
  688. for (int i = 0; !matched && (i < results.length); i++) {
  689. String s = results[i];
  690. matched = (null != s) && (-1 != s.indexOf(DEFAULT));
  691. }
  692. if (!matched) {
  693. fail(DEFAULT + " not found in " + Arrays.asList(results));
  694. }
  695. }
  696. public void testXOptions() {
  697. String[] xopts = new String[] {
  698. "serializableAspects",
  699. "lazyTjp",
  700. "reweavable",
  701. "reweavable:compress",
  702. "noInline"
  703. };
  704. for (int i = 0; i < xopts.length; i++) {
  705. AjcTask task = getTask(NOFILE);
  706. task.setX(xopts[i]);
  707. String[] cmd = task.makeCommand();
  708. checkContains(cmd,"-X" + xopts[i],true);
  709. }
  710. }
  711. public void testOutxml () {
  712. File destDir = getTempDir();
  713. assertTrue(
  714. "unable to create " + destDir,
  715. destDir.canRead() || destDir.mkdirs());
  716. AjcTask task = getTask("showweaveinfo.lst",destDir);
  717. task.setOutxml(true);
  718. checkRun(task,null);
  719. File outxmlFile = new File(destDir,"META-INF/aop-ajc.xml");
  720. assertTrue("META-INF/aop-ajc.xml missing",outxmlFile.exists());
  721. }
  722. public void testOutxmlFile () {
  723. String customName = "custom/aop.xml";
  724. File destDir = getTempDir();
  725. assertTrue(
  726. "unable to create " + destDir,
  727. destDir.canRead() || destDir.mkdirs());
  728. AjcTask task = getTask("showweaveinfo.lst",destDir);
  729. task.setOutxmlfile(customName);
  730. checkRun(task,null);
  731. File outxmlFile = new File(destDir,customName);
  732. assertTrue(customName + " missing",outxmlFile.exists());
  733. }
  734. // End of test cases
  735. // ------------------------------------------------------
  736. // ------------------------------------------------------
  737. // ------------------------------------------------------
  738. // ------------------------------------------------------
  739. // ------------------------------------------------------
  740. // ------------------------------------------------------
  741. protected void runTest(
  742. AjcTask task,
  743. Class exceptionType,
  744. MessageHolderChecker checker,
  745. String messageHolderClass) {
  746. task.setMessageHolderClass(messageHolderClass);
  747. runTest(task, exceptionType, checker, (MessageHandler) null);
  748. }
  749. protected void runTest(
  750. AjcTask task,
  751. Class exceptionType,
  752. MessageHolderChecker checker) {
  753. MessageHandler holder = new MessageHandler();
  754. task.setMessageHolder(holder);
  755. runTest(task, exceptionType, checker, holder);
  756. }
  757. protected void runTest(
  758. AjcTask task,
  759. Class exceptionType,
  760. MessageHolderChecker checker,
  761. MessageHandler holder) {
  762. Throwable thrown = null;
  763. // re-run forked iff tools.jar and expect to pass
  764. boolean rerunForked =
  765. ((null != aspectjtoolsJar)
  766. && (null == exceptionType)
  767. && ((null == checker) || !checker.expectFail()));
  768. String label = "same-vm ";
  769. while (true) { // same vm, then perhaps forked
  770. try {
  771. task.execute();
  772. } catch (Throwable t) {
  773. thrown = t;
  774. } finally {
  775. deleteTempDir();
  776. }
  777. if (null == exceptionType) {
  778. if (null != thrown) {
  779. assertTrue(label + "thrown: " + render(thrown), false);
  780. }
  781. } else if (null == thrown) {
  782. assertTrue(
  783. label + "expected " + exceptionType.getName(),
  784. false);
  785. } else if (!(exceptionType.isAssignableFrom(thrown.getClass()))) {
  786. assertTrue(
  787. label
  788. + "expected "
  789. + exceptionType.getName()
  790. + " got "
  791. + render(thrown),
  792. false);
  793. }
  794. if (null != holder) {
  795. if (null == checker) {
  796. checker = MessageHolderChecker.NONE;
  797. }
  798. checker.check(holder, label);
  799. }
  800. if (!rerunForked) {
  801. break;
  802. } else {
  803. label = "other-vm ";
  804. rerunForked = false;
  805. // can't reset without losing values...
  806. task.setFork(true);
  807. task.setFailonerror(true);
  808. task.setForkclasspath(
  809. new Path(task.getProject(), aspectjtoolsJar));
  810. }
  811. }
  812. }
  813. protected String render(Throwable thrown) {
  814. return LangUtil.renderException(thrown);
  815. }
  816. static class MessageHolderChecker { // XXX export to testing-utils
  817. /** use as value to ignore results */
  818. static int IGNORE = Integer.MIN_VALUE;
  819. static MessageHolderChecker NONE =
  820. new MessageHolderChecker(0, 0, 0, 0, 0);
  821. /** any number (0+) of info messages */
  822. static MessageHolderChecker INFOS =
  823. new MessageHolderChecker(0, 0, 0, 0, IGNORE);
  824. /** one error, any number of info messages */
  825. static MessageHolderChecker ONE_ERROR =
  826. new MessageHolderChecker(0, 0, 1, 0, IGNORE);
  827. static MessageHolderChecker ONE_ERROR_ONE_ABORT =
  828. new MessageHolderChecker(1, 0, 1, 0, IGNORE);
  829. /** one warning, any number of info messages */
  830. static MessageHolderChecker ONE_WARNING =
  831. new MessageHolderChecker(0, 0, 0, 1, IGNORE);
  832. int aborts, fails, errors, warnings, infos;
  833. int weaveinfos;
  834. public MessageHolderChecker(
  835. int aborts,
  836. int fails,
  837. int errors,
  838. int warnings,
  839. int infos) {
  840. this.aborts = aborts;
  841. this.fails = fails;
  842. this.errors = errors;
  843. this.warnings = warnings;
  844. this.infos = infos;
  845. this.weaveinfos = IGNORE;
  846. }
  847. public boolean expectFail() {
  848. return (0 < (aborts + fails + errors));
  849. }
  850. public void check(IMessageHolder holder, String label) {
  851. boolean failed = true;
  852. try {
  853. check(holder, aborts, IMessage.ABORT);
  854. check(holder, fails, IMessage.FAIL);
  855. check(holder, errors, IMessage.ERROR);
  856. check(holder, warnings, IMessage.WARNING);
  857. check(holder, infos, IMessage.INFO);
  858. check(holder, weaveinfos, IMessage.WEAVEINFO);
  859. failed = false;
  860. } finally {
  861. if (failed) {
  862. MessageUtil.print(System.err, holder, label + "failed?");
  863. }
  864. }
  865. }
  866. private void check(
  867. IMessageHolder holder,
  868. int num,
  869. IMessage.Kind kind) {
  870. if (num != IGNORE) {
  871. int actual = holder.numMessages(kind, false);
  872. if (num != actual) {
  873. if (actual > 0) {
  874. MessageUtil.print(
  875. System.err,
  876. holder,
  877. kind + " expected " + num + " got " + actual);
  878. }
  879. assertEquals(kind.toString(), num, actual);
  880. }
  881. }
  882. }
  883. }
  884. private static class LogListener implements BuildListener {
  885. private final ArrayList results = new ArrayList();
  886. private final int priority;
  887. private LogListener(int priority) {
  888. this.priority = priority;
  889. }
  890. public void buildFinished(BuildEvent event) {}
  891. public void buildStarted(BuildEvent event) {}
  892. public void messageLogged(BuildEvent event) {
  893. if (priority == event.getPriority()) {
  894. results.add(event.getMessage());
  895. }
  896. }
  897. public void targetFinished(BuildEvent event) {}
  898. public void targetStarted(BuildEvent event) {}
  899. public void taskFinished(BuildEvent event) {}
  900. public void taskStarted(BuildEvent event) {}
  901. String[] getResults() {
  902. return (String[]) results.toArray(new String[0]);
  903. }
  904. }
  905. }
  906. class SnoopingCommandEditor implements ICommandEditor {
  907. private static final String[] NONE = new String[0];
  908. String[] lastCommand;
  909. public String[] editCommand(String[] command) {
  910. lastCommand = (String[]) LangUtil.safeCopy(command, NONE);
  911. return command;
  912. }
  913. public String[] lastCommand() {
  914. return (String[]) LangUtil.safeCopy(lastCommand, NONE);
  915. }
  916. }
  917. class VerboseCommandEditor implements ICommandEditor {
  918. public static final String VERBOSE = "-verbose";
  919. public String[] editCommand(String[] command) {
  920. for (int i = 0; i < command.length; i++) {
  921. if (VERBOSE.equals(command[i])) {
  922. return command;
  923. }
  924. }
  925. String[] result = new String[1 + command.length];
  926. result[0] = VERBOSE;
  927. System.arraycopy(result, 1, command, 0, command.length);
  928. return result;
  929. }
  930. }
  931. class AppendingCommandEditor implements ICommandEditor {
  932. private static String[] NONE = new String[0];
  933. public static ICommandEditor VERBOSE =
  934. new AppendingCommandEditor(new String[] { "-verbose" }, NONE);
  935. public static ICommandEditor INVALID =
  936. new AppendingCommandEditor(NONE, new String[] { "-invalidOption" });
  937. final String[] prefix;
  938. final String[] suffix;
  939. public AppendingCommandEditor(String[] prefix, String[] suffix) {
  940. this.prefix = prefix;
  941. this.suffix = suffix;
  942. }
  943. public String[] editCommand(String[] command) {
  944. int len = command.length + prefix.length + suffix.length;
  945. String[] result = new String[len];
  946. System.arraycopy(result, 0, prefix, 0, prefix.length);
  947. System.arraycopy(result, prefix.length, command, 0, command.length);
  948. System.arraycopy(
  949. result,
  950. prefix.length + command.length,
  951. suffix,
  952. 0,
  953. suffix.length);
  954. return result;
  955. }
  956. }