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.

AjcTestCase.java 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. /* *******************************************************************
  2. * Copyright (c) 2004 IBM Corporation
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v 2.0
  6. * which accompanies this distribution and is available at
  7. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  8. *
  9. * Contributors:
  10. * Adrian Colyer, Abraham Nevado (lucierna)
  11. * ******************************************************************/
  12. package org.aspectj.tools.ajc;
  13. import java.io.BufferedReader;
  14. import java.io.ByteArrayOutputStream;
  15. import java.io.File;
  16. import java.io.IOException;
  17. import java.io.InputStreamReader;
  18. import java.io.OutputStream;
  19. import java.io.PrintStream;
  20. import java.io.PrintWriter;
  21. import java.lang.reflect.Constructor;
  22. import java.lang.reflect.InvocationTargetException;
  23. import java.lang.reflect.Method;
  24. import java.net.URL;
  25. import java.net.URLClassLoader;
  26. import java.util.ArrayList;
  27. import java.util.Arrays;
  28. import java.util.Collections;
  29. import java.util.List;
  30. import java.util.StringTokenizer;
  31. import java.util.stream.Collectors;
  32. import org.aspectj.bridge.IMessage;
  33. import org.aspectj.bridge.ISourceLocation;
  34. import org.aspectj.testing.util.TestUtil;
  35. import org.aspectj.util.LangUtil;
  36. import junit.framework.TestCase;
  37. import static java.io.File.pathSeparator;
  38. import static java.io.File.separator;
  39. /**
  40. * A TestCase class that acts as the superclass for all test cases wishing to drive the ajc compiler.
  41. * <p>
  42. * This class provides a number of utility methods that make programmatic testing of the compiler easy. See AjcTestCaseTest for a
  43. * couple of simple tests written using this class.
  44. * </p>
  45. * <p>
  46. * See the XMLBasedAjcTestCase subclass for TestCase class that can be used to drive compiler tests based on an ajcTests.xml format
  47. * test specification file.
  48. * </p>
  49. *
  50. * @see org.aspectj.tools.ajc.AjcTestCase.Message
  51. * @see org.aspectj.tools.ajc.AjcTestCase.MessageSpec
  52. * @see org.aspectj.tools.ajc.AjcTestCase.RunResult
  53. * @see org.aspectj.tools.ajc.AjcTestCaseTest
  54. * @see org.aspectj.testing.XMLBasedAjcTestCase
  55. */
  56. public abstract class AjcTestCase extends TestCase {
  57. private RunResult lastRunResult;
  58. /**
  59. * The Ajc (compiler) instance used for the test. Created afresh during the test setup.
  60. */
  61. protected Ajc ajc;
  62. public static final String CLASSPATH_ASM =
  63. Arrays.stream(System.getProperty("java.class.path")
  64. .split(pathSeparator))
  65. .filter(path -> path.replace('\\', '/').contains("org/ow2/asm/asm/"))
  66. .findFirst()
  67. .orElseThrow(() -> new RuntimeException("ASM library not found on classpath"));
  68. public static final String CLASSPATH_ASM_COMMONS =
  69. Arrays.stream(System.getProperty("java.class.path")
  70. .split(pathSeparator))
  71. .filter(path -> path.replace('\\', '/').contains("org/ow2/asm/asm-commons/"))
  72. .findFirst()
  73. .orElseThrow(() -> new RuntimeException("ASM Commons library not found on classpath"));
  74. public static final String CLASSPATH_JDT_CORE =
  75. Arrays.stream(System.getProperty("java.class.path")
  76. .split(pathSeparator))
  77. .filter(path -> path.replace('\\', '/').contains("/org/aspectj/org.eclipse.jdt.core/"))
  78. .findFirst()
  79. .orElseThrow(() -> new RuntimeException("AspectJ JDT Core library not found on classpath"));
  80. public static final String CLASSPATH_JUNIT =
  81. Arrays.stream(System.getProperty("java.class.path")
  82. .split(pathSeparator))
  83. .filter(path -> path.replace('\\', '/').contains("/junit/junit/"))
  84. .findFirst()
  85. .orElseThrow(() -> new RuntimeException("JUnit library not found on classpath"));
  86. // In 'useFullLTW' mode, aspectjweaver.jar is a Java agent. Therefore, what is contained in there
  87. // does not need to be on the classpath.
  88. public static final String DEFAULT_FULL_LTW_CLASSPATH_ENTRIES =
  89. Ajc.outputFolders("testing-client")
  90. + pathSeparator + CLASSPATH_JUNIT
  91. + pathSeparator + ".." + separator + "lib" + separator + "test" + separator + "testing-client.jar"
  92. ;
  93. // See Ajc and AntSpec
  94. public static final String DEFAULT_CLASSPATH_ENTRIES =
  95. DEFAULT_FULL_LTW_CLASSPATH_ENTRIES
  96. + Ajc.outputFolders("bridge", "util", "loadtime", "weaver", "asm", "runtime", "org.aspectj.matcher", "bcel-builder")
  97. + pathSeparator + ".." + separator + "lib" + separator + "bcel" + separator + "bcel.jar"
  98. + pathSeparator + ".." + separator + "lib" + separator + "bcel" + separator + "bcel-verifier.jar"
  99. + pathSeparator + CLASSPATH_JDT_CORE
  100. + pathSeparator + CLASSPATH_ASM
  101. + pathSeparator + CLASSPATH_ASM_COMMONS
  102. // hmmm, this next one should perhaps point to an aj-build jar...
  103. + pathSeparator + ".." + separator + "lib" + separator + "test" + separator + "aspectjrt.jar"
  104. ;
  105. /*
  106. * Save reference to real stderr and stdout before starting redirection
  107. */
  108. public final static PrintStream err = System.err;
  109. public final static PrintStream out = System.out;
  110. private final static DelegatingOutputStream delegatingErr;
  111. private final static DelegatingOutputStream delegatingOut;
  112. public final static boolean DEFAULT_VERBOSE = getBoolean("aspectj.tests.verbose", true);
  113. public final static boolean DEFAULT_ERR_VERBOSE = getBoolean("org.aspectj.tools.ajc.AjcTestCase.verbose.err", DEFAULT_VERBOSE);
  114. public final static boolean DEFAULT_OUT_VERBOSE = getBoolean("org.aspectj.tools.ajc.AjcTestCase.verbose.out", DEFAULT_VERBOSE);
  115. private Process exec;
  116. /**
  117. * Helper class that represents the specification of an individual message expected to be produced during a compilation run.
  118. * <p>
  119. * Message objects are combined in a MessageSpec which can then be passed to the various assertMessage methods.
  120. * </p>
  121. *
  122. * @see org.aspectj.tools.ajc.AjcTestCase.MessageSpec
  123. */
  124. public static class Message {
  125. private int line = -1;
  126. private String text;
  127. private String sourceFileName;
  128. private ISourceLocation[] seeAlsos;
  129. public boolean careAboutOtherMessages = true;
  130. /**
  131. * Create a message that will match any compiler message on the given line.
  132. */
  133. public Message(int line) {
  134. this.line = line;
  135. }
  136. /**
  137. * Create a message that will match any compiler message on the given line, where the message text contains
  138. * <code>text</code>.
  139. */
  140. public Message(int line, String text) {
  141. this.line = line;
  142. this.text = text;
  143. if (this.text != null && text.startsWith("*")) {
  144. // Don't care what other messages are around
  145. this.careAboutOtherMessages = false;
  146. this.text = this.text.substring(1);
  147. }
  148. }
  149. /**
  150. * Create a message that will match any compiler message on the given line, where the message text contains
  151. * <code>text</code>.
  152. * <p>
  153. * If srcFile is non-null, the source file location of the message must end with <code>srcFile</code>.
  154. * </p>
  155. * <p>
  156. * If <code>seeAlso</code> is non-null, each source location in seeAlso must be matched by an extraSourceLocation in the
  157. * message.
  158. * </p>
  159. */
  160. public Message(int line, String srcFile, String text, ISourceLocation[] seeAlso) {
  161. this.line = line;
  162. StringBuilder srcFileName = new StringBuilder();
  163. if (srcFile != null) {
  164. char[] chars = srcFile.toCharArray();
  165. for (char c : chars) {
  166. if ((c == '\\') || (c == '/')) {
  167. srcFileName.append(separator);
  168. } else {
  169. srcFileName.append(c);
  170. }
  171. }
  172. this.sourceFileName = srcFileName.toString();
  173. }
  174. this.text = text;
  175. if (this.text != null && text.startsWith("*")) {
  176. // Don't care what other messages are around
  177. this.careAboutOtherMessages = false;
  178. this.text = this.text.substring(1);
  179. }
  180. this.seeAlsos = seeAlso;
  181. }
  182. /**
  183. * Create a message spec that will match any compiler message where the message text includes <code>text</code>.
  184. */
  185. public Message(String text) {
  186. this.text = text;
  187. if (this.text != null && text.startsWith("*")) {
  188. // Don't care what other messages are around
  189. this.careAboutOtherMessages = false;
  190. this.text = this.text.substring(1);
  191. }
  192. }
  193. /**
  194. * Return true if this message spec matches the given compiler message.
  195. */
  196. public boolean matches(IMessage message) {
  197. ISourceLocation loc = message.getSourceLocation();
  198. if ((loc == null) && ((line != -1) || (sourceFileName != null))) {
  199. return false;
  200. }
  201. if (line != -1) {
  202. if (loc.getLine() != line) {
  203. return false;
  204. }
  205. }
  206. if (sourceFileName != null) {
  207. if (!loc.getSourceFile().getPath().endsWith(sourceFileName)) {
  208. return false;
  209. }
  210. }
  211. if (text != null) {
  212. if (!message.getMessage().contains(text)) {
  213. return false;
  214. }
  215. }
  216. if (seeAlsos != null) {
  217. List<ISourceLocation> extraLocations = message.getExtraSourceLocations();
  218. if (extraLocations.size() != seeAlsos.length) {
  219. return false;
  220. }
  221. for (ISourceLocation seeAlso : seeAlsos) {
  222. if (!hasAMatch(extraLocations, seeAlso)) {
  223. return false;
  224. }
  225. }
  226. }
  227. return true;
  228. }
  229. private boolean hasAMatch(List<ISourceLocation> srcLocations, ISourceLocation sLoc) {
  230. for (ISourceLocation thisLoc: srcLocations) {
  231. if (thisLoc.getLine() == sLoc.getLine()) {
  232. if (thisLoc.getSourceFile().getPath().equals(sLoc.getSourceFile().getPath())) {
  233. return true;
  234. }
  235. }
  236. }
  237. return false;
  238. }
  239. /**
  240. * Returns a string indicating what this <code>Message</code> will match.
  241. */
  242. @Override
  243. public String toString() {
  244. StringBuilder buff = new StringBuilder();
  245. buff.append("message ");
  246. if (sourceFileName != null)
  247. buff.append("in file ").append(sourceFileName).append(" ");
  248. if (line != -1)
  249. buff.append("on line ").append(line).append(" ");
  250. if (text != null)
  251. buff.append("containing text '").append(text).append("' ");
  252. if (seeAlsos != null) {
  253. buff.append("\n\twith see alsos:");
  254. for (ISourceLocation seeAlso : seeAlsos)
  255. buff.append("\t\t").append(seeAlso.getSourceFile().getPath()).append(":").append(seeAlso.getLine());
  256. }
  257. return buff.toString();
  258. }
  259. }
  260. /**
  261. * Helper class that represents the specification of a set of messages expected to be produced from a compiler run.
  262. * <p>
  263. * Instances of MessageSpec are passed to the assertMessage methods to validate <code>CompilationResult</code>s.
  264. */
  265. public static class MessageSpec {
  266. /**
  267. * Convenience constant that matches a CompilationResult with any number of information messages, but no others.
  268. */
  269. public static final MessageSpec EMPTY_MESSAGE_SET = new MessageSpec(
  270. null, Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
  271. Collections.EMPTY_LIST, Collections.EMPTY_LIST
  272. );
  273. boolean ignoreInfos = true;
  274. public List<AjcTestCase.Message> fails;
  275. public List<AjcTestCase.Message> infos;
  276. public List<AjcTestCase.Message> warnings;
  277. public List<AjcTestCase.Message> errors;
  278. public List<AjcTestCase.Message> weaves;
  279. public List<AjcTestCase.Message> usages;
  280. /**
  281. * Set to true to enable or disable comparison of information messages.
  282. */
  283. public void setInfoComparison(boolean enabled) {
  284. this.ignoreInfos = !enabled;
  285. }
  286. /**
  287. * True if information messages are not being included in matching.
  288. */
  289. public boolean isIgnoringInfoMessages() {
  290. return ignoreInfos;
  291. }
  292. /**
  293. * Create a message specification to test a CompilationResult for a given set of info, warning, error, and fail messages.
  294. *
  295. * @param infos The set of info messages to test for. Specifying a non-null value for this parameter enables info message
  296. * comparison.
  297. * @param warnings The set of warning messages to test for - can pass null to indicate empty set.
  298. * @param errors The set of error messages to test for - can pass null to indicate empty set.
  299. * @param fails The set of fail or abort messages to test for - can pass null to indicate empty set.
  300. */
  301. public MessageSpec(
  302. List<AjcTestCase.Message> infos,
  303. List<AjcTestCase.Message> warnings,
  304. List<AjcTestCase.Message> errors,
  305. List<AjcTestCase.Message> fails,
  306. List<AjcTestCase.Message> weaves,
  307. List<AjcTestCase.Message> usages
  308. ) {
  309. if (infos != null) {
  310. this.infos = infos;
  311. ignoreInfos = false;
  312. } else {
  313. this.infos = Collections.emptyList();
  314. }
  315. this.warnings = ((warnings == null) ? Collections.<AjcTestCase.Message>emptyList() : warnings);
  316. this.errors = ((errors == null) ? Collections.<AjcTestCase.Message>emptyList() : errors);
  317. this.fails = ((fails == null) ? Collections.<AjcTestCase.Message>emptyList() : fails);
  318. this.weaves = ((weaves == null) ? Collections.<AjcTestCase.Message>emptyList() : weaves);
  319. this.usages = ((weaves == null) ? Collections.<AjcTestCase.Message>emptyList() : usages);
  320. }
  321. /**
  322. * Create a message specification to test a CompilationResult for a given set of info, warning, and error messages. The
  323. * presence of any fail or abort messages in a CompilationResult will be a test failure.
  324. */
  325. public MessageSpec(List<AjcTestCase.Message> infos, List<AjcTestCase.Message> warnings, List<AjcTestCase.Message> errors) {
  326. this(infos, warnings, errors, null, null, null);
  327. }
  328. /**
  329. * Create a message specification to test a CompilationResult for a given set of warning, and error messages. The presence
  330. * of any fail or abort messages in a CompilationResult will be a test failure. Informational messages will be ignored.
  331. */
  332. public MessageSpec(List<AjcTestCase.Message> warnings, List<AjcTestCase.Message> errors) {
  333. this(null, warnings, errors, null, null, null);
  334. }
  335. }
  336. public static class EmptyMessageSpec extends MessageSpec {
  337. public EmptyMessageSpec() {
  338. super(null, null);
  339. }
  340. }
  341. /**
  342. * Helper class representing the results of running a test program built by the compiler. Provides access to the standard out
  343. * and error of the program, and the actual command that was executed.
  344. */
  345. public static class RunResult {
  346. private final String command;
  347. private final String stdOut;
  348. private final String stdErr;
  349. protected RunResult(String command, String stdOut, String stdErr) {
  350. this.command = command;
  351. this.stdOut = stdOut;
  352. this.stdErr = stdErr;
  353. }
  354. /**
  355. * Return the command that was executed, e.g. "java Driver".
  356. */
  357. public String getCommand() {
  358. return command;
  359. }
  360. /**
  361. * The standard output from the run.
  362. */
  363. public String getStdOut() {
  364. return stdOut;
  365. }
  366. /**
  367. * The standard error from the run.
  368. */
  369. public String getStdErr() {
  370. return stdErr;
  371. }
  372. /**
  373. * Returns the command that was executed to produce this result.
  374. */
  375. @Override
  376. public String toString() {
  377. return command;
  378. }
  379. }
  380. /**
  381. * Assert that no (non-informational) messages where produced during a compiler run.
  382. */
  383. public void assertNoMessages(CompilationResult result) {
  384. assertNoMessages(result, "Not expecting any compiler messages to be produced");
  385. }
  386. /**
  387. * Assert that no (non-informational) messages where produced during a compiler run.
  388. */
  389. public void assertNoMessages(CompilationResult result, String assertionFailedMessage) {
  390. assertMessages(result, assertionFailedMessage, MessageSpec.EMPTY_MESSAGE_SET);
  391. }
  392. /**
  393. * Assert that messages in accordance with the <code>expected</code> message specification where produced during a compiler run.
  394. */
  395. public void assertMessages(CompilationResult result, MessageSpec expected) {
  396. assertMessages(result, "Compilation results did not meet expected messages specification", expected);
  397. }
  398. /**
  399. * Assert that messages in accordance with the <code>expected</code> message specification where produced during a compiler run.
  400. */
  401. public void assertMessages(CompilationResult result, String assertionFailedMessage, MessageSpec expected) {
  402. if (result == null)
  403. fail("Attempt to compare null compilation results against expected.");
  404. List<AjcTestCase.Message> missingFails = copyAll(expected.fails);
  405. List<AjcTestCase.Message> missingInfos = copyAll(expected.infos);
  406. List<AjcTestCase.Message> missingWarnings = copyAll(expected.warnings);
  407. List<AjcTestCase.Message> missingErrors = copyAll(expected.errors);
  408. List<AjcTestCase.Message> missingWeaves = copyAll(expected.weaves);
  409. List<IMessage> extraFails = copyAll(result.getFailMessages());
  410. List<IMessage> extraInfos = copyAll(result.getInfoMessages());
  411. List<IMessage> extraWarnings = copyAll(result.getWarningMessages());
  412. List<IMessage> extraErrors = copyAll(result.getErrorMessages());
  413. List<IMessage> extraWeaves = copyAll(result.getWeaveMessages());
  414. compare(expected.fails, result.getFailMessages(), missingFails, extraFails);
  415. compare(expected.warnings, result.getWarningMessages(), missingWarnings, extraWarnings);
  416. compare(expected.errors, result.getErrorMessages(), missingErrors, extraErrors);
  417. if (!expected.isIgnoringInfoMessages()) {
  418. compare(expected.infos, result.getInfoMessages(), missingInfos, extraInfos);
  419. }
  420. compare(expected.weaves, result.getWeaveMessages(), missingWeaves, extraWeaves);
  421. boolean infosEmpty = expected.isIgnoringInfoMessages() || missingInfos.isEmpty() && extraInfos.isEmpty();
  422. if (!(missingFails.isEmpty() && missingWarnings.isEmpty() && missingErrors.isEmpty() && missingWeaves.isEmpty()
  423. && extraFails.isEmpty() && extraWarnings.isEmpty() && extraErrors.isEmpty() && extraWeaves.isEmpty() && infosEmpty)) {
  424. StringBuilder failureReport = new StringBuilder(assertionFailedMessage);
  425. failureReport.append("\n");
  426. if (!expected.isIgnoringInfoMessages()) {
  427. addMissing(failureReport, "info", missingInfos);
  428. }
  429. addMissing(failureReport, "warning", missingWarnings);
  430. addMissing(failureReport, "error", missingErrors);
  431. addMissing(failureReport, "fail", missingFails);
  432. addMissing(failureReport, "weaveInfo", missingWeaves);
  433. if (!expected.isIgnoringInfoMessages()) {
  434. addExtra(failureReport, "info", extraInfos);
  435. }
  436. addExtra(failureReport, "warning", extraWarnings);
  437. addExtra(failureReport, "error", extraErrors);
  438. addExtra(failureReport, "fail", extraFails);
  439. addExtra(failureReport, "weaveInfo", extraWeaves);
  440. failureReport.append("\nCommand: 'ajc");
  441. String[] args = result.getArgs();
  442. for (String arg : args)
  443. failureReport.append(" ").append(arg);
  444. String report = failureReport.toString();
  445. System.err.println(failureReport);
  446. fail(assertionFailedMessage + "'\n" + report);
  447. }
  448. }
  449. /**
  450. * Helper method to build a new message list for passing to a MessageSpec.
  451. */
  452. protected List<Message> newMessageList(Message m1) {
  453. List<Message> ret = new ArrayList<>();
  454. ret.add(m1);
  455. return ret;
  456. }
  457. /**
  458. * Helper method to build a new message list for passing to a MessageSpec.
  459. */
  460. protected List<Message> newMessageList(Message m1, Message m2) {
  461. List<Message> ret = new ArrayList<>();
  462. ret.add(m1);
  463. ret.add(m2);
  464. return ret;
  465. }
  466. /**
  467. * Helper method to build a new message list for passing to a MessageSpec.
  468. */
  469. protected List<Message> newMessageList(Message m1, Message m2, Message m3) {
  470. List<Message> ret = new ArrayList<>();
  471. ret.add(m1);
  472. ret.add(m2);
  473. ret.add(m3);
  474. return ret;
  475. }
  476. /**
  477. * Helper method to build a new message list for passing to a MessageSpec.
  478. */
  479. protected List newMessageList(Message[] messages) {
  480. List ret = new ArrayList();
  481. Collections.addAll(ret, messages);
  482. return ret;
  483. }
  484. /**
  485. * Perform a compilation and return the result.
  486. *
  487. * @param baseDir the base directory relative to which all relative paths and directories in the arguments will be interpreted.
  488. * @param args the compiler arguments, as you would specify on the command-line. See the Ajc class for a description of the
  489. * argument processing done in order to run the compilation in a sandbox.
  490. * @see org.aspectj.tools.ajc.Ajc
  491. */
  492. public CompilationResult ajc(File baseDir, String[] args) {
  493. try {
  494. ajc.setBaseDir(baseDir);
  495. args = fixupArgs(args);
  496. return ajc.compile(args);
  497. } catch (IOException ioEx) {
  498. fail("IOException thrown during compilation: " + ioEx);
  499. }
  500. return null;
  501. }
  502. public File getSandboxDirectory() {
  503. return ajc.getSandboxDirectory();
  504. }
  505. /**
  506. * Indicate whether or not the sandbox should be emptied before the next compile.
  507. *
  508. * @see org.aspectj.tools.ajc.Ajc#setShouldEmptySandbox(boolean)
  509. */
  510. public void setShouldEmptySandbox(boolean empty) {
  511. ajc.setShouldEmptySandbox(empty);
  512. }
  513. public RunResult getLastRunResult() {
  514. return lastRunResult;
  515. }
  516. /**
  517. * Run the given class (main method), and return the result in a RunResult. The program runs with a classpath containing the
  518. * sandbox directory, runtime, testing-client, bridge, and util projects (all used by the Tester class), and any jars in the
  519. * sandbox.
  520. */
  521. public RunResult run(String className) {
  522. return run(className, new String[0], null);
  523. }
  524. public RunResult run(String className, String[] args, String classpath) {
  525. return run(className, null, args, "", "", null, false,false);
  526. }
  527. /**
  528. * Run the given class, and return the result in a RunResult. The program runs with a classpath containing the sandbox
  529. * directory, runtime, testing-client, bridge, and util projects (all used by the Tester class), and any jars in the sandbox.
  530. *
  531. * @param args the arguments to pass to the program.
  532. * @param classpath the execution classpath, the sandbox directory, runtime, testing-client, bridge, and util projects will all
  533. * be appended to the classpath, as will any jars in the sandbox.
  534. * @param runSpec
  535. */
  536. public RunResult run(String className, String moduleName, String[] args, String vmargs, final String classpath, String modulepath, boolean useLTW, boolean useFullLTW) {
  537. if (args == null)
  538. args = new String[0];
  539. for (int i = 0; i < args.length; i++)
  540. args[i] = substituteSandbox(args[i]);
  541. lastRunResult = null;
  542. StringBuilder cp = new StringBuilder();
  543. if (classpath != null) {
  544. // allow replacing this special variable, rather than copying all files to allow tests of jars that don't end in .jar
  545. cp.append(substituteSandbox(classpath)).append(pathSeparator);
  546. }
  547. if (moduleName == null) {
  548. // When running modules, we want more control so don't try to be helpful by adding all jars
  549. cp.append(ajc.getSandboxDirectory().getAbsolutePath());
  550. getAnyJars(ajc.getSandboxDirectory(), cp);
  551. }
  552. StringBuilder mp = new StringBuilder();
  553. if (modulepath != null)
  554. mp.append(substituteSandbox(modulepath)).append(pathSeparator);
  555. URLClassLoader sandboxLoader;
  556. ClassLoader parentLoader = getClass().getClassLoader().getParent();
  557. /* Sandbox -> AspectJ -> Extension -> Bootstrap */
  558. if ( !useFullLTW && useLTW) {
  559. // URLClassLoader testLoader = (URLClassLoader) getClass().getClassLoader();
  560. /*
  561. * Create a new AspectJ class loader using the existing test CLASSPATH and any missing Java 5 projects
  562. */
  563. URL[] testUrls = new URL[0];//testLoader.getURLs();
  564. // What are the URLs on java 8?
  565. URL[] java5Urls = getURLs(DEFAULT_CLASSPATH_ENTRIES);
  566. URL[] urls = new URL[testUrls.length + java5Urls.length];
  567. System.arraycopy(testUrls, 0, urls, 0, testUrls.length);
  568. System.arraycopy(java5Urls, 0, urls, testUrls.length, java5Urls.length);
  569. // ClassLoader aspectjLoader = new URLClassLoader(getURLs(DEFAULT_CLASSPATH_ENTRIES),parent);
  570. ClassLoader aspectjLoader = new URLClassLoader(urls, parentLoader);
  571. URL[] sandboxUrls = getURLs(cp.toString());
  572. sandboxLoader = createWeavingClassLoader(sandboxUrls, aspectjLoader);
  573. // sandboxLoader = createWeavingClassLoader(sandboxUrls,testLoader);
  574. }
  575. else if(useFullLTW && useLTW) {
  576. if(vmargs == null){
  577. vmargs ="";
  578. }
  579. File directory = new File (".");
  580. String absPath = directory.getAbsolutePath();
  581. String javaagent = absPath + separator + ".." + separator + "lib" + separator + "aspectj" + separator + "lib" + separator + "aspectjweaver.jar";
  582. String defaultCpAbsolute = Arrays.stream(DEFAULT_FULL_LTW_CLASSPATH_ENTRIES.split(pathSeparator))
  583. .map(path -> new File(path).getAbsolutePath())
  584. .collect(Collectors.joining(pathSeparator));
  585. try {
  586. String command =
  587. "java " + vmargs +
  588. " -classpath " + cp + pathSeparator + defaultCpAbsolute +
  589. " -javaagent:" + javaagent + " " +
  590. className + " " + String.join(" ", args);
  591. if (Ajc.verbose)
  592. System.out.println("\nCommand: '" + command + "'\n");
  593. // Command is executed using ProcessBuilder to allow setting CWD for ajc sandbox compliance
  594. ProcessBuilder pb = new ProcessBuilder(tokenizeCommand(command));
  595. pb.directory( new File(ajc.getSandboxDirectory().getAbsolutePath()));
  596. exec = pb.start();
  597. BufferedReader stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream()));
  598. BufferedReader stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream()));
  599. exec.waitFor();
  600. lastRunResult = createResultFromBufferReaders(command,stdInput, stdError);
  601. } catch (Exception e) {
  602. System.out.println("Error executing full LTW test: " + e);
  603. e.printStackTrace();
  604. }
  605. return lastRunResult;
  606. }
  607. else if (moduleName != null) {
  608. // CODE FOR RUNNING MODULES
  609. if(vmargs == null){
  610. vmargs ="";
  611. }
  612. try {
  613. if (mp.indexOf("$runtimemodule") != -1) {
  614. mp = mp.replace(mp.indexOf("$runtimemodule"),"$runtimemodule".length(),TestUtil.aspectjrtPath(true).toString());
  615. }
  616. if (mp.indexOf("$runtime") != -1) {
  617. mp = mp.replace(mp.indexOf("$runtime"),"$runtime".length(),TestUtil.aspectjrtPath().toString());
  618. }
  619. if (cp.indexOf("aspectjrt") == -1)
  620. cp.append(TestUtil.aspectjrtPath().getPath()).append(pathSeparator);
  621. String command = LangUtil.getJavaExecutable().getAbsolutePath() + " " + vmargs + (cp.length() == 0 ? "" : " -classpath " + cp) + " -p " + mp + " --module " + moduleName;
  622. if (Ajc.verbose)
  623. System.out.println("\nCommand: '" + command + "'\n");
  624. // Command is executed using ProcessBuilder to allow setting CWD for ajc sandbox compliance
  625. ProcessBuilder pb = new ProcessBuilder(tokenizeCommand(command));
  626. pb.directory( new File(ajc.getSandboxDirectory().getAbsolutePath()));
  627. exec = pb.start();
  628. BufferedReader stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream()));
  629. BufferedReader stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream()));
  630. exec.waitFor();
  631. lastRunResult = createResultFromBufferReaders(command,stdInput, stdError);
  632. } catch (Exception e) {
  633. System.out.println("Error executing module test: " + e);
  634. e.printStackTrace();
  635. }
  636. return lastRunResult;
  637. }
  638. else if (
  639. vmargs != null && (
  640. vmargs.contains("--enable-preview") ||
  641. vmargs.contains("--add-modules") ||
  642. vmargs.contains("--limit-modules") ||
  643. vmargs.contains("--add-reads") ||
  644. vmargs.contains("--add-exports")
  645. )
  646. ) {
  647. // If --add-modules supplied, need to fork the test
  648. try {
  649. // if (mp.indexOf("$runtime") != -1) {
  650. // mp = mp.replace(mp.indexOf("$runtime"),"$runtime".length(),TestUtil.aspectjrtPath().toString());
  651. // }
  652. if (cp.indexOf("aspectjrt")==-1) {
  653. cp.append(pathSeparator).append(TestUtil.aspectjrtPath().getPath());
  654. }
  655. String command = LangUtil.getJavaExecutable().getAbsolutePath() + " " +vmargs+ (cp.length()==0?"":" -classpath " + cp) + " " + className ;
  656. if (Ajc.verbose)
  657. System.out.println("\nCommand: '" + command + "'\n");
  658. // Command is executed using ProcessBuilder to allow setting CWD for ajc sandbox compliance
  659. ProcessBuilder pb = new ProcessBuilder(tokenizeCommand(command));
  660. pb.directory( new File(ajc.getSandboxDirectory().getAbsolutePath()));
  661. exec = pb.start();
  662. BufferedReader stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream()));
  663. BufferedReader stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream()));
  664. exec.waitFor();
  665. lastRunResult = createResultFromBufferReaders(command,stdInput, stdError);
  666. } catch (Exception e) {
  667. System.out.println("Error executing module test: " + e);
  668. e.printStackTrace();
  669. }
  670. return lastRunResult;
  671. }
  672. else {
  673. cp.append(DEFAULT_CLASSPATH_ENTRIES);
  674. URL[] urls = getURLs(cp.toString());
  675. sandboxLoader = new URLClassLoader(urls, parentLoader);
  676. }
  677. ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
  678. ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
  679. StringBuilder command = new StringBuilder();
  680. command.append("java -classpath ").append(cp).append(" ").append(className);
  681. for (String arg : args)
  682. command.append(" ").append(arg);
  683. if (Ajc.verbose)
  684. System.out.println("\nCommand: '" + command + "'\n");
  685. // try {
  686. // // Enable the security manager
  687. // Policy.setPolicy(new MyPolicy());
  688. // SecurityManager sm = new SecurityManager();
  689. // System.setSecurityManager(sm);
  690. // } catch (SecurityException se) {
  691. // // SecurityManager already set
  692. // }
  693. ClassLoader contexClassLoader = Thread.currentThread().getContextClassLoader();
  694. try {
  695. try {
  696. Class<?> testerClass = sandboxLoader.loadClass("org.aspectj.testing.Tester");
  697. Method setBaseDir = testerClass.getDeclaredMethod("setBASEDIR", new Class[] { File.class });
  698. setBaseDir.invoke(null, new Object[] { ajc.getSandboxDirectory() });
  699. } catch (InvocationTargetException itEx) {
  700. fail("Unable to prepare org.aspectj.testing.Tester for test run: " + itEx.getTargetException());
  701. } catch (Exception ex) {
  702. fail("Unable to prepare org.aspectj.testing.Tester for test run: " + ex);
  703. }
  704. startCapture(baosErr, baosOut);
  705. /* Frameworks like XML use context class loader for dynamic loading */
  706. Thread.currentThread().setContextClassLoader(sandboxLoader);
  707. Class<?> toRun = sandboxLoader.loadClass(className);
  708. Method mainMethod = toRun.getMethod("main", String[].class);
  709. // Since JDK 21, a public main method of a non-public (e.g. default-scoped) class can no longer be invoked without
  710. // making it accessible first. Because many test sources contain multiple aspects and classes in one file, this is
  711. // a frequent use case.
  712. mainMethod.setAccessible(true);
  713. mainMethod.invoke(null, new Object[] { args });
  714. } catch (ClassNotFoundException cnf) {
  715. fail("Can't find class: " + className);
  716. } catch (NoSuchMethodException nsm) {
  717. fail(className + " does not have a main method");
  718. } catch (IllegalAccessException illEx) {
  719. fail("main method in class " + className + " is not public");
  720. } catch (InvocationTargetException invTgt) {
  721. // the main method threw an exception...
  722. fail("Exception thrown by " + className + ".main(String[]) :" + invTgt.getTargetException());
  723. } finally {
  724. // try {
  725. // // Enable the security manager
  726. // SecurityManager sm = new SecurityManager();
  727. // System.setSecurityManager(null);
  728. // } catch (SecurityException se) {
  729. // se.printStackTrace();
  730. // // SecurityManager already set
  731. // }
  732. Thread.currentThread().setContextClassLoader(contexClassLoader);
  733. stopCapture(baosErr, baosOut);
  734. lastRunResult = new RunResult(command.toString(), new String(baosOut.toByteArray()), new String(baosErr.toByteArray()));
  735. }
  736. return lastRunResult;
  737. }
  738. private List<String >tokenizeCommand(String command) {
  739. StringTokenizer st = new StringTokenizer(command," ", false);
  740. List<String> arguments = new ArrayList<>();
  741. while(st.hasMoreElements()){
  742. String nextToken =st.nextToken();
  743. arguments.add(nextToken);
  744. }
  745. return arguments;
  746. }
  747. private RunResult createResultFromBufferReaders(String command,
  748. BufferedReader stdInput, BufferedReader stdError) throws IOException {
  749. String line = "";
  750. ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
  751. ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
  752. PrintWriter stdOutWriter = new PrintWriter(baosOut);
  753. PrintWriter stdErrWriter = new PrintWriter(baosErr);
  754. if (Ajc.verbose) {
  755. System.out.println();
  756. }
  757. while ((line = stdInput.readLine()) != null) {
  758. stdOutWriter.println(line);
  759. if (Ajc.verbose) {
  760. System.out.println(line);
  761. }
  762. }
  763. stdOutWriter.flush();
  764. while ((line = stdError.readLine()) != null) {
  765. stdErrWriter.println(line);
  766. if (Ajc.verbose) {
  767. System.err.println(line);
  768. }
  769. }
  770. stdErrWriter.flush();
  771. baosOut.close();
  772. baosErr.close();
  773. return new RunResult(command.toString(), new String(baosOut.toByteArray()), new String(baosErr.toByteArray()));
  774. }
  775. // static class MyPolicy extends Policy {
  776. //
  777. // @Override
  778. // public boolean implies(ProtectionDomain domain, Permission permission) {
  779. // // if (permission != SecurityConstants.GET_POLICY_PERMISSION) {
  780. // // // System.out.println(domain + " " + permission.getName());
  781. // // System.out.println(permission.getName());
  782. // // }
  783. // // if (true) {
  784. // // return true;
  785. // // }
  786. // if (permission instanceof PropertyPermission) {
  787. // return true;
  788. // }
  789. // if (permission instanceof RuntimePermission) {
  790. // return true;
  791. // }
  792. // if (permission instanceof FilePermission) {
  793. // // System.out.println(permission);
  794. // return true;
  795. // }
  796. // if (permission instanceof ReflectPermission) {
  797. // return true;
  798. // }
  799. // // System.out.println(permission);
  800. // return super.implies(domain, permission);
  801. // // return true;
  802. // }
  803. // }
  804. /*
  805. * Must create weaving class loader reflectively using new parent so we don't have a reference to a World loaded from CLASSPATH
  806. * which won't be able to resolve Java 5 specific extensions and may cause ClassCastExceptions
  807. */
  808. private URLClassLoader createWeavingClassLoader(URL[] urls, ClassLoader parent) {
  809. URLClassLoader loader = null;
  810. try {
  811. Class loaderClazz = Class.forName("org.aspectj.weaver.loadtime.WeavingURLClassLoader", false, parent);
  812. Class[] parameterTypes = new Class[] { urls.getClass(), ClassLoader.class };
  813. Object[] parameters = new Object[] { urls, parent };
  814. Constructor constructor = loaderClazz.getConstructor(parameterTypes);
  815. loader = (URLClassLoader) constructor.newInstance(parameters);
  816. } catch (InvocationTargetException ex) {
  817. ex.printStackTrace();
  818. fail("Cannot create weaving class loader: " + ex.getTargetException());
  819. } catch (Exception ex) {
  820. ex.printStackTrace();
  821. fail("Cannot create weaving class loader: " + ex.toString());
  822. }
  823. return loader;
  824. }
  825. private URL[] getURLs(String classpath) {
  826. StringTokenizer strTok = new StringTokenizer(classpath, pathSeparator);
  827. URL[] urls = new URL[strTok.countTokens()];
  828. try {
  829. for (int i = 0; i < urls.length; i++) {
  830. urls[i] = new File(strTok.nextToken()).getCanonicalFile().toURI().toURL();
  831. }
  832. } catch (Exception malEx) {
  833. fail("Bad classpath specification: " + classpath);
  834. }
  835. return urls;
  836. }
  837. private String substituteSandbox(String path) {
  838. // the longhand form of the non 1.3 API: path.replace("$sandbox", ajc.getSandboxDirectory().getAbsolutePath());
  839. while (path.contains("$sandbox")) {
  840. int pos = path.indexOf("$sandbox");
  841. String firstbit = path.substring(0, pos);
  842. String endbit = path.substring(pos + 8);
  843. path = firstbit + ajc.getSandboxDirectory().getAbsolutePath() + endbit;
  844. }
  845. return path;
  846. }
  847. /**
  848. * Any central pre-processing of args. This supplies aspectjrt.jar if available and classpath not set.
  849. *
  850. * @param args the String[] args to fix up
  851. * @return the String[] args to use
  852. */
  853. protected String[] fixupArgs(String[] args) {
  854. if (null == args) {
  855. return null;
  856. }
  857. int cpIndex = -1;
  858. boolean hasruntime = false;
  859. for (int i = 0; i < args.length - 1; i++) {
  860. args[i] = adaptToPlatform(args[i]);
  861. if ("-classpath".equals(args[i])) {
  862. cpIndex = i;
  863. args[i + 1] = substituteSandbox(args[i + 1]);
  864. String next = args[i + 1];
  865. hasruntime = ((null != next) && (next.contains("aspectjrt.jar")));
  866. } else if ("-p".equals(args[i]) || "--module-path".equals(args[i])) {
  867. args[i + 1] = substituteSandbox(args[i + 1]);
  868. }
  869. }
  870. if (-1 == cpIndex) {
  871. String[] newargs = new String[args.length + 2];
  872. newargs[0] = "-classpath";
  873. newargs[1] = TestUtil.aspectjrtPath(false).getPath();
  874. System.arraycopy(args, 0, newargs, 2, args.length);
  875. args = newargs;
  876. cpIndex = 1;
  877. } else {
  878. if (!hasruntime) {
  879. cpIndex++;
  880. String[] newargs = new String[args.length];
  881. System.arraycopy(args, 0, newargs, 0, args.length);
  882. newargs[cpIndex] = args[cpIndex] + pathSeparator + TestUtil.aspectjrtPath().getPath();
  883. args = newargs;
  884. }
  885. }
  886. boolean needsJRTFS = LangUtil.is9VMOrGreater();
  887. if (needsJRTFS) {
  888. if (!args[cpIndex].contains(LangUtil.JRT_FS)) {
  889. String jrtfsPath = LangUtil.getJrtFsFilePath();
  890. args[cpIndex] = jrtfsPath + pathSeparator + args[cpIndex];
  891. }
  892. }
  893. return args;
  894. }
  895. private String adaptToPlatform(String s) {
  896. String ret = s.replace(';', File.pathSeparatorChar);
  897. // ret = ret.replace(':',File.pathSeparatorChar);
  898. return ret;
  899. }
  900. private <T> List<T> copyAll(List<T> in) {
  901. if (in == Collections.EMPTY_LIST)
  902. return in;
  903. List<T> out = new ArrayList<>();
  904. for (T t : in) {
  905. out.add(t);
  906. }
  907. return out;
  908. }
  909. /**
  910. * Compare the set of expected messages against the set of actual messages, leaving in missingElements the set of messages that
  911. * were expected but did not occur, and in extraElements the set of messages that occured but were not excpected
  912. *
  913. * @param expected the expected messages
  914. * @param actual the actual messages
  915. * @param missingElements the missing messages, when passed in must contain all of the expected messages
  916. * @param extraElements the additional messages, when passed in must contain all of the actual messages
  917. */
  918. private void compare(List<AjcTestCase.Message> expected, List<IMessage> actual, List<AjcTestCase.Message> missingElements, List<IMessage> extraElements) {
  919. for (Message expectedMessage: expected) {
  920. for (IMessage actualMessage: actual) {
  921. if (expectedMessage.matches(actualMessage)) {
  922. if (expectedMessage.careAboutOtherMessages) {
  923. missingElements.remove(expectedMessage);
  924. extraElements.remove(actualMessage);
  925. }
  926. else {
  927. missingElements.clear();
  928. extraElements.clear();
  929. }
  930. }
  931. }
  932. }
  933. }
  934. private void addMissing(StringBuilder buff, String type, List<AjcTestCase.Message> messages) {
  935. if (!messages.isEmpty()) {
  936. buff.append("Missing expected ").append(type).append(" messages:\n");
  937. for (Message message : messages)
  938. buff.append("\t").append(message.toString()).append("\n");
  939. }
  940. }
  941. private void addExtra(StringBuilder buff, String type, List messages) {
  942. if (!messages.isEmpty()) {
  943. buff.append("Unexpected ").append(type).append(" messages:\n");
  944. for (Object message : messages)
  945. buff.append("\t").append(message.toString()).append("\n");
  946. }
  947. }
  948. // add any jars in the directory to the classpath
  949. private void getAnyJars(File dir, StringBuilder buff) {
  950. File[] files = dir.listFiles();
  951. for (File file : files) {
  952. if (file.getName().endsWith(".jar"))
  953. buff.append(pathSeparator).append(file.getAbsolutePath());
  954. else if (file.isDirectory())
  955. getAnyJars(file, buff);
  956. }
  957. }
  958. private static void startCapture(OutputStream errOS, OutputStream outOS) {
  959. delegatingErr.add(errOS);
  960. delegatingOut.add(outOS);
  961. delegatingErr.setVerbose(DEFAULT_ERR_VERBOSE);
  962. delegatingOut.setVerbose(DEFAULT_OUT_VERBOSE);
  963. }
  964. private static void stopCapture(OutputStream errOS, OutputStream outOS) {
  965. delegatingErr.setVerbose(true);
  966. delegatingOut.setVerbose(true);
  967. delegatingErr.remove(errOS);
  968. delegatingOut.remove(outOS);
  969. }
  970. private static boolean getBoolean(String name, boolean def) {
  971. String defaultValue = String.valueOf(def);
  972. String value = System.getProperty(name, defaultValue);
  973. return Boolean.parseBoolean(value);
  974. }
  975. /*
  976. * (non-Javadoc)
  977. *
  978. * @see junit.framework.TestCase#setUp()
  979. */
  980. @Override
  981. protected void setUp() throws Exception {
  982. super.setUp();
  983. ajc = new Ajc();
  984. }
  985. /*
  986. * (non-Javadoc)
  987. *
  988. * @see junit.framework.TestCase#tearDown()
  989. */
  990. @Override
  991. protected void tearDown() throws Exception {
  992. super.tearDown();
  993. // ajc = null;
  994. }
  995. static {
  996. // new RuntimeException("*** AjcTestCase.<clinit>()").printStackTrace();
  997. delegatingErr = new DelegatingOutputStream(err);
  998. System.setErr(new PrintStream(delegatingErr));
  999. delegatingOut = new DelegatingOutputStream(out);
  1000. System.setOut(new PrintStream(delegatingOut));
  1001. }
  1002. }