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

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