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

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