選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

XMLBasedAjcTestCase.java 16KB

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