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

XMLBasedAjcTestCase.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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.ResolvedMember;
  41. import org.aspectj.weaver.ResolvedType;
  42. import org.aspectj.weaver.WeaverStateInfo;
  43. import org.aspectj.weaver.AjAttribute.WeaverState;
  44. import org.aspectj.weaver.AjAttribute.WeaverVersionInfo;
  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. /*
  192. * The rules for parsing a suite spec file. The Digester using bean properties to match attributes in the XML document to
  193. * properties in the associated classes, so this simple implementation should be very easy to maintain and extend should you
  194. * ever need to.
  195. */
  196. protected Digester getDigester() {
  197. Digester digester = new Digester();
  198. digester.push(this);
  199. digester.addObjectCreate("suite/ajc-test", AjcTest.class);
  200. digester.addSetProperties("suite/ajc-test");
  201. digester.addSetNext("suite/ajc-test", "addTest", "org.aspectj.testing.AjcTest");
  202. digester.addObjectCreate("suite/ajc-test/compile", CompileSpec.class);
  203. digester.addSetProperties("suite/ajc-test/compile");
  204. digester.addSetNext("suite/ajc-test/compile", "addTestStep", "org.aspectj.testing.ITestStep");
  205. digester.addObjectCreate("suite/ajc-test/file", FileSpec.class);
  206. digester.addSetProperties("suite/ajc-test/file");
  207. digester.addSetNext("suite/ajc-test/file", "addTestStep", "org.aspectj.testing.ITestStep");
  208. digester.addObjectCreate("suite/ajc-test/run", RunSpec.class);
  209. digester.addSetProperties("suite/ajc-test/run", "class", "classToRun");
  210. digester.addSetProperties("suite/ajc-test/run", "module", "moduleToRun");
  211. digester.addSetProperties("suite/ajc-test/run", "ltw", "ltwFile");
  212. digester.addSetProperties("suite/ajc-test/run", "xlintfile", "xlintFile");
  213. digester.addSetProperties("suite/ajc-test/run/stderr", "ordered", "orderedStderr");
  214. digester.addSetNext("suite/ajc-test/run", "addTestStep", "org.aspectj.testing.ITestStep");
  215. digester.addObjectCreate("*/message", ExpectedMessageSpec.class);
  216. digester.addSetProperties("*/message");
  217. digester.addSetNext("*/message", "addExpectedMessage", "org.aspectj.testing.ExpectedMessageSpec");
  218. digester.addObjectCreate("suite/ajc-test/weave", WeaveSpec.class);
  219. digester.addSetProperties("suite/ajc-test/weave");
  220. digester.addSetNext("suite/ajc-test/weave", "addTestStep", "org.aspectj.testing.ITestStep");
  221. digester.addObjectCreate("suite/ajc-test/ant", AntSpec.class);
  222. digester.addSetProperties("suite/ajc-test/ant");
  223. digester.addSetNext("suite/ajc-test/ant", "addTestStep", "org.aspectj.testing.ITestStep");
  224. digester.addObjectCreate("suite/ajc-test/ant/stderr", OutputSpec.class);
  225. digester.addSetProperties("suite/ajc-test/ant/stderr");
  226. digester.addSetNext("suite/ajc-test/ant/stderr", "addStdErrSpec", "org.aspectj.testing.OutputSpec");
  227. digester.addObjectCreate("suite/ajc-test/ant/stdout", OutputSpec.class);
  228. digester.addSetProperties("suite/ajc-test/ant/stdout");
  229. digester.addSetNext("suite/ajc-test/ant/stdout", "addStdOutSpec", "org.aspectj.testing.OutputSpec");
  230. digester.addObjectCreate("suite/ajc-test/run/stderr", OutputSpec.class);
  231. digester.addSetProperties("suite/ajc-test/run/stderr");
  232. digester.addSetNext("suite/ajc-test/run/stderr", "addStdErrSpec", "org.aspectj.testing.OutputSpec");
  233. digester.addObjectCreate("suite/ajc-test/run/stdout", OutputSpec.class);
  234. digester.addSetProperties("suite/ajc-test/run/stdout");
  235. digester.addSetNext("suite/ajc-test/run/stdout", "addStdOutSpec", "org.aspectj.testing.OutputSpec");
  236. digester.addObjectCreate("*/line", OutputLine.class);
  237. digester.addSetProperties("*/line");
  238. digester.addSetNext("*/line", "addLine", "org.aspectj.testing.OutputLine");
  239. return digester;
  240. }
  241. /*
  242. * (non-Javadoc)
  243. *
  244. * @see org.aspectj.tools.ajc.AjcTestCase#setUp()
  245. */
  246. protected void setUp() throws Exception {
  247. super.setUp();
  248. if (!suiteLoaded) {
  249. testMap = new HashMap<String,AjcTest>();
  250. System.out.println("LOADING SUITE: " + getSpecFile().getPath());
  251. Digester d = getDigester();
  252. try {
  253. InputStreamReader isr = new InputStreamReader(getSpecFile().openConnection().getInputStream());
  254. d.parse(isr);
  255. } catch (Exception ex) {
  256. fail("Unable to load suite " + getSpecFile().getPath() + " : " + ex);
  257. }
  258. suiteLoaded = true;
  259. }
  260. }
  261. protected long nextIncrement(boolean doWait) {
  262. long time = System.currentTimeMillis();
  263. if (doWait) {
  264. try {
  265. Thread.sleep(1000);
  266. } catch (InterruptedException intEx) {
  267. }
  268. }
  269. return time;
  270. }
  271. protected void copyFile(String from, String to) throws Exception {
  272. String dir = getCurrentTest().getDir();
  273. FileUtil.copyFile(new File(dir + File.separator + from), new File(ajc.getSandboxDirectory(), to));
  274. }
  275. protected void copyFileAndDoIncrementalBuild(String from, String to) throws Exception {
  276. copyFile(from, to);
  277. CompilationResult result = ajc.doIncrementalCompile();
  278. assertNoMessages(result, "Expected clean compile from test '" + getCurrentTest().getTitle() + "'");
  279. }
  280. protected void copyFileAndDoIncrementalBuild(String from, String to, MessageSpec expectedResults) throws Exception {
  281. String dir = getCurrentTest().getDir();
  282. FileUtil.copyFile(new File(dir + File.separator + from), new File(ajc.getSandboxDirectory(), to));
  283. CompilationResult result = ajc.doIncrementalCompile();
  284. assertMessages(result, "Test '" + getCurrentTest().getTitle() + "' did not produce expected messages", expectedResults);
  285. }
  286. protected void deleteFile(String file) {
  287. new File(ajc.getSandboxDirectory(), file).delete();
  288. }
  289. protected void deleteFileAndDoIncrementalBuild(String file, MessageSpec expectedResult) throws Exception {
  290. deleteFile(file);
  291. CompilationResult result = ajc.doIncrementalCompile();
  292. assertMessages(result, "Test '" + getCurrentTest().getTitle() + "' did not produce expected messages", expectedResult);
  293. }
  294. protected void deleteFileAndDoIncrementalBuild(String file) throws Exception {
  295. deleteFileAndDoIncrementalBuild(file, MessageSpec.EMPTY_MESSAGE_SET);
  296. }
  297. protected void assertAdded(String file) {
  298. assertTrue("File " + file + " should have been added", new File(ajc.getSandboxDirectory(), file).exists());
  299. }
  300. protected void assertDeleted(String file) {
  301. assertFalse("File " + file + " should have been deleted", new File(ajc.getSandboxDirectory(), file).exists());
  302. }
  303. protected void assertUpdated(String file, long sinceTime) {
  304. File f = new File(ajc.getSandboxDirectory(), file);
  305. assertTrue("File " + file + " should have been updated", f.lastModified() > sinceTime);
  306. }
  307. public SyntheticRepository createRepos(File cpentry) {
  308. ClassPath cp = new ClassPath(cpentry + File.pathSeparator + System.getProperty("java.class.path"));
  309. return SyntheticRepository.getInstance(cp);
  310. }
  311. protected byte[] loadFileAsByteArray(File f) {
  312. try {
  313. byte[] bs = new byte[100000];
  314. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
  315. int pos = 0;
  316. int len = 0;
  317. while ((len=bis.read(bs, pos, 100000-pos))!=-1) {
  318. pos+=len;
  319. }
  320. bis.close();
  321. return bs;
  322. } catch (Exception e) {
  323. return null;
  324. }
  325. }
  326. public JavaClass getClassFrom(File where, String clazzname) throws ClassNotFoundException {
  327. SyntheticRepository repos = createRepos(where);
  328. return repos.loadClass(clazzname);
  329. }
  330. protected Method getMethodStartsWith(JavaClass jc, String prefix) {
  331. return getMethodStartsWith(jc,prefix,1);
  332. }
  333. protected Attribute getAttributeStartsWith(Attribute[] attributes, String prefix) {
  334. StringBuilder buf = new StringBuilder();
  335. for (Attribute a: attributes) {
  336. if (a.getName().startsWith(prefix)) {
  337. return a;
  338. }
  339. buf.append(a.toString()).append("\n");
  340. }
  341. fail("Failed to find '"+prefix+"' in attributes:\n"+buf.toString());
  342. return null;
  343. }
  344. protected Method getMethodStartsWith(JavaClass jc, String prefix, int whichone) {
  345. Method[] meths = jc.getMethods();
  346. for (int i = 0; i < meths.length; i++) {
  347. Method method = meths[i];
  348. System.out.println(method);
  349. if (method.getName().startsWith(prefix)) {
  350. whichone--;
  351. if (whichone==0) {
  352. return method;
  353. }
  354. }
  355. }
  356. return null;
  357. }
  358. /**
  359. * Sort it by name then start position
  360. */
  361. public List<LocalVariable> sortedLocalVariables(LocalVariableTable lvt) {
  362. List<LocalVariable> l = new ArrayList<LocalVariable>();
  363. LocalVariable lv[] = lvt.getLocalVariableTable();
  364. for (int i = 0; i < lv.length; i++) {
  365. LocalVariable lvEntry = lv[i];
  366. l.add(lvEntry);
  367. }
  368. Collections.sort(l, new MyComparator());
  369. return l;
  370. }
  371. public String stringify(LocalVariableTable lvt, int slotIndex) {
  372. LocalVariable lv[] = lvt.getLocalVariableTable();
  373. LocalVariable lvEntry = lv[slotIndex];
  374. StringBuffer sb = new StringBuffer();
  375. sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex())
  376. .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength());
  377. return sb.toString();
  378. }
  379. public String stringify(List<LocalVariable> l, int slotIndex) {
  380. LocalVariable lvEntry = (LocalVariable) l.get(slotIndex);
  381. StringBuffer sb = new StringBuffer();
  382. sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex())
  383. .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength());
  384. return sb.toString();
  385. }
  386. public String stringify(LocalVariableTable lvt) {
  387. if (lvt == null) {
  388. return "";
  389. }
  390. StringBuffer sb = new StringBuffer();
  391. sb.append("LocalVariableTable. Entries=#" + lvt.getTableLength()).append("\n");
  392. LocalVariable lv[] = lvt.getLocalVariableTable();
  393. for (int i = 0; i < lv.length; i++) {
  394. LocalVariable lvEntry = lv[i];
  395. sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex())
  396. .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength()).append("\n");
  397. }
  398. return sb.toString();
  399. }
  400. public static class CountingFilenameFilter implements FilenameFilter {
  401. private String suffix;
  402. private int count;
  403. public CountingFilenameFilter(String s) {
  404. this.suffix = s;
  405. }
  406. public boolean accept(File dir, String name) {
  407. if (name.endsWith(suffix)) {
  408. count++;
  409. }
  410. return false;
  411. }
  412. public int getCount() {
  413. return count;
  414. }
  415. }
  416. public static class MyComparator implements Comparator<LocalVariable> {
  417. public int compare(LocalVariable o1, LocalVariable o2) {
  418. LocalVariable l1 = (LocalVariable) o1;
  419. LocalVariable l2 = (LocalVariable) o2;
  420. if (l1.getName().equals(l2.getName())) {
  421. return l1.getStartPC() - l2.getStartPC();
  422. } else {
  423. return l1.getName().compareTo(l2.getName());
  424. }
  425. }
  426. }
  427. protected Method getMethodFromClass(JavaClass clazz, String methodName) {
  428. Method[] meths = clazz.getMethods();
  429. for (int i = 0; i < meths.length; i++) {
  430. Method method = meths[i];
  431. if (method.getName().equals(methodName)) {
  432. return meths[i];
  433. }
  434. }
  435. return null;
  436. }
  437. protected URL getClassResource(String resourceName) {
  438. return getClass().getResource(resourceName);
  439. }
  440. protected Method findMethod(JavaClass jc, String string) {
  441. for (Method m : jc.getMethods()) {
  442. if (m.getName().equals(string)) {
  443. return m;
  444. }
  445. }
  446. return null;
  447. }
  448. protected ResolvedMember findMethod(ResolvedType outerType, String string) {
  449. for (ResolvedMember method: outerType.getDeclaredMethods()) {
  450. if (method.getName().equals(string)) {
  451. return method;
  452. }
  453. }
  454. return null;
  455. }
  456. }