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.

XMLBasedAjcTestCase.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Adrian Colyer,
  11. * ******************************************************************/
  12. package org.aspectj.testing;
  13. import java.io.File;
  14. import java.io.FileInputStream;
  15. import java.io.FilenameFilter;
  16. import java.io.InputStreamReader;
  17. import java.util.ArrayList;
  18. import java.util.Collections;
  19. import java.util.Comparator;
  20. import java.util.HashMap;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Stack;
  24. import junit.extensions.TestSetup;
  25. import junit.framework.Test;
  26. import junit.framework.TestSuite;
  27. import org.apache.commons.digester.Digester;
  28. import org.aspectj.apache.bcel.classfile.JavaClass;
  29. import org.aspectj.apache.bcel.classfile.LocalVariable;
  30. import org.aspectj.apache.bcel.classfile.LocalVariableTable;
  31. import org.aspectj.apache.bcel.classfile.Method;
  32. import org.aspectj.apache.bcel.util.ClassPath;
  33. import org.aspectj.apache.bcel.util.SyntheticRepository;
  34. import org.aspectj.tools.ajc.AjcTestCase;
  35. import org.aspectj.tools.ajc.CompilationResult;
  36. import org.aspectj.util.FileUtil;
  37. /**
  38. * Root class for all Test suites that are based on an AspectJ XML test suite file. Extends AjcTestCase allowing a mix of
  39. * programmatic and spec-file driven testing. See org.aspectj.systemtest.incremental.IncrementalTests for an example of this mixed
  40. * style.
  41. * <p>
  42. * The class org.aspectj.testing.MakeTestClass will generate a subclass of this class for you, given a suite spec. file as input...
  43. * </p>
  44. */
  45. public abstract class XMLBasedAjcTestCase extends AjcTestCase {
  46. private static Map testMap = new HashMap();
  47. private static boolean suiteLoaded = false;
  48. private AjcTest currentTest = null;
  49. private Stack clearTestAfterRun = new Stack();
  50. public XMLBasedAjcTestCase() {
  51. }
  52. /**
  53. * You must define a suite() method in subclasses, and return the result of calling this method. (Don't you hate static methods
  54. * in programming models). For example:
  55. *
  56. * <pre>
  57. * public static Test suite() {
  58. * return XMLBasedAjcTestCase.loadSuite(MyTestCaseClass.class);
  59. * }
  60. * </pre>
  61. *
  62. * @param testCaseClass
  63. * @return
  64. */
  65. public static Test loadSuite(Class testCaseClass) {
  66. TestSuite suite = new TestSuite(testCaseClass.getName());
  67. suite.addTestSuite(testCaseClass);
  68. TestSetup wrapper = new TestSetup(suite) {
  69. /*
  70. * (non-Javadoc)
  71. *
  72. * @see junit.extensions.TestSetup#setUp()
  73. */
  74. protected void setUp() throws Exception {
  75. super.setUp();
  76. suiteLoaded = false;
  77. }
  78. /*
  79. * (non-Javadoc)
  80. *
  81. * @see junit.extensions.TestSetup#tearDown()
  82. */
  83. protected void tearDown() throws Exception {
  84. super.tearDown();
  85. suiteLoaded = false;
  86. }
  87. };
  88. return wrapper;
  89. }
  90. /**
  91. * The file containing the XML specification for the tests.
  92. */
  93. protected abstract File getSpecFile();
  94. /*
  95. * Return a map from (String) test title -> AjcTest
  96. */
  97. protected Map getSuiteTests() {
  98. return testMap;
  99. }
  100. /**
  101. * This helper method runs the test with the given title in the suite spec file. All tests steps in given ajc-test execute in
  102. * the same sandbox.
  103. */
  104. protected void runTest(String title, boolean print) {
  105. try {
  106. currentTest = (AjcTest) testMap.get(title);
  107. final boolean clearTest = clearTestAfterRun();
  108. if (currentTest == null) {
  109. if (clearTest) {
  110. System.err.println("test already run: " + title);
  111. return;
  112. } else {
  113. fail("No test '" + title + "' in suite.");
  114. }
  115. }
  116. boolean run = currentTest.runTest(this);
  117. assertTrue("Test not run", run);
  118. if (clearTest) {
  119. testMap.remove(title);
  120. }
  121. } finally {
  122. if (print) {
  123. System.out.println("SYSOUT");
  124. System.out.println(ajc.getLastCompilationResult().getStandardOutput());
  125. }
  126. }
  127. }
  128. protected void runTest(String title) {
  129. runTest(title, false);
  130. }
  131. /**
  132. * Get the currently executing test. Useful for access to e.g. AjcTest.getTitle() etc..
  133. */
  134. protected AjcTest getCurrentTest() {
  135. return currentTest;
  136. }
  137. /**
  138. * For use by the Digester. As the XML document is parsed, it creates instances of AjcTest objects, which are added to this
  139. * TestCase by the Digester by calling this method.
  140. */
  141. public void addTest(AjcTest test) {
  142. testMap.put(test.getTitle(), test);
  143. }
  144. protected final void pushClearTestAfterRun(boolean val) {
  145. clearTestAfterRun.push(val ? Boolean.FALSE : Boolean.TRUE);
  146. }
  147. protected final boolean popClearTestAfterRun() {
  148. return clearTest(true);
  149. }
  150. protected final boolean clearTestAfterRun() {
  151. return clearTest(false);
  152. }
  153. private boolean clearTest(boolean pop) {
  154. if (clearTestAfterRun.isEmpty()) {
  155. return false;
  156. }
  157. boolean result = ((Boolean) clearTestAfterRun.peek()).booleanValue();
  158. if (pop) {
  159. clearTestAfterRun.pop();
  160. }
  161. return result;
  162. }
  163. /*
  164. * The rules for parsing a suite spec file. The Digester using bean properties to match attributes in the XML document to
  165. * properties in the associated classes, so this simple implementation should be very easy to maintain and extend should you
  166. * ever need to.
  167. */
  168. protected Digester getDigester() {
  169. Digester digester = new Digester();
  170. digester.push(this);
  171. digester.addObjectCreate("suite/ajc-test", AjcTest.class);
  172. digester.addSetProperties("suite/ajc-test");
  173. digester.addSetNext("suite/ajc-test", "addTest", "org.aspectj.testing.AjcTest");
  174. digester.addObjectCreate("suite/ajc-test/compile", CompileSpec.class);
  175. digester.addSetProperties("suite/ajc-test/compile");
  176. digester.addSetNext("suite/ajc-test/compile", "addTestStep", "org.aspectj.testing.ITestStep");
  177. digester.addObjectCreate("suite/ajc-test/file", FileSpec.class);
  178. digester.addSetProperties("suite/ajc-test/file");
  179. digester.addSetNext("suite/ajc-test/file", "addTestStep", "org.aspectj.testing.ITestStep");
  180. digester.addObjectCreate("suite/ajc-test/run", RunSpec.class);
  181. digester.addSetProperties("suite/ajc-test/run", "class", "classToRun");
  182. digester.addSetProperties("suite/ajc-test/run", "ltw", "ltwFile");
  183. digester.addSetProperties("suite/ajc-test/run", "xlintfile", "xlintFile");
  184. digester.addSetProperties("suite/ajc-test/run/stderr", "ordered", "orderedStderr");
  185. digester.addSetNext("suite/ajc-test/run", "addTestStep", "org.aspectj.testing.ITestStep");
  186. digester.addObjectCreate("*/message", ExpectedMessageSpec.class);
  187. digester.addSetProperties("*/message");
  188. digester.addSetNext("*/message", "addExpectedMessage", "org.aspectj.testing.ExpectedMessageSpec");
  189. digester.addObjectCreate("suite/ajc-test/weave", WeaveSpec.class);
  190. digester.addSetProperties("suite/ajc-test/weave");
  191. digester.addSetNext("suite/ajc-test/weave", "addTestStep", "org.aspectj.testing.ITestStep");
  192. digester.addObjectCreate("suite/ajc-test/ant", AntSpec.class);
  193. digester.addSetProperties("suite/ajc-test/ant");
  194. digester.addSetNext("suite/ajc-test/ant", "addTestStep", "org.aspectj.testing.ITestStep");
  195. digester.addObjectCreate("suite/ajc-test/ant/stderr", OutputSpec.class);
  196. digester.addSetProperties("suite/ajc-test/ant/stderr");
  197. digester.addSetNext("suite/ajc-test/ant/stderr", "addStdErrSpec", "org.aspectj.testing.OutputSpec");
  198. digester.addObjectCreate("suite/ajc-test/ant/stdout", OutputSpec.class);
  199. digester.addSetProperties("suite/ajc-test/ant/stdout");
  200. digester.addSetNext("suite/ajc-test/ant/stdout", "addStdOutSpec", "org.aspectj.testing.OutputSpec");
  201. digester.addObjectCreate("suite/ajc-test/run/stderr", OutputSpec.class);
  202. digester.addSetProperties("suite/ajc-test/run/stderr");
  203. digester.addSetNext("suite/ajc-test/run/stderr", "addStdErrSpec", "org.aspectj.testing.OutputSpec");
  204. digester.addObjectCreate("suite/ajc-test/run/stdout", OutputSpec.class);
  205. digester.addSetProperties("suite/ajc-test/run/stdout");
  206. digester.addSetNext("suite/ajc-test/run/stdout", "addStdOutSpec", "org.aspectj.testing.OutputSpec");
  207. digester.addObjectCreate("*/line", OutputLine.class);
  208. digester.addSetProperties("*/line");
  209. digester.addSetNext("*/line", "addLine", "org.aspectj.testing.OutputLine");
  210. return digester;
  211. }
  212. /*
  213. * (non-Javadoc)
  214. *
  215. * @see org.aspectj.tools.ajc.AjcTestCase#setUp()
  216. */
  217. protected void setUp() throws Exception {
  218. super.setUp();
  219. if (!suiteLoaded) {
  220. testMap = new HashMap();
  221. System.out.println("LOADING SUITE: " + getSpecFile().getPath());
  222. Digester d = getDigester();
  223. try {
  224. InputStreamReader isr = new InputStreamReader(new FileInputStream(getSpecFile()));
  225. d.parse(isr);
  226. } catch (Exception ex) {
  227. fail("Unable to load suite " + getSpecFile().getPath() + " : " + ex);
  228. }
  229. suiteLoaded = true;
  230. }
  231. }
  232. protected long nextIncrement(boolean doWait) {
  233. long time = System.currentTimeMillis();
  234. if (doWait) {
  235. try {
  236. Thread.sleep(1000);
  237. } catch (InterruptedException intEx) {
  238. }
  239. }
  240. return time;
  241. }
  242. protected void copyFile(String from, String to) throws Exception {
  243. String dir = getCurrentTest().getDir();
  244. FileUtil.copyFile(new File(dir + File.separator + from), new File(ajc.getSandboxDirectory(), to));
  245. }
  246. protected void copyFileAndDoIncrementalBuild(String from, String to) throws Exception {
  247. copyFile(from, to);
  248. CompilationResult result = ajc.doIncrementalCompile();
  249. assertNoMessages(result, "Expected clean compile from test '" + getCurrentTest().getTitle() + "'");
  250. }
  251. protected void copyFileAndDoIncrementalBuild(String from, String to, MessageSpec expectedResults) throws Exception {
  252. String dir = getCurrentTest().getDir();
  253. FileUtil.copyFile(new File(dir + File.separator + from), new File(ajc.getSandboxDirectory(), to));
  254. CompilationResult result = ajc.doIncrementalCompile();
  255. assertMessages(result, "Test '" + getCurrentTest().getTitle() + "' did not produce expected messages", expectedResults);
  256. }
  257. protected void deleteFile(String file) {
  258. new File(ajc.getSandboxDirectory(), file).delete();
  259. }
  260. protected void deleteFileAndDoIncrementalBuild(String file, MessageSpec expectedResult) throws Exception {
  261. deleteFile(file);
  262. CompilationResult result = ajc.doIncrementalCompile();
  263. assertMessages(result, "Test '" + getCurrentTest().getTitle() + "' did not produce expected messages", expectedResult);
  264. }
  265. protected void deleteFileAndDoIncrementalBuild(String file) throws Exception {
  266. deleteFileAndDoIncrementalBuild(file, MessageSpec.EMPTY_MESSAGE_SET);
  267. }
  268. protected void assertAdded(String file) {
  269. assertTrue("File " + file + " should have been added", new File(ajc.getSandboxDirectory(), file).exists());
  270. }
  271. protected void assertDeleted(String file) {
  272. assertFalse("File " + file + " should have been deleted", new File(ajc.getSandboxDirectory(), file).exists());
  273. }
  274. protected void assertUpdated(String file, long sinceTime) {
  275. File f = new File(ajc.getSandboxDirectory(), file);
  276. assertTrue("File " + file + " should have been updated", f.lastModified() > sinceTime);
  277. }
  278. public SyntheticRepository createRepos(File cpentry) {
  279. ClassPath cp = new ClassPath(cpentry + File.pathSeparator + System.getProperty("java.class.path"));
  280. return SyntheticRepository.getInstance(cp);
  281. }
  282. public JavaClass getClassFrom(File where, String clazzname) throws ClassNotFoundException {
  283. SyntheticRepository repos = createRepos(where);
  284. return repos.loadClass(clazzname);
  285. }
  286. protected Method getMethodStartsWith(JavaClass jc, String prefix) {
  287. return getMethodStartsWith(jc,prefix,1);
  288. }
  289. protected Method getMethodStartsWith(JavaClass jc, String prefix, int whichone) {
  290. Method[] meths = jc.getMethods();
  291. for (int i = 0; i < meths.length; i++) {
  292. Method method = meths[i];
  293. System.out.println(method);
  294. if (method.getName().startsWith(prefix)) {
  295. whichone--;
  296. if (whichone==0) {
  297. return method;
  298. }
  299. }
  300. }
  301. return null;
  302. }
  303. /**
  304. * Sort it by name then start position
  305. */
  306. public List<LocalVariable> sortedLocalVariables(LocalVariableTable lvt) {
  307. List<LocalVariable> l = new ArrayList<LocalVariable>();
  308. LocalVariable lv[] = lvt.getLocalVariableTable();
  309. for (int i = 0; i < lv.length; i++) {
  310. LocalVariable lvEntry = lv[i];
  311. l.add(lvEntry);
  312. }
  313. Collections.sort(l, new MyComparator());
  314. return l;
  315. }
  316. public String stringify(LocalVariableTable lvt, int slotIndex) {
  317. LocalVariable lv[] = lvt.getLocalVariableTable();
  318. LocalVariable lvEntry = lv[slotIndex];
  319. StringBuffer sb = new StringBuffer();
  320. sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex())
  321. .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength());
  322. return sb.toString();
  323. }
  324. public String stringify(List<LocalVariable> l, int slotIndex) {
  325. LocalVariable lvEntry = (LocalVariable) l.get(slotIndex);
  326. StringBuffer sb = new StringBuffer();
  327. sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex())
  328. .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength());
  329. return sb.toString();
  330. }
  331. public String stringify(LocalVariableTable lvt) {
  332. if (lvt == null) {
  333. return "";
  334. }
  335. StringBuffer sb = new StringBuffer();
  336. sb.append("LocalVariableTable. Entries=#" + lvt.getTableLength()).append("\n");
  337. LocalVariable lv[] = lvt.getLocalVariableTable();
  338. for (int i = 0; i < lv.length; i++) {
  339. LocalVariable lvEntry = lv[i];
  340. sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex())
  341. .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength()).append("\n");
  342. }
  343. return sb.toString();
  344. }
  345. public static class CountingFilenameFilter implements FilenameFilter {
  346. private String suffix;
  347. private int count;
  348. public CountingFilenameFilter(String s) {
  349. this.suffix = s;
  350. }
  351. public boolean accept(File dir, String name) {
  352. if (name.endsWith(suffix)) {
  353. count++;
  354. }
  355. return false;
  356. }
  357. public int getCount() {
  358. return count;
  359. }
  360. }
  361. public static class MyComparator implements Comparator<LocalVariable> {
  362. public int compare(LocalVariable o1, LocalVariable o2) {
  363. LocalVariable l1 = (LocalVariable) o1;
  364. LocalVariable l2 = (LocalVariable) o2;
  365. if (l1.getName().equals(l2.getName())) {
  366. return l1.getStartPC() - l2.getStartPC();
  367. } else {
  368. return l1.getName().compareTo(l2.getName());
  369. }
  370. }
  371. }
  372. }