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

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