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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. // The test program produces three errors with the current 1.8 compiler, this may change by 1.8 release and so
  481. // this will need reverting back to "e"
  482. assertEquals("messages", "eee", result);
  483. }
  484. // TODO skipped test - works locally but not on build machine?
  485. public void skip_testMessageHolderClassWithDoneSignal() {
  486. AjcTask task = getTask("default.lst");
  487. task.setFailonerror(false);
  488. String DONE = "This is a unique message, not confused with others.";
  489. task.setXDoneSignal(DONE);
  490. MESSAGES.setLength(0);
  491. runTest(
  492. task,
  493. null,
  494. MessageHolderChecker.INFOS,
  495. InfoHolder.class.getName());
  496. final String result = MESSAGES.toString();
  497. String temp = new String(result);
  498. MESSAGES.setLength(0);
  499. if (!temp.endsWith(DONE)) {
  500. if (temp.length() > 20) {
  501. temp = "..." + temp.substring(temp.length()-20, temp.length());
  502. }
  503. assertTrue(DONE + " is not suffix of \"" + temp + "\"", false);
  504. }
  505. // exactly one such message
  506. temp = new String(result);
  507. temp = temp.substring(0, temp.length()-DONE.length());
  508. if (temp.endsWith(DONE)) {
  509. temp = new String(result);
  510. if (temp.length() > 20) {
  511. temp = "..." + temp.substring(temp.length()-20, temp.length());
  512. }
  513. assertTrue(DONE + " signalled twice: \"" + temp + "\"", false);
  514. }
  515. }
  516. public void testDefaultListForkedNoTools() {
  517. AjcTask task = getTask("default.lst");
  518. task.setFork(true);
  519. boolean passed = false;
  520. try {
  521. runTest(task, BuildException.class, MessageHolderChecker.NONE);
  522. passed = true;
  523. } finally {
  524. if (!passed) {
  525. String m =
  526. "AjcTaskTest.testDefaultListForkedNoTools()"
  527. + " fails if aspectjtools.jar is on the classpath";
  528. System.err.println(m);
  529. }
  530. }
  531. }
  532. public void testDefaultListForkedIncremental() {
  533. AjcTask task = getTask("default.lst");
  534. task.setFork(true);
  535. task.setIncremental(true);
  536. runTest(task, BuildException.class, MessageHolderChecker.NONE);
  537. }
  538. /** failonerror should default to true, unlike other booleans */
  539. public void testCompileErrorFailOnErrorDefault() {
  540. AjcTask task = getTask("compileError.lst");
  541. final PrintStream serr = System.err;
  542. try {
  543. System.setErr(new PrintStream(new java.io.ByteArrayOutputStream()));
  544. // Current 1.8 compiler produces 3 errors for this test program, may need reverting to ONE_ERROR by release
  545. runTest(task, BuildException.class, MessageHolderChecker.THREE_ERRORS);
  546. } finally {
  547. System.setErr(serr);
  548. }
  549. }
  550. public void testCompileErrorListDefaultHolder() {
  551. AjcTask task = getTask("compileError.lst");
  552. final PrintStream serr = System.err;
  553. try {
  554. System.setErr(new PrintStream(new java.io.ByteArrayOutputStream()));
  555. task.execute();
  556. fail("expected BuildException from failed compile by default");
  557. } catch (BuildException t) {
  558. // ok
  559. } finally {
  560. System.setErr(serr);
  561. deleteTempDir();
  562. }
  563. }
  564. public void testDefaultList() {
  565. AjcTask task = getTask("default.lst");
  566. runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  567. }
  568. public void testCompileErrorList() {
  569. AjcTask task = getTask("compileError.lst");
  570. task.setFailonerror(false);
  571. // Prior to the 1.8 compiler there is one error here, 'syntax error on here'
  572. // With 1.8 there are 3 errors about completing the method header, ending the class body, ending the method - this may
  573. // change by 1.8 final... this might need reverting back to ONE_ERROR
  574. runTest(task, NO_EXCEPTION, MessageHolderChecker.THREE_ERRORS);
  575. }
  576. public void testShowWeaveInfo() {
  577. AjcTask task = getTask("showweaveinfo.lst");
  578. task.setShowWeaveInfo(true);
  579. MessageHandler mh = new MessageHandler(false);
  580. mh.dontIgnore(IMessage.WEAVEINFO);
  581. MessageHolderChecker mhc = new MessageHolderChecker(0,0,0,0,MessageHolderChecker.IGNORE);
  582. mhc.weaveinfos = 2; // Expect 2 weaving messages
  583. runTest(task,NO_EXCEPTION,mhc);
  584. mhc.weaveinfos = MessageHolderChecker.IGNORE;
  585. }
  586. public void testCompileWarningList() {
  587. AjcTask task = getTask("compileWarning.lst");
  588. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING);
  589. }
  590. public void testNoSuchFileList() {
  591. AjcTask task = getTask("NoSuchFile.lst");
  592. task.setFailonerror(false);
  593. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
  594. }
  595. public void testVersions() {
  596. String[] inputs = AjcTask.TARGET_INPUTS;
  597. for (int i = 0; i < inputs.length; i++) {
  598. AjcTask task = getTask(NOFILE);
  599. task.setTarget(inputs[i]);
  600. String[] cmd = task.makeCommand();
  601. checkContains(cmd, "-target", true);
  602. checkContains(cmd, inputs[i], true);
  603. }
  604. inputs = AjcTask.SOURCE_INPUTS;
  605. for (int i = 0; i < inputs.length; i++) {
  606. AjcTask task = getTask(NOFILE);
  607. task.setSource(inputs[i]);
  608. String[] cmd = task.makeCommand();
  609. checkContains(cmd, "-source", true);
  610. checkContains(cmd, inputs[i], true);
  611. }
  612. inputs = AjcTask.COMPLIANCE_INPUTS;
  613. for (int i = 0; i < inputs.length; i++) {
  614. AjcTask task = getTask(NOFILE);
  615. task.setCompliance(inputs[i]);
  616. String[] cmd = task.makeCommand();
  617. checkContains(cmd, inputs[i], true);
  618. }
  619. }
  620. public void testClasspath() {
  621. AjcTask task = getTask(NOFILE);
  622. String[] cmd = task.makeCommand();
  623. checkContains(cmd, "-bootclasspath", false);
  624. String classpath = null;
  625. for (int i = 0; i < cmd.length; i++) {
  626. if ("-classpath".equals(cmd[i])) {
  627. classpath = cmd[i + 1];
  628. break;
  629. }
  630. }
  631. assertTrue(
  632. "expecting aspectj in classpath",
  633. (-1 != classpath.indexOf("aspectjrt.jar")));
  634. }
  635. // ---------------------------------------- sourcefile
  636. // XXX need to figure out how to specify files directly programmatically
  637. // public void testDefaultFile() {
  638. // AjcTask task = getTask("testdata/Default.java");
  639. // runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  640. // }
  641. public void testNoFile() {
  642. AjcTask task = getTask(NOFILE);
  643. task.setFailonerror(false);
  644. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
  645. }
  646. public void testCompileErrorFile() {
  647. AjcTask task = getTask("compileError.lst");
  648. task.setFailonerror(false);
  649. // 1.8 compiler currently produces 3 errors for the test program, may need to revert to ONE_ERROR by 1.8 release
  650. runTest(task, NO_EXCEPTION, MessageHolderChecker.THREE_ERRORS);
  651. }
  652. public void testCompileWarningFile() {
  653. AjcTask task = getTask("compileWarning.lst");
  654. task.setFailonerror(false);
  655. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_WARNING);
  656. }
  657. public void testNoSuchFile() {
  658. AjcTask task = getTask("NoSuchFile.lst");
  659. task.setFailonerror(false);
  660. runTest(task, NO_EXCEPTION, MessageHolderChecker.ONE_ERROR_ONE_ABORT);
  661. }
  662. public void testDefaultFileComplete() {
  663. AjcTask task = getTask("default.lst");
  664. defaultSettings(task);
  665. runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  666. }
  667. private void defaultSettings(AjcTask task) {
  668. task.setDebugLevel("none");
  669. task.setDeprecation(true);
  670. task.setFailonerror(false);
  671. task.setNoExit(true); // ok to override Ant?
  672. task.setNoImportError(true);
  673. task.setNowarn(true);
  674. task.setXTerminateAfterCompilation(true);
  675. task.setPreserveAllLocals(true);
  676. task.setProceedOnError(true);
  677. task.setReferenceInfo(true);
  678. task.setSource("1.3");
  679. task.setTarget("1.1");
  680. task.setTime(true);
  681. task.setVerbose(true);
  682. task.setXlint("info");
  683. }
  684. public void testLogCommand() {
  685. final String DEFAULT = "default.lst";
  686. AjcTask task = getTask(DEFAULT);
  687. defaultSettings(task);
  688. task.setVerbose(false);
  689. task.setLogCommand(true);
  690. LogListener listener = new LogListener(Project.MSG_INFO);
  691. task.getProject().addBuildListener(listener);
  692. runTest(task, NO_EXCEPTION, MessageHolderChecker.INFOS);
  693. String[] results = listener.getResults();
  694. boolean matched = false;
  695. for (int i = 0; !matched && (i < results.length); i++) {
  696. String s = results[i];
  697. matched = (null != s) && (-1 != s.indexOf(DEFAULT));
  698. }
  699. if (!matched) {
  700. fail(DEFAULT + " not found in " + Arrays.asList(results));
  701. }
  702. }
  703. public void testXOptions() {
  704. String[] xopts = new String[] {
  705. "serializableAspects",
  706. "lazyTjp",
  707. "reweavable",
  708. "reweavable:compress",
  709. "noInline"
  710. };
  711. for (int i = 0; i < xopts.length; i++) {
  712. AjcTask task = getTask(NOFILE);
  713. task.setX(xopts[i]);
  714. String[] cmd = task.makeCommand();
  715. checkContains(cmd,"-X" + xopts[i],true);
  716. }
  717. }
  718. public void testAptProc() {
  719. AjcTask task = getTask(NOFILE);
  720. task.setProc("none");
  721. checkContains(task.makeCommand(), "-proc:none", true);
  722. task.setProc("only");
  723. checkContains(task.makeCommand(), "-proc:only", true);
  724. }
  725. public void testAptProcessor() {
  726. AjcTask task = getTask(NOFILE);
  727. task.setProcessor("some.SomeClass");
  728. checkContains(task.makeCommand(), "-processor", true);
  729. checkContains(task.makeCommand(), "some.SomeClass", true);
  730. }
  731. public void testAptProcessorpath() {
  732. AjcTask task = getTask(NOFILE);
  733. task.setProcessorpath("some/path");
  734. checkContains(task.makeCommand(), "-processorpath", true);
  735. checkContains(task.makeCommand(), "some/path", true);
  736. }
  737. public void testAptGeneratedDirectory() {
  738. AjcTask task = getTask(NOFILE);
  739. task.setS("some/path");
  740. checkContains(task.makeCommand(), "-s", true);
  741. checkContains(task.makeCommand(), "some/path", true);
  742. }
  743. public void testOutxml () {
  744. File destDir = getTempDir();
  745. assertTrue(
  746. "unable to create " + destDir,
  747. destDir.canRead() || destDir.mkdirs());
  748. AjcTask task = getTask("showweaveinfo.lst",destDir);
  749. task.setOutxml(true);
  750. checkRun(task,null);
  751. File outxmlFile = new File(destDir,"META-INF/aop-ajc.xml");
  752. assertTrue("META-INF/aop-ajc.xml missing",outxmlFile.exists());
  753. }
  754. public void testOutxmlFile () {
  755. String customName = "custom/aop.xml";
  756. File destDir = getTempDir();
  757. assertTrue(
  758. "unable to create " + destDir,
  759. destDir.canRead() || destDir.mkdirs());
  760. AjcTask task = getTask("showweaveinfo.lst",destDir);
  761. task.setOutxmlfile(customName);
  762. checkRun(task,null);
  763. File outxmlFile = new File(destDir,customName);
  764. assertTrue(customName + " missing",outxmlFile.exists());
  765. }
  766. // End of test cases
  767. // ------------------------------------------------------
  768. // ------------------------------------------------------
  769. // ------------------------------------------------------
  770. // ------------------------------------------------------
  771. // ------------------------------------------------------
  772. // ------------------------------------------------------
  773. protected void runTest(
  774. AjcTask task,
  775. Class exceptionType,
  776. MessageHolderChecker checker,
  777. String messageHolderClass) {
  778. task.setMessageHolderClass(messageHolderClass);
  779. runTest(task, exceptionType, checker, (MessageHandler) null);
  780. }
  781. protected void runTest(
  782. AjcTask task,
  783. Class exceptionType,
  784. MessageHolderChecker checker) {
  785. MessageHandler holder = new MessageHandler();
  786. task.setMessageHolder(holder);
  787. runTest(task, exceptionType, checker, holder);
  788. }
  789. protected void runTest(
  790. AjcTask task,
  791. Class exceptionType,
  792. MessageHolderChecker checker,
  793. MessageHandler holder) {
  794. Throwable thrown = null;
  795. // re-run forked iff tools.jar and expect to pass
  796. boolean rerunForked =
  797. ((null != aspectjtoolsJar)
  798. && (null == exceptionType)
  799. && ((null == checker) || !checker.expectFail()));
  800. String label = "same-vm ";
  801. while (true) { // same vm, then perhaps forked
  802. try {
  803. task.execute();
  804. } catch (Throwable t) {
  805. thrown = t;
  806. } finally {
  807. deleteTempDir();
  808. }
  809. if (null == exceptionType) {
  810. if (null != thrown) {
  811. assertTrue(label + "thrown: " + render(thrown), false);
  812. }
  813. } else if (null == thrown) {
  814. assertTrue(
  815. label + "expected " + exceptionType.getName(),
  816. false);
  817. } else if (!(exceptionType.isAssignableFrom(thrown.getClass()))) {
  818. assertTrue(
  819. label
  820. + "expected "
  821. + exceptionType.getName()
  822. + " got "
  823. + render(thrown),
  824. false);
  825. }
  826. if (null != holder) {
  827. if (null == checker) {
  828. checker = MessageHolderChecker.NONE;
  829. }
  830. checker.check(holder, label);
  831. }
  832. if (!rerunForked) {
  833. break;
  834. } else {
  835. label = "other-vm ";
  836. rerunForked = false;
  837. // can't reset without losing values...
  838. task.setFork(true);
  839. task.setFailonerror(true);
  840. task.setForkclasspath(
  841. new Path(task.getProject(), aspectjtoolsJar));
  842. }
  843. }
  844. }
  845. protected String render(Throwable thrown) {
  846. return LangUtil.renderException(thrown);
  847. }
  848. static class MessageHolderChecker { // XXX export to testing-utils
  849. /** use as value to ignore results */
  850. static int IGNORE = Integer.MIN_VALUE;
  851. static MessageHolderChecker NONE =
  852. new MessageHolderChecker(0, 0, 0, 0, 0);
  853. /** any number (0+) of info messages */
  854. static MessageHolderChecker INFOS =
  855. new MessageHolderChecker(0, 0, 0, 0, IGNORE);
  856. /** one error, any number of info messages */
  857. static MessageHolderChecker ONE_ERROR =
  858. new MessageHolderChecker(0, 0, 1, 0, IGNORE);
  859. static MessageHolderChecker ONE_ERROR_ONE_ABORT =
  860. new MessageHolderChecker(1, 0, 1, 0, IGNORE);
  861. /** one warning, any number of info messages */
  862. static MessageHolderChecker ONE_WARNING =
  863. new MessageHolderChecker(0, 0, 0, 1, IGNORE);
  864. static MessageHolderChecker THREE_ERRORS =
  865. new MessageHolderChecker(0, 0, 3, 0, IGNORE);
  866. int aborts, fails, errors, warnings, infos;
  867. int weaveinfos;
  868. public MessageHolderChecker(
  869. int aborts,
  870. int fails,
  871. int errors,
  872. int warnings,
  873. int infos) {
  874. this.aborts = aborts;
  875. this.fails = fails;
  876. this.errors = errors;
  877. this.warnings = warnings;
  878. this.infos = infos;
  879. this.weaveinfos = IGNORE;
  880. }
  881. public boolean expectFail() {
  882. return (0 < (aborts + fails + errors));
  883. }
  884. public void check(IMessageHolder holder, String label) {
  885. boolean failed = true;
  886. try {
  887. check(holder, aborts, IMessage.ABORT);
  888. check(holder, fails, IMessage.FAIL);
  889. check(holder, errors, IMessage.ERROR);
  890. check(holder, warnings, IMessage.WARNING);
  891. check(holder, infos, IMessage.INFO);
  892. check(holder, weaveinfos, IMessage.WEAVEINFO);
  893. failed = false;
  894. } finally {
  895. if (failed) {
  896. MessageUtil.print(System.err, holder, label + "failed?");
  897. }
  898. }
  899. }
  900. private void check(
  901. IMessageHolder holder,
  902. int num,
  903. IMessage.Kind kind) {
  904. if (num != IGNORE) {
  905. int actual = holder.numMessages(kind, false);
  906. if (num != actual) {
  907. if (actual > 0) {
  908. MessageUtil.print(
  909. System.err,
  910. holder,
  911. kind + " expected " + num + " got " + actual);
  912. }
  913. assertEquals(kind.toString(), num, actual);
  914. }
  915. }
  916. }
  917. }
  918. private static class LogListener implements BuildListener {
  919. private final ArrayList results = new ArrayList();
  920. private final int priority;
  921. private LogListener(int priority) {
  922. this.priority = priority;
  923. }
  924. public void buildFinished(BuildEvent event) {}
  925. public void buildStarted(BuildEvent event) {}
  926. public void messageLogged(BuildEvent event) {
  927. if (priority == event.getPriority()) {
  928. results.add(event.getMessage());
  929. }
  930. }
  931. public void targetFinished(BuildEvent event) {}
  932. public void targetStarted(BuildEvent event) {}
  933. public void taskFinished(BuildEvent event) {}
  934. public void taskStarted(BuildEvent event) {}
  935. String[] getResults() {
  936. return (String[]) results.toArray(new String[0]);
  937. }
  938. }
  939. }
  940. class SnoopingCommandEditor implements ICommandEditor {
  941. private static final String[] NONE = new String[0];
  942. String[] lastCommand;
  943. public String[] editCommand(String[] command) {
  944. lastCommand = (String[]) LangUtil.safeCopy(command, NONE);
  945. return command;
  946. }
  947. public String[] lastCommand() {
  948. return (String[]) LangUtil.safeCopy(lastCommand, NONE);
  949. }
  950. }
  951. class VerboseCommandEditor implements ICommandEditor {
  952. public static final String VERBOSE = "-verbose";
  953. public String[] editCommand(String[] command) {
  954. for (int i = 0; i < command.length; i++) {
  955. if (VERBOSE.equals(command[i])) {
  956. return command;
  957. }
  958. }
  959. String[] result = new String[1 + command.length];
  960. result[0] = VERBOSE;
  961. System.arraycopy(result, 1, command, 0, command.length);
  962. return result;
  963. }
  964. }
  965. class AppendingCommandEditor implements ICommandEditor {
  966. private static String[] NONE = new String[0];
  967. public static ICommandEditor VERBOSE =
  968. new AppendingCommandEditor(new String[] { "-verbose" }, NONE);
  969. public static ICommandEditor INVALID =
  970. new AppendingCommandEditor(NONE, new String[] { "-invalidOption" });
  971. final String[] prefix;
  972. final String[] suffix;
  973. public AppendingCommandEditor(String[] prefix, String[] suffix) {
  974. this.prefix = prefix;
  975. this.suffix = suffix;
  976. }
  977. public String[] editCommand(String[] command) {
  978. int len = command.length + prefix.length + suffix.length;
  979. String[] result = new String[len];
  980. System.arraycopy(result, 0, prefix, 0, prefix.length);
  981. System.arraycopy(result, prefix.length, command, 0, command.length);
  982. System.arraycopy(
  983. result,
  984. prefix.length + command.length,
  985. suffix,
  986. 0,
  987. suffix.length);
  988. return result;
  989. }
  990. }