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

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