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

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