diff options
Diffstat (limited to 'testing/src')
110 files changed, 6828 insertions, 0 deletions
diff --git a/testing/src/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java b/testing/src/main/java/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java index 8fb274176..8fb274176 100644 --- a/testing/src/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java +++ b/testing/src/main/java/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java diff --git a/testing/src/org/aspectj/internal/tools/ant/taskdefs/MainWrapper.java b/testing/src/main/java/org/aspectj/internal/tools/ant/taskdefs/MainWrapper.java index 6ce22df24..6ce22df24 100644 --- a/testing/src/org/aspectj/internal/tools/ant/taskdefs/MainWrapper.java +++ b/testing/src/main/java/org/aspectj/internal/tools/ant/taskdefs/MainWrapper.java diff --git a/testing/src/main/java/org/aspectj/testing/AjcTest.java b/testing/src/main/java/org/aspectj/testing/AjcTest.java new file mode 100644 index 000000000..4cb9a8722 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/AjcTest.java @@ -0,0 +1,169 @@ +/* ******************************************************************* + * Copyright (c) 2004,2018 IBM Corporation, contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * ******************************************************************/ +package org.aspectj.testing; + +import java.util.ArrayList; +import java.util.List; + +import org.aspectj.tools.ajc.AjcTestCase; +import org.aspectj.util.LangUtil; + +/** + * @author Adrian Colyer + * @author Andy Clement + */ +public class AjcTest { + +// private static boolean is13VMOrGreater = true; + private static boolean is14VMOrGreater = true; + private static boolean is15VMOrGreater = false; + private static boolean is16VMOrGreater = false; + private static boolean is17VMOrGreater = false; + private static boolean is18VMOrGreater = false; + private static boolean is19VMOrGreater = false; + private static boolean is10VMOrGreater = false; + private static boolean is11VMOrGreater = false; + + static { // matching logic is also in org.aspectj.util.LangUtil + is14VMOrGreater = LangUtil.is14VMOrGreater(); + is15VMOrGreater = LangUtil.is15VMOrGreater(); + is16VMOrGreater = LangUtil.is16VMOrGreater(); + is17VMOrGreater = LangUtil.is17VMOrGreater(); + is18VMOrGreater = LangUtil.is18VMOrGreater(); + is19VMOrGreater = LangUtil.is19VMOrGreater(); + is10VMOrGreater = LangUtil.is10VMOrGreater(); + is11VMOrGreater = LangUtil.is11VMOrGreater(); + } + + private List<ITestStep> testSteps = new ArrayList<ITestStep>(); + + private String dir; + private String pr; + private String title; + private String keywords; + private String comment; + private String vmLevel = "1.3"; + + public AjcTest() { + } + + public void addTestStep(ITestStep step) { + testSteps.add(step); + step.setTest(this); + } + + public boolean runTest(AjcTestCase testCase) { + if (!canRunOnThisVM()) return false; + try { + System.out.print("TEST: " + getTitle() + "\t"); + for (ITestStep step: testSteps) { + step.setBaseDir(getDir()); + System.out.print("."); + step.execute(testCase); + } + } finally { + System.out.println("DONE"); + } + return true; + } + + public boolean canRunOnThisVM() { + if (vmLevel.equals("1.3")) return true; + boolean canRun = true; + if (vmLevel.equals("1.4")) canRun = is14VMOrGreater; + if (vmLevel.equals("1.5")) canRun = is15VMOrGreater; + if (vmLevel.equals("1.6")) canRun = is16VMOrGreater; + if (vmLevel.equals("1.7")) canRun = is17VMOrGreater; + if (vmLevel.equals("1.8")) canRun = is18VMOrGreater; + if (vmLevel.equals("1.9")) canRun = is19VMOrGreater; + if (vmLevel.equals("10")) canRun = is10VMOrGreater; + if (vmLevel.equals("11")) canRun = is11VMOrGreater; + if (!canRun) { + System.out.println("***SKIPPING TEST***" + getTitle()+ " needs " + getVmLevel() + + ", currently running on " + System.getProperty("java.vm.version")); + } + return canRun; + } + + /** + * @return Returns the comment. + */ + public String getComment() { + return comment; + } + /** + * @param comment The comment to set. + */ + public void setComment(String comment) { + this.comment = comment; + } + /** + * @return Returns the dir. + */ + public String getDir() { + return dir; + } + /** + * @param dir The dir to set. + */ + public void setDir(String dir) { + dir = "../tests/" + dir; + this.dir = dir; + } + /** + * @return Returns the keywords. + */ + public String getKeywords() { + return keywords; + } + /** + * @param keywords The keywords to set. + */ + public void setKeywords(String keywords) { + this.keywords = keywords; + } + /** + * @return Returns the pr. + */ + public String getPr() { + return pr; + } + /** + * @param pr The pr to set. + */ + public void setPr(String pr) { + this.pr = pr; + } + /** + * @return Returns the title. + */ + public String getTitle() { + return title; + } + /** + * @param title The title to set. + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * @param vmLevel The vmLevel to set. + */ + public void setVm(String vmLevel) { + this.vmLevel = vmLevel; + } + + /** + * @return Returns the vmLevel. + */ + public String getVmLevel() { + return vmLevel; + } +} diff --git a/testing/src/main/java/org/aspectj/testing/AntSpec.java b/testing/src/main/java/org/aspectj/testing/AntSpec.java new file mode 100644 index 000000000..ceba08b29 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/AntSpec.java @@ -0,0 +1,265 @@ +/******************************************************************************* + * Copyright (c) 2005 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://eclipse.org/legal/epl-v10.html + * + * Contributors: + * Alexandre Vasseur initial implementation + *******************************************************************************/ +package org.aspectj.testing; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.StringTokenizer; + +import org.apache.tools.ant.BuildEvent; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.DefaultLogger; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.ProjectHelper; +import org.apache.tools.ant.Target; +import org.apache.tools.ant.taskdefs.Java; +import org.apache.tools.ant.types.Path; +import org.aspectj.tools.ajc.AjcTestCase; + +/** + * Element that allow to run an abritrary Ant target in a sandbox. + * <p/> + * Such a spec is used in a "<ajc-test><ant file="myAnt.xml" [target="..."] [verbose="true"]/> XML element. The "target" is + * optional. If not set, default myAnt.xml target is used. The "file" file is looked up from the <ajc-test dir="..."/> attribute. If + * "verbose" is set to "true", the ant -v output is piped, else nothing is reported except errors. + * <p/> + * The called Ant target benefits from 2 implicit variables: "${aj.sandbox}" points to the test current sandbox folder. "aj.path" is + * an Ant refid on the classpath formed with the sandbox folder + ltw + the AjcTestCase classpath (ie usually aspectjrt, junit, and + * testing infra) + * <p/> + * Element "<stdout><line text="..">" and "<stderr><line text="..">" can be used. For now a full match is performed on the output of + * the runned target only (not the whole Ant invocation). This is experimental and advised to use a "<junit>" task instead or a + * "<java>" whose main that throws some exception upon failure. + * + * + * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> + */ +public class AntSpec implements ITestStep { + + // ALSO SEE AJC + private final static String DEFAULT_LTW_CLASSPATH_ENTRIES = ".." + File.separator + "asm/bin" + File.pathSeparator + ".." + + File.separator + "bridge/bin" + File.pathSeparator + ".." + File.separator + "loadtime/bin" + File.pathSeparator + + ".." + File.separator + "loadtime5/bin" + File.pathSeparator + ".." + File.separator + "weaver/bin" + + File.pathSeparator + ".." + File.separator + "org.aspectj.matcher/bin" + File.pathSeparator + ".." + File.separator + + "lib/bcel/bcel.jar" + File.pathSeparator + ".." + File.separator + "lib/bcel/bcel-verifier.jar";; + + private boolean m_verbose = false; + private AjcTest m_ajcTest; + private OutputSpec m_stdErrSpec; + private OutputSpec m_stdOutSpec; + private String m_antFile; + private String m_antTarget; + + public void execute(final AjcTestCase inTestCase) { + final String failMessage = "test \"" + m_ajcTest.getTitle() + "\" failed: "; + + File buildFile = new File(m_ajcTest.getDir() + File.separatorChar + m_antFile); + if (!buildFile.exists()) { + AjcTestCase.fail(failMessage + "no such Ant file " + buildFile.getAbsolutePath()); + } + Project p = new Project(); + final StringBuffer stdout = new StringBuffer(); + final StringBuffer stderr = new StringBuffer(); + final StringBuffer verboseLog = new StringBuffer(); + try { + // read the Ant file + p.init(); + p.setUserProperty("ant.file", buildFile.getAbsolutePath()); + // setup aj.sandbox + p.setUserProperty("aj.sandbox", inTestCase.getSandboxDirectory().getAbsolutePath()); + // setup aj.dir "modules" folder + p.setUserProperty("aj.root", new File("..").getAbsolutePath()); + + // create the test implicit path aj.path that contains the sandbox + regular test infra path + Path path = new Path(p, inTestCase.getSandboxDirectory().getAbsolutePath()); + populatePath(path, DEFAULT_LTW_CLASSPATH_ENTRIES); + populatePath(path, AjcTestCase.DEFAULT_CLASSPATH_ENTRIES); + p.addReference("aj.path", path); + p.setBasedir(buildFile.getAbsoluteFile().getParent()); + ProjectHelper helper = ProjectHelper.getProjectHelper(); + helper.parse(p, buildFile); + + // use default target if no target specified + if (m_antTarget == null) { + m_antTarget = p.getDefaultTarget(); + } + + // make sure we listen for failure + DefaultLogger consoleLogger = new DefaultLogger() { + public void buildFinished(BuildEvent event) { + super.buildFinished(event); + if (event.getException() != null) { + + try { + File antout = new File(inTestCase.getSandboxDirectory().getAbsolutePath(), "antout"); + if (antout.exists()) { + stdout.append("Forked java command stdout:\n"); + System.out.println("Forked java command stdout:"); + FileReader fr = new FileReader(antout); + BufferedReader br = new BufferedReader(fr); + String line = br.readLine(); + while (line != null) { + stdout.append(line).append("\n"); + System.out.println(stdout); + line = br.readLine(); + } + fr.close(); + } + + File anterr = new File(inTestCase.getSandboxDirectory().getAbsolutePath(), "anterr"); + if (anterr.exists()) { + stdout.append("Forked java command stderr:\n"); + System.out.println("Forked java command stderr:"); + FileReader fr = new FileReader(anterr); + BufferedReader br = new BufferedReader(fr); + String line = br.readLine(); + while (line != null) { + stdout.append(line).append("\n"); + System.out.println(stdout); + line = br.readLine(); + } + fr.close(); + } + } catch (Exception e) { + System.out.println("Exception whilst loading forked java task output " + e.getMessage() + "\n"); + e.printStackTrace(); + stdout.append("Exception whilst loading forked java task output " + e.getMessage() + "\n"); + } + + StringBuffer message = new StringBuffer(); + message.append(event.getException().toString()).append("\n"); + message.append(verboseLog); + message.append(stdout); + message.append(stderr); + // AjcTestCase.fail(failMessage + "failure " + event.getException()); + AjcTestCase.fail(message.toString()); + } + } + + public void targetFinished(BuildEvent event) { + super.targetFinished(event); + if (event.getException() != null) { + AjcTestCase.fail(failMessage + "failure in '" + event.getTarget() + "' " + event.getException()); + } + } + + public void messageLogged(BuildEvent event) { + super.messageLogged(event); + + Target target = event.getTarget(); + if (target != null && m_antTarget.equals(target.getName()) && event.getSource() instanceof Java) + switch (event.getPriority()) { + case Project.MSG_INFO: + stdout.append(event.getMessage()).append('\n'); + break; + case Project.MSG_WARN: + stderr.append(event.getMessage()).append('\n'); + break; + case Project.MSG_VERBOSE: + verboseLog.append(event.getMessage()).append('\n'); + break; + } + } + }; + consoleLogger.setErrorPrintStream(System.err); + consoleLogger.setOutputPrintStream(System.out); + consoleLogger.setMessageOutputLevel(m_verbose ? Project.MSG_VERBOSE : Project.MSG_ERR); + p.addBuildListener(consoleLogger); + } catch (Throwable t) { + AjcTestCase.fail(failMessage + "invalid Ant script :" + t.toString()); + } + try { + p.setProperty("verbose", "true"); + p.fireBuildStarted(); + p.executeTarget(m_antTarget); + p.fireBuildFinished(null); + } catch (BuildException e) { + p.fireBuildFinished(e); + } catch (Throwable t) { + AjcTestCase.fail(failMessage + "error when invoking target :" + t.toString()); + } + + /* See if stdout/stderr matches test specification */ + if (m_stdOutSpec != null) { + m_stdOutSpec.matchAgainst(stdout.toString()); + } + if (m_stdErrSpec != null) { + String stderr2 = stderr.toString(); + // Working around this rediculous message that still comes out of Java7 builds: + if (stderr2.indexOf("Class JavaLaunchHelper is implemented in both")!=-1 && stderr2.indexOf('\n')!=-1) { + stderr2 = stderr2.replaceAll("objc\\[[0-9]*\\]: Class JavaLaunchHelper is implemented in both [^\n]*\n",""); + } + // JDK 11 is complaining about illegal reflective calls - temporary measure ignore these - does that get all tests passing and this is the last problem? + if (stderr2.indexOf("WARNING: Illegal reflective access using Lookup on org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor") != -1) { +// WARNING: An illegal reflective access operation has occurred +// WARNING: Illegal reflective access using Lookup on org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor (file:/Users/aclement/gits/org.aspectj/loadtime/bin/) to class java.lang.ClassLoader +// WARNING: Please consider reporting this to the maintainers of org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor +// WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations +// WARNING: All illegal access operations will be denied in a future release + + stderr2 = stderr2.replaceAll("WARNING: An illegal reflective access operation has occurred\n",""); + stderr2 = stderr2.replaceAll("WARNING: Illegal reflective access using Lookup on org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor[^\n]*\n",""); + stderr2 = stderr2.replaceAll("WARNING: Please consider reporting this to the maintainers of org.aspectj.weaver.loadtime.ClassLoaderWeavingAdaptor\n",""); + stderr2 = stderr2.replaceAll("WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations\n",""); + stderr2 = stderr2.replaceAll("WARNING: All illegal access operations will be denied in a future release\n",""); + } + + m_stdErrSpec.matchAgainst(stderr2); + } + } + + public void addStdErrSpec(OutputSpec spec) { + if (m_stdErrSpec != null) + throw new UnsupportedOperationException("only one 'stderr' allowed in 'ant'"); + m_stdErrSpec = spec; + } + + public void addStdOutSpec(OutputSpec spec) { + if (m_stdOutSpec != null) + throw new UnsupportedOperationException("only one 'stdout' allowed in 'ant'"); + m_stdOutSpec = spec; + } + + public void setVerbose(String verbose) { + if (verbose != null && "true".equalsIgnoreCase(verbose)) { + m_verbose = true; + } + } + + public void setFile(String file) { + m_antFile = file; + } + + public void setTarget(String target) { + m_antTarget = target; + } + + public void addExpectedMessage(ExpectedMessageSpec message) { + throw new UnsupportedOperationException("don't use 'message' in 'ant' specs."); + } + + public void setBaseDir(String dir) { + ; + } + + public void setTest(AjcTest test) { + m_ajcTest = test; + } + + private static void populatePath(Path path, String pathEntries) { + StringTokenizer st = new StringTokenizer(pathEntries, File.pathSeparator); + while (st.hasMoreTokens()) { + path.setPath(new File(st.nextToken()).getAbsolutePath()); + } + } +} diff --git a/testing/src/main/java/org/aspectj/testing/AutowiredXMLBasedAjcTestCase.java b/testing/src/main/java/org/aspectj/testing/AutowiredXMLBasedAjcTestCase.java new file mode 100644 index 000000000..467d9f236 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/AutowiredXMLBasedAjcTestCase.java @@ -0,0 +1,154 @@ +/******************************************************************************* + * Copyright (c) 2005 Contributors + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * initial implementation Alexandre Vasseur + *******************************************************************************/ +package org.aspectj.testing; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; +import junit.extensions.TestSetup; + +import java.lang.reflect.Method; +import java.util.Iterator; +import java.util.Map; +import java.util.HashMap; +import java.io.InputStreamReader; +import java.io.FileInputStream; + +import org.apache.commons.digester.Digester; +import org.aspectj.tools.ajc.Ajc; + +/** + * Autowiring of XML test spec file as JUnit tests. + * <p/> + * Extend this class and implement the getSpecFile and the static suite() method. + * All tests described in the XML spec file will be auto-registered as JUnit tests. + * Any regular test() method will be registered as well. + * + * @author <a href="mailto:alex AT gnilux DOT com">Alexandre Vasseur</a> + */ +public abstract class AutowiredXMLBasedAjcTestCase extends XMLBasedAjcTestCase { + + private Map<String,AjcTest> testMap = new HashMap<String,AjcTest>(); + + public void addTest(AjcTest test) { + testMap.put(test.getTitle(), test); + } + + /* + * Return a map from (String) test title -> AjcTest + */ + protected Map<String,AjcTest> getSuiteTests() { + return testMap; + } + + public static Test loadSuite(Class<?> testCaseClass) { + TestSuite suite = new TestSuite(testCaseClass.getName()); + //suite.addTestSuite(testCaseClass); + + // wire the spec file + try { + final AutowiredXMLBasedAjcTestCase wired = (AutowiredXMLBasedAjcTestCase) testCaseClass.newInstance(); + System.out.println("LOADING SUITE: " + wired.getSpecFile().getPath()); + Digester d = wired.getDigester(); + try { + InputStreamReader isr = new InputStreamReader(new FileInputStream(wired.getSpecFile())); + d.parse(isr); + } catch (Exception ex) { + fail("Unable to load suite " + wired.getSpecFile().getPath() + " : " + ex); + } + wired.ajc = new Ajc(); + + Map<String,AjcTest> ajTests = wired.getSuiteTests(); + + for (Iterator<Map.Entry<String,AjcTest>> iterator = ajTests.entrySet().iterator(); iterator.hasNext();) { + final Map.Entry<String,AjcTest> entry = iterator.next(); + + suite.addTest( + new TestCase(entry.getKey().toString()) { + + protected void runTest() { + entry.getValue().runTest(wired); + } + + public String getName() { + return entry.getKey(); + } + } + ); + } + } catch (Throwable t) { + final String message = t.toString(); + suite.addTest( + new TestCase("error") { + protected void runTest() { + fail(message); + } + } + ); + } + + // wire the test methods as well if any + // this simple check avoids failure when no test.. method is found. + // it could be refined to lookup in the hierarchy as well, and excluding private method as JUnit does. + Method[] testMethods = testCaseClass.getDeclaredMethods(); + for (int i = 0; i < testMethods.length; i++) { + Method testMethod = testMethods[i]; + if (testMethod.getName().startsWith("test")) { + suite.addTestSuite(testCaseClass); + break; + } + } + + TestSetup wrapper = new TestSetup(suite) { + /* (non-Javadoc) + * @see junit.extensions.TestSetup#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + //suiteLoaded = false; + } + /* (non-Javadoc) + * @see junit.extensions.TestSetup#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + //suiteLoaded = false; + } + }; + return wrapper; + + //return suite; + } + + /* (non-Javadoc) + * @see org.aspectj.tools.ajc.AjcTestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + } + + /** + * This helper method runs the test with the given title in the + * suite spec file. All tests steps in given ajc-test execute + * in the same sandbox. + */ + protected void runTest(String title) { + AjcTest currentTest = (AjcTest) testMap.get(title); + if (currentTest == null) { + fail("No test '" + title + "' in suite."); + } + ajc.setShouldEmptySandbox(true); + currentTest.runTest(this); + } + + + +} diff --git a/testing/src/main/java/org/aspectj/testing/CompileSpec.java b/testing/src/main/java/org/aspectj/testing/CompileSpec.java new file mode 100644 index 000000000..22570e3d1 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/CompileSpec.java @@ -0,0 +1,336 @@ +/* ******************************************************************* + * Copyright (c) 2004,2016 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, + * ******************************************************************/ +package org.aspectj.testing; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import org.aspectj.testing.util.TestUtil; +import org.aspectj.tools.ajc.AjcTestCase; +import org.aspectj.tools.ajc.CompilationResult; + +/** + * @author Adrian Colyer + * @author Andy Clement + */ +public class CompileSpec implements ITestStep { + + private List<ExpectedMessageSpec> expected = new ArrayList<ExpectedMessageSpec>(); + + private String files; + private boolean includeClassesDir; + private String aspectpath; + private String classpath; + private String modulepath; + private String inpath; + private String sourceroots; + private String outjar; + private String outxml; + private String xlintfile; + private String options; + private String baseDir; + private String extdirs; + private AjcTest myTest; + + public CompileSpec() { + } + + public void execute(AjcTestCase inTestCase) { + File base = new File(baseDir); + String[] args = buildArgs(); + CompilationResult result = inTestCase.ajc(base,args); + AjcTestCase.MessageSpec messageSpec = buildMessageSpec(); + String failMessage = "test \"" + myTest.getTitle() + "\" failed"; + inTestCase.assertMessages(result,failMessage,messageSpec); + inTestCase.setShouldEmptySandbox(false); // so subsequent steps in same test see my results + } + + public void addExpectedMessage(ExpectedMessageSpec message) { + expected.add(message); + } + + public void setBaseDir(String dir) { + this.baseDir = dir; + } + + protected String getBaseDir() { return baseDir; } + + public void setTest(AjcTest t) { + this.myTest = t; + if (options != null && (options.indexOf("-1.5") != -1)) { + myTest.setVm("1.5"); + } + } + + protected AjcTest getTest() { return myTest; } + + /** + * @return Returns the aspectpath. + */ + public String getAspectpath() { + return aspectpath; + } + /** + * @param aspectpath The aspectpath to set. + */ + public void setAspectpath(String aspectpath) { + this.aspectpath = aspectpath.replace(',',File.pathSeparatorChar); + } + /** + * @return Returns the classpath. + */ + public String getClasspath() { + return classpath; + } + /** + * @param classpath The classpath to set. + */ + public void setClasspath(String classpath) { + this.classpath = classpath.replace(',',File.pathSeparatorChar); + } + + public String getModulepath() { + return this.modulepath; + } + + public void setModulepath(String modulepath) { + this.modulepath = modulepath.replace(',', File.pathSeparatorChar); + } + /** + * @return Returns the files. + */ + public String getFiles() { + return files; + } + /** + * @param files The files to set. + */ + public void setFiles(String files) { + this.files = files; + } + /** + * @return Returns the includeClassesDir. + */ + public boolean isIncludeClassesDir() { + return includeClassesDir; + } + /** + * @param includeClassesDir The includeClassesDir to set. + */ + public void setIncludeClassesDir(boolean includeClassesDir) { + this.includeClassesDir = includeClassesDir; + } + /** + * @return Returns the inpath. + */ + public String getInpath() { + return inpath; + } + /** + * @param inpath The inpath to set. + */ + public void setInpath(String inpath) { + this.inpath = inpath.replace(',',File.pathSeparatorChar).replace(';',File.pathSeparatorChar); + } + /** + * @return Returns the options. + */ + public String getOptions() { + return options; + } + /** + * @param options The options to set. + */ + public void setOptions(String options) { + int i = options.indexOf("!eclipse"); + if (i != -1) { + this.options = options.substring(0,i); + this.options += options.substring(i + "!eclipse".length()); + } else { + this.options = options; + } + } + /** + * @return Returns the outjar. + */ + public String getOutjar() { + return outjar; + } + /** + * @param outjar The outjar to set. + */ + public void setOutjar(String outjar) { + this.outjar = outjar; + } + + /** + * @return Returns the outxml. + */ + public String getOutxmlfile() { + return outxml; + } + + /** + * @param outxml The the of the aop.xml file to generate + */ + public void setOutxmlfile(String outxml) { + this.outxml = outxml; + } + /** + * @return Returns the sourceroots. + */ + public String getSourceroots() { + return sourceroots; + } + /** + * @param sourceroots The sourceroots to set. + */ + public void setSourceroots(String sourceroots) { + this.sourceroots = sourceroots; + } + /** + * @return Returns the xlintfile. + */ + public String getXlintfile() { + return xlintfile; + } + /** + * @param xlintfile The xlintfile to set. + */ + public void setXlintfile(String xlintfile) { + this.xlintfile = xlintfile; + } + + public String getExtdirs() { return extdirs;} + public void setExtdirs(String extdirs) { this.extdirs = extdirs; } + + protected String[] buildArgs() { + StringBuffer args = new StringBuffer(); + // add any set options, and then files to compile at the end + if (getAspectpath() != null) { + args.append("-aspectpath "); + args.append(getAspectpath()); + args.append(" "); + } + if (getSourceroots() != null) { + args.append("-sourceroots "); + args.append(getSourceroots()); + args.append(" "); + } + if (getOutjar() != null) { + args.append("-outjar "); + args.append(getOutjar()); + args.append(" "); + } + if (getOutxmlfile() != null) { + args.append("-outxmlfile "); + args.append(getOutxmlfile()); + args.append(" "); + } + if (getOptions() != null) { + StringTokenizer strTok = new StringTokenizer(getOptions(),","); + while (strTok.hasMoreTokens()) { + // For an option containing a comma, pass in a { in its place + args.append(strTok.nextToken().replace('{', ',')); + args.append(" "); + } + } + if (getClasspath() != null) { + args.append("-classpath "); + args.append(getClasspath()); + args.append(" "); + } + if (getModulepath() != null) { + args.append("-p "); + args.append(rewrite(getModulepath())); + args.append(" "); + } + if (getXlintfile() != null) { + args.append("-Xlintfile "); + args.append(getXlintfile()); + args.append(" "); + } + if (getExtdirs() != null) { + args.append("-extdirs "); + args.append(getExtdirs()); + args.append(" "); + } + List<String> fileList = new ArrayList<String>(); + List<String> jarList = new ArrayList<String>(); + // convention that any jar on file list should be added to inpath + String files = getFiles(); + if (files == null) files = ""; + StringTokenizer strTok = new StringTokenizer(files,","); + while (strTok.hasMoreTokens()) { + final String file = strTok.nextToken(); + if (file.endsWith(".jar")) { + jarList.add(file); + } else { + fileList.add(file); + } + } + if ((getInpath() != null) || !jarList.isEmpty()) { + args.append("-inpath "); + if (getInpath() != null) args.append(getInpath()); + for (String jar: jarList) { + args.append(File.pathSeparator); + args.append(jar); + } + args.append(" "); + } + for (String file: fileList) { + args.append(file); + args.append(" "); + } + String argumentString = args.toString(); + strTok = new StringTokenizer(argumentString," "); + String[] ret = new String[strTok.countTokens()]; + for (int i = 0; i < ret.length; i++) { + ret[i] = strTok.nextToken(); + } + return ret; + } + + private String rewrite(String path) { + path = path.replace("$runtime", TestUtil.aspectjrtPath().toString()); + return path; + } + + protected AjcTestCase.MessageSpec buildMessageSpec() { + List<AjcTestCase.Message> infos = null; + List<AjcTestCase.Message> warnings = new ArrayList<AjcTestCase.Message>(); + List<AjcTestCase.Message> errors = new ArrayList<AjcTestCase.Message>(); + List<AjcTestCase.Message> fails = new ArrayList<AjcTestCase.Message>(); + List<AjcTestCase.Message> weaveInfos = new ArrayList<AjcTestCase.Message>(); + for (ExpectedMessageSpec exMsg: expected) { + String kind = exMsg.getKind(); + if (kind.equals("info")) { + if (infos == null) infos = new ArrayList<AjcTestCase.Message>(); + infos.add(exMsg.toMessage()); + } else if (kind.equals("warning")) { + warnings.add(exMsg.toMessage()); + } else if (kind.equals("error")) { + errors.add(exMsg.toMessage()); + } else if (kind.equals("fail")) { + fails.add(exMsg.toMessage()); + } else if (kind.equals("abort")) { + fails.add(exMsg.toMessage()); + } else if (kind.equals("weave")) { + weaveInfos.add(exMsg.toMessage()); + } + } + return new AjcTestCase.MessageSpec(infos,warnings,errors,fails,weaveInfos); + } + +} diff --git a/testing/src/main/java/org/aspectj/testing/ExpectedMessageSpec.java b/testing/src/main/java/org/aspectj/testing/ExpectedMessageSpec.java new file mode 100644 index 000000000..2193b55ae --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/ExpectedMessageSpec.java @@ -0,0 +1,94 @@ +/* ******************************************************************* + * Copyright (c) 2004 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, + * ******************************************************************/ +package org.aspectj.testing; + +import org.aspectj.tools.ajc.AjcTestCase; + +/** + * @author colyer + * + * TODO To change the template for this generated type comment go to + * Window - Preferences - Java - Code Style - Code Templates + */ +public class ExpectedMessageSpec { + + private String kind = "error"; + private int line = -1; + private String text; + private String file; + private String details; + + public AjcTestCase.Message toMessage() { + return new AjcTestCase.Message(line,file,text,null); + } + + /** + * @return Returns the details. + */ + public String getDetails() { + return details; + } + /** + * @param details The details to set. + */ + public void setDetails(String details) { + this.details = details; + } + /** + * @return Returns the file. + */ + public String getFile() { + return file; + } + /** + * @param file The file to set. + */ + public void setFile(String file) { + this.file = file; + } + /** + * @return Returns the kind. + */ + public String getKind() { + return kind; + } + /** + * @param kind The kind to set. + */ + public void setKind(String kind) { + this.kind = kind; + } + /** + * @return Returns the line. + */ + public int getLine() { + return line; + } + /** + * @param line The line to set. + */ + public void setLine(int line) { + this.line = line; + } + /** + * @return Returns the text. + */ + public String getText() { + return text; + } + /** + * @param text The text to set. + */ + public void setText(String text) { + this.text = text; + } +} diff --git a/testing/src/main/java/org/aspectj/testing/FileSpec.java b/testing/src/main/java/org/aspectj/testing/FileSpec.java new file mode 100644 index 000000000..2164f38f1 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/FileSpec.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright (c) 2010 Contributors + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement - SpringSource + *******************************************************************************/ +package org.aspectj.testing; + +import java.io.File; + +import org.aspectj.tools.ajc.AjcTestCase; + +/** + * Support simple file system operations in a test spec. Example:<br> + * <file deletefile="foo.jar"/> will delete the file foo.jar from the sandbox. + * + * @author Andy Clement + */ +public class FileSpec implements ITestStep { + + private String toDelete; + + private String renameFrom; + private String renameTo; + + // private String dir; + // private AjcTest test; + + public FileSpec() { + } + + public void setRenameFrom(String file) { + this.renameFrom = file; + } + + public void setRenameTo(String file) { + this.renameTo = file; + } + + public void setDeletefile(String file) { + this.toDelete = file; + } + + @Override + public void addExpectedMessage(ExpectedMessageSpec message) { + } + + @Override + public void execute(AjcTestCase inTestCase) { + File sandbox = inTestCase.getSandboxDirectory(); + if (toDelete != null) { + File targetForDeletion = new File(sandbox, toDelete); + if (targetForDeletion.isFile()) { + targetForDeletion.delete(); + } else { + recursiveDelete(targetForDeletion); + } + } + if (renameFrom != null) { + if (renameTo == null) { + throw new IllegalStateException("If setting renameFrom the renameTo should also be set"); + } + File fileFrom = new File(sandbox, renameFrom); + File fileTo = new File(sandbox, renameTo); + fileFrom.renameTo(fileTo); + } + } + + private void recursiveDelete(File toDelete) { + if (toDelete.isDirectory()) { + File[] files = toDelete.listFiles(); + for (File f: files) { + recursiveDelete(f); + } + } + toDelete.delete(); + } + + @Override + public void setBaseDir(String dir) { + // this.dir = dir; + } + + @Override + public void setTest(AjcTest test) { + // this.test = test; + } + +} diff --git a/testing/src/main/java/org/aspectj/testing/ITestStep.java b/testing/src/main/java/org/aspectj/testing/ITestStep.java new file mode 100644 index 000000000..673d6c66d --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/ITestStep.java @@ -0,0 +1,28 @@ +/* ******************************************************************* + * Copyright (c) 2004 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, + * ******************************************************************/ +package org.aspectj.testing; + +import org.aspectj.tools.ajc.AjcTestCase; + +/** + * @author Adrian Colyer + */ +public interface ITestStep { + + void execute(AjcTestCase inTestCase); + + void addExpectedMessage(ExpectedMessageSpec message); + + void setBaseDir(String dir); + + void setTest(AjcTest test); +} diff --git a/testing/src/main/java/org/aspectj/testing/MakeTestClass.java b/testing/src/main/java/org/aspectj/testing/MakeTestClass.java new file mode 100644 index 000000000..721cb623b --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/MakeTestClass.java @@ -0,0 +1,118 @@ +/* + * Created on 02-Aug-2004 + * + */ +package org.aspectj.testing; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.digester.Digester; + +/** + * @author colyer + * + * TODO To change the template for this generated type comment go to + * Window - Preferences - Java - Code Style - Code Templates + */ +public class MakeTestClass { + + private static final String HEADER = + "/* *******************************************************************\n" + + " * Copyright (c) 2004 IBM Corporation\n" + + " * All rights reserved.\n" + + " * This program and the accompanying materials are made available\n" + + " * under the terms of the Eclipse Public License v1.0\n" + + " * which accompanies this distribution and is available at\n" + + " * http://www.eclipse.org/legal/epl-v10.html \n" + + " * \n" + + " * ******************************************************************/\n" + + "package org.aspectj.systemtest.XXX;\n" + + "\n" + + "import java.io.File;\n" + + "import junit.framework.Test;\n" + + "import org.aspectj.testing.XMLBasedAjcTestCase;\n" + + "\n" + + "public class "; + + private static final String BODY_1 = + " extends org.aspectj.testing.XMLBasedAjcTestCase {\n" + + "\n" + + " public static Test suite() {\n" + + " return XMLBasedAjcTestCase.loadSuite("; + + private static final String BODY_2 = + ".class);\n" + + " }\n" + + "\n" + + " protected File getSpecFile() {\n" + + " return new File(\""; + + private static final String BODY_3 = + "\");\n" + + " }\n"; + + private static final String FOOTER = + "}\n"; + + private List<AjcTest> tests = new ArrayList<AjcTest>(); + private String className; + private String suiteFile; + + public static void main(String[] args) throws Exception { + new MakeTestClass(args[0],args[1]).makeTestClass(); + } + + public MakeTestClass(String className, String suiteFile)throws Exception { + this.className = className; + this.suiteFile = suiteFile; + Digester d = getDigester(); + InputStreamReader isr = new InputStreamReader(new FileInputStream(suiteFile)); + d.parse(isr); + } + + public void addTest(AjcTest test) { + tests.add(test); + } + + public void makeTestClass() throws Exception { + FileOutputStream fos = new FileOutputStream(className + ".java"); + PrintStream out = new PrintStream(fos); + out.print(HEADER); + out.print(className); + out.print(BODY_1); + out.print(className); + out.print(BODY_2); + out.print(suiteFile); + out.print(BODY_3); + out.println(); + int testNo = 1; + NumberFormat nf = NumberFormat.getInstance(); + nf.setMinimumIntegerDigits(3); + for (AjcTest test: tests) { + out.println(); + out.print(" public void test"); + out.print(nf.format(testNo++)); + out.println("(){"); + out.println(" runTest(\"" + test.getTitle() + "\");"); + out.println(" }"); + } + out.println(); + out.println(FOOTER); + out.close(); + } + + private Digester getDigester() { + Digester digester = new Digester(); + digester.push(this); + digester.addObjectCreate("suite/ajc-test",AjcTest.class); + digester.addSetProperties("suite/ajc-test"); + digester.addSetNext("suite/ajc-test","addTest","org.aspectj.testing.AjcTest"); + return digester; + } +} diff --git a/testing/src/main/java/org/aspectj/testing/OutputLine.java b/testing/src/main/java/org/aspectj/testing/OutputLine.java new file mode 100644 index 000000000..fc6fe4ce9 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/OutputLine.java @@ -0,0 +1,42 @@ +/* ******************************************************************* + * Copyright (c) 2005 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, + * ******************************************************************/ +package org.aspectj.testing; + +/** + * @author Adrian Colyer + * @author Andy Clement + */ +public class OutputLine { + + // Expected text + private String text; + + // Comma separated list of vm versions on which this is expected + private String vm; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getVm() { + return vm; + } + + public void setVm(String vm) { + this.vm = vm; + } + +} diff --git a/testing/src/main/java/org/aspectj/testing/OutputSpec.java b/testing/src/main/java/org/aspectj/testing/OutputSpec.java new file mode 100644 index 000000000..9eab46098 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/OutputSpec.java @@ -0,0 +1,134 @@ +/* ******************************************************************* + * Copyright (c) 2005 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, + * ******************************************************************/ +package org.aspectj.testing; +import java.util.Iterator; +import java.util.List; +import java.util.ArrayList; +import java.util.StringTokenizer; + +import org.aspectj.tools.ajc.AjcTestCase; +import org.aspectj.util.LangUtil; + +public class OutputSpec { + + private List<String> expectedOutputLines = new ArrayList<String>(); + + public void addLine(OutputLine line) { + if (line.getVm() == null || matchesThisVm(line.getVm())) { + expectedOutputLines.add(line.getText()); + } + } + + /** + * For a test output line that has specified a vm version, check if it matches the vm we are running on. + * vm might be "1.2,1.3,1.4,1.5" or simply "9" or it may be a version with a '+' suffix indicating that + * level or later, e.g. "9+" should be ok on Java 10 + * @return true if the current vm version matches the spec + */ + private boolean matchesThisVm(String vm) { + // vm might be 1.2, 1.3, 1.4, 1.5 or 1.9 possibly with a '+' in there + // For now assume + is attached to there only being one version, like "9+" + if (vm.contains(LangUtil.getVmVersionString())) { + return true; + } + if (vm.endsWith("+")) { + double vmVersion = LangUtil.getVmVersion(); + double vmSpecified = Double.parseDouble(vm.substring(0,vm.length()-1)); + return vmVersion >= vmSpecified; + } + return false; + } + + public void matchAgainst(String output) { + matchAgainst(output, "yes"); + } + + public void matchAgainst(String output, String ordered) { + if (ordered != null && ordered.equals("no")) { + unorderedMatchAgainst(output); + return; + } + boolean matches = false; + int lineNo = 0; + StringTokenizer strTok = new StringTokenizer(output,"\n"); + if (strTok.countTokens() == expectedOutputLines.size()) { + matches = true; + for (String line: expectedOutputLines) { + lineNo++; + String outputLine = strTok.nextToken().trim(); + /* Avoid trying to match on ajSandbox source names that appear in messages */ + if (outputLine.indexOf(line) == -1) { + matches = false; + break; + } + } + } else { lineNo = -1; } + if (!matches) { + createFailureMessage(output, lineNo, strTok.countTokens()); + } + } + + public void unorderedMatchAgainst(String output) { + List<String> outputFound = getOutputFound(output); + if(outputFound.size() != expectedOutputLines.size()) { + createFailureMessage(output, -1, outputFound.size()); + return; + } + List<String> expected = new ArrayList<String>(); + expected.addAll(expectedOutputLines); + List<String> found = new ArrayList<String>(); + found.addAll(outputFound); + for (Iterator<String> iterator = outputFound.iterator(); iterator.hasNext();) { + String lineFound = (String) iterator.next(); + for (Iterator<String> iterator2 = expectedOutputLines.iterator(); iterator2.hasNext();) { + String lineExpected = (String) iterator2.next(); + if (lineFound.indexOf(lineExpected)!= -1) { + found.remove(lineFound); + expected.remove(lineExpected); + continue; + } + } + } + if (!found.isEmpty() || !expected.isEmpty()) { + createFailureMessage(output,-2,outputFound.size()); + } + } + + private void createFailureMessage(String output, int lineNo, int sizeFound) { + StringBuffer failMessage = new StringBuffer(); + failMessage.append("\n expecting output:\n"); + for (String line: expectedOutputLines) { + failMessage.append(line); + failMessage.append("\n"); + } + failMessage.append(" but found output:\n"); + failMessage.append(output); + failMessage.append("\n"); + if (lineNo==-1) { + failMessage.append("Expected "+expectedOutputLines.size()+" lines of output but there are "+sizeFound); + } else if (lineNo >= 0) { + failMessage.append("First difference is on line " + lineNo); + } + failMessage.append("\n"); + AjcTestCase.fail(failMessage.toString()); + } + + private List<String> getOutputFound(String output) { + List<String> found = new ArrayList<String>(); + StringTokenizer strTok = new StringTokenizer(output,"\n"); + while(strTok.hasMoreTokens()) { + String outputLine = strTok.nextToken().trim(); + found.add(outputLine); + } + return found; + } +} diff --git a/testing/src/main/java/org/aspectj/testing/RunSpec.java b/testing/src/main/java/org/aspectj/testing/RunSpec.java new file mode 100644 index 000000000..62b93bcb0 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/RunSpec.java @@ -0,0 +1,262 @@ +/* ******************************************************************* + * Copyright (c) 2004 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, Abraham Nevado (lucierna) + * ******************************************************************/ +package org.aspectj.testing; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Properties; +import java.util.StringTokenizer; + +import org.aspectj.tools.ajc.AjcTestCase; +import org.aspectj.util.FileUtil; + +/** + * @author Adrian Colyer + */ +public class RunSpec implements ITestStep { + + private List<ExpectedMessageSpec> expected = new ArrayList<ExpectedMessageSpec>(); + private String classToRun; + private String moduleToRun; // alternative to classToRun on JDK9+ + private String baseDir; + private String options; + private String cpath; + private String mpath; + private String orderedStderr; + private AjcTest myTest; + private OutputSpec stdErrSpec; + private OutputSpec stdOutSpec; + private String ltwFile; + private String xlintFile; + private String vmargs; + private String usefullltw; + + @Override + public String toString() { + return "RunSpec: Running '"+classToRun+"' in directory '"+baseDir+"'. Classpath of '"+cpath+"'"; + } + public RunSpec() { + } + + @Override + public void execute(AjcTestCase inTestCase) { + if (!expected.isEmpty()) { + System.err.println("Warning, message spec for run command is currently ignored (org.aspectj.testing.RunSpec)"); + } + String[] args = buildArgs(); +// System.err.println("? execute() inTestCase='" + inTestCase + "', ltwFile=" + ltwFile); + boolean useLtw = copyLtwFile(inTestCase.getSandboxDirectory()); + + copyXlintFile(inTestCase.getSandboxDirectory()); + try { + setSystemProperty("test.base.dir", inTestCase.getSandboxDirectory().getAbsolutePath()); + + AjcTestCase.RunResult rr = inTestCase.run(getClassToRun(), getModuleToRun(), args, vmargs, getClasspath(), getModulepath(), useLtw, "true".equalsIgnoreCase(usefullltw)); + + if (stdErrSpec != null) { + stdErrSpec.matchAgainst(rr.getStdErr(), orderedStderr); + } + if (stdOutSpec != null) { + stdOutSpec.matchAgainst(rr.getStdOut()); + } + } finally { + restoreProperties(); + } + } + + /* + * Logic to save/restore system properties. Copied from LTWTests. As Matthew noted, need to refactor LTWTests to use this + */ + + private Properties savedProperties = new Properties(); + + public void setSystemProperty(String key, String value) { + Properties systemProperties = System.getProperties(); + copyProperty(key, systemProperties, savedProperties); + systemProperties.setProperty(key, value); + } + + private static void copyProperty(String key, Properties from, Properties to) { + String value = from.getProperty(key, NULL); + to.setProperty(key, value); + } + + private final static String NULL = "null"; + + protected void restoreProperties() { + Properties systemProperties = System.getProperties(); + for (Enumeration<Object> enu = savedProperties.keys(); enu.hasMoreElements();) { + String key = (String) enu.nextElement(); + String value = savedProperties.getProperty(key); + if (value == NULL) + systemProperties.remove(key); + else + systemProperties.setProperty(key, value); + } + } + + @Override + public void addExpectedMessage(ExpectedMessageSpec message) { + expected.add(message); + } + + @Override + public void setBaseDir(String dir) { + this.baseDir = dir; + } + + @Override + public void setTest(AjcTest test) { + this.myTest = test; + } + + public AjcTest getTest() { + return this.myTest; + } + + public String getOptions() { + return options; + } + + public void setOptions(String options) { + this.options = options; + } + + public String getClasspath() { + if (cpath == null) + return null; + return this.cpath.replace('/', File.separatorChar).replace(',', File.pathSeparatorChar); + } + + public String getModulepath() { + if (mpath == null) + return null; + return this.mpath.replace('/', File.separatorChar).replace(',', File.pathSeparatorChar); + } + + public void setModulepath(String mpath) { + this.mpath = mpath; + } + + public void setClasspath(String cpath) { + this.cpath = cpath; + } + + public void addStdErrSpec(OutputSpec spec) { + this.stdErrSpec = spec; + } + + public void addStdOutSpec(OutputSpec spec) { + this.stdOutSpec = spec; + } + + public void setOrderedStderr(String orderedStderr) { + this.orderedStderr = orderedStderr; + } + + public String getClassToRun() { + return classToRun; + } + + public void setClassToRun(String classToRun) { + this.classToRun = classToRun; + } + + public void setModuleToRun(String moduleToRun) { + this.moduleToRun = moduleToRun; + } + + public String getModuleToRun() { + return this.moduleToRun; + } + + public String getLtwFile() { + return ltwFile; + } + + public void setLtwFile(String ltwFile) { + this.ltwFile = ltwFile; + } + + private String[] buildArgs() { + if (options == null) + return new String[0]; + StringTokenizer strTok = new StringTokenizer(options, ","); + String[] ret = new String[strTok.countTokens()]; + for (int i = 0; i < ret.length; i++) { + ret[i] = strTok.nextToken(); + } + return ret; + } + + private boolean copyLtwFile(File sandboxDirectory) { + boolean useLtw = false; + + if (ltwFile != null) { + // TODO maw use flag rather than empty file name + if (ltwFile.trim().length() == 0) + return true; + + File from = new File(baseDir, ltwFile); + File to = new File(sandboxDirectory, "META-INF" + File.separator + "aop.xml"); + // System.out.println("RunSpec.copyLtwFile() from=" + from.getAbsolutePath() + " to=" + to.getAbsolutePath()); + try { + FileUtil.copyFile(from, to); + useLtw = true; + } catch (IOException ex) { + AjcTestCase.fail(ex.toString()); + } + } + + return useLtw; + } + + public String getXlintFile() { + return xlintFile; + } + + public void setXlintFile(String xlintFile) { + this.xlintFile = xlintFile; + } + + public void setVmargs(String vmargs) { + this.vmargs = vmargs; + } + + public String getVmargs() { + return vmargs; + } + + + public String getUsefullltw() { + return usefullltw; + } + + public void setUsefullltw(String usefullltw) { + this.usefullltw = usefullltw; + } + + private void copyXlintFile(File sandboxDirectory) { + if (xlintFile != null) { + File from = new File(baseDir, xlintFile); + File to = new File(sandboxDirectory, File.separator + xlintFile); + try { + FileUtil.copyFile(from, to); + } catch (IOException ex) { + AjcTestCase.fail(ex.toString()); + } + } + } +} diff --git a/testing/src/main/java/org/aspectj/testing/WeaveSpec.java b/testing/src/main/java/org/aspectj/testing/WeaveSpec.java new file mode 100644 index 000000000..2793b63ac --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/WeaveSpec.java @@ -0,0 +1,164 @@ +/* ******************************************************************* + * Copyright (c) 2005 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, + * ******************************************************************/ +package org.aspectj.testing; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.StringTokenizer; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; + +import org.aspectj.tools.ajc.AjcTestCase; +import org.aspectj.tools.ajc.CompilationResult; + +/** + * @author colyer + * + * TODO To change the template for this generated type comment go to + * Window - Preferences - Java - Code Style - Code Templates + */ +public class WeaveSpec extends CompileSpec { + + private String classesFiles; + private String aspectsFiles; + private List<File> classFilesFromClasses; + + /* (non-Javadoc) + * @see org.aspectj.testing.ITestStep#execute(org.aspectj.tools.ajc.AjcTestCase) + */ + public void execute(AjcTestCase inTestCase) { + String failMessage = "test \"" + getTest().getTitle() + "\" failed"; + try { + File base = new File(getBaseDir()); + classFilesFromClasses = new ArrayList<File>(); + setFiles(classesFiles); + String[] args = buildArgs(); + CompilationResult result = inTestCase.ajc(base,args); + inTestCase.assertNoMessages(result,failMessage); + File sandbox = inTestCase.getSandboxDirectory(); + createJar(sandbox,"classes.jar",true); + + inTestCase.setShouldEmptySandbox(false); + setFiles(aspectsFiles); + String options = getOptions(); + if (options == null) { + setOptions(""); + } + setClasspath("classes.jar"); + args = buildArgs(); + result = inTestCase.ajc(base,args); + inTestCase.assertNoMessages(result,failMessage); + createJar(sandbox,"aspects.jar",false); + + args = buildWeaveArgs(); + inTestCase.setShouldEmptySandbox(false); + result = inTestCase.ajc(base,args); + AjcTestCase.MessageSpec messageSpec = buildMessageSpec(); + inTestCase.assertMessages(result,failMessage,messageSpec); + inTestCase.setShouldEmptySandbox(false); // so subsequent steps in same test see my results + } catch (IOException e) { + AjcTestCase.fail(failMessage + " " + e); + } + } + + public void setClassesFiles(String files) { + this.classesFiles = files; + } + + public void setAspectsFiles(String files) { + this.aspectsFiles = files; + } + + /** + * Find all the .class files under the dir, package them into a jar file, + * and then delete them. + * @param inDir + * @param name + */ + private void createJar(File inDir, String name, boolean isClasses) throws IOException { + File outJar = new File(inDir,name); + FileOutputStream fos = new FileOutputStream(outJar); + JarOutputStream jarOut = new JarOutputStream(fos); + List<File> classFiles = new ArrayList<File>(); + List<File> toExclude = isClasses ? Collections.<File>emptyList() : classFilesFromClasses; + collectClassFiles(inDir,classFiles,toExclude); + if (isClasses) classFilesFromClasses = classFiles; + String prefix = inDir.getPath() + File.separator; + for (File f: classFiles) { + String thisPath = f.getPath(); + if (thisPath.startsWith(prefix)) { + thisPath = thisPath.substring(prefix.length()); + } + JarEntry entry = new JarEntry(thisPath); + jarOut.putNextEntry(entry); + copyFile(f,jarOut); + jarOut.closeEntry(); + } + jarOut.flush(); + jarOut.close(); + } + + private void collectClassFiles(File inDir, List<File> inList, List<File> toExclude) { + File[] contents = inDir.listFiles(); + for (int i = 0; i < contents.length; i++) { + if (contents[i].getName().endsWith(".class")) { + if (!toExclude.contains(contents[i])) { + inList.add(contents[i]); + } + } else if (contents[i].isDirectory()) { + collectClassFiles(contents[i],inList, toExclude); + } + } + } + + private void copyFile(File f, OutputStream dest) throws IOException { + FileInputStream fis = new FileInputStream(f); + byte[] buf = new byte[4096]; + int read = -1; + while((read = fis.read(buf)) != -1) { + dest.write(buf,0,read); + } + fis.close(); + } + + private String[] buildWeaveArgs() { + StringBuffer args = new StringBuffer(); + if (getOptions() != null) { + StringTokenizer strTok = new StringTokenizer(getOptions(),","); + while (strTok.hasMoreTokens()) { + args.append(strTok.nextToken()); + args.append(" "); + } + } + args.append("-inpath "); + args.append("classes.jar"); + args.append(File.pathSeparator); + args.append("aspects.jar"); + args.append(" "); + args.append("-aspectpath "); + args.append("aspects.jar"); + String argumentString = args.toString(); + StringTokenizer strTok = new StringTokenizer(argumentString," "); + String[] ret = new String[strTok.countTokens()]; + for (int i = 0; i < ret.length; i++) { + ret[i] = strTok.nextToken(); + } + return ret; + } + +} diff --git a/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCase.java b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCase.java new file mode 100644 index 000000000..13bbf844e --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCase.java @@ -0,0 +1,522 @@ +/* ******************************************************************* + * Copyright (c) 2004 IBM Corporation + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Adrian Colyer, + * ******************************************************************/ +package org.aspectj.testing; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FilenameFilter; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Stack; + +import org.apache.commons.digester.Digester; +import org.aspectj.apache.bcel.classfile.Attribute; +import org.aspectj.apache.bcel.classfile.JavaClass; +import org.aspectj.apache.bcel.classfile.LocalVariable; +import org.aspectj.apache.bcel.classfile.LocalVariableTable; +import org.aspectj.apache.bcel.classfile.Method; +import org.aspectj.apache.bcel.util.ClassPath; +import org.aspectj.apache.bcel.util.SyntheticRepository; +import org.aspectj.tools.ajc.AjcTestCase; +import org.aspectj.tools.ajc.CompilationResult; +import org.aspectj.util.FileUtil; +import org.aspectj.weaver.AjAttribute; +import org.aspectj.weaver.ResolvedMember; +import org.aspectj.weaver.ResolvedType; +import org.aspectj.weaver.WeaverStateInfo; +import org.aspectj.weaver.AjAttribute.WeaverState; +import org.aspectj.weaver.AjAttribute.WeaverVersionInfo; +import org.aspectj.weaver.bcel.BcelConstantPoolReader; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestSuite; + +/** + * Root class for all Test suites that are based on an AspectJ XML test suite file. Extends AjcTestCase allowing a mix of + * programmatic and spec-file driven testing. See org.aspectj.systemtest.incremental.IncrementalTests for an example of this mixed + * style. + * <p> + * The class org.aspectj.testing.MakeTestClass will generate a subclass of this class for you, given a suite spec. file as input... + * </p> + */ +public abstract class XMLBasedAjcTestCase extends AjcTestCase { + + private static Map<String,AjcTest> testMap = new HashMap<String,AjcTest>(); + private static boolean suiteLoaded = false; + private AjcTest currentTest = null; + private Stack<Boolean> clearTestAfterRun = new Stack<Boolean>(); + + public XMLBasedAjcTestCase() { + } + + /** + * You must define a suite() method in subclasses, and return the result of calling this method. (Don't you hate static methods + * in programming models). For example: + * + * <pre> + * public static Test suite() { + * return XMLBasedAjcTestCase.loadSuite(MyTestCaseClass.class); + * } + * </pre> + * + * @param testCaseClass + * @return + */ + public static Test loadSuite(Class<?> testCaseClass) { + TestSuite suite = new TestSuite(testCaseClass.getName()); + suite.addTestSuite(testCaseClass); + TestSetup wrapper = new TestSetup(suite) { + /* + * (non-Javadoc) + * + * @see junit.extensions.TestSetup#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + suiteLoaded = false; + } + + /* + * (non-Javadoc) + * + * @see junit.extensions.TestSetup#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + suiteLoaded = false; + } + }; + return wrapper; + } + + /** + * The file containing the XML specification for the tests. + */ + protected abstract File getSpecFile(); + + /* + * Return a map from (String) test title -> AjcTest + */ + protected Map<String,AjcTest> getSuiteTests() { + return testMap; + } + + protected WeaverStateInfo getWeaverStateInfo(JavaClass jc) { + WeaverStateInfo wsi = null; + try { + for (Attribute attribute : jc.getAttributes()) { + if (attribute.getName().equals("org.aspectj.weaver.WeaverState")) { + if (wsi != null) { + fail("Found two WeaverState attributes"); + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + attribute.dump(new DataOutputStream(baos)); + baos.close(); + byte[] byteArray = baos.toByteArray(); + byte[] newbytes = new byte[byteArray.length-6]; + System.arraycopy(byteArray, 6, newbytes, 0, newbytes.length); + WeaverState read = (WeaverState) + AjAttribute.read(new WeaverVersionInfo(), WeaverState.AttributeName, + newbytes, null, null, + new BcelConstantPoolReader(jc.getConstantPool())); + wsi = read.reify(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return wsi; + } + + /** + * This helper method runs the test with the given title in the suite spec file. All tests steps in given ajc-test execute in + * the same sandbox. + */ + protected void runTest(String title, boolean print) { + try { + currentTest = (AjcTest) testMap.get(title); + final boolean clearTest = clearTestAfterRun(); + if (currentTest == null) { + if (clearTest) { + System.err.println("test already run: " + title); + return; + } else { + fail("No test '" + title + "' in suite."); + } + } + boolean run = currentTest.runTest(this); + assertTrue("Test not run", run); + if (clearTest) { + testMap.remove(title); + } + } finally { + if (print) { + System.out.println("SYSOUT"); + System.out.println(ajc.getLastCompilationResult().getStandardOutput()); + } + } + } + + protected void runTest(String title) { + runTest(title, false); + } + + /** + * Get the currently executing test. Useful for access to e.g. AjcTest.getTitle() etc.. + */ + protected AjcTest getCurrentTest() { + return currentTest; + } + + /** + * For use by the Digester. As the XML document is parsed, it creates instances of AjcTest objects, which are added to this + * TestCase by the Digester by calling this method. + */ + public void addTest(AjcTest test) { + testMap.put(test.getTitle(), test); + } + + protected final void pushClearTestAfterRun(boolean val) { + clearTestAfterRun.push(val ? Boolean.FALSE : Boolean.TRUE); + } + + protected final boolean popClearTestAfterRun() { + return clearTest(true); + } + + protected final boolean clearTestAfterRun() { + return clearTest(false); + } + + private boolean clearTest(boolean pop) { + if (clearTestAfterRun.isEmpty()) { + return false; + } + boolean result = clearTestAfterRun.peek().booleanValue(); + if (pop) { + clearTestAfterRun.pop(); + } + return result; + } + + /* + * The rules for parsing a suite spec file. The Digester using bean properties to match attributes in the XML document to + * properties in the associated classes, so this simple implementation should be very easy to maintain and extend should you + * ever need to. + */ + protected Digester getDigester() { + Digester digester = new Digester(); + digester.push(this); + digester.addObjectCreate("suite/ajc-test", AjcTest.class); + digester.addSetProperties("suite/ajc-test"); + digester.addSetNext("suite/ajc-test", "addTest", "org.aspectj.testing.AjcTest"); + digester.addObjectCreate("suite/ajc-test/compile", CompileSpec.class); + digester.addSetProperties("suite/ajc-test/compile"); + digester.addSetNext("suite/ajc-test/compile", "addTestStep", "org.aspectj.testing.ITestStep"); + digester.addObjectCreate("suite/ajc-test/file", FileSpec.class); + digester.addSetProperties("suite/ajc-test/file"); + digester.addSetNext("suite/ajc-test/file", "addTestStep", "org.aspectj.testing.ITestStep"); + digester.addObjectCreate("suite/ajc-test/run", RunSpec.class); + digester.addSetProperties("suite/ajc-test/run", "class", "classToRun"); + digester.addSetProperties("suite/ajc-test/run", "module", "moduleToRun"); + digester.addSetProperties("suite/ajc-test/run", "ltw", "ltwFile"); + digester.addSetProperties("suite/ajc-test/run", "xlintfile", "xlintFile"); + digester.addSetProperties("suite/ajc-test/run/stderr", "ordered", "orderedStderr"); + digester.addSetNext("suite/ajc-test/run", "addTestStep", "org.aspectj.testing.ITestStep"); + digester.addObjectCreate("*/message", ExpectedMessageSpec.class); + digester.addSetProperties("*/message"); + digester.addSetNext("*/message", "addExpectedMessage", "org.aspectj.testing.ExpectedMessageSpec"); + digester.addObjectCreate("suite/ajc-test/weave", WeaveSpec.class); + digester.addSetProperties("suite/ajc-test/weave"); + digester.addSetNext("suite/ajc-test/weave", "addTestStep", "org.aspectj.testing.ITestStep"); + + digester.addObjectCreate("suite/ajc-test/ant", AntSpec.class); + digester.addSetProperties("suite/ajc-test/ant"); + digester.addSetNext("suite/ajc-test/ant", "addTestStep", "org.aspectj.testing.ITestStep"); + digester.addObjectCreate("suite/ajc-test/ant/stderr", OutputSpec.class); + digester.addSetProperties("suite/ajc-test/ant/stderr"); + digester.addSetNext("suite/ajc-test/ant/stderr", "addStdErrSpec", "org.aspectj.testing.OutputSpec"); + digester.addObjectCreate("suite/ajc-test/ant/stdout", OutputSpec.class); + digester.addSetProperties("suite/ajc-test/ant/stdout"); + digester.addSetNext("suite/ajc-test/ant/stdout", "addStdOutSpec", "org.aspectj.testing.OutputSpec"); + + digester.addObjectCreate("suite/ajc-test/run/stderr", OutputSpec.class); + digester.addSetProperties("suite/ajc-test/run/stderr"); + digester.addSetNext("suite/ajc-test/run/stderr", "addStdErrSpec", "org.aspectj.testing.OutputSpec"); + digester.addObjectCreate("suite/ajc-test/run/stdout", OutputSpec.class); + digester.addSetProperties("suite/ajc-test/run/stdout"); + digester.addSetNext("suite/ajc-test/run/stdout", "addStdOutSpec", "org.aspectj.testing.OutputSpec"); + digester.addObjectCreate("*/line", OutputLine.class); + digester.addSetProperties("*/line"); + digester.addSetNext("*/line", "addLine", "org.aspectj.testing.OutputLine"); + return digester; + } + + /* + * (non-Javadoc) + * + * @see org.aspectj.tools.ajc.AjcTestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + if (!suiteLoaded) { + testMap = new HashMap<String,AjcTest>(); + System.out.println("LOADING SUITE: " + getSpecFile().getPath()); + Digester d = getDigester(); + try { + InputStreamReader isr = new InputStreamReader(new FileInputStream(getSpecFile())); + d.parse(isr); + } catch (Exception ex) { + fail("Unable to load suite " + getSpecFile().getPath() + " : " + ex); + } + suiteLoaded = true; + } + } + + protected long nextIncrement(boolean doWait) { + long time = System.currentTimeMillis(); + if (doWait) { + try { + Thread.sleep(1000); + } catch (InterruptedException intEx) { + } + } + return time; + } + + protected void copyFile(String from, String to) throws Exception { + String dir = getCurrentTest().getDir(); + FileUtil.copyFile(new File(dir + File.separator + from), new File(ajc.getSandboxDirectory(), to)); + } + + protected void copyFileAndDoIncrementalBuild(String from, String to) throws Exception { + copyFile(from, to); + CompilationResult result = ajc.doIncrementalCompile(); + assertNoMessages(result, "Expected clean compile from test '" + getCurrentTest().getTitle() + "'"); + } + + protected void copyFileAndDoIncrementalBuild(String from, String to, MessageSpec expectedResults) throws Exception { + String dir = getCurrentTest().getDir(); + FileUtil.copyFile(new File(dir + File.separator + from), new File(ajc.getSandboxDirectory(), to)); + CompilationResult result = ajc.doIncrementalCompile(); + assertMessages(result, "Test '" + getCurrentTest().getTitle() + "' did not produce expected messages", expectedResults); + } + + protected void deleteFile(String file) { + new File(ajc.getSandboxDirectory(), file).delete(); + } + + protected void deleteFileAndDoIncrementalBuild(String file, MessageSpec expectedResult) throws Exception { + deleteFile(file); + CompilationResult result = ajc.doIncrementalCompile(); + assertMessages(result, "Test '" + getCurrentTest().getTitle() + "' did not produce expected messages", expectedResult); + } + + protected void deleteFileAndDoIncrementalBuild(String file) throws Exception { + deleteFileAndDoIncrementalBuild(file, MessageSpec.EMPTY_MESSAGE_SET); + } + + protected void assertAdded(String file) { + assertTrue("File " + file + " should have been added", new File(ajc.getSandboxDirectory(), file).exists()); + } + + protected void assertDeleted(String file) { + assertFalse("File " + file + " should have been deleted", new File(ajc.getSandboxDirectory(), file).exists()); + } + + protected void assertUpdated(String file, long sinceTime) { + File f = new File(ajc.getSandboxDirectory(), file); + assertTrue("File " + file + " should have been updated", f.lastModified() > sinceTime); + } + + public SyntheticRepository createRepos(File cpentry) { + ClassPath cp = new ClassPath(cpentry + File.pathSeparator + System.getProperty("java.class.path")); + return SyntheticRepository.getInstance(cp); + } + + protected byte[] loadFileAsByteArray(File f) { + try { + byte[] bs = new byte[100000]; + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); + int pos = 0; + int len = 0; + while ((len=bis.read(bs, pos, 100000-pos))!=-1) { + pos+=len; + } + bis.close(); + return bs; + } catch (Exception e) { + return null; + } + } + + public JavaClass getClassFrom(File where, String clazzname) throws ClassNotFoundException { + SyntheticRepository repos = createRepos(where); + return repos.loadClass(clazzname); + } + + protected Method getMethodStartsWith(JavaClass jc, String prefix) { + return getMethodStartsWith(jc,prefix,1); + } + + protected Attribute getAttributeStartsWith(Attribute[] attributes, String prefix) { + StringBuilder buf = new StringBuilder(); + for (Attribute a: attributes) { + if (a.getName().startsWith(prefix)) { + return a; + } + buf.append(a.toString()).append("\n"); + } + fail("Failed to find '"+prefix+"' in attributes:\n"+buf.toString()); + return null; + } + + protected Method getMethodStartsWith(JavaClass jc, String prefix, int whichone) { + Method[] meths = jc.getMethods(); + for (int i = 0; i < meths.length; i++) { + Method method = meths[i]; + System.out.println(method); + if (method.getName().startsWith(prefix)) { + whichone--; + if (whichone==0) { + return method; + } + } + } + return null; + } + + /** + * Sort it by name then start position + */ + public List<LocalVariable> sortedLocalVariables(LocalVariableTable lvt) { + List<LocalVariable> l = new ArrayList<LocalVariable>(); + LocalVariable lv[] = lvt.getLocalVariableTable(); + for (int i = 0; i < lv.length; i++) { + LocalVariable lvEntry = lv[i]; + l.add(lvEntry); + } + Collections.sort(l, new MyComparator()); + return l; + } + + public String stringify(LocalVariableTable lvt, int slotIndex) { + LocalVariable lv[] = lvt.getLocalVariableTable(); + LocalVariable lvEntry = lv[slotIndex]; + StringBuffer sb = new StringBuffer(); + sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex()) + .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength()); + return sb.toString(); + } + + public String stringify(List<LocalVariable> l, int slotIndex) { + LocalVariable lvEntry = (LocalVariable) l.get(slotIndex); + StringBuffer sb = new StringBuffer(); + sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex()) + .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength()); + return sb.toString(); + } + + public String stringify(LocalVariableTable lvt) { + if (lvt == null) { + return ""; + } + StringBuffer sb = new StringBuffer(); + sb.append("LocalVariableTable. Entries=#" + lvt.getTableLength()).append("\n"); + LocalVariable lv[] = lvt.getLocalVariableTable(); + for (int i = 0; i < lv.length; i++) { + LocalVariable lvEntry = lv[i]; + sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex()) + .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength()).append("\n"); + } + + return sb.toString(); + } + + public static class CountingFilenameFilter implements FilenameFilter { + + private String suffix; + private int count; + + public CountingFilenameFilter(String s) { + this.suffix = s; + } + + public boolean accept(File dir, String name) { + if (name.endsWith(suffix)) { + count++; + } + return false; + } + + public int getCount() { + return count; + } + } + + public static class MyComparator implements Comparator<LocalVariable> { + public int compare(LocalVariable o1, LocalVariable o2) { + LocalVariable l1 = (LocalVariable) o1; + LocalVariable l2 = (LocalVariable) o2; + if (l1.getName().equals(l2.getName())) { + return l1.getStartPC() - l2.getStartPC(); + } else { + return l1.getName().compareTo(l2.getName()); + } + } + + } + + protected Method getMethodFromClass(JavaClass clazz, String methodName) { + Method[] meths = clazz.getMethods(); + for (int i = 0; i < meths.length; i++) { + Method method = meths[i]; + if (method.getName().equals(methodName)) { + return meths[i]; + } + } + return null; + } + + protected File getClassResource(String resourceName) { + return new File(getClass().getResource(resourceName).getFile()); + } + + protected Method findMethod(JavaClass jc, String string) { + for (Method m : jc.getMethods()) { + if (m.getName().equals(string)) { + return m; + } + } + return null; + } + + protected ResolvedMember findMethod(ResolvedType outerType, String string) { + for (ResolvedMember method: outerType.getDeclaredMethods()) { + if (method.getName().equals(string)) { + return method; + } + } + return null; + } + + +} diff --git a/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava10OrLater.java b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava10OrLater.java new file mode 100644 index 000000000..4a8c63f11 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava10OrLater.java @@ -0,0 +1,31 @@ +/* ******************************************************************* + * Copyright (c) 2018 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement + * ******************************************************************/ +package org.aspectj.testing; + +import org.aspectj.util.LangUtil; + +/** + * Ensure sure tests are running on the right level of JDK. + * + * @author Andy Clement + */ +public abstract class XMLBasedAjcTestCaseForJava10OrLater extends XMLBasedAjcTestCase { + + @Override + public void runTest(String title) { + if (!LangUtil.is10VMOrGreater()) { + throw new IllegalStateException("These tests should be run on Java 10 or later"); + } + super.runTest(title); + } + +} diff --git a/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava11OrLater.java b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava11OrLater.java new file mode 100644 index 000000000..b71fc19e9 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava11OrLater.java @@ -0,0 +1,31 @@ +/* ******************************************************************* + * Copyright (c) 2018 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement + * ******************************************************************/ +package org.aspectj.testing; + +/** + * Makes sure tests are running on the right level of JDK. + * + * @author Andy Clement + */ +public abstract class XMLBasedAjcTestCaseForJava11OrLater extends XMLBasedAjcTestCase { + + @Override + public void runTest(String title) { + // Check we are on Java11 + String property = System.getProperty("java.version"); + if (!property.startsWith("11")) { + throw new IllegalStateException("These tests should be run on Java 11 or later"); + } + super.runTest(title); + } + +} diff --git a/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava9OrLater.java b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava9OrLater.java new file mode 100644 index 000000000..205b55273 --- /dev/null +++ b/testing/src/main/java/org/aspectj/testing/XMLBasedAjcTestCaseForJava9OrLater.java @@ -0,0 +1,32 @@ +/* ******************************************************************* + * Copyright (c) 2018 Contributors + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Andy Clement + * ******************************************************************/ +package org.aspectj.testing; + +import org.aspectj.util.LangUtil; + +/** + * Makes sure tests are running on the right level of JDK. + * + * @author Andy Clement + */ +public abstract class XMLBasedAjcTestCaseForJava9OrLater extends XMLBasedAjcTestCase { + + @Override + public void runTest(String title) { + // Check we are on Java9 or later + if (!LangUtil.is19VMOrGreater()) { + throw new IllegalStateException("These tests should be run on Java 9 or later"); + } + super.runTest(title); + } + +} diff --git a/testing/src/org/aspectj/testing/ajde/CompileCommand.java b/testing/src/main/java/org/aspectj/testing/ajde/CompileCommand.java index 86c5fbaf7..86c5fbaf7 100644 --- a/testing/src/org/aspectj/testing/ajde/CompileCommand.java +++ b/testing/src/main/java/org/aspectj/testing/ajde/CompileCommand.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/AbstractRunSpec.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/AbstractRunSpec.java index 4e61a512c..4e61a512c 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/AbstractRunSpec.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/AbstractRunSpec.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/AjcMessageHandler.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/AjcMessageHandler.java index f4a88c3b2..f4a88c3b2 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/AjcMessageHandler.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/AjcMessageHandler.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/AjcTest.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/AjcTest.java index bdebae02c..bdebae02c 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/AjcTest.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/AjcTest.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/CompilerRun.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/CompilerRun.java index 8d6c587fe..8d6c587fe 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/CompilerRun.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/CompilerRun.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/DirChanges.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/DirChanges.java index 13281607b..13281607b 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/DirChanges.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/DirChanges.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/FlatSuiteReader.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/FlatSuiteReader.java index 8d75d5620..8d75d5620 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/FlatSuiteReader.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/FlatSuiteReader.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/Globals.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/Globals.java index ad62c9735..ad62c9735 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/Globals.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/Globals.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/IAjcRun.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/IAjcRun.java index e685df5dd..e685df5dd 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/IAjcRun.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/IAjcRun.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/IRunSpec.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/IRunSpec.java index dc35b493d..dc35b493d 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/IRunSpec.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/IRunSpec.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/IncCompilerRun.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/IncCompilerRun.java index 7c7f2c54e..7c7f2c54e 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/IncCompilerRun.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/IncCompilerRun.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/JavaRun.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/JavaRun.java index aade35f48..aade35f48 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/JavaRun.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/JavaRun.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/RunSpecIterator.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/RunSpecIterator.java index e5792236b..e5792236b 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/RunSpecIterator.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/RunSpecIterator.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/Sandbox.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/Sandbox.java index f7f4df31e..f7f4df31e 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/Sandbox.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/Sandbox.java diff --git a/testing/src/org/aspectj/testing/harness/bridge/Validator.java b/testing/src/main/java/org/aspectj/testing/harness/bridge/Validator.java index 37ddd005e..37ddd005e 100644 --- a/testing/src/org/aspectj/testing/harness/bridge/Validator.java +++ b/testing/src/main/java/org/aspectj/testing/harness/bridge/Validator.java diff --git a/testing/src/org/aspectj/testing/run/IRun.java b/testing/src/main/java/org/aspectj/testing/run/IRun.java index 57639016b..57639016b 100644 --- a/testing/src/org/aspectj/testing/run/IRun.java +++ b/testing/src/main/java/org/aspectj/testing/run/IRun.java diff --git a/testing/src/org/aspectj/testing/run/IRunIterator.java b/testing/src/main/java/org/aspectj/testing/run/IRunIterator.java index 5035b216f..5035b216f 100644 --- a/testing/src/org/aspectj/testing/run/IRunIterator.java +++ b/testing/src/main/java/org/aspectj/testing/run/IRunIterator.java diff --git a/testing/src/org/aspectj/testing/run/IRunListener.java b/testing/src/main/java/org/aspectj/testing/run/IRunListener.java index 4318d618f..4318d618f 100644 --- a/testing/src/org/aspectj/testing/run/IRunListener.java +++ b/testing/src/main/java/org/aspectj/testing/run/IRunListener.java diff --git a/testing/src/org/aspectj/testing/run/IRunStatus.java b/testing/src/main/java/org/aspectj/testing/run/IRunStatus.java index 9c8665728..9c8665728 100644 --- a/testing/src/org/aspectj/testing/run/IRunStatus.java +++ b/testing/src/main/java/org/aspectj/testing/run/IRunStatus.java diff --git a/testing/src/org/aspectj/testing/run/IRunValidator.java b/testing/src/main/java/org/aspectj/testing/run/IRunValidator.java index a341aa167..a341aa167 100644 --- a/testing/src/org/aspectj/testing/run/IRunValidator.java +++ b/testing/src/main/java/org/aspectj/testing/run/IRunValidator.java diff --git a/testing/src/org/aspectj/testing/run/RunIterator.java b/testing/src/main/java/org/aspectj/testing/run/RunIterator.java index 1b5c8f307..1b5c8f307 100644 --- a/testing/src/org/aspectj/testing/run/RunIterator.java +++ b/testing/src/main/java/org/aspectj/testing/run/RunIterator.java diff --git a/testing/src/org/aspectj/testing/run/RunListener.java b/testing/src/main/java/org/aspectj/testing/run/RunListener.java index 0d7c9fc76..0d7c9fc76 100644 --- a/testing/src/org/aspectj/testing/run/RunListener.java +++ b/testing/src/main/java/org/aspectj/testing/run/RunListener.java diff --git a/testing/src/org/aspectj/testing/run/RunListeners.java b/testing/src/main/java/org/aspectj/testing/run/RunListeners.java index 4eb8e7a74..4eb8e7a74 100644 --- a/testing/src/org/aspectj/testing/run/RunListeners.java +++ b/testing/src/main/java/org/aspectj/testing/run/RunListeners.java diff --git a/testing/src/org/aspectj/testing/run/RunStatus.java b/testing/src/main/java/org/aspectj/testing/run/RunStatus.java index ac22280ba..ac22280ba 100644 --- a/testing/src/org/aspectj/testing/run/RunStatus.java +++ b/testing/src/main/java/org/aspectj/testing/run/RunStatus.java diff --git a/testing/src/org/aspectj/testing/run/RunValidator.java b/testing/src/main/java/org/aspectj/testing/run/RunValidator.java index 70131f71a..70131f71a 100644 --- a/testing/src/org/aspectj/testing/run/RunValidator.java +++ b/testing/src/main/java/org/aspectj/testing/run/RunValidator.java diff --git a/testing/src/org/aspectj/testing/run/Runner.java b/testing/src/main/java/org/aspectj/testing/run/Runner.java index 58860be6f..58860be6f 100644 --- a/testing/src/org/aspectj/testing/run/Runner.java +++ b/testing/src/main/java/org/aspectj/testing/run/Runner.java diff --git a/testing/src/org/aspectj/testing/run/WrappedRunIterator.java b/testing/src/main/java/org/aspectj/testing/run/WrappedRunIterator.java index 75be92cb7..75be92cb7 100644 --- a/testing/src/org/aspectj/testing/run/WrappedRunIterator.java +++ b/testing/src/main/java/org/aspectj/testing/run/WrappedRunIterator.java diff --git a/testing/src/org/aspectj/testing/taskdefs/AjcTaskCompileCommand.java b/testing/src/main/java/org/aspectj/testing/taskdefs/AjcTaskCompileCommand.java index 1f5325e82..1f5325e82 100644 --- a/testing/src/org/aspectj/testing/taskdefs/AjcTaskCompileCommand.java +++ b/testing/src/main/java/org/aspectj/testing/taskdefs/AjcTaskCompileCommand.java diff --git a/testing/src/org/aspectj/testing/util/AccumulatingFileFilter.java b/testing/src/main/java/org/aspectj/testing/util/AccumulatingFileFilter.java index e01f71874..e01f71874 100644 --- a/testing/src/org/aspectj/testing/util/AccumulatingFileFilter.java +++ b/testing/src/main/java/org/aspectj/testing/util/AccumulatingFileFilter.java diff --git a/testing/src/org/aspectj/testing/util/BridgeUtil.java b/testing/src/main/java/org/aspectj/testing/util/BridgeUtil.java index f06e93850..f06e93850 100644 --- a/testing/src/org/aspectj/testing/util/BridgeUtil.java +++ b/testing/src/main/java/org/aspectj/testing/util/BridgeUtil.java diff --git a/testing/src/org/aspectj/testing/util/CollectorFileFilter.java b/testing/src/main/java/org/aspectj/testing/util/CollectorFileFilter.java index 7c63c3b6c..7c63c3b6c 100644 --- a/testing/src/org/aspectj/testing/util/CollectorFileFilter.java +++ b/testing/src/main/java/org/aspectj/testing/util/CollectorFileFilter.java diff --git a/testing/src/org/aspectj/testing/util/Diffs.java b/testing/src/main/java/org/aspectj/testing/util/Diffs.java index a6edf0d87..a6edf0d87 100644 --- a/testing/src/org/aspectj/testing/util/Diffs.java +++ b/testing/src/main/java/org/aspectj/testing/util/Diffs.java diff --git a/testing/src/org/aspectj/testing/util/FileUtil.java b/testing/src/main/java/org/aspectj/testing/util/FileUtil.java index db77cbd10..db77cbd10 100644 --- a/testing/src/org/aspectj/testing/util/FileUtil.java +++ b/testing/src/main/java/org/aspectj/testing/util/FileUtil.java diff --git a/testing/src/org/aspectj/testing/util/IntRange.java b/testing/src/main/java/org/aspectj/testing/util/IntRange.java index 1f44f69bd..1f44f69bd 100644 --- a/testing/src/org/aspectj/testing/util/IntRange.java +++ b/testing/src/main/java/org/aspectj/testing/util/IntRange.java diff --git a/testing/src/org/aspectj/testing/util/IntValidator.java b/testing/src/main/java/org/aspectj/testing/util/IntValidator.java index e3697d1aa..e3697d1aa 100644 --- a/testing/src/org/aspectj/testing/util/IntValidator.java +++ b/testing/src/main/java/org/aspectj/testing/util/IntValidator.java diff --git a/testing/src/org/aspectj/testing/util/IteratorWrapper.java b/testing/src/main/java/org/aspectj/testing/util/IteratorWrapper.java index 5b7c13af9..5b7c13af9 100644 --- a/testing/src/org/aspectj/testing/util/IteratorWrapper.java +++ b/testing/src/main/java/org/aspectj/testing/util/IteratorWrapper.java diff --git a/testing/src/org/aspectj/testing/util/LangUtil.java b/testing/src/main/java/org/aspectj/testing/util/LangUtil.java index 2baf81c48..2baf81c48 100644 --- a/testing/src/org/aspectj/testing/util/LangUtil.java +++ b/testing/src/main/java/org/aspectj/testing/util/LangUtil.java diff --git a/testing/src/org/aspectj/testing/util/LineReader.java b/testing/src/main/java/org/aspectj/testing/util/LineReader.java index a6af8266a..a6af8266a 100644 --- a/testing/src/org/aspectj/testing/util/LineReader.java +++ b/testing/src/main/java/org/aspectj/testing/util/LineReader.java diff --git a/testing/src/org/aspectj/testing/util/LinkCheck.java b/testing/src/main/java/org/aspectj/testing/util/LinkCheck.java index 3f1ef92a1..3f1ef92a1 100644 --- a/testing/src/org/aspectj/testing/util/LinkCheck.java +++ b/testing/src/main/java/org/aspectj/testing/util/LinkCheck.java diff --git a/testing/src/org/aspectj/testing/util/Node.java b/testing/src/main/java/org/aspectj/testing/util/Node.java index 9439e57e4..9439e57e4 100644 --- a/testing/src/org/aspectj/testing/util/Node.java +++ b/testing/src/main/java/org/aspectj/testing/util/Node.java diff --git a/testing/src/org/aspectj/testing/util/NullPrintStream.java b/testing/src/main/java/org/aspectj/testing/util/NullPrintStream.java index 686c9c8e2..686c9c8e2 100644 --- a/testing/src/org/aspectj/testing/util/NullPrintStream.java +++ b/testing/src/main/java/org/aspectj/testing/util/NullPrintStream.java diff --git a/testing/src/org/aspectj/testing/util/ObjectChecker.java b/testing/src/main/java/org/aspectj/testing/util/ObjectChecker.java index 25985ae5e..25985ae5e 100644 --- a/testing/src/org/aspectj/testing/util/ObjectChecker.java +++ b/testing/src/main/java/org/aspectj/testing/util/ObjectChecker.java diff --git a/testing/src/org/aspectj/testing/util/ProxyPrintStream.java b/testing/src/main/java/org/aspectj/testing/util/ProxyPrintStream.java index 5c5bbe9de..5c5bbe9de 100644 --- a/testing/src/org/aspectj/testing/util/ProxyPrintStream.java +++ b/testing/src/main/java/org/aspectj/testing/util/ProxyPrintStream.java diff --git a/testing/src/org/aspectj/testing/util/RunUtils.java b/testing/src/main/java/org/aspectj/testing/util/RunUtils.java index 86c29a4a2..86c29a4a2 100644 --- a/testing/src/org/aspectj/testing/util/RunUtils.java +++ b/testing/src/main/java/org/aspectj/testing/util/RunUtils.java diff --git a/testing/src/org/aspectj/testing/util/SFileReader.java b/testing/src/main/java/org/aspectj/testing/util/SFileReader.java index eecf2d304..eecf2d304 100644 --- a/testing/src/org/aspectj/testing/util/SFileReader.java +++ b/testing/src/main/java/org/aspectj/testing/util/SFileReader.java diff --git a/testing/src/org/aspectj/testing/util/StandardObjectChecker.java b/testing/src/main/java/org/aspectj/testing/util/StandardObjectChecker.java index bc2f520ad..bc2f520ad 100644 --- a/testing/src/org/aspectj/testing/util/StandardObjectChecker.java +++ b/testing/src/main/java/org/aspectj/testing/util/StandardObjectChecker.java diff --git a/testing/src/org/aspectj/testing/util/StreamSniffer.java b/testing/src/main/java/org/aspectj/testing/util/StreamSniffer.java index cb143604e..cb143604e 100644 --- a/testing/src/org/aspectj/testing/util/StreamSniffer.java +++ b/testing/src/main/java/org/aspectj/testing/util/StreamSniffer.java diff --git a/testing/src/org/aspectj/testing/util/StreamsHandler.java b/testing/src/main/java/org/aspectj/testing/util/StreamsHandler.java index fc69d9900..fc69d9900 100644 --- a/testing/src/org/aspectj/testing/util/StreamsHandler.java +++ b/testing/src/main/java/org/aspectj/testing/util/StreamsHandler.java diff --git a/testing/src/org/aspectj/testing/util/StringAccumulator.java b/testing/src/main/java/org/aspectj/testing/util/StringAccumulator.java index 234592386..234592386 100644 --- a/testing/src/org/aspectj/testing/util/StringAccumulator.java +++ b/testing/src/main/java/org/aspectj/testing/util/StringAccumulator.java diff --git a/testing/src/org/aspectj/testing/util/StringVisitor.java b/testing/src/main/java/org/aspectj/testing/util/StringVisitor.java index 123376df4..123376df4 100644 --- a/testing/src/org/aspectj/testing/util/StringVisitor.java +++ b/testing/src/main/java/org/aspectj/testing/util/StringVisitor.java diff --git a/testing/src/org/aspectj/testing/util/StructureModelUtil.java b/testing/src/main/java/org/aspectj/testing/util/StructureModelUtil.java index 10e03dd22..10e03dd22 100644 --- a/testing/src/org/aspectj/testing/util/StructureModelUtil.java +++ b/testing/src/main/java/org/aspectj/testing/util/StructureModelUtil.java diff --git a/testing/src/org/aspectj/testing/util/TestClassLoader.java b/testing/src/main/java/org/aspectj/testing/util/TestClassLoader.java index dd9c10c8f..dd9c10c8f 100644 --- a/testing/src/org/aspectj/testing/util/TestClassLoader.java +++ b/testing/src/main/java/org/aspectj/testing/util/TestClassLoader.java diff --git a/testing/src/org/aspectj/testing/util/TestDiffs.java b/testing/src/main/java/org/aspectj/testing/util/TestDiffs.java index 54f72e9b9..54f72e9b9 100644 --- a/testing/src/org/aspectj/testing/util/TestDiffs.java +++ b/testing/src/main/java/org/aspectj/testing/util/TestDiffs.java diff --git a/testing/src/org/aspectj/testing/util/UtilLineReader.java b/testing/src/main/java/org/aspectj/testing/util/UtilLineReader.java index ebb6c9d98..ebb6c9d98 100644 --- a/testing/src/org/aspectj/testing/util/UtilLineReader.java +++ b/testing/src/main/java/org/aspectj/testing/util/UtilLineReader.java diff --git a/testing/src/org/aspectj/testing/util/ValidFileFilter.java b/testing/src/main/java/org/aspectj/testing/util/ValidFileFilter.java index 8d069af0f..8d069af0f 100644 --- a/testing/src/org/aspectj/testing/util/ValidFileFilter.java +++ b/testing/src/main/java/org/aspectj/testing/util/ValidFileFilter.java diff --git a/testing/src/org/aspectj/testing/util/WebInstall.java b/testing/src/main/java/org/aspectj/testing/util/WebInstall.java index 3433d55b6..3433d55b6 100644 --- a/testing/src/org/aspectj/testing/util/WebInstall.java +++ b/testing/src/main/java/org/aspectj/testing/util/WebInstall.java diff --git a/testing/src/org/aspectj/testing/util/options/Option.java b/testing/src/main/java/org/aspectj/testing/util/options/Option.java index e845a89bf..e845a89bf 100644 --- a/testing/src/org/aspectj/testing/util/options/Option.java +++ b/testing/src/main/java/org/aspectj/testing/util/options/Option.java diff --git a/testing/src/org/aspectj/testing/util/options/Options.java b/testing/src/main/java/org/aspectj/testing/util/options/Options.java index 04a968d88..04a968d88 100644 --- a/testing/src/org/aspectj/testing/util/options/Options.java +++ b/testing/src/main/java/org/aspectj/testing/util/options/Options.java diff --git a/testing/src/org/aspectj/testing/util/options/Values.java b/testing/src/main/java/org/aspectj/testing/util/options/Values.java index 574969080..574969080 100644 --- a/testing/src/org/aspectj/testing/util/options/Values.java +++ b/testing/src/main/java/org/aspectj/testing/util/options/Values.java diff --git a/testing/src/org/aspectj/testing/xml/AjcSpecXmlReader.java b/testing/src/main/java/org/aspectj/testing/xml/AjcSpecXmlReader.java index 370a9ac91..370a9ac91 100644 --- a/testing/src/org/aspectj/testing/xml/AjcSpecXmlReader.java +++ b/testing/src/main/java/org/aspectj/testing/xml/AjcSpecXmlReader.java diff --git a/testing/src/org/aspectj/testing/xml/IXmlWritable.java b/testing/src/main/java/org/aspectj/testing/xml/IXmlWritable.java index a11b32be3..a11b32be3 100644 --- a/testing/src/org/aspectj/testing/xml/IXmlWritable.java +++ b/testing/src/main/java/org/aspectj/testing/xml/IXmlWritable.java diff --git a/testing/src/org/aspectj/testing/xml/MessageListXmlReader.java b/testing/src/main/java/org/aspectj/testing/xml/MessageListXmlReader.java index cde5e99dd..cde5e99dd 100644 --- a/testing/src/org/aspectj/testing/xml/MessageListXmlReader.java +++ b/testing/src/main/java/org/aspectj/testing/xml/MessageListXmlReader.java diff --git a/testing/src/org/aspectj/testing/xml/SoftMessage.java b/testing/src/main/java/org/aspectj/testing/xml/SoftMessage.java index f59bf397e..f59bf397e 100644 --- a/testing/src/org/aspectj/testing/xml/SoftMessage.java +++ b/testing/src/main/java/org/aspectj/testing/xml/SoftMessage.java diff --git a/testing/src/org/aspectj/testing/xml/SoftSourceLocation.java b/testing/src/main/java/org/aspectj/testing/xml/SoftSourceLocation.java index 17f5ae673..17f5ae673 100644 --- a/testing/src/org/aspectj/testing/xml/SoftSourceLocation.java +++ b/testing/src/main/java/org/aspectj/testing/xml/SoftSourceLocation.java diff --git a/testing/src/org/aspectj/testing/xml/XMLWriter.java b/testing/src/main/java/org/aspectj/testing/xml/XMLWriter.java index 422576c56..422576c56 100644 --- a/testing/src/org/aspectj/testing/xml/XMLWriter.java +++ b/testing/src/main/java/org/aspectj/testing/xml/XMLWriter.java diff --git a/testing/src/test/java/org/aspectj/testing/TestingModuleTests.java b/testing/src/test/java/org/aspectj/testing/TestingModuleTests.java new file mode 100644 index 000000000..b6c20b215 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/TestingModuleTests.java @@ -0,0 +1,36 @@ +package org.aspectj.testing; +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +// default package + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class TestingModuleTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(TestingModuleTests.class.getName()); + suite.addTest(org.aspectj.testing.harness.bridge.TestingBridgeTests.suite()); + suite.addTest(org.aspectj.testing.taskdefs.TaskdefTests.suite()); + suite.addTest(org.aspectj.testing.util.UtilTests.suite()); + suite.addTest(org.aspectj.testing.util.options.OptionsTests.suite()); + suite.addTest(org.aspectj.testing.xml.TestingXmlTests.suite()); + return suite; + } + + public TestingModuleTests(String name) { super(name); } + +} diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/AbstractRunSpecTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/AbstractRunSpecTest.java new file mode 100644 index 000000000..1f6ab38ab --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/AbstractRunSpecTest.java @@ -0,0 +1,65 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.harness.bridge; + +import java.io.PrintWriter; +import java.util.List; + +import junit.framework.TestCase; + +import org.aspectj.testing.run.IRunIterator; +import org.aspectj.testing.xml.XMLWriter; + +/** + * + */ +public class AbstractRunSpecTest extends TestCase { + + public AbstractRunSpecTest(String name) { + super(name); + } + + public void testXmlWrite() { + AbstractRunSpec spec = new TestSpec(); + spec.setOptions("-option1,-option2"); + spec.setKeywords("keyword1, keyword2"); + spec.setPaths("path1.java, path2.java"); + spec.setDescription("some description, with extra"); + XMLWriter out = new XMLWriter(new PrintWriter(System.out)); + spec.writeXml(out); + //out.close();//FIXME this close System.out and makes the IntelliJ test runner hang (AV) + } + + public void testSetOptions() { + AbstractRunSpec spec = new TestSpec(); + spec.setOptions("1,2"); + List options = spec.getOptionsList(); + String s = "" + options; + assertTrue(s, "[1, 2]".equals(s)); + } + + static class TestSpec extends AbstractRunSpec { + TestSpec() { + super("testspec"); + } + /** + * @see org.aspectj.testing.harness.bridge.AbstractRunSpec#makeRunIterator(Sandbox, Validator) + */ + public IRunIterator makeRunIterator( + Sandbox sandbox, + Validator validator) { + return null; + } + } +} diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcSpecTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcSpecTest.java new file mode 100644 index 000000000..0c469ec3a --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcSpecTest.java @@ -0,0 +1,378 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.harness.bridge; + +import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.Assert; +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +import org.aspectj.bridge.*; +import org.aspectj.bridge.IMessage; +import org.aspectj.bridge.ISourceLocation; +import org.aspectj.bridge.MessageUtil; + +/** + * Primarily used by others to test AjcTest + */ +public class AjcSpecTest extends TestCase { + public static final String NOTSAME = " != "; + public static void sameAjcSuiteSpec( + AjcTest.Suite.Spec lhsSpec, + AjcTest.Suite.Spec rhsSpec, + Assert a) { + assertNotNull(lhsSpec); + assertNotNull(rhsSpec); + Iterator lhs = lhsSpec.getChildren().iterator(); + Iterator rhs = rhsSpec.getChildren().iterator(); + while (lhs.hasNext() && rhs.hasNext()) { + AjcTest.Spec lhsTest = (AjcTest.Spec) lhs.next(); + AjcTest.Spec rhsTest = (AjcTest.Spec) rhs.next(); + AjcSpecTest.sameAjcTestSpec(lhsTest, rhsTest, a); + } + assertTrue(!lhs.hasNext()); + assertTrue(!rhs.hasNext()); + } + + public static void sameAjcTestSpec( + AjcTest.Spec lhsTest, + AjcTest.Spec rhsTest, + Assert a) { + assertNotNull(lhsTest); + assertNotNull(rhsTest); + assertEquals(lhsTest.getBugId(), rhsTest.getBugId()); + assertEquals(lhsTest.getTestDirOffset(), rhsTest.getTestDirOffset()); + // XXX suiteDir varies by run.. + // description, options, paths, comments, keywords + sameAbstractRunSpec(lhsTest, rhsTest, a); + } + + public static void sameAbstractRunSpec( + AbstractRunSpec lhs, + AbstractRunSpec rhs, + Assert a) { + assertEquals(lhs.description, rhs.description); + // XXX keywords added in .txt reading - + //sameList(lhs.getKeywordsList(), rhs.getKeywordsList(), a); + // XXX sameList(lhs.globalOptions, rhs.globalOptions, a); + sameList(lhs.getOptionsList(), rhs.getOptionsList(), a); + sameList(lhs.getPathsList(), rhs.getPathsList(), a); + assertEquals(lhs.isStaging(), rhs.isStaging()); + sameList(lhs.keywords, rhs.keywords, a); + assertEquals(lhs.comment, rhs.comment); + assertEquals(lhs.badInput, rhs.badInput); + // xml adds sourceloc? + //sameSourceLocation(lhs.getSourceLocation(), rhs.getSourceLocation(), a); + // XXX also sourceLocations? + sameMessages(lhs.getMessages(), rhs.getMessages(), a); + } + + /** @return normal form - null is "", "" is "", and others are {fully.qualified.class}.toString().trim() */ + static String normal(Object input) { + if ((null == input) || ("".equals(input))) { + return ""; + } else { + return input.getClass().getName() + "." + input.toString().trim(); + } + } + + /** @return true if these match after normalizing */ + public static void same(Object lhs, Object rhs, Assert a) { + lhs = normal(lhs); + rhs = normal(rhs); + assertTrue(lhs + NOTSAME + rhs, lhs.equals(rhs)); + } + + /** @return true if both are empty (null or no entries) or if all match */ + public static void sameRA(String[] lhs, String[] rhs, Assert a) { + if (null == lhs) { + assertTrue((null == rhs) || (0 == rhs.length)); + } else if (null == rhs) { + assertTrue(0 == lhs.length); + } else { + String l = normal(lhs); + String r = normal(rhs); + assertTrue(l + NOTSAME + r, l.equals(r)); + } + } + + /** @return normal form for String[] items*/ + static String normal(String[] items) { + return (null == items ? "[]" : normal(Arrays.asList(items))); + } + + /** @return normal form for list items */ + static String normal(List list) { + StringBuffer sb = new StringBuffer(); + sb.append("["); + boolean first = true; + for (Iterator iter = list.iterator(); iter.hasNext();) { + Object o = iter.next(); + if (!first) { + sb.append(", "); + } else { + first = false; + } + sb.append(normal(o)); + } + sb.append("]"); + return sb.toString(); + } + + /** @return true if both are empty (null or no entries) or if all match after trimming */ + public static void sameListSize(List lhs, List rhs) { + if (null == lhs) { + assertTrue((null == rhs) || (0 == rhs.size())); + } else if (null == rhs) { + assertTrue(0 == lhs.size()); + } else { + assertTrue(rhs.size() == lhs.size()); + } + } + + /** @return true if both are empty (null or no entries) or if all match after trimming */ + public static void sameList(List lhs, List rhs, Assert a) { + sameListSize(lhs, rhs); + String l = normal(lhs); + String r = normal(rhs); + String label = l + NOTSAME + r; + assertTrue(label, l.equals(r)); + } + +// /** +// * Normalize and compare: +// * <li>bug id's are not compared since extracted during xml writing</li> +// * <li>keyword compare is disabled since keywords are generated during xml reading.</li> +// * <li>description compare is normalized by stripping bug ids</li> +// * <li>String and arrays are equal when empty (null or 0-length)</li> +// * @see Ajctest#stripBugId(String) +// */ +// public static void sameAjcTest(AjcTest lhs, AjcTest rhs, Assert reporter) { +// Assert a = reporter; +// String label = lhs + NOTSAME + rhs; +// assertTrue(label, null != lhs); +// assertTrue(label, null != rhs); +// //assertTrue(label, lhs.ignoreWarnings == rhs.ignoreWarnings); +// // XXX disabled - not in .txt +// // sameStringList(lhs.keywords, rhs.keywords, a); +// // sameString(lhs.bugId, rhs.bugId, a); +// // argh - bugid stripped from description +// //same(AjcTest.stripBugId(lhs.description), AjcTest.stripBugId(lhs.description), a); +// //sameRA(lhs.globals, rhs.globals, a); +// //lhs.reset(); +// //rhs.reset(); +// boolean gotOne = false; +// IMessageHolder holder = new MessageHandler(); +// assertTrue(label, !holder.hasAnyMessage(IMessage.FAIL, IMessageHolder.ORGREATER)); +// while (lhs.hasNextRun() && rhs.hasNextRun()) { +// sameIAjcRun((IAjcRun) lhs.nextRun(holder), (IAjcRun) rhs.nextRun(holder), reporter); +// assertTrue(label, !holder.hasAnyMessage(IMessage.FAIL, IMessageHolder.ORGREATER)); +// if (!gotOne) { +// gotOne = true; +// } +// } +// assertTrue(label, gotOne); +// assertTrue(label, !lhs.hasNextRun()); +// assertTrue(label, !rhs.hasNextRun()); +// } + + public static void sameIAjcRun(IAjcRun lhs, IAjcRun rhs, Assert reporter) { +// Assert a = reporter; + assertTrue(lhs != null); + assertTrue(rhs != null); + Class c = lhs.getClass(); + assertTrue(c == rhs.getClass()); + AbstractRunSpec lhsSpec; + AbstractRunSpec rhsSpec; + + if (c == CompilerRun.class) { + CompilerRun.Spec l = ((CompilerRun) lhs).spec; + CompilerRun.Spec r = ((CompilerRun) rhs).spec; + lhsSpec = l; + rhsSpec = r; + assertEquals(l.argfiles, r.argfiles); + assertEquals(l.aspectpath, r.aspectpath); + assertEquals(l.testSrcDirOffset, r.testSrcDirOffset); + assertEquals(l.compiler, r.compiler); + assertEquals(l.includeClassesDir, r.includeClassesDir); + assertEquals(l.reuseCompiler, r.reuseCompiler); + assertEquals(l.sourceroots, r.sourceroots); + assertEquals(l.extdirs, r.extdirs); + } else if (c == JavaRun.class) { + JavaRun.Spec l = ((JavaRun) lhs).spec; + JavaRun.Spec r = ((JavaRun) rhs).spec; + lhsSpec = l; + rhsSpec = r; + assertTrue(l.skipTester == r.skipTester); + assertEquals(l.className, r.className); + assertEquals(l.javaVersion, r.javaVersion); + assertEquals(l.skipTester, r.skipTester); + assertEquals(l.outStreamIsError, r.outStreamIsError); + assertEquals(l.errStreamIsError, r.errStreamIsError); + } else if (c == IncCompilerRun.class) { + IncCompilerRun.Spec l = ((IncCompilerRun) lhs).spec; + IncCompilerRun.Spec r = ((IncCompilerRun) rhs).spec; + lhsSpec = l; + rhsSpec = r; + assertEquals(l.tag, r.tag); + assertEquals(l.fresh, r.fresh); + } else { + assertTrue(lhs.equals(rhs)); + return; + } + sameSpec(lhsSpec, rhsSpec, reporter); + } + + public static void sameSpec(AbstractRunSpec lhs, AbstractRunSpec rhs, Assert a) { + if ((null == lhs) && (null == rhs)) { + return; + } + assertTrue(lhs != null); + assertTrue(rhs != null); + assertEquals(""+lhs.getOptionsList(), ""+rhs.getOptionsList()); + sameList(lhs.getPathsList(), rhs.getPathsList(), a); + sameMessages(lhs.getMessages(), rhs.getMessages(), a); + sameDirChangesList(lhs.dirChanges, rhs.dirChanges, a); + } + + public static void sameDirChangesList(ArrayList lhs, ArrayList rhs, Assert a) { + if ((null == lhs) && (null == rhs)) { + return; + } + assertTrue(rhs != null); + assertTrue(lhs != null); + sameListSize(lhs, rhs); + Iterator lhsIter = lhs.iterator(); + Iterator rhsIter = rhs.iterator(); + while (lhsIter.hasNext() && rhsIter.hasNext()) { + sameDirChangesSpec((DirChanges.Spec) lhsIter.next(), (DirChanges.Spec) rhsIter.next(), a); + } + } + + public static void sameDirChangesSpec(DirChanges.Spec lhs, DirChanges.Spec rhs, Assert a) { + if ((null == lhs) && (null == rhs)) { + return; + } + assertTrue(rhs != null); + assertTrue(lhs != null); + assertEquals(lhs.defaultSuffix, rhs.defaultSuffix); + assertEquals(lhs.dirToken, rhs.dirToken); + assertEquals(lhs.fastFail, rhs.fastFail); + assertEquals(lhs.expDir, rhs.expDir); // XXX normalize? + sameList(lhs.updated, rhs.updated, a); + sameList(lhs.removed, rhs.removed, a); + sameList(lhs.added, rhs.added, a); + } + + public static void sameMessages(IMessageHolder one, IMessageHolder two, Assert a) { + if ((null == one) && (null == two)) { + return; + } + // order matters here + ListIterator lhs = one.getUnmodifiableListView().listIterator(); + ListIterator rhs = two.getUnmodifiableListView().listIterator(); + while (lhs.hasNext() && rhs.hasNext()) { + sameMessage((IMessage) lhs.next(), (IMessage) rhs.next(), a); + } + assertTrue(!lhs.hasNext()); + assertTrue(!rhs.hasNext()); + } + + public static void sameMessage(IMessage lhs, IMessage rhs, Assert a) { + if ((null == lhs) && (null == rhs)) { + return; + } + assertTrue(lhs != null); + assertTrue(rhs != null); + assertTrue(lhs.getKind() == rhs.getKind()); + same(lhs.getMessage(), rhs.getMessage(), a); + same(lhs.getDetails(), rhs.getDetails(), a); + assertEquals(lhs.getThrown(), rhs.getThrown()); + sameSourceLocation(lhs.getSourceLocation(), rhs.getSourceLocation()); + sameSourceLocations(lhs.getExtraSourceLocations(), rhs.getExtraSourceLocations()); + } + public static void sameSourceLocations(List lhs, List rhs) { + sameListSize(lhs, rhs); + if ((null == lhs) || (0 == lhs.size())) { + return; + } + // ok, do order-dependent check.. + ListIterator iterLeft = lhs.listIterator(); + ListIterator iterRight = rhs.listIterator(); + while (iterLeft.hasNext() && iterRight.hasNext()) { + ISourceLocation left = (ISourceLocation) iterLeft.next(); + ISourceLocation right = (ISourceLocation) iterRight.next(); + sameSourceLocation(left, right); + } + assertTrue(!iterLeft.hasNext()); + assertTrue(!iterRight.hasNext()); + + } + + public static void sameSourceLocation(ISourceLocation lhs, ISourceLocation rhs) { + if ((null == lhs) && (null == rhs)) { + return; + } + assertTrue(lhs != null); + assertTrue(rhs != null); + assertTrue(lhs.getLine() == rhs.getLine()); + assertTrue(lhs.getColumn() == rhs.getColumn()); + assertTrue(lhs.getOffset() == rhs.getOffset()); + assertTrue(lhs.getEndLine() == rhs.getEndLine()); + // XXX need to compare files, permitting null == NONE + } + + /** + * Constructor for AjcSpecTest. + * @param name + */ + public AjcSpecTest(String name) { + super(name); + } + + public void testMinimal() { + AjcTest.Spec one = new AjcTest.Spec(); + AjcTest.Spec two = new AjcTest.Spec(); + // empty/identity tests + sameAjcTestSpec(one, two, this); + + one.addOption("-one"); + one.addKeyword("keyword"); + one.addPath("path"); + IMessage m = MessageUtil.info("info message"); + one.addMessage(m); + DirChanges.Spec dcspec = new DirChanges.Spec(); + dcspec.setDirToken("dirToken"); + dcspec.setDefaultSuffix(".suffix"); + one.addDirChanges(dcspec); + + // full/identity tests + sameAjcTestSpec(one, one, this); + // XXX need to clone... + + // XXX need to test that more differences are detected + boolean passed = false; + try { + sameAjcTestSpec(one, two, this); + } catch (AssertionFailedError e) { + passed = true; + } + assertTrue("did not get expected exception", passed); + } +} diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunSpecTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunSpecTest.java new file mode 100644 index 000000000..83e14cf10 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunSpecTest.java @@ -0,0 +1,567 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC), + * 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * Wes Isberg 2003 modifications + * ******************************************************************/ + +package org.aspectj.testing.harness.bridge; + +import java.util.*; +import java.util.Arrays; + +import junit.framework.TestCase; + +import org.aspectj.bridge.MessageHandler; +import org.aspectj.bridge.MessageUtil; +import org.aspectj.testing.harness.bridge.CompilerRun.Spec.CRSOptions; +import org.aspectj.testing.util.options.*; +import org.aspectj.testing.util.options.Options; +import org.aspectj.util.LangUtil; + +/** + * + */ +public class CompilerRunSpecTest extends TestCase { + + private static boolean PRINTING = true; + private static final boolean SETUP_JAVA13 = + haveProperty(Globals.J2SE13_RTJAR_NAME); + private static final boolean SETUP_JAVA14 = + haveProperty(Globals.J2SE14_RTJAR_NAME); + static { + if (!SETUP_JAVA14) { + System.err.println( + "warning: set -D" + + Globals.J2SE14_RTJAR_NAME + + "=... in order to run all tests"); + } + if (!SETUP_JAVA13) { + System.err.println( + "warning: set -D" + + Globals.J2SE13_RTJAR_NAME + + "=... in order to run all tests"); + } + } + + private static String[][] duplicate(String[][] input, String prefix) { + String[][] output = new String[input.length][]; + final int prefixLength = (null == prefix ? 0 : prefix.length()); + for (int i = 0; i < output.length; i++) { + int length = input[i].length; + output[i] = new String[length]; + if ((length > 0) && (prefixLength > 0)) { + System.arraycopy(input[i], 0, output[i], 0, length); + output[i][0] = + prefix + output[i][0].substring(prefixLength); + } + } + return output; + } + + private static boolean haveProperty(String key) { + try { + return (null != System.getProperty(key)); + } catch (Throwable t) { + // ignore + } + return false; + } + + /** + * Constructor for CompilerRunSpecTest. + * @param name + */ + public CompilerRunSpecTest(String name) { + super(name); + } + + public void testSetupArgs() { + checkSetupArgs("eclipse", true); + checkSetupArgs("verbose", false); + } + + public void testCompliance() { + // 1.3 should work + String specOptions = "-1.3"; + String[] globalOptions = new String[0]; + boolean expectAdopted = true; + String resultContains = "1.3"; + String messagesContain = null; + MessageHandler handler = + runTest( + specOptions, + globalOptions, + expectAdopted, + resultContains, + messagesContain); + checkMessages(handler, null); + + // 1.3 should work with collision? + globalOptions = new String[] { "-1.3" }; + resultContains = "1.3"; + handler = + runTest( + specOptions, + globalOptions, + expectAdopted, + resultContains, + messagesContain); + checkMessages(handler, null); + + // 1.4 should work + globalOptions = new String[0]; + specOptions = "-1.4"; + resultContains = "1.4"; + handler = + runTest( + specOptions, + globalOptions, + expectAdopted, + resultContains, + messagesContain); + checkMessages(handler, null); + + // compliance not checked for valid numbers, so -1.2 would pass + } + + private void checkMessages(MessageHandler handler, String contains) { + if (null == contains) { + if (0 != handler.numMessages(null, true)) { + assertTrue("" + handler, false); + } + } else { + String messages = "" + handler; + if (-1 == messages.indexOf(contains)) { + assertTrue(messages, false); + } + } + } + + /** @testcase check -target converts for 1.1 and 1.2, not others */ + public void testTarget() { + final boolean PASS = true; + final boolean FAIL = false; + checkSourceTargetVersionConversion("target", 1, PASS, null); + checkSourceTargetVersionConversion("target", 2, PASS, null); + checkSourceTargetVersionConversion("target", 3, PASS, null); + checkSourceTargetVersionConversion("target", 4, PASS, null); + checkSourceTargetVersionConversion("target", 5, PASS, null); + checkSourceTargetVersionConversion("target", 6, FAIL, "illegal input"); + } + + /** @testcase check -source converts for 1.3 and 1.4, not others */ + public void testSource() { + final boolean PASS = true; + final boolean FAIL = false; + if (SETUP_JAVA13) { + checkSourceTargetVersionConversion("source", 3, PASS, null); + } + if (SETUP_JAVA14) { + checkSourceTargetVersionConversion("source", 4, PASS, null); + } + + checkSourceTargetVersionConversion( + "source", + 2, + FAIL, + "not permitted"); + checkSourceTargetVersionConversion( + "source", + 6, + FAIL, + "not permitted"); + } + + public void testSourceOverride() { + if (SETUP_JAVA13 && SETUP_JAVA14) { + checkSourceTargetOverride("source", 3, 4); + checkSourceTargetOverride("source", 4, 3); + checkSourceTargetOverride("source", 3, 3); + checkSourceTargetOverride("source", 4, 4); + } + } + + public void testTargetOverride() { + checkSourceTargetOverride("target", 1, 2); + checkSourceTargetOverride("target", 2, 1); + checkSourceTargetOverride("target", 1, 1); + checkSourceTargetOverride("target", 2, 2); + } + + public void testCompilerOptions() { + checkCompilerOption(null, CompilerRun.Spec.DEFAULT_COMPILER); + CRSOptions crsOptions = CompilerRun.Spec.testAccessToCRSOptions(); + Set options = crsOptions.compilerOptions(); + assertTrue(null != options); + StringBuffer notLoaded = new StringBuffer(); + for (Iterator iter = options.iterator(); iter.hasNext();) { + Option compilerOption = (Option) iter.next(); + if (!(crsOptions.compilerIsLoadable(compilerOption))) { + notLoaded.append(" " + compilerOption); + } else { + String className = crsOptions.compilerClassName(compilerOption); + String argValue = compilerOption.toString(); // XXX snoop + String arg = Option.ON.render(argValue); + checkCompilerOption(arg, className); + } + } + if (0 < notLoaded.length()) { + System.err.println( + getClass().getName() + + ".testCompilerOptions()" + + " warning: compiler options not tested because not loadable: " + + notLoaded); + } + } + + /** + * Checck that setting arg as spec compiler and setting up args + * results in this compiler classname. + * @param arg + * @param className + */ + void checkCompilerOption(String arg, String className) { + MessageHandler handler = new MessageHandler(); + try { + CompilerRun.Spec spec = null; + try { + spec = new CompilerRun.Spec(); + } catch (Throwable t) { + t.printStackTrace(System.err); + } + assertTrue(spec != null); + AbstractRunSpec.RT parentRuntime = new AbstractRunSpec.RT(); + String result; +// String expResult; + + if (null != arg) { + parentRuntime.setOptions(new String[] { arg }); + } + if (!spec.adoptParentValues(parentRuntime, handler)) { + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } else { + assertTrue("adopt failed, but no messages", false); + } + } + result = "" + spec.testSetup.commandOptions; + assertEquals("[]", result); + assertEquals(className, spec.testSetup.compilerName); + } finally { + } + } + + public void testSpecOptions() { + Options options = CompilerRun.Spec.testAccessToOptions(); + OptionChecker optionChecker = new OptionChecker(options); + // known failures: extdirs, aspectpath, Xlintfile <file> + // progress, time, noExit, repeat <n>, + // help, + String[][] input = + new String[][] { + new String[] { "-verbose" }, + new String[] { "-incremental" }, + new String[] { "-emacssym" }, + new String[] { "-Xlint" }, + new String[] { "-Xlint:error" }, + new String[] { "-1.3" }, + new String[] { "-1.4" }, + new String[] { "-source", "1.3" }, + new String[] { "-source", "1.4" }, + new String[] { "-target", "1.1" }, + new String[] { "-target", "1.2" }, + new String[] { "-preserveAllLocals" }, + new String[] { "-referenceInfo" }, + new String[] { "-deprecation" }, + new String[] { "-noImportError" }, + new String[] { "-proceedOnError" } + }; + String[][] literalInput = + new String[][] { + new String[] { "-nowarn" }, + new String[] { "-warn:deprecated" }, + new String[] { "-warn:deprecated,unverified" }, + new String[] { "-warn:deprecated", "-warn:unusedLocals" }, + new String[] { "-g" }, + new String[] { "-g", "-g:none" }, + new String[] { "-g:vars,source" }, + new String[] { "-verbose", "-g:vars,source" }, + }; + // normal + for (int i = 0; i < input.length; i++) { + optionChecker.checkOptions(input[i], input[i]); + } + for (int i = 0; i < literalInput.length; i++) { + optionChecker.checkOptions(literalInput[i], literalInput[i]); + } + // force-on + String[][] forceInput = duplicate(input, "!"); + for (int i = 0; i < input.length; i++) { + optionChecker.checkOptions(forceInput[i], input[i]); + } + // force-off + forceInput = duplicate(input, "^"); + String[] none = new String[0]; + for (int i = 0; i < input.length; i++) { + optionChecker.checkOptions(forceInput[i], none); + } + } + + public void checkSourceTargetOverride(String name, int from, int to) { + final String specOptions = "-" + name + ", 1." + from; + String[] globalOptions = new String[] { "!" + name, "1." + to }; + boolean expectAdopted = true; + String resultContains = "[-" + name + ", 1." + to; + String messagesContain = null; + MessageHandler handler = + runTest( + specOptions, + globalOptions, + expectAdopted, + resultContains, + messagesContain); + checkMessages(handler, null); + } + + void checkSourceTargetVersionConversion( + String name, + int i, + boolean expectPass, + String expectedErr) { + final String specOptions = "-" + name + ", 1." + i; + String[] globalOptions = new String[0]; + boolean expectAdopted = expectPass; + String resultContains = + !expectPass ? null : "[-" + name + ", 1." + i; + String messagesContain = expectedErr; + /*MessageHandler handler =*/ + runTest( + specOptions, + globalOptions, + expectAdopted, + resultContains, + messagesContain); + } + + /** + * Drive option-setting for CompilerRun.Spec, including + * expected errors. + * @param specOptions + * @param globalOptions + * @param expectAdopted + * @param resultContains + * @param messagesContain + * @return + */ + + MessageHandler runTest( + String specOptions, + String[] globalOptions, + boolean expectAdopted, + String resultContains, + String messagesContain) { + MessageHandler handler = new MessageHandler(); + try { + CompilerRun.Spec spec = new CompilerRun.Spec(); + AbstractRunSpec.RT parentRuntime = new AbstractRunSpec.RT(); + + if (!LangUtil.isEmpty(specOptions)) { + spec.setOptions(specOptions); + } + if (!LangUtil.isEmpty(globalOptions)) { + parentRuntime.setOptions(globalOptions); + } + boolean adopted = + spec.adoptParentValues(parentRuntime, handler); + if (adopted != expectAdopted) { + String s = + (expectAdopted ? "not " : "") + + "adopted spec=" + + specOptions + + " globals=" + + (LangUtil.isEmpty(globalOptions) + ? "[]" + : Arrays.asList(globalOptions).toString()) + + " -- " + + handler; + assertTrue(s, false); + } + if (null != resultContains) { + String result = "" + spec.testSetup.commandOptions; + if (-1 == result.indexOf(resultContains)) { + assertTrue( + "expected " + resultContains + " got " + result, + false); + } + } + if (null != messagesContain) { + boolean haveMessages = + (0 != handler.numMessages(null, true)); + if (!haveMessages) { + assertTrue("expected " + messagesContain, false); + } else { + String messages = handler.toString(); + if (-1 == messages.indexOf(messagesContain)) { + assertTrue( + "expected " + + messagesContain + + " got " + + messages, + false); + } + } + } + return handler; + } finally { + } + } + + void checkSetupArgs(String arg, final boolean isTestArg) { + MessageHandler handler = new MessageHandler(); + try { + CompilerRun.Spec spec = null; + try { + spec = new CompilerRun.Spec(); + } catch (Throwable t) { + t.printStackTrace(System.err); + } + assertTrue(spec != null); + AbstractRunSpec.RT parentRuntime = new AbstractRunSpec.RT(); + String result; + String expResult; + + // -------- local set + // global - (set) does not change local-set + parentRuntime.setOptions(new String[] { "-" + arg }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + expResult = (isTestArg ? "[]" : "[-" + arg + "]"); + assertTrue(result, expResult.equals(result)); + + // global ^ (force-off) to disable + spec.setOptions("-" + arg); + parentRuntime.setOptions(new String[] { "^" + arg }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + assertTrue(result, "[]".equals(result)); + + // global ! (force-on) does not change local-set + parentRuntime.setOptions(new String[] { "!" + arg }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + expResult = (isTestArg ? "[]" : "[-" + arg + "]"); + if (!expResult.equals(result)) { + assertTrue( + "expected " + expResult + " got " + result, + false); + } + + // global (unset) does not change local-set + parentRuntime.setOptions(new String[] { "" }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + expResult = (isTestArg ? "[]" : "[-" + arg + "]"); + assertTrue(result, expResult.equals(result)); + + // -------- local force-on + // global ^ (force-off) conflicts with local force-on + spec.setOptions("!" + arg); + parentRuntime.setOptions(new String[] { "^" + arg }); + assertTrue(!spec.adoptParentValues(parentRuntime, handler)); + assertTrue(0 != handler.numMessages(null, true)); + handler.init(); + + // global ! (force-on) does not change local force-on + parentRuntime.setOptions(new String[] { "!" + arg }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + expResult = (isTestArg ? "[]" : "[-" + arg + "]"); + assertTrue(result, expResult.equals(result)); + + // global - (set) does not change local force-on + parentRuntime.setOptions(new String[] { "-" + arg }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + expResult = (isTestArg ? "[]" : "[-" + arg + "]"); + assertTrue(result, expResult.equals(result)); + + // global (unset) does not change local force-on + parentRuntime.setOptions(new String[] { "" }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + expResult = (isTestArg ? "[]" : "[-" + arg + "]"); + assertTrue(result, expResult.equals(result)); + + // -------- local force-off + // global ^ (force-off) does not change local force-off + spec.setOptions("^" + arg); + parentRuntime.setOptions(new String[] { "^" + arg }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + assertTrue(result, ("[]").equals(result)); + + // global ! (force-on) conflicts with local force-off + parentRuntime.setOptions(new String[] { "!" + arg }); + assertTrue(!spec.adoptParentValues(parentRuntime, handler)); + assertTrue(0 != handler.numMessages(null, true)); + handler.init(); + + // global - (set) overridden by local force-off + parentRuntime.setOptions(new String[] { "-" + arg }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + assertTrue(result, ("[]").equals(result)); + + // global (unset) does not change local force-off + parentRuntime.setOptions(new String[] { "" }); + assertTrue(spec.adoptParentValues(parentRuntime, handler)); + if (0 != handler.numMessages(null, true)) { + assertTrue(handler.toString(), false); + } + result = "" + spec.testSetup.commandOptions; + assertTrue(result, ("[]").equals(result)); + + // undefined whether global set overrides local set + // for different sibling options + } finally { + if (PRINTING && (0 < handler.numMessages(null, true))) { + MessageUtil.print(System.err, handler, "checkSetupArgs: "); + } + } + } +} diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunTest.java new file mode 100644 index 000000000..ddfaee1f4 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunTest.java @@ -0,0 +1,182 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.testing.harness.bridge; + +import java.io.File; +import java.util.*; + +import junit.framework.TestCase; + +import org.aspectj.bridge.*; +import org.aspectj.testing.run.*; +import org.aspectj.util.*; +import org.aspectj.util.LangUtil; + +/** + * Use a stub compiler/ICommand to verify command-line passed + * to the compiler by the harness. + */ +public class CompilerRunTest extends TestCase { + + /** String for each dummy report: {run|repeat}: [{args}] */ + private static ArrayList dummyReports = new ArrayList(); + + private static void dummyRunning(String[] args) { + dummyReports.add("run: " + Arrays.asList(args)); + } + +// private static void dummyRepeating(String[] args) { +// dummyReports.add("repeat: " + Arrays.asList(args)); +// } + + private File testBaseDir; + + public CompilerRunTest(String name) { + super(name); + } + + public void setUp() { + testBaseDir = new File("../testing/temp-CompilerRunTest"); + File f = new File(testBaseDir, "one"); + f.mkdirs(); + assertTrue(f.canRead()); + f = new File(testBaseDir, "two"); + f.mkdirs(); + assertTrue(f.canRead()); + f = new File(testBaseDir, "Foo.java"); + String foo = "public class Foo { public void main(String[] s) { System.out.println(\"Hello!\");}}"; + String err = FileUtil.writeAsString(f, foo); + assertTrue(err, null == err); + assertTrue(f.canRead()); + } + + public void tearDown() { + FileUtil.deleteContents(testBaseDir); + testBaseDir.delete(); + testBaseDir = null; + } + + public void testExtDirs() { +// String[] globals = null; + CompilerRun.Spec spec = new CompilerRun.Spec(); + spec.setExtdirs("one,two"); + spec.setFiles("Foo.java"); + checkCommandLine(testBaseDir, spec, null, "-extdirs"); + } + + void checkCommandLine( + File testBaseDir, + CompilerRun.Spec spec, + String[] globals, + String expectedInCommand) { + assertTrue(0 == dummyReports.size()); + assertTrue(checkCompilerRun(testBaseDir, spec, globals, null)); + assertTrue(dummyReports.toString(), 1 == dummyReports.size()); + String command = (String) dummyReports.remove(0); + assertTrue(0 == dummyReports.size()); + if ((null == command) + || (-1 == command.indexOf(expectedInCommand))) { + assertTrue("expected " + + expectedInCommand + + "got " + + command, + false); + } + } + + /** run with dummy compiler */ + boolean checkCompilerRun( + File testBaseDir, + CompilerRun.Spec spec, + String[] globals, + MessageHandler handler) { + LangUtil.throwIaxIfNull(spec, "spec"); + if (null == handler) { + handler = new MessageHandler(); + } + spec.setPermitAnyCompiler(true); + spec.setCompiler(DummyCompiler.class.getName()); + AbstractRunSpec.RT parentRuntime = new AbstractRunSpec.RT(); + + if (!LangUtil.isEmpty(globals)) { + parentRuntime.setOptions(globals); + } + boolean adopted = + spec.adoptParentValues(parentRuntime, handler); + if (!adopted) { + String s = "not adopted spec=" + + spec + + " globals=" + + (LangUtil.isEmpty(globals) + ? "[]" + : Arrays.asList(globals).toString()) + + " -- " + + handler; + assertTrue(s, false); + } + if (0 != handler.numMessages(null, true)) { + assertTrue("unexpected " + handler, false); + } + return run(testBaseDir, spec); + } + + /** Run the compiler run specified by the spec */ + protected boolean run(File testBaseDir, CompilerRun.Spec spec) { + +// his is created using the Spec.</li> +// * <li>setupAjcRun(Sandbox, Validator) is invoked, +// * at which point this populates the shared sandbox +// * with values derived from the spec and also +// * sets up internal state based on both the sandbox +// * and the spec.</li> +// * <li>run(IRunStatus) is invoked, + + LangUtil.throwIaxIfNull(spec, "spec"); + Runner runner = new Runner(); + IMessageHolder holder = new MessageHandler(); + RunStatus status = new RunStatus(holder, runner); + status.setIdentifier(spec); + Validator validator = new Validator(status); + validator.lock(this); + Sandbox sandbox = null; + try { + sandbox = new Sandbox(testBaseDir, validator); + IRunIterator test = spec.makeRunIterator(sandbox, validator); + return runner.runIterator(test, status, null); + } finally { + validator.unlock(this); + validator.deleteTempFiles(true); + } + } + + + public static class DummyCompiler implements ICommand { + private String[] command; + + public DummyCompiler() { + } + + public boolean runCommand( + String[] args, + IMessageHandler handler) { + command = (String[]) LangUtil.safeCopy(args, new String[0]); + CompilerRunTest.dummyRunning(command); + return true; + } + + public boolean repeatCommand(IMessageHandler handler) { + CompilerRunTest.dummyRunning(command); + return true; + } + } +} diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/DirChangesTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/DirChangesTest.java new file mode 100644 index 000000000..3ee0fd041 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/DirChangesTest.java @@ -0,0 +1,232 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.harness.bridge; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +import org.aspectj.bridge.IMessage; +import org.aspectj.bridge.MessageHandler; +import org.aspectj.bridge.MessageUtil; +import org.aspectj.testing.xml.MessageListXmlReader; +import org.aspectj.testing.xml.XMLWriter; +import org.aspectj.util.LangUtil; + +/** + * (broken) tests for unutilized feature to read in + * expected directory changes as messages. + */ +public class DirChangesTest extends TestCase { + private static final boolean PRINTING = false; + + /** name of file in srcBaseDir with any expected messages */ + public static final String EXPECTED_NAME = "expectedMessages.xml"; + + public DirChangesTest(String name) { + super(name); + } + + /* XXX update tests to read expected messages from files + * then just iterate over directories in dirChangesTestDir + */ + + /** + * Uses testdata/dirChangesTestDir/same + */ + public void skip_testSameExpDir() { + doCheck("same"); + } + public void testNothingForAntJUnit() {} + /** + * Uses testdata/dirChangesTestDir/diff + */ + public void skip_testDiffExpDir() { + doCheck("diff"); + } + + public void skip_testWriteEmpty() { + DirChanges.Spec spec = new DirChanges.Spec(); + String expected = ""; + checkWrite(spec, expected); + } + + public void skip_testWriteExpDir() { + DirChanges.Spec spec = new DirChanges.Spec(); + spec.setExpDir("expected directory"); + String expected = + "<dir-changes expDir=\"expected directory\"/>" + + LangUtil.EOL; + checkWrite(spec, expected); + } + + public void skip_testWriteAdded() { + DirChanges.Spec spec = new DirChanges.Spec(); + spec.setAdded("one,two,three"); + String expected = + "<dir-changes added=\"one,two,three\"/>" + + LangUtil.EOL; + checkWrite(spec, expected); + } + + /** write spec to XML and compare with expected */ + private void checkWrite(DirChanges.Spec spec, String expected) { + StringWriter actual = new StringWriter(); + XMLWriter writer = new XMLWriter(new PrintWriter(actual, true)); + spec.writeXml(writer); + assertEquals(expected, actual.toString()); + } + + private void doCheck(String dir) { + DirChanges.Spec spec = new DirChanges.Spec(); + File srcBaseDir = new File("testdata/dirChangesTestDir/" + dir); + // actual = baseDir + File baseDir = new File(srcBaseDir, "actual"); + // expected = srcBaseDir + spec.expDir + spec.setExpDir("expected"); + IMessage[] expected = null; + File expMssgFile = new File(srcBaseDir, EXPECTED_NAME); + if (expMssgFile.canRead()) { + try { + expected = new MessageListXmlReader().readMessages(expMssgFile); + } catch (IOException e) { + System.err.println("Continuing after error reading " + expMssgFile); + e.printStackTrace(System.err); + } + } + checkDirChanges(spec, baseDir, srcBaseDir, null, expected); + } + + // XXX WEAK upgrade to read expected-diffs from file in directory + private void checkDirChanges( + DirChanges.Spec spec, + File baseDir, + File srcBaseDir, + Runnable dirChanger, + IMessage[] expected) { + DirChanges dc = new DirChanges(spec); + MessageHandler handler = new MessageHandler(); + try { + if (!dc.start(handler, baseDir)) { + //assertTrue(!shouldPass); + assertSameMessages(expected, handler); + return; // exiting after (XXX) undertested expected failure? + } else { + assertTrue(0 == handler.numMessages(IMessage.ERROR, true)); + } + if (null != dirChanger) { + dirChanger.run(); + } + if (!dc.end(handler, srcBaseDir)) { + //assertTrue(!shouldPass); + assertSameMessages(expected, handler); + } else { + assertTrue(0 == handler.numMessages(IMessage.ERROR, true)); + } + } catch (Throwable t) { + if (PRINTING) { + t.printStackTrace(System.err); + } + throw new AssertionFailedError(LangUtil.renderException(t)); + } finally { + if (0 < handler.numMessages(null, true)) { + if (PRINTING) { + MessageUtil.print(System.err, handler, "checkDirChanges: "); + } + IMessage[] toprint = handler.getMessages(null, true); + File output = new File(srcBaseDir, EXPECTED_NAME); + try { + //toprint[0].getISourceLocation().getSourceFile(); + System.out.println("XXX writing to " + output + + " messages " + LangUtil.arrayAsList(toprint)); + new MessageListXmlReader().writeMessages(output, toprint); + } catch (IOException e) { + System.err.println("Error writing to " + output + + " messages " + LangUtil.arrayAsList(toprint)); + e.printStackTrace(System.err); + } + } + } + } + + /** + * Assert unless messages in handler match all expected messages. + * @param expected + * @param handler + */ + private void assertSameMessages( + IMessage[] expected, + MessageHandler handler) { + IMessage[] actual = handler.getMessages(null, true); + for (int i = 0; i < actual.length; i++) { + int found = find(actual[i], expected); + if (-1 != found) { + expected[found] = null; + actual[i] = null; + } + } + StringBuffer sb = new StringBuffer(); + { + IMessage[] expNotFound = (IMessage[]) + LangUtil.safeCopy(expected, new IMessage[0]); + if (0 < expNotFound.length) { + sb.append("expected not found: "); + sb.append(LangUtil.arrayAsList(expNotFound).toString()); + } + } + { + IMessage[] actFound = (IMessage[]) + LangUtil.safeCopy(actual, new IMessage[0]); + if (0 < actFound.length) { + sb.append(" not expected but found: "); + sb.append(LangUtil.arrayAsList(actFound).toString()); + } + } + + if (0 < sb.length()) { + assertTrue(sb.toString(), false); + } + } + + /** + * Find message in array, comparing by contents + * but ignoring exceptions thrown and source location XXX. + * @param message the IMessage to find + * @param expected the + * @return int + */ + private int find(IMessage message, IMessage[] expected) { + if ((null != expected) && (0 != expected.length) + && (null != message)) { + final IMessage.Kind kind = message.getKind(); + final String text = message.getMessage(); + for (int i = 0; i < expected.length; i++) { + IMessage exp = expected[i]; + if (null != exp) { + if (kind.equals(exp.getKind()) + && text.equals(exp.getMessage())) { + return i; + } + } + } + } + return -1; + } + + +} diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/ParseTestCase.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/ParseTestCase.java new file mode 100644 index 000000000..cfbc6b0e1 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/ParseTestCase.java @@ -0,0 +1,224 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.harness.bridge; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import junit.framework.TestCase; + +import org.aspectj.bridge.IMessage; +import org.aspectj.bridge.IMessageHolder; +import org.aspectj.bridge.ISourceLocation; +import org.aspectj.bridge.Message; +import org.aspectj.bridge.MessageHandler; +import org.aspectj.bridge.MessageUtil; +import org.aspectj.bridge.SourceLocation; +import org.aspectj.testing.run.IRunIterator; +import org.aspectj.testing.run.IRunListener; +import org.aspectj.testing.run.RunStatus; +import org.aspectj.testing.run.Runner; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +public class ParseTestCase extends TestCase { + + public ParseTestCase(String name) { + super(name); + } + + public void testNothingBecauseOthersSkipped() {} + + public void skiptestParse() throws Exception { // XXX failing b/c of iteration + Runner runner = new Runner(); + IMessageHolder handler = new MessageHandler(); + RunStatus status; + Validator validator = new Validator(handler); + final File suiteFile = new File("../testing/testdata/suite.xml"); + List tests = parseSuite(suiteFile); + Sandbox sandbox = new Sandbox(new File("testdata"), validator); + IRunListener listenerNULL = null; + ISourceLocation sl = new SourceLocation(suiteFile, 0, 0,0); + for (Iterator iter = tests.iterator(); iter.hasNext();) { + status = new RunStatus(handler, runner); + AjcTest.Spec test = (AjcTest.Spec) iter.next(); + test.setSourceLocation(sl); + IRunIterator child = test.makeRunIterator(sandbox, validator); + //test.setup(new String[0], validator); // XXX + //IRun child = runner.wrap(test, null); + // huh? runIterator not generating child status? + //RunStatus childStatus = runner.makeChildStatus(); + runner.runIterator(child, status, listenerNULL); + MessageUtil.print(System.err, status); + } + } + + private List parseSuite(File file) throws ParserConfigurationException, IOException, SAXException{ + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setValidating(true); + factory.setIgnoringElementContentWhitespace(true); + factory.setIgnoringComments(true); + + + DocumentBuilder builder = factory.newDocumentBuilder(); + System.out.println(file.getAbsoluteFile()); + Document doc = builder.parse(file); + + dump(doc.getDocumentElement(), 0); + + List ret = new ArrayList(); + Node suiteNode = doc.getDocumentElement(); + + NodeList children = suiteNode.getChildNodes(); + for (int i=0; i < children.getLength(); i++) { + ret.add(parseTest(children.item(i))); + } + + return ret; + } + + private AjcTest.Spec parseTest(Node node) { + String title = getAttributeString(node, "title"); + String pr = getAttributeString(node, "pr"); + String dir = getAttributeString(node, "dir"); + + ISourceLocation sourceLocation = + new SourceLocation(new File("Missing"), 0, 0, 0); + AjcTest.Spec test = new AjcTest.Spec(); + test.setDescription(title); + test.setTestDirOffset(dir); + test.setBugId(Integer.valueOf(pr).intValue()); + test.setSourceLocation(sourceLocation); + //AjcTest test = new AjcTest(title, dir, pr, sourceLocation); + + System.out.println(test); + +// List ret = new ArrayList(); + + NodeList children = node.getChildNodes(); + for (int i=0; i < children.getLength(); i++) { + test.addChild(parseIRun(test, children.item(i), dir)); +// test.addRunSpec(parseIRun(test, children.item(i), dir)); + } + + return test; + } + + private IRunSpec parseIRun(AjcTest.Spec test, Node node, String baseDir) { + String kind = node.getNodeName(); + if (kind.equals("compile")) { + List args = parseChildrenStrings(node, "arg"); + /*List files = */parseChildrenStrings(node, "file"); + List expectedMessages = parseChildrenMessages(node); + CompilerRun.Spec spec = new CompilerRun.Spec(); + spec.addOptions((String[]) args.toArray(new String[0])); + spec.addPaths((String[]) args.toArray(new String[0])); + spec.addMessages(expectedMessages); + spec.testSrcDirOffset = null; // baseDir; + return spec; + } else if (kind.equals("run")) { + JavaRun.Spec spec = new JavaRun.Spec(); + spec.className = getAttributeString(node, "class"); + spec.addOptions(new String[0]); //??? could add support here + /*JavaRun run = */new JavaRun(spec); + return spec; + } + + return null; + } + + private List parseChildrenMessages(Node node) { + List ret = new ArrayList(); + + NodeList children = node.getChildNodes(); + for (int i=0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeName().equals("message")) { + ret.add(parseMessage(child)); + } + } + return ret; + } + + private IMessage parseMessage(Node child) { + IMessage.Kind kind; + String sKind = getAttributeString(child, "kind"); + if (sKind.equals("error")) { kind = IMessage.ERROR; } + else if (sKind.equals("warning")) { kind = IMessage.WARNING; } + else { + throw new RuntimeException("unknown kind: " + sKind); + } + String filename = getAttributeString(child, "file"); + File file; + if (filename != null) { + file = new File(filename); + } else { + file = new File("XXX"); //XXX + } + + int line = Integer.valueOf(getAttributeString(child, "line")).intValue(); + + ISourceLocation sourceLocation = new SourceLocation(file, line, line, 0); + + return new Message("", kind, null, sourceLocation); + } + + + + private List parseChildrenStrings(Node node, String kind) { + List ret = new ArrayList(); + + NodeList children = node.getChildNodes(); + for (int i=0; i < children.getLength(); i++) { + Node child = children.item(i); + if (child.getNodeName().equals(kind)) { + Node first = child.getFirstChild(); + if (null != first) { + ret.add(first.getNodeValue());// XXX + } + } + } + return ret; + } + + + + private String getAttributeString(Node node, String name) { + Node attrNode = node.getAttributes().getNamedItem(name); + if (attrNode == null) return null; + return attrNode.getNodeValue(); + } + + + + + private void dump(Node node, int indent) { + for (int i=0; i < indent; i++) System.out.print(" "); + System.out.println(node); + NodeList children = node.getChildNodes(); + for (int i=0; i < children.getLength(); i++) { + dump(children.item(i), indent+1); + } + } + + +} diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/TestingBridgeTests.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/TestingBridgeTests.java new file mode 100644 index 000000000..1fd4cb342 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/TestingBridgeTests.java @@ -0,0 +1,38 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.testing.harness.bridge; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class TestingBridgeTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(TestingBridgeTests.class.getName()); + // XXX disabled DirChangesTest pending implementation + //$JUnit-BEGIN$ + suite.addTestSuite(AbstractRunSpecTest.class); + suite.addTestSuite(AjcSpecTest.class); + suite.addTestSuite(CompilerRunTest.class); + suite.addTestSuite(CompilerRunSpecTest.class); + suite.addTestSuite(ParseTestCase.class); + //$JUnit-END$ + return suite; + } + + public TestingBridgeTests(String name) { super(name); } + +} diff --git a/testing/src/test/java/org/aspectj/testing/taskdefs/AjcTaskCompileCommandTest.java b/testing/src/test/java/org/aspectj/testing/taskdefs/AjcTaskCompileCommandTest.java new file mode 100644 index 000000000..42a2063a4 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/taskdefs/AjcTaskCompileCommandTest.java @@ -0,0 +1,278 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.testing.taskdefs; + +import java.io.File; +import java.util.ArrayList; + +import org.aspectj.bridge.*; +import org.aspectj.bridge.MessageHandler; +import org.aspectj.testing.harness.bridge.Globals; +import org.aspectj.util.*; +import org.aspectj.util.LangUtil; + +import junit.framework.TestCase; + + +/** + * Test AjcTaskCompileCommand adapter. + * This assumes it is run from a peer directory of the + * taskdefs module, which contains the target files. + */ +public class AjcTaskCompileCommandTest extends TestCase { + static boolean loggedWarning = false; + static boolean runAllTests = true; + static ArrayList<File> tempFiles = new ArrayList<File>(); + + private static File getClassesDir() { + File tempDir = FileUtil.getTempDir("AjcTaskCompileCommandTest-classes"); + tempFiles.add(tempDir); + return tempDir; + } + + private static void addCommonArgs(ArrayList<String> list) { + list.add("-d"); + list.add(getClassesDir().getAbsolutePath()); + list.add("-classpath"); + StringBuilder classpath = new StringBuilder(); + classpath.append(Globals.F_aspectjrt_jar.getAbsolutePath()); + if (LangUtil.is19VMOrGreater()) { + classpath.append(File.pathSeparator).append(LangUtil.getJrtFsFilePath()); + } + list.add(classpath.toString()); + } + + static boolean doWait(IMessageHolder holder, int seconds, int timeout) { + return AjcTaskCompileCommand + .waitUntilMessagesQuiet(holder, seconds, timeout); + } + + public AjcTaskCompileCommandTest(String name) { + super(name); + } + + public void testWaitUntilMessagesQuiet_InputErrors() { + MessageHandler mhandler = new MessageHandler(); + assertFalse(doWait(mhandler, 0, 10)); + assertFalse(doWait(mhandler, 10, 0)); + assertFalse(doWait(mhandler, 1, 1)); + assertFalse(doWait(mhandler, 10, 1)); + boolean thrown = false; + try { + doWait(null, 1, 10); + } catch (IllegalArgumentException e) { + thrown = true; + } + assertTrue("no exception thrown", thrown); + } + + public void testDefault() { + runSimpleTest("../taskdefs/testdata/Default.java", 0); + } + + public void testDefaultList() { + runSimpleTest("../taskdefs/testdata/default.lst", 0); + } + + public void testCompileErrorList() { + runSimpleTest("../taskdefs/testdata/compileError.lst", 1); + } + + + public void testWaitUntilMessagesQuiet_1_2() { + if (runAllTests) checkWait(1, 2, 0, 0); + } + + public void testWaitUntilMessagesQuiet_1_10() { + if (runAllTests) checkWait(1, 10, 0, 0); + } + + public void testWaitUntilMessagesQuiet_8_10() { + checkWait(8, 10, 0, 0); + } + + // XXX two async tests might fail if adder thread starved + + public void testWaitUntilMessagesQuiet_1_10_4_1() { + if (runAllTests) checkWait(1, 10, 4, 1); + } + + public void testWaitUntilMessagesQuiet_8_10_2_1() { + if (runAllTests) checkWait(8, 20, 2, 1); + } + + void runSimpleTest(String path, int expectedErrors) { + File file = new File(path); + assertTrue(path, file.canRead()); + ArrayList<String> list = new ArrayList<String>(); + addCommonArgs(list); + if (path.endsWith(".lst")) { + list.add("-argfile"); + list.add(file.getAbsolutePath()); + } else if (FileUtil.hasSourceSuffix(path)) { + list.add(file.getAbsolutePath()); + } else { + assertTrue("unrecognized file: " + path, false); + return; + } + runTest(list, expectedErrors); + } + + void runTest(ArrayList<String> args, int expectedErrors) { + AjcTaskCompileCommand command = + new AjcTaskCompileCommand(); + MessageHandler handler = new MessageHandler(); + String[] parms = (String[]) args.toArray(new String[0]); + boolean result = command.runCommand(parms, handler); + boolean expectPass = (0 == expectedErrors); + final boolean pass = (result == expectPass); + if (!pass) { + String m = expectPass ? "pass" : "fail"; + assertTrue("expected " + m + ": " + args, false); + } + } + + void checkWait(final int seconds, final int timeout, int toAdd, int addInterval) { + final String testCase = "checkWait(seconds=" + + seconds + ", timeout=" + timeout; + final MessageHandler mhandler = new MessageHandler(); + final long startTime = System.currentTimeMillis(); + final long testTimeout = startTime + (timeout * 2000l); + final boolean result; + if (0 == toAdd) { // do no-adds synchronously + result = doWait(mhandler, seconds, timeout); + assertTrue("result " + testCase, result); + } else { + if (!loggedWarning) { + System.out.println("warning - test will fail if adder thread starved"); + loggedWarning = true; + } + final MessageAdder adder + = new MessageAdder(mhandler, toAdd, addInterval); + final String label = testCase + " wait(" + toAdd + ", " + addInterval + ")"; + class Result { + boolean result; + Thread addedThread; + } + final Result waitResult = new Result(); + Thread testThread = new Thread( new Runnable() { + public void run() { + waitResult.addedThread + = new Thread(adder, label + "-child"); + waitResult.addedThread.start(); + waitResult.result = + AjcTaskCompileCommandTest.doWait(mhandler, seconds, timeout); + } + }, label); + + testThread.start(); + + try { + testThread.join(testTimeout - startTime); + } catch (InterruptedException e) { + // ignore + } + try { + if (null != waitResult.addedThread) { + long wait = testTimeout - System.currentTimeMillis(); + if (0 < wait) { + waitResult.addedThread.join(wait); + } + } + } catch (InterruptedException e) { + // ignore + } + result = waitResult.result; + int added = adder.getNumAdded(); + assertEquals(testCase + " added", added, toAdd); + if (!result) { + assertTrue(testCase + " result " + adder, false); + } + } + long endTime = System.currentTimeMillis(); + long elapsed = endTime - startTime; + assertTrue(seconds + " seconds: " + elapsed, elapsed >= (seconds*1000)); + assertTrue(timeout + " timeout: " + elapsed, elapsed <= (timeout*1000)); + } + +} + +class MessageAdder implements Runnable { + /** 30-second max test */ + public static long MAX_MILLIS = 1000 * 30; + public boolean stop; + public boolean wait; + + private final IMessageHolder messages; + private final int numToAdd; + private final int interval; + private int numAdded; + + /** + * @param holder the IMessageHolder to add to + * @param num the int number of messages to add + * @param interval the int seconds between messages added + */ + MessageAdder(IMessageHolder holder, int num, int interval) { + LangUtil.throwIaxIfNull(holder, "holder"); + LangUtil.throwIaxIfFalse(num > 0, "numToAdd: " + num); + LangUtil.throwIaxIfFalse(interval > 0, "interval: " + interval); + LangUtil.throwIaxIfFalse(num*interval*1000 < MAX_MILLIS, "too long"); + this.messages = holder; + this.numToAdd = num; + this.interval = interval; + } + + public void run() { + final long waitBetweenAdds = interval * 1000l; + long curTime = System.currentTimeMillis(); + final long timeout = curTime + MAX_MILLIS; +// final Thread thread = Thread.currentThread(); + int numAdded = 0; + while (!stop && (timeout > curTime) + && (numAdded < numToAdd)) { + long targetTime = curTime + waitBetweenAdds; + while (!stop && (curTime < timeout) + && (curTime < targetTime)) { + try { + Thread.sleep(targetTime - curTime); + } catch (InterruptedException e) { + // ignore + } + curTime = System.currentTimeMillis(); + } + if (!stop && (curTime < timeout)) { + MessageUtil.info(messages, "time is " + curTime); + numAdded++; + } + } + this.numAdded = numAdded; + } + int getNumAdded() { + return numAdded; + } + + public String toString() { + return "MessageAdder(" + + "numAdded=" + numAdded + + ", numToAdd=" + numToAdd + + ", interval=" + interval + + ", stop=" + stop + + ", wait=" + wait + + ", numMessages=" + + (null == messages + ? 0 + : messages.numMessages(null, true)) + + ")"; + } +}
\ No newline at end of file diff --git a/testing/src/test/java/org/aspectj/testing/taskdefs/TaskdefTests.java b/testing/src/test/java/org/aspectj/testing/taskdefs/TaskdefTests.java new file mode 100644 index 000000000..5a86f8558 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/taskdefs/TaskdefTests.java @@ -0,0 +1,29 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.testing.taskdefs; + +import junit.framework.*; + +public class TaskdefTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(TaskdefTests.class.getName()); + //$JUnit-BEGIN$ + suite.addTestSuite(AjcTaskCompileCommandTest.class); + //$JUnit-END$ + return suite; + } + + public TaskdefTests(String name) { super(name); } + +} diff --git a/testing/src/test/java/org/aspectj/testing/util/BridgeUtilTest.java b/testing/src/test/java/org/aspectj/testing/util/BridgeUtilTest.java new file mode 100644 index 000000000..a0299889b --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/BridgeUtilTest.java @@ -0,0 +1,99 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util; + +import junit.framework.TestCase; + +import org.aspectj.bridge.MessageHandler; +import org.aspectj.testing.run.IRun; +import org.aspectj.testing.run.IRunStatus; +import org.aspectj.testing.run.RunStatus; +import org.aspectj.testing.run.Runner; + +/** + * + */ +public class BridgeUtilTest extends TestCase { + + public BridgeUtilTest(String name) { + super(name); + } + + public void testChildString() { + String expect; + String id; + id = "run status identifier"; + expect = "PASS " + id + " 0 tests"; + checkChildString(id, 0, 0, 0, 0, expect); + expect = "PASS " + id + " 2 tests (2 skipped)"; + checkChildString(id, 2, 0, 0, 0, expect); + expect = "PASS " + id + " 3 tests (1 skipped, 2 passed)"; + checkChildString(id, 1, 0, 0, 2, expect); + expect = "FAIL " + id + " 3 tests (1 skipped, 2 failed)"; + checkChildString(id, 1, 0, 2, 0, expect); + expect = "FAIL " + id + " 6 tests (1 skipped, 2 failed, 3 passed)"; + checkChildString(id, 1, 0, 2, 3, expect); + expect = "FAIL " + id + " 1 tests (1 failed)"; + checkChildString(id, 0, 0, 1, 0, expect); + expect = "FAIL " + id + " 4 tests (1 failed, 3 passed)"; + checkChildString(id, 0, 0, 1, 3, expect); + expect = "PASS " + id + " 1 tests (1 passed)"; + checkChildString(id, 0, 0, 0, 1, expect); + + // "incomplete" variants + expect = "PASS " + id + " 5 tests (5 incomplete)"; + checkChildString(id, 0, 5, 0, 0, expect); + expect = "PASS " + id + " 7 tests (2 skipped, 5 incomplete)"; + checkChildString(id, 2, 5, 0, 0, expect); + expect = "PASS " + id + " 8 tests (1 skipped, 5 incomplete, 2 passed)"; + checkChildString(id, 1, 5, 0, 2, expect); + expect = "FAIL " + id + " 8 tests (1 skipped, 5 incomplete, 2 failed)"; + checkChildString(id, 1, 5, 2, 0, expect); + expect = "FAIL " + id + " 11 tests (1 skipped, 5 incomplete, 2 failed, 3 passed)"; + checkChildString(id, 1, 5, 2, 3, expect); + expect = "FAIL " + id + " 6 tests (5 incomplete, 1 failed)"; + checkChildString(id, 0, 5, 1, 0, expect); + expect = "FAIL " + id + " 9 tests (5 incomplete, 1 failed, 3 passed)"; + checkChildString(id, 0, 5, 1, 3, expect); + expect = "PASS " + id + " 6 tests (5 incomplete, 1 passed)"; + checkChildString(id, 0, 5, 0, 1, expect); + } + + void checkChildString(String id, int numSkips, int numIncomplete, int numFails, int numPasses, + String expected) { + Runner runner = new Runner(); + MessageHandler holder = new MessageHandler(); + RunStatus status = new RunStatus(holder, runner); + status.setIdentifier(id); + status.start(); + + final IRun failer = new IRun() { + public boolean run(IRunStatus status) { return false; } + }; + final IRun passer = new IRun() { + public boolean run(IRunStatus status) { return true; } + }; + final Object result = (numFails > 0 ? IRunStatus.FAIL : IRunStatus.PASS); + while (numFails-- > 0) { + runner.runChild(failer,status, null, null); + } + while (numPasses-- > 0) { + runner.runChild(passer,status, null, null); + } + status.finish(result); + String actual = BridgeUtil.childString(status, numSkips, numIncomplete); + String label = " expected \"" + expected + "\" got \"" + actual + "\""; + assertTrue(label, expected.equals(actual)); + } +} diff --git a/testing/src/test/java/org/aspectj/testing/util/FileUtilTest.java b/testing/src/test/java/org/aspectj/testing/util/FileUtilTest.java new file mode 100644 index 000000000..ddafcfb53 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/FileUtilTest.java @@ -0,0 +1,44 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util; + +import junit.framework.TestCase; + +/** + * + */ +public class FileUtilTest extends TestCase { + + /** + * Constructor for FileUtilTest. + * @param arg0 + */ + public FileUtilTest(String arg0) { + super(arg0); + } + + public void testFileEquals() { + // File.equals(..) is based on lexical compare of filenames +// File rf = new File("testsrc/org/aspectj/testing/util/FileUtilTest.java"); +// File rb = new File("testsrc\\org\\aspectj\\testing\\util\\FileUtilTest.java"); +// String a = rf.getAbsolutePath().replace('\\', '/'); +// File af = new File(a); +// File ab = new File(a.replace('/', '\\')); +// list.add(af); +// list.add(ab); +// list.add(rb); +// assertTrue(list.contains(duplicateTwo)); +// assertTrue(list.contains(anotherOne)); + } +} diff --git a/testing/src/test/java/org/aspectj/testing/util/IteratorWrapperTest.java b/testing/src/test/java/org/aspectj/testing/util/IteratorWrapperTest.java new file mode 100644 index 000000000..a079a2685 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/IteratorWrapperTest.java @@ -0,0 +1,164 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import junit.framework.TestCase; + +/** + * + */ +public class IteratorWrapperTest extends TestCase { + + /** + * Constructor for IteratorWrapperTest. + * @param name + */ + public IteratorWrapperTest(String name) { + super(name); + } + + public void testIteratorWrapper() { + Object[][] exp = new Object[][] {}; + List[] in = new List[] {}; + checkIteratorWrapper(in, exp); + + in = new List[] {Collections.EMPTY_LIST}; + checkIteratorWrapper(in, exp); + + in = new List[] {Collections.EMPTY_LIST, Collections.EMPTY_LIST}; + checkIteratorWrapper(in, exp); + + Object[] ra1 = new Object[] { "1" }; + List one = Collections.unmodifiableList(Arrays.asList(ra1)); + in = new List[] {one}; + exp = new Object[][] { ra1 }; + checkIteratorWrapper(in, exp); + + in = new List[] {one, one}; + exp = new Object[][] { new Object[] { "1", "1"} }; + checkIteratorWrapper(in, exp); + + Object[] RA_ab = new String[] { "a", "b" }; + List List_ab = Collections.unmodifiableList(Arrays.asList(RA_ab)); + in = new List[] {List_ab}; + exp = new Object[][] { + new Object[] { "a" }, + new Object[] { "b" } + }; + checkIteratorWrapper(in, exp); + + in = new List[] {one, List_ab}; + exp = new Object[][] { + new Object[] { "1", "a" }, + new Object[] { "1", "b" }, + }; + checkIteratorWrapper(in, exp); + + Object[] RA_cd = new String[] { "c", "d" }; + List List_cd = Collections.unmodifiableList(Arrays.asList(RA_cd)); + + in = new List[] {List_ab, List_cd}; + exp = new Object[][] { + new Object[] { "a", "c" }, + new Object[] { "b", "c" }, + new Object[] { "a", "d" }, + new Object[] { "b", "d" } + }; + checkIteratorWrapper(in, exp); + + in = new List[] {one, one, one}; + exp = new Object[][] { + new Object[] { "1", "1", "1" } + }; + checkIteratorWrapper(in, exp); + + in = new List[] {List_ab, List_ab, List_ab}; + exp = new Object[][] { + new Object[] { "a", "a", "a" }, + new Object[] { "b", "a", "a" }, + new Object[] { "a", "b", "a" }, + new Object[] { "b", "b", "a" }, + new Object[] { "a", "a", "b" }, + new Object[] { "b", "a", "b" }, + new Object[] { "a", "b", "b" }, + new Object[] { "b", "b", "b" } + }; + checkIteratorWrapper(in, exp); + + in = new List[] {one, List_ab, List_ab}; + exp = new Object[][] { + new Object[] { "1", "a", "a" }, + new Object[] { "1", "b", "a" }, + new Object[] { "1", "a", "b" }, + new Object[] { "1", "b", "b" }, + }; + checkIteratorWrapper(in, exp); + + in = new List[] {one, List_ab, one}; + exp = new Object[][] { + new Object[] { "1", "a", "1" }, + new Object[] { "1", "b", "1" } + }; + checkIteratorWrapper(in, exp); + + in = new List[] {List_ab, one, List_ab}; + exp = new Object[][] { + new Object[] { "a", "1", "a" }, + new Object[] { "b", "1", "a" }, + new Object[] { "a", "1", "b" }, + new Object[] { "b", "1", "b" } + }; + checkIteratorWrapper(in, exp); + + in = new List[] {List_ab, one, List_ab, List_ab, Collections.EMPTY_LIST}; + exp = new Object[][] {}; + checkIteratorWrapper(in, exp); + + } + + void checkIteratorWrapper(List[] lists, Object[][] exp) { + IteratorWrapper it = new IteratorWrapper(lists); + for (int i = 0; i < exp.length; i++) { + Object[] e = exp[i]; + if (!it.hasNext()) { + String s = "exp[" + i + "]: " + Arrays.asList(e) + " it=" + it; + assertTrue(s, false); + } + Object[] actual = (Object[]) it.next(); + checkEquals(e, actual, i); + } + if (it.hasNext()) { + String s = "> " + exp.length + " it=" + it; + assertTrue(s, false); + } + } + + void checkEquals(Object[] exp, Object[] actual, int index) { + if (null == exp) { + assertTrue(null == actual); + } else { + assertTrue(null != actual); + } + String s = "] exp=" + Arrays.asList(exp) + " act=" + Arrays.asList(actual); + assertTrue(s, exp.length == actual.length); + for (int i = 0; i < actual.length; i++) { + assertTrue(null != exp[i]); + assertTrue("[" + index + ", " + i + s, exp[i].equals(actual[i])); + } + } +} diff --git a/testing/src/test/java/org/aspectj/testing/util/LangUtilTest.java b/testing/src/test/java/org/aspectj/testing/util/LangUtilTest.java new file mode 100644 index 000000000..8131fdf7e --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/LangUtilTest.java @@ -0,0 +1,351 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.StringTokenizer; + +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.textui.TestRunner; + +/** + * + * @author isberg + */ +public class LangUtilTest extends TestCase { + + private static final String ME + = "org.aspectj.testing.util.LangUtilTest"; + + /** @param args ignored */ + public static void main(String[] args) throws Exception { + class C extends TestRunner { + public TestResult go(String[] a) throws Exception { + return start(a); + } + } + TestResult r = new C().go(new String[] {ME}); + if (!r.wasSuccessful()) { + System.err.println(r.errorCount() + "/" + r.failureCount()); + } + } + + /** + * Constructor for LangUtilTest. + * @param name + */ + public LangUtilTest(String name) { + super(name); + } + + void check(String l, StringTokenizer st, int max, String delim) { + for (int i = 0; i < max; i++) { + if ((i > 0) && (null != delim)) { + assertEquals(l, delim, st.nextToken()); + } + assertEquals(l, ""+i, st.nextToken()); + } + assertTrue(l, !st.hasMoreTokens()); + } + + + void checkUnflatten(FTest test) { + String[] exp = test.unflattened; + ArrayList result = LangUtil.unflatten(test.toUnflatten, test.spec); + String label = test + " -> " + result; + assertNotNull(label, result); + + assertEquals(label, exp.length, result.size()); + for (int i = 0; i < exp.length; i++) { + assertEquals(label, exp[i], result.get(i)); + } + } + + + public void skiptestUnflatten() { +// LangUtil.FlattenSpec COMMA = LangUtil.FlattenSpec.COMMA; + LangUtil.FlattenSpec LIST = LangUtil.FlattenSpec.LIST; + + FTest[] tests = new FTest[] + { new FTest("[]", new String[0], LIST) + , new FTest("[1]", new String[] {"1"}, LIST) + , new FTest("[1, 2]", new String[] {"1", "2"}, LIST) + , new FTest("[1,2]", new String[] {"1,2"}, LIST) + , new FTest("[1, 2, 3]", new String[] {"1","2","3"}, LIST) + }; + for (int i = 0; i < tests.length; i++) { + checkUnflatten(tests[i]); + } + } + + + public void testArrayList() { + ArrayList l = new ArrayList(); + l.add(null); + l.add(null); + assertTrue(null == l.get(0)); + assertTrue(null == l.get(1)); + assertTrue(2 == l.size()); + assertEquals("[null, null]", "" + l); + } + + public void testCombineStrings() { + String[] one = new String[]{}; + String[] two = new String[]{}; + String[] expect = new String[]{}; + checkCombineStrings(one, two, expect); + + one = new String[]{null}; + two = new String[]{null}; + expect = new String[]{}; + checkCombineStrings(one, two, expect); + + one = new String[]{"1"}; + two = new String[]{null}; + expect = new String[]{"1"}; + checkCombineStrings(one, two, expect); + + one = new String[]{null}; + two = new String[]{"2"}; + expect = new String[]{"2"}; + checkCombineStrings(one, two, expect); + + one = new String[]{"1"}; + two = new String[]{"2"}; + expect = new String[]{"1", "2"}; + checkCombineStrings(one, two, expect); + + one = new String[]{null, null, "1", null, null}; + two = new String[]{null, "2", null}; + expect = new String[]{"1", "2"}; + checkCombineStrings(one, two, expect); + + one = new String[]{"1", "2", "3", "4"}; + two = new String[]{"5", null, "6"}; + expect = new String[]{"1", "2", "3", "4", "5", "6"}; + checkCombineStrings(one, two, expect); + + } + void checkCombineStrings(String[] one, String[] two, String[] expected) { + String[] actual = LangUtil.combine(one, two); + String aString = LangUtil.arrayAsList(actual).toString(); + String eString = LangUtil.arrayAsList(expected).toString(); + String both = "actual=\"" + aString + "\" expected=\"" + eString + "\""; + assertTrue(both, aString.equals(eString)); + } + + final String[] sABCDE = new String[] {"A", "B", "C", "D", "E" }; + final String[] sABC = new String[] {"A", "B", "C" }; + final String[] sDE = new String[] {"D", "E" }; + final String[] sabcde = new String[] {"a", "b", "c", "d", "e" }; + final String[] sabc = new String[] {"a", "b", "c" }; + final String[] sde = new String[] {"d", "e" }; + final String[] s12345 = new String[] {"1", "2", "3", "4", "5" }; + final String[] s13579 = new String[] {"1", "3", "5", "7", "9" }; + final String[] s02468 = new String[] {"0", "2", "4", "6", "8" }; + final String[] s135 = new String[] {"1", "3", "5" }; + final String[] s79 = new String[] {"7", "9" }; + final String[] s24 = new String[] {"2", "4" }; + final String[] s0 = new String[] {"0"}; + final String[] s068 = new String[] {"0", "6", "8" }; + final boolean unmodifiable = true; + final boolean modifiable = false; + final List lABCDE = makeList(unmodifiable, sABCDE); + final List lABC = makeList(unmodifiable, sABC); + final List lDE = makeList(unmodifiable, sDE); + final List labcde = makeList(unmodifiable, sabcde); + final List labc = makeList(unmodifiable, sabc); + final List lde = makeList(unmodifiable, sde); + final List l12345 = makeList(unmodifiable, s12345); + final List l13579 = makeList(unmodifiable, s13579); + final List l02468 = makeList(unmodifiable, s02468); + final List l135 = makeList(unmodifiable, s135); + final List l79 = makeList(unmodifiable, s79); + final List l24 = makeList(unmodifiable, s24); + final List l0 = makeList(unmodifiable, s0); + final List l068 = makeList(unmodifiable, s068); + final List rlabcde = makeList(modifiable, sabcde); + final List rlabc = makeList(modifiable, sabc); + final List rlde = makeList(modifiable, sde); + final List rlABCDE = makeList(modifiable, sABCDE); + final List rlABC = makeList(modifiable, sABC); + final List rlDE = makeList(modifiable, sDE); + final List rl12345 = makeList(modifiable, s12345); + final List rl13579 = makeList(modifiable, s13579); + final List rl02468 = makeList(modifiable, s02468); + final List rl135 = makeList(modifiable, s135); + final List rl79 = makeList(modifiable, s79); + final List rl24 = makeList(modifiable, s24); + final List rl0 = makeList(modifiable, s0); + final List rl068 = makeList(modifiable, s068); + final List NONE = Collections.EMPTY_LIST; + { + Collections.shuffle(rlABCDE); + Collections.shuffle(rlABC); + Collections.shuffle(rlDE); + Collections.shuffle(rlabcde); + Collections.shuffle(rlabc); + Collections.shuffle(rlde); + Collections.shuffle(rl12345); + Collections.shuffle(rl13579); + Collections.shuffle(rl02468); + Collections.shuffle(rl135); + Collections.shuffle(rl79); + Collections.shuffle(rl24); + Collections.shuffle(rl0); + Collections.shuffle(rl068); + } + + + public void testDiffsEmptyIdentities() { + checkDiff(l02468, null, l02468, NONE); + checkDiff(null, l02468, NONE, l02468); + checkDiff(l0, null, l0, NONE); + checkDiff(null, l0, NONE, l0); + checkDiff(l0, rl0, NONE, NONE); + checkDiff(labc, rlabc, NONE, NONE); + } + + public void testDiffsEmpties() { + checkDiff(NONE, NONE, NONE, NONE); + checkDiff(null, NONE, NONE, NONE); + checkDiff(NONE, null, NONE, NONE); + checkDiff(null, null, NONE, NONE); + checkDiff(null, null, NONE, NONE); + } + + public void testDiffsIdentities() { + checkDiff(l02468, l02468, NONE, NONE); + checkDiff(rl02468, l02468, NONE, NONE); + checkDiff(l02468, rl02468, NONE, NONE); + checkDiff(l13579, l13579, NONE, NONE); + checkDiff(rl13579, l13579, NONE, NONE); + checkDiff(l13579, rl13579, NONE, NONE); + checkDiff(l13579, rl13579, NONE, NONE); + } + public void testDiffsEvens() { + checkDiff(l02468, l12345, l068, l135); + checkDiff(rl02468, rl12345, rl068, rl135); + } + + public void testDiffsOdds() { + checkDiff(l13579, l12345, l79, l24); + checkDiff(rl13579, rl12345, rl79, rl24); + checkDiff(l13579, rl12345, l79, rl24); + checkDiff(rl13579, l12345, rl79, l24); + } + + public void testSoftDiffs() { + checkDiffSoft(labcde, lABCDE, NONE, NONE); + checkDiffSoft(lABC, labc, NONE, NONE); + checkDiffSoft(lABCDE, lABC, lDE, NONE); + checkDiffSoft(lDE, lABCDE, NONE, lABC); + checkDiffSoft(rlABCDE, rlABC, rlDE, NONE); + checkDiffSoft(rlDE, rlABCDE, NONE, rlABC); + checkDiffSoft(labcde, lABC, lDE, NONE); + checkDiffSoft(lde, lABCDE, NONE, lABC); + checkDiffSoft(rlabcde, rlABC, rlDE, NONE); + checkDiffSoft(rlde, rlABCDE, NONE, rlABC); + } + + // ---------------------- utilities + List makeList(boolean unmodifiable, String[] ra) { + if (unmodifiable) { + return Collections.unmodifiableList(Arrays.asList(ra)); + } else { + ArrayList list = new ArrayList(); + list.addAll(Arrays.asList(ra)); + return list; + } + } + + /** check both hard and soft - assuming list contain String */ + void checkDiff(List expected, List actual, List missing, List extra) { + ArrayList extraOut = new ArrayList(); + ArrayList missingOut = new ArrayList(); + LangUtil.makeDiffs(expected, actual, missingOut, extraOut); + checkSame(missing, missingOut); + checkSame(extra, extraOut); + extraOut.clear(); + missingOut.clear(); + + LangUtil.makeSoftDiffs(expected, actual, missingOut, extraOut, + String.CASE_INSENSITIVE_ORDER); + checkSame(missing, missingOut); // XXX does not detect bad order + checkSame(extra, extraOut); + } + + void checkSame(Collection one, Collection two) { // just convert and string-compare? + String label = one + "?=" + two; + assertTrue(label, (null == one) == (null == two)); + if (null != one) { + assertTrue(label, one.containsAll(two)); + assertTrue(label, two.containsAll(one)); + } + } + + /** check only soft - assuming list contain String */ + void checkDiffSoft(List expected, List actual, List missing, List extra) { + ArrayList extraOut = new ArrayList(); + ArrayList missingOut = new ArrayList(); + LangUtil.makeSoftDiffs(expected, actual, missingOut, extraOut, + String.CASE_INSENSITIVE_ORDER); + checkSameSoft(missing, missingOut); + checkSameSoft(extra, extraOut); + } + + /** @param one modifiable List of String + * @param two modifiable List of String + */ + void checkSameSoft(List one, List two) { // assume String + String label = one + "?=" + two; + assertTrue(label, (null == one) == (null == two)); + if (null != one) { + ArrayList aone = new ArrayList(); + aone.addAll(one); + ArrayList atwo = new ArrayList(); + aone.addAll(two); + Collections.sort(aone); + Collections.sort(atwo); + String sone = (""+aone).toLowerCase(); + String stwo = (""+aone).toLowerCase(); + assertTrue(label, sone.equals(stwo)); + } + } + + static class FTest { + String toUnflatten; + String[] unflattened; + LangUtil.FlattenSpec spec; + FTest(String in, String[] out, LangUtil.FlattenSpec spec) { + toUnflatten = in; + unflattened = out; + this.spec = spec; + } + public String toString() { + return "FTest(" + + "toUnflatten=" + toUnflatten + + ", unflattened=" + Arrays.asList(unflattened) + + ", spec=" + spec + + ")"; + } + } + + +} diff --git a/testing/src/test/java/org/aspectj/testing/util/MessageUtilTest.java b/testing/src/test/java/org/aspectj/testing/util/MessageUtilTest.java new file mode 100644 index 000000000..51ec73efd --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/MessageUtilTest.java @@ -0,0 +1,130 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.testing.util; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import junit.framework.TestCase; + +import org.aspectj.bridge.IMessage; +import org.aspectj.bridge.ISourceLocation; +import org.aspectj.bridge.Message; +import org.aspectj.bridge.MessageHandler; +import org.aspectj.bridge.MessageUtil; +import org.aspectj.bridge.SourceLocation; + +/** + * + */ +public class MessageUtilTest extends TestCase { + public MessageUtilTest(String s) { + super(s); + } + + MessageHandler samples; + List /* Exception */ exceptions; + List /*ISourceLocation*/ locations; + List /*String */ messageTexts; + + + public void testMessageRendering() { + MessageHandler messages = getSampleMessages(); + System.out.println("testMessageRendering(): run manually evaluate by inspection"); + PrintStream oldOut = System.out; + // comment to inspect manually + System.setOut(NullPrintStream.NULL_PrintStream); + try { + MessageUtil.print(System.out, messages, "all label -> ", MessageUtil.MESSAGE_LABEL, MessageUtil.PICK_ALL); + MessageUtil.print(System.out, messages, "info short -> ", MessageUtil.MESSAGE_SHORT, MessageUtil.PICK_INFO); + MessageUtil.print(System.out, messages, "fail line -> ", MessageUtil.MESSAGE_LINE, MessageUtil.PICK_FAIL); + MessageUtil.print(System.out, messages, "debug wide line -> ", MessageUtil.MESSAGE_WIDELINE, MessageUtil.PICK_DEBUG); + MessageUtil.print(System.out, messages, "warn no-loc label -> ", MessageUtil.MESSAGE_LABEL_NOLOC, MessageUtil.PICK_WARNING); + MessageUtil.print(System.out, messages, "abort force-loc line -> ", MessageUtil.MESSAGE_LINE_FORCE_LOC, MessageUtil.PICK_ABORT); + MessageUtil.print(System.out, messages, "info+ short -> ", MessageUtil.MESSAGE_SHORT, MessageUtil.PICK_INFO_PLUS); + MessageUtil.print(System.out, messages, "fail+ line -> ", MessageUtil.MESSAGE_LINE, MessageUtil.PICK_FAIL_PLUS); + MessageUtil.print(System.out, messages, "debug+ wide line -> ", MessageUtil.MESSAGE_WIDELINE, MessageUtil.PICK_DEBUG_PLUS); + MessageUtil.print(System.out, messages, "warn+ no-loc label -> ", MessageUtil.MESSAGE_LABEL_NOLOC, MessageUtil.PICK_WARNING_PLUS); + MessageUtil.print(System.out, messages, "abort+ force-loc line -> ", MessageUtil.MESSAGE_LINE_FORCE_LOC, MessageUtil.PICK_ABORT_PLUS); + } finally { + System.setOut(oldOut); + } + } + + + List getSampleMessageTexts() { + if (null == messageTexts) { + ArrayList result = new ArrayList(); + result.addAll(Arrays.asList(new String[] + { "one", "two", "now is the time for all good men..." })); + messageTexts = result; + } + return messageTexts; + } + + List getSampleExceptions() { + if (null == exceptions) { + ArrayList result = new ArrayList(); + int i = 1; + result.add(new Error("Error " + i++)); + result.add(new RuntimeException("RuntimeException " + i++)); + result.add(new IOException("IOException " + i++)); + exceptions = result; + } + return exceptions; + } + + List getSampleLocations() { + if (null == locations) { + ArrayList result = new ArrayList(); + File file = new File("testsrc/org/aspectj/testing/util/MessageUtilTest.java"); + result.add(new SourceLocation(file, 1, 2, 1)); + result.add(new SourceLocation(file, 100, 100, 0)); + locations = result; + } + return locations; + } + + MessageHandler getSampleMessages() { + MessageHandler result = new MessageHandler(); + for (Iterator kinds = IMessage.KINDS.iterator(); kinds.hasNext();) { + IMessage.Kind kind = (IMessage.Kind) kinds.next(); + for (Iterator locs = getSampleLocations().iterator(); locs.hasNext();) { + ISourceLocation sourceLoc = (ISourceLocation) locs.next(); + for (Iterator texts = getSampleMessageTexts().iterator(); + texts.hasNext(); + ) { + String text = (String) texts.next(); + for (Iterator exs = getSampleExceptions().iterator(); + exs.hasNext(); + ) { + Throwable thrown = (Throwable) exs.next(); + result.handleMessage(new Message(text, kind, thrown, sourceLoc)); + } + result.handleMessage(new Message(text, kind, null, sourceLoc)); + } + result.handleMessage(new Message("", kind, null, sourceLoc)); + } + result.handleMessage(new Message("", kind, null, null)); + } + return result; + } + +} diff --git a/testing/src/test/java/org/aspectj/testing/util/StreamGrabberTest.java b/testing/src/test/java/org/aspectj/testing/util/StreamGrabberTest.java new file mode 100644 index 000000000..80ff2ea1a --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/StreamGrabberTest.java @@ -0,0 +1,121 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +/* + * StreamGrabberTest.java created on May 16, 2002 + * + */ +package org.aspectj.testing.util; + + +import java.io.PrintStream; + +import junit.framework.TestCase; +import junit.framework.TestResult; +import junit.textui.TestRunner; + +/** + * + * @author isberg + */ +public class StreamGrabberTest extends TestCase { + + + private static final String ME + = "org.aspectj.testing.util.StreamGrabberTest"; + + /** @param args ignored */ + public static void main(String[] args) throws Exception { + class C extends TestRunner { + public TestResult go(String[] a) throws Exception { + return start(a); + } + } + TestResult r = new C().go(args); + if (!r.wasSuccessful()) { + System.err.println(r.errorCount() + "/" + r.failureCount()); + } + } + + public StreamGrabberTest(String s) { super(s); } + + public void testHide() { + PrintStream restore = System.out; + System.setOut(new PrintStream(NullPrintStream.NULL_OutputStream)); + System.out.println("OutputStream should not print!!!!!!!!!!!!!!!!!!!"); + System.setOut(new PrintStream(NullPrintStream.NULL_PrintStream)); + System.out.println("PrintStream should not print!!!!!!!!!!!!!!!!!!!"); + System.setOut(restore); + } + + /** + * Test StreamSniffer by setting up a delegate System.out + * and a normal System.out (delegating to System.out) + * and verifying that both get the same result. + */ + public void testGrab() { + StringBuffer delegate = new StringBuffer(); + StreamSniffer out = new StreamSniffer(System.out); + out.setBuffer(delegate); + System.setOut(new PrintStream(out)); + StreamSniffer g = new StreamSniffer(System.out); + System.setOut(new PrintStream(g)); + StringBuffer buf = new StringBuffer(); + g.setBuffer(buf); + + printLoop("f", buf, delegate); + printLoop("now is the time for all good men...", buf, delegate); + printlnLoop("f", buf, delegate); + printlnLoop("now is the time for all good men...", buf, delegate); + } + + private void printLoop(String expect, StringBuffer buf, StringBuffer delegate) { + System.out.print(expect); + String actual = buf.toString(); + String delegateActual = delegate.toString(); + assertTrue(expect + "=" + actual, expect.equals(actual)); + assertTrue(expect + "=" + delegateActual, expect.equals(delegateActual)); + buf.setLength(0); + delegate.setLength(0); + System.out.print(expect); + + actual = buf.toString(); + delegateActual = delegate.toString(); + assertTrue(expect + "=" + actual, expect.equals(actual)); + assertTrue(expect + "=" + delegateActual, expect.equals(delegateActual)); + buf.setLength(0); + delegate.setLength(0); + } + + private void printlnLoop(String expect, StringBuffer buf, StringBuffer delegate) { + // copy/paste of printLoop, using println + expect = expect.trim(); + System.out.println(expect); + String actual = buf.toString().trim(); + String delegateActual = delegate.toString().trim(); + assertTrue(expect + "=" + actual, expect.equals(actual)); + assertTrue(expect + "=" + delegateActual, expect.equals(delegateActual)); + buf.setLength(0); + delegate.setLength(0); + + System.out.println(expect); + actual = buf.toString().trim(); + delegateActual = delegate.toString().trim(); + assertTrue(expect + "=" + actual, expect.equals(actual)); + assertTrue(expect + "=" + delegateActual, expect.equals(delegateActual)); + buf.setLength(0); + delegate.setLength(0); + } + +} diff --git a/testing/src/test/java/org/aspectj/testing/util/StructureModelUtilTest.java b/testing/src/test/java/org/aspectj/testing/util/StructureModelUtilTest.java new file mode 100644 index 000000000..e3f91decc --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/StructureModelUtilTest.java @@ -0,0 +1,79 @@ +/* ******************************************************************* + * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * Helen Hawkins Converted to new interface (bug 148190) + * ******************************************************************/ + +package org.aspectj.testing.util; + +import java.io.File; +import java.util.List; + +import junit.framework.TestSuite; + +import org.aspectj.ajde.core.AjdeCoreTestCase; +import org.aspectj.ajde.core.TestCompilerConfiguration; +import org.aspectj.asm.IProgramElement; + +/** + * @author Mik Kersten + */ +public class StructureModelUtilTest extends AjdeCoreTestCase { + + private final String[] files = new String[] { "figures" + File.separator + "Debug.java", + "figures" + File.separator + "Figure.java", "figures" + File.separator + "FigureElement.java", + "figures" + File.separator + "Main.java", "figures" + File.separator + "composites" + File.separator + "Line.java", + "figures" + File.separator + "composites" + File.separator + "Square.java", + "figures" + File.separator + "primitives" + File.separator + "planar" + File.separator + "Point.java", + "figures" + File.separator + "primitives" + File.separator + "solid" + File.separator + "SolidPoint.java" }; + + public static void main(String[] args) { + junit.swingui.TestRunner.run(StructureModelUtilTest.class); + } + + public static TestSuite suite() { + TestSuite result = new TestSuite(); + result.addTestSuite(StructureModelUtilTest.class); + return result; + } + + public void testPackageViewUtil() { + List packages = StructureModelUtil.getPackagesInModel(getCompiler().getModel()); + assertTrue("packages list not null", packages != null); + assertTrue("packages list not empty", !packages.isEmpty()); + + IProgramElement packageNode = (IProgramElement) ((Object[]) packages.get(0))[0]; + assertTrue("package node not null", packageNode != null); + + List files = StructureModelUtil.getFilesInPackage(packageNode); + assertTrue("fle list not null", files != null); + + // TODO: re-enable + // Map lineAdviceMap = StructureModelUtil.getLinesToAspectMap( + // ((IProgramElement)files.get(0)).getSourceLocation().getSourceFile().getAbsolutePath() + // ); + // + // assertTrue("line->advice map not null", lineAdviceMap != null); + // + // Set aspects = StructureModelUtil.getAspectsAffectingPackage(packageNode); + // assertTrue("aspect list not null", aspects != null); + } + + protected void setUp() throws Exception { + initialiseProject("figures-coverage"); + TestCompilerConfiguration compilerConfig = (TestCompilerConfiguration) getCompiler().getCompilerConfiguration(); + compilerConfig.setProjectSourceFiles(getSourceFileList(files)); + doBuild(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } +} diff --git a/testing/src/test/java/org/aspectj/testing/util/TestDiffsTest.java b/testing/src/test/java/org/aspectj/testing/util/TestDiffsTest.java new file mode 100644 index 000000000..af13aed03 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/TestDiffsTest.java @@ -0,0 +1,115 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.ListIterator; + +import junit.framework.TestCase; + +import org.aspectj.util.FileUtil; + +/** + * + */ +public class TestDiffsTest extends TestCase { + + /** + * Expected results in test below. + */ + private static void genTestInput(File expected, File actual) throws IOException { + FileWriter writer = null; + try { + writer = new FileWriter(expected); + PrintWriter pw = new PrintWriter(writer); + pw.println("PASS passed in both"); + pw.println("## random text to ignore: " + System.currentTimeMillis()); + pw.println("FAIL failed in both"); + pw.println("PASS failed in actual (broken)"); + pw.println("FAIL passed in actual (fixed)"); + pw.println("PASS not in actual (missing-pass)"); + pw.println("FAIL not in actual (missing-fail)"); + pw.flush(); + writer.close(); + + writer = new FileWriter(actual); + pw = new PrintWriter(writer); + pw.println("PASS passed in actual (fixed)"); + pw.println("## random text to ignore: " + System.currentTimeMillis()); + pw.println("PASS not in expected (added-pass)"); + pw.println("FAIL failed in both"); + pw.println("PASS passed in both"); + pw.println("FAIL failed in actual (broken)"); + pw.println("FAIL not in expected (added-fail)"); + pw.flush(); + writer.close(); + writer = null; + } finally { + if (null != writer) { + try { writer.close(); } + catch (IOException e) { } // ignore + } + } + } + + ArrayList tempFiles; + /** + * Constructor for FileUtilTest. + * @param arg0 + */ + public TestDiffsTest(String arg0) { + super(arg0); + tempFiles = new ArrayList(); + } + + public void tearDown() { + for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) { + File dir = (File) iter.next(); + FileUtil.deleteContents(dir); + dir.delete(); + iter.remove(); + } + } + + + public void testCompareResults() { + File tempDir = org.aspectj.util.FileUtil.getTempDir("testCompareResults"); + File expected = new File(tempDir, "expected.txt"); + File actual = new File(tempDir, "actual.txt"); + tempFiles.add(expected); + tempFiles.add(actual); + try { + genTestInput(expected, actual); + } catch (IOException e) { + assertTrue(e.getMessage(), false); + } + TestDiffs result = TestDiffs.compareResults(expected, actual); + assertEquals(2, result.missing.size()); + assertEquals(2, result.added.size()); + assertEquals(1, result.fixed.size()); + assertEquals(1, result.broken.size()); + assertEquals(3, result.actualFailed.size()); + assertEquals(3, result.actualPassed.size()); + assertEquals(6, result.actual.size()); + assertEquals(3, result.expectedFailed.size()); + assertEquals(3, result.expectedPassed.size()); + assertEquals(6, result.expected.size()); + assertEquals(1, result.stillFailing.size()); + assertEquals(1, result.stillPassing.size()); + } +} diff --git a/testing/src/test/java/org/aspectj/testing/util/UtilTests.java b/testing/src/test/java/org/aspectj/testing/util/UtilTests.java new file mode 100644 index 000000000..f5583725d --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/UtilTests.java @@ -0,0 +1,39 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.testing.util; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class UtilTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(UtilTests.class.getName()); + //$JUnit-BEGIN$ + suite.addTestSuite(BridgeUtilTest.class); + suite.addTestSuite(FileUtilTest.class); + suite.addTestSuite(IteratorWrapperTest.class); + suite.addTestSuite(LangUtilTest.class); + suite.addTestSuite(MessageUtilTest.class); + suite.addTestSuite(StreamGrabberTest.class); + suite.addTestSuite(StructureModelUtilTest.class); + //$JUnit-END$ + return suite; + } + + public UtilTests(String name) { super(name); } + +} diff --git a/testing/src/test/java/org/aspectj/testing/util/options/OptionChecker.java b/testing/src/test/java/org/aspectj/testing/util/options/OptionChecker.java new file mode 100644 index 000000000..a8b3b2c5a --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/options/OptionChecker.java @@ -0,0 +1,197 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util.options; + +import java.util.Arrays; + +import junit.framework.Assert; + +import org.aspectj.testing.util.LangUtil; + +/** + * Drivers to test a given set of Options. + * They now throw AssertionFailedError on failure, + * but subclasses can reimplement + * <code>assertionFailed(String)</code> + * to handle failures differently. + */ +public class OptionChecker { + private final Options options; + + public OptionChecker(Options options) { + this.options = options; + LangUtil.throwIaxIfNull(options, "options"); + } + + /** + * Subclasses override this to throw different exceptions + * on assertion failures. + * This implementation delegates to + * <code>Assert.assertTrue(label, false)</code>. + * @param label the String message for the assertion + * + */ + public void assertionFailed(String label) { + Assert.assertTrue(label, false); + } + + public void checkAssertion(String label, boolean test) { + if (!test) { + assertionFailed(label); + } + } + + public void checkOptions(String[] input, String[] expected) { + checkOptions(input, expected, true); + } + + public void checkOptions( + String[] input, + String[] expected, + boolean resolve) { + Values values = getValues(input); + if (resolve) { + String err = values.resolve(); + checkAssertion("error: \"" + err + "\"", null == err); + } + String[] actual = values.render(); // Value.render(values); + checkEqual(expected, actual); + } + + public void checkOptionsNegative( + String[] input, + String expectedMissedMatchErr, + String expectedResolveErr) { + checkOptionsNegative( + input, + null, + expectedMissedMatchErr, + expectedResolveErr); + } + + public void checkOptionsNegative( + String[] input, + String expectedInValuesException, + String expectedMissedMatchErr, + String expectedResolveErr) { + Values values = + getValuesNegative(input, expectedInValuesException); + if (null == expectedInValuesException) { + String err = Options.missedMatchError(input, values); + checkContains(expectedMissedMatchErr, err); + err = values.resolve(); + checkContains(expectedResolveErr, err); + } + } + + private Values getValuesNegative( + String[] input, + String expectedInExceptionMessage, + Options options) { + try { + return options.acceptInput(input); + } catch (Option.InvalidInputException e) { + String m = e.getFullMessage(); + boolean ok = + (null != expectedInExceptionMessage) + && (-1 != m.indexOf(expectedInExceptionMessage)); + if (!ok) { + e.printStackTrace(System.err); + if (null != expectedInExceptionMessage) { + m = + "expected \"" + + expectedInExceptionMessage + + "\" in " + + m; + } + assertionFailed(m); + } + return null; // actually never executed + } + } + + private Values getValuesNegative( + String[] input, + String expectedInExceptionMessage) { + return getValuesNegative( + input, + expectedInExceptionMessage, + options); + } + +// private Values getValues(String[] input, Options options) { +// return getValuesNegative(input, null, options); +// } + + private Values getValues(String[] input) { + return getValuesNegative(input, null); + } + + private void checkContains(String expected, String expectedIn) { + if (null == expected) { + if (null != expectedIn) { + assertionFailed("did not expect \"" + expectedIn + "\""); + } + } else { + if ((null == expectedIn) + || (-1 == expectedIn.indexOf(expected))) { + assertionFailed( + "expected \"" + + expected + + "\" in \"" + + expectedIn + + "\""); + } + } + } + + private String safeString(String[] ra) { + return (null == ra ? "null" : Arrays.asList(ra).toString()); + } + + private void checkEqual(String[] expected, String[] actual) { + if (!isEqual(expected, actual)) { + assertionFailed( + "expected \"" + + safeString(expected) + + "\" got \"" + + safeString(actual) + + "\""); + } + } + + private boolean isEqual(String[] expected, String[] actual) { + if (null == expected) { + return (null == actual ? true : false); + } else if (null == actual) { + return false; + } else if (expected.length != actual.length) { + return false; + } + for (int i = 0; i < actual.length; i++) { + String e = expected[i]; + String a = actual[i]; + if (null == e) { + if (null != a) { + return false; + } + } else if (null == a) { + return false; + } else if (!(e.equals(a))) { + return false; + } + } + return true; + } + +} diff --git a/testing/src/test/java/org/aspectj/testing/util/options/OptionsTest.java b/testing/src/test/java/org/aspectj/testing/util/options/OptionsTest.java new file mode 100644 index 000000000..4d8efdf2e --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/options/OptionsTest.java @@ -0,0 +1,486 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util.options; + +import junit.framework.*; + +import org.aspectj.testing.util.options.Option.InvalidInputException; + +/** + */ +public class OptionsTest extends TestCase { + + private static Options OPTIONS; + + private static Options getOptions() { + if (null == OPTIONS) { + OPTIONS = new Options(true); + Option.Factory factory = new Option.Factory("OptionsTest"); + OPTIONS.addOption(factory.create("verbose")); + OPTIONS.addOption(factory.create("quiet")); + OPTIONS.addOption(factory.create("debug")); + OPTIONS.addOption( + factory.create("ajc", "compiler", Option.FORCE_PREFIXES, false)); + OPTIONS.addOption( + factory.create( + "eclipse", + "compiler", + Option.FORCE_PREFIXES, + false)); + OPTIONS.addOption( + factory.create( + "ajdeCompiler", + "compiler", + Option.FORCE_PREFIXES, + false)); + OPTIONS.addOption( + factory.create("1.3", "compliance", Option.FORCE_PREFIXES, false)); + OPTIONS.addOption( + factory.create("1.4", "compliance", Option.FORCE_PREFIXES, false)); + + // treating multi-arg as single - extrinsic flatten/unflatten + OPTIONS.addOption( + factory.create("target11", "target", Option.FORCE_PREFIXES, false)); + OPTIONS.addOption( + factory.create("target12", "target", Option.FORCE_PREFIXES, false)); + OPTIONS.addOption( + factory.create("source13", "source", Option.FORCE_PREFIXES, false)); + OPTIONS.addOption( + factory.create("source14", "source", Option.FORCE_PREFIXES, false)); + + // suffix options (a) -warn:... (b) -g, -g:... + Assert.assertTrue(factory.setupFamily("warning", true)); + OPTIONS.addOption( + factory.create("warn", "warning", Option.STANDARD_PREFIXES, true)); + + Assert.assertTrue(factory.setupFamily("debugSymbols", true)); + OPTIONS.addOption( + factory.create( + "g", + "debugSymbols", + Option.STANDARD_PREFIXES, + false)); + OPTIONS.addOption( + factory.create( + "g:", + "debugSymbols", + Option.STANDARD_PREFIXES, + true)); + + // treating multi-arg as single - intrinsic flatten/unflatten + OPTIONS + .addOption( + factory + .create( + "target", + "target", + Option.FORCE_PREFIXES, + false, + new String[][] { + new String[] { "1.1", "1.2" } + })); + OPTIONS + .addOption( + factory + .create( + "source", + "source", + Option.FORCE_PREFIXES, + false, + new String[][] { + new String[] { "1.3", "1.4" } + })); + OPTIONS.freeze(); + } + return OPTIONS; + } + +// private boolean verbose; + private OptionChecker localOptionChecker; + + public void testDebugCase() { + OptionChecker optionChecker = getOptionChecker(); + String[] input = new String[] { + }; + String[] expected = new String[0]; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-target", "1.1", "^target", "1.2" }; + expected = new String[] { "-target", "1.1" }; + + optionChecker.checkOptions(input, expected); + } + public void testNegDebugCase() { + OptionChecker optionChecker = getOptionChecker(); + String[] input = new String[] { "-target" }; + String expectedInValuesException = "not enough arguments"; + String expectedMissedMatchErr = null; + String expectedResolveErr = null; + + optionChecker.checkOptionsNegative( + input, + expectedInValuesException, + expectedMissedMatchErr, + expectedResolveErr); + } + + public void testOptionsPositive() { + OptionChecker optionChecker = getOptionChecker(); + String[] input = new String[] { + }; + String[] expected = new String[0]; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-verbose" }; + expected = new String[] { "-verbose" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!verbose" }; + expected = new String[] { "-verbose" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!verbose", "-verbose" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-verbose", "!verbose" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "^verbose" }; + expected = new String[] { + }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "^verbose", "-verbose" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-verbose", "^verbose" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-verbose", "-debug" }; + expected = new String[] { "-verbose", "-debug" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!verbose", "!debug" }; + expected = new String[] { "-verbose", "-debug" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-verbose", "^verbose", "!debug" }; + expected = new String[] { "-debug" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "^verbose", "-verbose", "!debug" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!debug", "^verbose", "-verbose" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-ajc" }; + expected = new String[] { "-ajc" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-eclipse" }; + expected = new String[] { "-eclipse" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-eclipse", "-ajc", "!ajc" }; + expected = new String[] { "-ajc" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-eclipse", "!ajc" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-ajdeCompiler", "^ajc" }; + expected = new String[] { "-ajdeCompiler" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!ajdeCompiler", "^ajc" }; + optionChecker.checkOptions(input, expected); + + input = + new String[] { + "-verbose", + "^verbose", + "!quiet", + "-quiet", + "-debug", + "^debug" }; + expected = new String[] { "-quiet" }; + optionChecker.checkOptions(input, expected); + + input = + new String[] { + "-verbose", + "^debug", + "!quiet", + "!quiet", + "-debug", + "^verbose" }; + expected = new String[] { "-quiet" }; + optionChecker.checkOptions(input, expected); + } + + public void testOptionsNegative() { + OptionChecker optionChecker = getOptionChecker(); + String[] input = new String[] { "-unknown" }; + String expectedMissedMatchErr = "-unknown"; + String expectedResolveErr = null; + optionChecker.checkOptionsNegative( + input, + expectedMissedMatchErr, + expectedResolveErr); + + input = new String[] { "!verbose", "^verbose" }; + expectedMissedMatchErr = null; + expectedResolveErr = "conflict"; + optionChecker.checkOptionsNegative( + input, + expectedMissedMatchErr, + expectedResolveErr); + + input = new String[] { "!ajc", "!eclipse" }; + optionChecker.checkOptionsNegative( + input, + expectedMissedMatchErr, + expectedResolveErr); + + input = new String[] { "-ajc", "-eclipse" }; + expectedResolveErr = "collision"; + optionChecker.checkOptionsNegative( + input, + expectedMissedMatchErr, + expectedResolveErr); + + input = new String[] { "-verbose", "-verbose" }; + expectedResolveErr = null; // duplicates redundant, not colliding + optionChecker.checkOptionsNegative( + input, + expectedMissedMatchErr, + expectedResolveErr); + } + + public void testMissedMatches() throws InvalidInputException { + checkMissedMatches(new int[0], Values.EMPTY); + checkMissedMatches(new int[] { 0 }, + Values.wrapValues(new Option.Value[1])); // null in [0] + checkMissedMatches( + new int[] { 0, 1, 2 }, + Values.wrapValues(new Option.Value[] { null, null, null })); + + Option.Factory factory = new Option.Factory("testMissedMatches"); + Option single = factory.create("verbose"); + Option multiple = + factory + .create( + "source", + "source", + Option.STANDARD_PREFIXES, + false, + new String[][] { new String[] { "1.3", "1.4" } + }); + + Options options = new Options(false); + options.addOption(single); + options.addOption(multiple); + options.freeze(); + int[] expectNone = new int[0]; + String[] input = new String[] { "-verbose" }; + Values result = options.acceptInput(input); + checkMissedMatches(expectNone, result); + + input = new String[] { "-verbose", "-verbose" }; + result = options.acceptInput(input); + checkMissedMatches(expectNone, result); + + input = new String[] { "-source", "1.3" }; + result = options.acceptInput(input); + checkMissedMatches(expectNone, result); + + input = new String[] { "-source", "1.4" }; + result = options.acceptInput(input); + checkMissedMatches(expectNone, result); + + input = new String[] { "-verbose", "-missed" }; + result = options.acceptInput(input); + checkMissedMatches(new int[] { 1 }, result); + + input = new String[] { "-source", "1.4", "-missed" }; + result = options.acceptInput(input); + checkMissedMatches(new int[] { 2 }, result); + + input = new String[] { "-source", "1.4", "-missed", "-verbose" }; + result = options.acceptInput(input); + checkMissedMatches(new int[] { 2 }, result); + + } + + void checkMissedMatches(int[] expected, Values actual) { + int[] result = actual.indexMissedMatches(); + boolean failed = (result.length != expected.length); + + for (int i = 0; !failed && (i < result.length); i++) { + failed = (result[i] != expected[i]); + } + if (failed) { + assertTrue( + "expected " + + Values.IntList.render(expected) + + " got " + + Values.IntList.render(result) + + " for " + + actual, + false); + } + } + + public void testComplexOptionsPositive() { + OptionChecker optionChecker = getOptionChecker(); + String[] input = new String[] { + }; + String[] expected = new String[0]; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-target11" }; + expected = new String[] { "-target11" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!target12" }; + expected = new String[] { "-target12" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!target12", "-target11" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!target12", "^target11" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "^target12", "^target11" }; + expected = new String[] { + }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!1.3" }; + expected = new String[] { "-1.3" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!1.3", "-1.4" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!1.3", "^1.4" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "^1.3", "^1.4" }; + expected = new String[] { + }; + optionChecker.checkOptions(input, expected); + + } + + public void testMultiArgOptionsPositive() { + OptionChecker optionChecker = getOptionChecker(); + String[] input = new String[] { + }; + String[] expected = new String[0]; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-target", "1.1" }; + expected = new String[] { "-target", "1.1" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!target", "1.1" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!target", "1.1", "-target", "1.2" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-target", "1.1", "^target", "1.2" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-source", "1.3" }; + expected = new String[] { "-source", "1.3" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "!source", "1.3", "-source", "1.4" }; + optionChecker.checkOptions(input, expected); + + input = new String[] { "-source", "1.3", "^source", "1.4" }; + input = + new String[] { + "-source", + "1.3", + "^source", + "1.4", + "!source", + "1.3", + "-source", + "1.4" }; + optionChecker.checkOptions(input, expected); + } + + public void testMultiArgOptionsNegative() { + OptionChecker optionChecker = getOptionChecker(); + String[] input = new String[] { "-target" }; + String expectedException = "not enough arguments"; + + optionChecker.checkOptionsNegative( + input, + expectedException, + null, + null); + + input = new String[] { "-source" }; + optionChecker.checkOptionsNegative( + input, + expectedException, + null, + null); + + input = new String[] { "-source", "1.1" }; + expectedException = "not permitted"; + optionChecker.checkOptionsNegative( + input, + expectedException, + null, + null); + + input = new String[] { "-target", "1.3" }; + optionChecker.checkOptionsNegative( + input, + expectedException, + null, + null); + } + + public void testMultipleInput() { + OptionChecker optionChecker = getOptionChecker(); + String[][] input = + new String[][] { + new String[] { "-warn:deprecated" }, + new String[] { "-warn:deprecated,unverified" }, + new String[] { "-warn:deprecated", "-warn:unusedLocals" }, + new String[] { "-g" }, + new String[] { "-g", "-g:none" }, + new String[] { "-g:vars,source" }, + new String[] { "-verbose", "-g:vars,source" }, + }; + for (int i = 0; i < input.length; i++) { + optionChecker.checkOptions(input[i], input[i]); + } + } + + private OptionChecker getOptionChecker() { + if (null == localOptionChecker) { + localOptionChecker = new OptionChecker(getOptions()); + } + return localOptionChecker; + } +} diff --git a/testing/src/test/java/org/aspectj/testing/util/options/OptionsTests.java b/testing/src/test/java/org/aspectj/testing/util/options/OptionsTests.java new file mode 100644 index 000000000..0b82c7dc9 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/options/OptionsTests.java @@ -0,0 +1,30 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + + +package org.aspectj.testing.util.options; + +import junit.framework.*; + +public class OptionsTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(OptionsTests.class.getName()); + //$JUnit-BEGIN$ + suite.addTestSuite(OptionsTest.class); + //$JUnit-END$ + return suite; + } + + public OptionsTests(String name) { super(name); } + +} diff --git a/testing/src/test/java/org/aspectj/testing/util/options/ValuesTest.java b/testing/src/test/java/org/aspectj/testing/util/options/ValuesTest.java new file mode 100644 index 000000000..e1a3b3c01 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/util/options/ValuesTest.java @@ -0,0 +1,69 @@ +/* ******************************************************************* + * Copyright (c) 2003 Contributors. + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Wes Isberg initial implementation + * ******************************************************************/ + +package org.aspectj.testing.util.options; + +import junit.framework.TestCase; + +/** + */ +public class ValuesTest extends TestCase { + + public ValuesTest(String s) { + super(s); + } + public void testInvert() { + checkInvert(new int[0], 0, new int[0]); // no input or missed => none found + checkInvert(new int[0], 1, new int[] {0}); // no missed, input 1 => 1 found + checkInvert(new int[] {0}, 1, new int[] {}); // 1 (all) missed, input 1 => none found + checkInvert(new int[] {}, 1, new int[] {0}); // 0 (none) missed, input 1 => 1 found + checkInvert(new int[] {1,2}, 3, new int[] {0}); // 2 missed, input 3 => 1 (first) found + checkInvert(new int[] {0,2}, 3, new int[] {1}); // 2 missed, input 3 => 1 (middle) found + checkInvert(new int[] {0,1}, 3, new int[] {2}); // 2 missed, input 3 => 1 (last) found + checkInvert(new int[] {1,3}, 4, new int[] {0,2}); // 2 missed, input 4 => 2 found + checkInvert(new int[] {5,6,7}, 8, new int[] {0,1,2,3,4}); // starting run + checkInvert(new int[] {0,1,2,3,4}, 8, new int[] {5,6,7}); // ending run + checkInvert(new int[] {0,5,6,7}, 8, new int[] {1,2,3,4}); // middle run + checkInvert(new int[] {0,5,6,9},10, new int[] {1,2,3,4,7,8}); // two middle run + checkInvert(new int[] {1,2,5,6,9},10, new int[] {0,3,4,7,8}); // start, 2 middle run + checkInvert(new int[] {0,1,2,5,6},10, new int[] {3,4,7,8,9}); // middle, end run + } + + void checkInvert(int[] missed, int length, int[] expected) { + int[] actual = Values.invert(missed, length); + assertTrue(null != actual); + assertTrue(actual.length == expected.length); + for (int i = 0; i < actual.length; i++) { + if (expected[i] != actual[i]) { + assertTrue("failed at " + i + render(expected, actual), false); + } + } + } + static String render(int[] expected, int[] actual) { + StringBuffer sb = new StringBuffer(); + sb.append(" expected "); + render(expected, sb); + sb.append(" actual "); + render(actual, sb); + return sb.toString(); + } + static void render(int[] ra, StringBuffer sb) { + sb.append("["); + for (int i = 0; i < ra.length; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append("" + ra[i]); + } + sb.append("]"); + } +} diff --git a/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReaderTest.java b/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReaderTest.java new file mode 100644 index 000000000..bff18c024 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReaderTest.java @@ -0,0 +1,243 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.xml; + +import java.beans.BeanInfo; +import java.beans.IntrospectionException; +import java.beans.Introspector; +import java.beans.PropertyDescriptor; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; + +//import junit.framework.*; +import junit.framework.TestCase; + +import org.aspectj.testing.harness.bridge.AjcSpecTest; +import org.aspectj.testing.harness.bridge.AjcTest; +import org.aspectj.testing.harness.bridge.FlatSuiteReader; +import org.aspectj.util.LangUtil; + +/** + * + */ +public class AjcSpecXmlReaderTest extends TestCase { + + ArrayList<File> tempFiles = new ArrayList<File>(); + /** + * Constructor for AjcSpecXmlReaderTest. + * @param name + */ + public AjcSpecXmlReaderTest(String name) { + super(name); + } + + public void setUp() { + tempFiles.clear(); + //System.out.println("XXX test requires compiler and bridgeImpl projects on classpath"); + } + + public void tearDown() { + if (!LangUtil.isEmpty(tempFiles)) { + for (Iterator<File> iter = tempFiles.iterator(); iter.hasNext();) { + File file = (File) iter.next(); + if (file.canRead()) { + file.delete(); + } + } + } + } + + /** test that all AjcSpecXmlReader.me.expectedProperties() are bean-writable */ + public void testBeanInfo() throws IntrospectionException { +// AjcSpecXmlReader me = AjcSpecXmlReader.getReader(); + AjcSpecXmlReader.BProps[] expected + = AjcSpecXmlReader.expectedProperties(); + PropertyDescriptor[] des; + for (int i = 0; i < expected.length; i++) { + Class<?> clazz = expected[i].cl; + BeanInfo beanInfo = Introspector.getBeanInfo(clazz); + assertTrue(null != beanInfo); + des = beanInfo.getPropertyDescriptors(); + for (int j = 0; j < expected[i].props.length; j++) { + String name = expected[i].props[j]; + String fqn = clazz.getName() + "." + name; + boolean gotIt = false; + for (int k = 0; k < des.length; k++) { + String desName = des[k].getName(); + if (name.equals(desName)) { + assertTrue(fqn, null != des[k].getWriteMethod()); + gotIt = true; + } + } + assertTrue("no such property: " + fqn, gotIt); + } + } + + } + public void testAjcTests() throws IOException { + checkXmlRoundTrip("../tests/ajcTests"); + } + + public void testAjcTests10() throws IOException { + checkXmlRoundTrip("../tests/ajcTests10"); + } + + public void testAjcTestsBroken() throws IOException { + checkXmlRoundTrip("../tests/ajcTestsBroken"); + } + + public void testAjcTestsAttic() throws IOException { + checkXmlRoundTrip("../tests/ajcTestsAttic"); + } + + public void testAjcHarnessTests() throws IOException { + checkXmlRoundTrip("../tests/ajcHarnessTests"); + } + + void checkXmlRoundTrip(String path) throws IOException { + String xmlPath = path + ".xml"; + String xml2Path = path + ".tmp.xml"; + + final File file1 = new File(xmlPath); + final ArrayList<File> toDelete = new ArrayList<File>(); + final AjcSpecXmlReader writer = AjcSpecXmlReader.getReader(); + + assertTrue("" + file1, file1.canRead()); + AjcTest.Suite.Spec suite1 = writer.readAjcSuite(file1); + assertNotNull(suite1); + + File file2 = new File(xml2Path); + String warning = writer.writeSuiteToXmlFile(file2, suite1); + toDelete.add(file2); + assertTrue(warning, null == warning); + + AjcTest.Suite.Spec suite2 = writer.readAjcSuite(file1); + assertNotNull(suite2); + AjcSpecTest.sameAjcSuiteSpec(suite1, suite2, this); + + // check clone while we're here + try { + Object clone = (AjcTest.Suite.Spec) suite1.clone(); + AjcSpecTest.sameAjcSuiteSpec(suite1, (AjcTest.Suite.Spec) clone, this); + clone = (AjcTest.Suite.Spec) suite2.clone(); + AjcSpecTest.sameAjcSuiteSpec(suite2, (AjcTest.Suite.Spec) clone, this); + AjcSpecTest.sameAjcSuiteSpec(suite1, (AjcTest.Suite.Spec) clone, this); + } catch (CloneNotSupportedException e) { + e.printStackTrace(System.err); + assertTrue("CloneNotSupportedException: " + e.getMessage(), false); + } + + for (Iterator<File> iter = toDelete.iterator(); iter.hasNext();) { + iter.next().delete(); + } + } + + void checkRoundTrip(String path) throws IOException, Exception { + // XXX once .txt gone, add bugId and keywords to test + String txtPath = path + ".txt"; + String xmlPath = path + ".tmp.xml"; + String xml2Path = path + ".tmp2.xml"; + + // read flat, write the xml variant, read back, and compare + AjcSpecXmlReader writer = AjcSpecXmlReader.getReader(); + File file0 = new File(txtPath); + File file1 = new File(xmlPath); + ArrayList<File> toDelete = new ArrayList<File>(); + AjcTest.Suite.Spec suite0 = null; + if (file0.canRead()) { + System.out.println("reading " + file0); + suite0 = FlatSuiteReader.ME.readSuite(file0); + String warning = writer.writeSuiteToXmlFile(file1, suite0); + toDelete.add(file1); + assertTrue(warning, null == warning); + } else { + file1 = new File(path + ".xml"); + if (file1.canRead()) { + System.out.println("reading " + file1); + suite0 = writer.readAjcSuite(file1); + } else { + System.err.println("Skipping as not in module: " + file0); + return; + } + } + assertNotNull(suite0); + + //System.err.println("----------------------- suite0 " + txtPath); + //suite0.printAll(System.err, ""); + assertTrue("" + file1, file1.canRead()); + System.out.println("reading " + file1); + AjcTest.Suite.Spec suite1 = writer.readAjcSuite(file1); + assertNotNull(suite1); + //System.err.println("----------------------- suite1 " + xmlPath); + //suite0.printAll(System.err, ""); + AjcSpecTest.sameAjcSuiteSpec(suite0, suite1, this); + + // same for second-generation xml + file1 = new File(xml2Path); + String warning = writer.writeSuiteToXmlFile(file1, suite1); + toDelete.add(file1); + // XXX enable later assertTrue(warning, null == warning); + if (null != warning) { + System.out.println("warning " + file1 + ": " + warning); + } + System.out.println("reading " + file1); + AjcTest.Suite.Spec suite2 = writer.readAjcSuite(file1); + assertNotNull(suite2); + //System.err.println("----------------------- suite2 " + xml2Path); + AjcSpecTest.sameAjcSuiteSpec(suite1, suite2, this); + AjcSpecTest.sameAjcSuiteSpec(suite0, suite2, this); + + for (Iterator<File> iter = toDelete.iterator(); iter.hasNext();) { + iter.next().delete(); + } + } +} + + // ------------------- XXX retry execution round-trips when eclipse working + //AjcSpecTest.sameAjcTestSpec(txtList, xmlSpec, this); + +// List xmlList = writer.readAjcTests(xmlFile); +// AjcSpecTest.sameAjcTestLists(txtList, xmlList, this); +// List xml2List = writer.readAjcTests(xmlFile); +// AjcSpecTest.sameAjcTestLists(xmlList, xml2List, this); + + + // ------------------ now run them both and compare results +// // run the flat and xml variants, then compare +// MessageHandler xmlHandler = new MessageHandler(); +// IRunStatus xmlStatus = runFile(xmlPath, xmlHandler); +// MessageHandler txtHandler = new MessageHandler(); +// IRunStatus txtStatus = runFile(txtPath, txtHandler); +// +// +// // both should pass or fail.. +// IRunValidator v = RunValidator.NORMAL; +// boolean xmlPassed = v.runPassed(xmlStatus); +// boolean txtPassed = v.runPassed(txtStatus); +// boolean passed = (xmlPassed == txtPassed); +// if (!xmlPassed) { +// MessageUtil.print(System.err, xmlStatus); +// } +// if (!txtPassed) { +// MessageUtil.print(System.err, txtStatus); +// } +// if (!passed) { // calculate diffs +// } +// IRunStatus runFile(String path, MessageHandler handler) throws IOException { +// Main runner = new Main(new String[] {path}, handler); +// String id = "AjcSpecXmlReaderTest.runFile(" + path + ")"; +// return runner.runMain(id, handler, System.err); +// } diff --git a/testing/src/test/java/org/aspectj/testing/xml/MessageListXmlReaderTest.java b/testing/src/test/java/org/aspectj/testing/xml/MessageListXmlReaderTest.java new file mode 100644 index 000000000..aa393f5de --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/xml/MessageListXmlReaderTest.java @@ -0,0 +1,78 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.xml; + +import org.aspectj.bridge.IMessage; +import org.aspectj.util.LangUtil; + +import java.io.File; +import java.util.ArrayList; +import java.util.Iterator; + +import junit.framework.TestCase; + +/** + * + */ +public class MessageListXmlReaderTest extends TestCase { + + ArrayList tempFiles = new ArrayList(); + public MessageListXmlReaderTest(String name) { + super(name); + } + + public void setUp() { + tempFiles.clear(); + } + + public void tearDown() { + if (!LangUtil.isEmpty(tempFiles)) { + for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { + File file = (File) iter.next(); + if (file.canRead()) { + file.delete(); + } + } + } + } + public void testNothingOthersSkipped() {} + + public void skiptestMessageReading() throws Exception { + + //assertTrue("XXX need better XML wrapping - has < character", false); + //checkXmlRoundTrip("testdata/dirChangesTestDir/diff/expectedMessages"); + //checkXmlRoundTrip("testdata/dirChangesTestDir/same/expectedMessages"); + } + + void checkXmlRoundTrip(String path) throws Exception { + String xmlPath = path + ".xml"; + String xml2Path = path + ".tmp.xml"; + final File file1 = new File(xmlPath); + assertTrue("" + file1, file1.canRead()); + + MessageListXmlReader reader = new MessageListXmlReader(); + IMessage[] messages = reader.readMessages(file1); + assertNotNull(messages); + assertTrue("empty messages", 0 != messages.length); + + File file2 = new File(xml2Path); + String warning = reader.writeMessages(file2, messages); + assertTrue(warning, null == warning); + tempFiles.add(file2); + + IMessage[] messages2 = reader.readMessages(file2); + assertEquals(LangUtil.arrayAsList(messages).toString(), + LangUtil.arrayAsList(messages2).toString()); + } +} diff --git a/testing/src/test/java/org/aspectj/testing/xml/TestingXmlTests.java b/testing/src/test/java/org/aspectj/testing/xml/TestingXmlTests.java new file mode 100644 index 000000000..ff8093c32 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/xml/TestingXmlTests.java @@ -0,0 +1,35 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + + +package org.aspectj.testing.xml; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +public class TestingXmlTests extends TestCase { + + public static Test suite() { + TestSuite suite = new TestSuite(TestingXmlTests.class.getName()); + //$JUnit-BEGIN$ + suite.addTestSuite(AjcSpecXmlReaderTest.class); + suite.addTestSuite(MessageListXmlReaderTest.class); + suite.addTestSuite(XMLWriterTest.class); + //$JUnit-END$ + return suite; + } + + public TestingXmlTests(String name) { super(name); } + +} diff --git a/testing/src/test/java/org/aspectj/testing/xml/XMLWriterTest.java b/testing/src/test/java/org/aspectj/testing/xml/XMLWriterTest.java new file mode 100644 index 000000000..13d2652e0 --- /dev/null +++ b/testing/src/test/java/org/aspectj/testing/xml/XMLWriterTest.java @@ -0,0 +1,44 @@ +/* ******************************************************************* + * Copyright (c) 1999-2001 Xerox Corporation, + * 2002 Palo Alto Research Center, Incorporated (PARC). + * All rights reserved. + * This program and the accompanying materials are made available + * under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Xerox/PARC initial implementation + * ******************************************************************/ + +package org.aspectj.testing.xml; + +import java.util.Arrays; + +import junit.framework.TestCase; + +/** + * + */ +public class XMLWriterTest extends TestCase { + + public XMLWriterTest(String name) { + super(name); + } + + /** @see LangUtilTest#testCommaSplit() */ + public void testUnflattenList() { + checkUnflattenList("", new String[] {""}); + checkUnflattenList("1", new String[] {"1"}); + checkUnflattenList(" 1 2 ", new String[] {"1 2"}); + checkUnflattenList(" 1 , 2 ", new String[] {"1", "2"}); + checkUnflattenList("1,2,3,4", new String[] {"1", "2", "3", "4"}); + } + + void checkUnflattenList(String input, String[] expected) { + String[] actual = XMLWriter.unflattenList(input); + String a = "" + Arrays.asList(actual); + String e = "" + Arrays.asList(expected); + assertTrue(e + "==" + a, e.equals(a)); + } +} |