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

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