diff --git a/build.xml b/build.xml index 7f67ea0ac..b3678947a 100644 --- a/build.xml +++ b/build.xml @@ -19,7 +19,7 @@ + (and without typing -D on each invocation) --> @@ -80,7 +80,8 @@ - + + @@ -97,8 +98,10 @@ - - + + + + @@ -416,6 +419,9 @@ + @@ -1542,52 +1548,116 @@ Run testcase =================================================================== --> - - Unit tests failed see ${build.tests.reports} + + + + + + + + + + + + Unit tests failed; see ${build.junit.reports} / ${antunit.reports} - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + - + - + @@ -1595,7 +1665,7 @@ - + @@ -1736,15 +1806,15 @@ - - - + @@ -1756,6 +1826,41 @@ fork="true"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ",project.getProperty("string.with.default")); + assertEquals(".",project.getProperty("string.without.default")); + assertEquals("2002/01/21 12:18", project.getProperty("ethans.birth")); + assertEquals("2003/01/21", project.getProperty("first.birthday")); + assertEquals("0124", project.getProperty("olderThanAWeek")); + assertEquals("37", project.getProperty("existing.prop")); + assertEquals("6",project.getProperty("int.without.value")); + } + + public void testValueDoesNotGetOverwritten() { + // this test shows that the bug report 21505 is fixed + executeTarget("bugDemo1"); + executeTarget("bugDemo2"); + assertEquals("5", project.getProperty("foo")); + } +/* + public void testDirect() throws Exception { + PropertyFile pf = new PropertyFile(); + pf.setProject(project); + pf.setFile(new File(System.getProperty("root"), testPropsFilePath)); + PropertyFile.Entry entry = pf.createEntry(); + + entry.setKey("date"); + entry.setValue("123"); + PropertyFile.Entry.Type type = new PropertyFile.Entry.Type(); + type.setValue("date"); + entry.setType(type); + + entry.setPattern("yyyy/MM/dd"); + + PropertyFile.Entry.Operation operation = new PropertyFile.Entry.Operation(); + operation.setValue("+"); + pf.execute(); + + Properties props = getTestProperties(); + assertEquals("yeehaw", props.getProperty("date")); + } +*/ + + private Properties getTestProperties() throws Exception { + Properties testProps = new Properties(); + FileInputStream propsFile = new FileInputStream(new File(System.getProperty("root"), testPropsFilePath)); + testProps.load(propsFile); + propsFile.close(); + return testProps; + } + + + private void initTestPropFile() throws Exception { + Properties testProps = new Properties(); + testProps.put(FNAME_KEY, FNAME); + testProps.put(LNAME_KEY, LNAME); + testProps.put(EMAIL_KEY, EMAIL); + testProps.put("existing.prop", "37"); + + FileOutputStream fos = new FileOutputStream(new File(System.getProperty("root"), testPropsFilePath)); + testProps.store(fos, "defaults"); + fos.close(); + } + + + private void initBuildPropFile() throws Exception { + Properties buildProps = new Properties(); + buildProps.put(testPropertyFileKey, testPropertyFile); + buildProps.put(FNAME_KEY, NEW_FNAME); + buildProps.put(LNAME_KEY, NEW_LNAME); + buildProps.put(EMAIL_KEY, NEW_EMAIL); + buildProps.put(PHONE_KEY, NEW_PHONE); + buildProps.put(AGE_KEY, NEW_AGE); + buildProps.put(DATE_KEY, NEW_DATE); + + FileOutputStream fos = new FileOutputStream(new File(System.getProperty("root"), buildPropsFilePath)); + buildProps.store(fos, null); + fos.close(); + } + + + private void destroyTempFiles() { + File tempFile = new File(System.getProperty("root"), testPropsFilePath); + tempFile.delete(); + tempFile = null; + + tempFile = new File(System.getProperty("root"), buildPropsFilePath); + tempFile.delete(); + tempFile = null; + + tempFile = new File(System.getProperty("root"), valueDoesNotGetOverwrittenPropsFilePath); + tempFile.delete(); + tempFile = null; + } + + + + private static final String + projectFilePath = "src/etc/testcases/taskdefs/optional/propertyfile.xml", + + testPropertyFile = "propertyfile.test.properties", + testPropertyFileKey = "test.propertyfile", + testPropsFilePath = "src/etc/testcases/taskdefs/optional/" + testPropertyFile, + + valueDoesNotGetOverwrittenPropertyFile = "overwrite.test.properties", + valueDoesNotGetOverwrittenPropertyFileKey = "overwrite.test.propertyfile", + valueDoesNotGetOverwrittenPropsFilePath = "src/etc/testcases/taskdefs/optional/" + valueDoesNotGetOverwrittenPropertyFile, + + buildPropsFilePath = "src/etc/testcases/taskdefs/optional/propertyfile.build.properties", + + FNAME = "Bruce", + NEW_FNAME = "Clark", + FNAME_KEY = "firstname", + + LNAME = "Banner", + NEW_LNAME = "Kent", + LNAME_KEY = "lastname", + + EMAIL = "incredible@hulk.com", + NEW_EMAIL = "kc@superman.com", + EMAIL_KEY = "email", + + NEW_PHONE = "(520) 555-1212", + PHONE_KEY = "phone", + + NEW_AGE = "30", + AGE_KEY = "age", + + NEW_DATE = "2001/01/01 12:45", + DATE_KEY = "date"; +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PvcsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PvcsTest.java new file mode 100644 index 000000000..0dc1d7092 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PvcsTest.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + */ +public class PvcsTest extends BuildFileTest { + + public PvcsTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/taskdefs/optional/pvcs.xml"); + } + + public void test1() { + expectBuildException("test1", "Required argument repository not specified"); + } + + public void test2() { + executeTarget("test2"); + } + + public void test3() { + executeTarget("test3"); + } + + public void test4() { + executeTarget("test4"); + } + + public void test5() { + executeTarget("test5"); + } + + public void test6() { + expectBuildException("test6", "Failed executing: /never/heard/of/a/directory/structure/like/this/pcli lvf -z -aw -pr//ct4serv2/pvcs/monitor /. Exception: /never/heard/of/a/directory/structure/like/this/pcli: not found"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ReplaceRegExpTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ReplaceRegExpTest.java new file mode 100644 index 000000000..bc18d05cf --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ReplaceRegExpTest.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.util.FileUtils; + +import java.util.Properties; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +/** + * JUnit Testcase for the optional replaceregexp task. + * + */ +public class ReplaceRegExpTest extends BuildFileTest { + private static final String PROJECT_PATH = "src/etc/testcases/taskdefs/optional"; + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + + public ReplaceRegExpTest(String name) { + super(name); + } + + public void setUp() { + configureProject(PROJECT_PATH + "/replaceregexp.xml"); + } + + public void tearDown() { + executeTarget("cleanup"); + } + + public void testReplace() throws IOException { + Properties original = new Properties(); + FileInputStream propsFile = null; + try { + propsFile = new FileInputStream(new File(System.getProperty("root"), PROJECT_PATH + "/replaceregexp.properties")); + original.load(propsFile); + } finally { + if (propsFile != null) { + propsFile.close(); + propsFile = null; + } + } + + assertEquals("Def", original.get("OldAbc")); + + executeTarget("testReplace"); + + Properties after = new Properties(); + try { + propsFile = new FileInputStream(new File(System.getProperty("root"), PROJECT_PATH + "/test.properties")); + after.load(propsFile); + } finally { + if (propsFile != null) { + propsFile.close(); + propsFile = null; + } + } + + assertNull(after.get("OldAbc")); + assertEquals("AbcDef", after.get("NewProp")); + } + // inspired by bug 22541 + public void testDirectoryDateDoesNotChange() { + executeTarget("touchDirectory"); + File myFile = new File(System.getProperty("root"), PROJECT_PATH + "/" + getProject().getProperty("tmpregexp")); + long timeStampBefore = myFile.lastModified(); + executeTarget("testDirectoryDateDoesNotChange"); + long timeStampAfter = myFile.lastModified(); + assertEquals("directory date should not change", + timeStampBefore, timeStampAfter); + } + public void testDontAddNewline1() throws IOException { + executeTarget("testDontAddNewline1"); + assertTrue("Files match", + FILE_UTILS + .contentEquals(new File(System.getProperty("root"), PROJECT_PATH + "/test.properties"), + new File(System.getProperty("root"), PROJECT_PATH + "/replaceregexp2.result.properties"))); + } + + public void testDontAddNewline2() throws IOException { + executeTarget("testDontAddNewline2"); + assertTrue("Files match", + FILE_UTILS + .contentEquals(new File(System.getProperty("root"), PROJECT_PATH + "/test.properties"), + new File(System.getProperty("root"), PROJECT_PATH + "/replaceregexp2.result.properties"))); + } + +}// ReplaceRegExpTest diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoReferenceTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoReferenceTest.java new file mode 100644 index 000000000..64ae4f4a7 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoReferenceTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Tests using an undefined reference. + * + * @since Ant 1.6 + */ +public class RhinoReferenceTest extends BuildFileTest { + + public RhinoReferenceTest(String name) { + super(name); + } + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject( + "src/etc/testcases/taskdefs/optional/script_reference.xml"); + } + + public void testScript() { + executeTarget("script"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java new file mode 100644 index 000000000..b754058b0 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Tests the examples of the <script> task docs. + * + * @since Ant 1.5.2 + */ +public class RhinoScriptTest extends BuildFileTest { + + public RhinoScriptTest(String name) { + super(name); + } + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject("src/etc/testcases/taskdefs/optional/script.xml"); + } + + public void testExample1() { + executeTarget("example1"); + int index = getLog().indexOf("1"); + assertTrue(index > -1); + index = getLog().indexOf("4", index); + assertTrue(index > -1); + index = getLog().indexOf("9", index); + assertTrue(index > -1); + index = getLog().indexOf("16", index); + assertTrue(index > -1); + index = getLog().indexOf("25", index); + assertTrue(index > -1); + index = getLog().indexOf("36", index); + assertTrue(index > -1); + index = getLog().indexOf("49", index); + assertTrue(index > -1); + index = getLog().indexOf("64", index); + assertTrue(index > -1); + index = getLog().indexOf("81", index); + assertTrue(index > -1); + index = getLog().indexOf("100", index); + assertTrue(index > -1); + } + + public void testExample2() { + executeTarget("example2"); + assertTrue(getLog().indexOf("In sub1") > -1); + assertTrue(getLog().indexOf("In sub2") > -1); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RpmTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RpmTest.java new file mode 100644 index 000000000..aca68d2eb --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RpmTest.java @@ -0,0 +1,66 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.Execute; +import org.apache.tools.ant.taskdefs.ExecuteStreamHandler; +import org.apache.tools.ant.types.Commandline; +import junit.framework.TestCase; + +public class RpmTest extends TestCase { + + public void testShouldThrowExceptionWhenRpmFails() throws Exception { + Rpm rpm = new MyRpm(); + rpm.setProject(new org.apache.tools.ant.Project()); + rpm.setFailOnError(true); + // execute + try { + rpm.execute(); + fail("should have thrown a build exception"); + } catch (BuildException ex) { + assertTrue(ex.getMessage() + .indexOf("' failed with exit code 2") != -1); + } + } + + public void testShouldNotThrowExceptionWhenRpmFails() throws Exception { + Rpm rpm = new MyRpm(); + rpm.execute(); + } + + // override some of the code so we can test the handling of the + // return code only. + public static class MyRpm extends Rpm { + protected Execute getExecute(Commandline toExecute, + ExecuteStreamHandler streamhandler) { + return new Execute() { + public int execute() { + // 2 is != 0 and even, so it is considered + // failure on any platform currently supported + // by Execute#isFailure. + return 2; + } + }; + } + + public void log(String msg, int msgLevel) { + } + } + +} \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/SchemaValidateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/SchemaValidateTest.java new file mode 100644 index 000000000..3793e2fdc --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/SchemaValidateTest.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Test schema validation + */ + +public class SchemaValidateTest extends BuildFileTest { + + /** + * where tasks run + */ + private final static String TASKDEFS_DIR = + "src/etc/testcases/taskdefs/optional/"; + + /** + * Constructor + * + * @param name testname + */ + public SchemaValidateTest(String name) { + super(name); + } + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject(TASKDEFS_DIR + "schemavalidate.xml"); + } + + /** + * test with no namespace + */ + public void testNoNamespace() throws Exception { + executeTarget("testNoNamespace"); + } + + /** + * add namespace awareness. + */ + public void testNSMapping() throws Exception { + executeTarget("testNSMapping"); + } + + public void testNoEmptySchemaNamespace() throws Exception { + expectBuildExceptionContaining("testNoEmptySchemaNamespace", + "empty namespace URI",SchemaValidate.SchemaLocation.ERROR_NO_URI); + } + + public void testNoEmptySchemaLocation() throws Exception { + expectBuildExceptionContaining("testNoEmptySchemaLocation", + "empty schema location", + SchemaValidate.SchemaLocation.ERROR_NO_LOCATION); + } + + public void testNoFile() throws Exception { + expectBuildExceptionContaining("testNoFile", + "no file at file attribute", + SchemaValidate.SchemaLocation.ERROR_NO_FILE); + } + + public void testNoDoubleSchemaLocation() throws Exception { + expectBuildExceptionContaining("testNoDoubleSchemaLocation", + "two locations for schemas", + SchemaValidate.SchemaLocation.ERROR_TWO_LOCATIONS); + } + public void testNoDuplicateSchema() throws Exception { + expectBuildExceptionContaining("testNoDuplicateSchema", + "duplicate schemas with different values", + SchemaValidate.ERROR_DUPLICATE_SCHEMA); + } + + public void testEqualsSchemasOK() throws Exception { + executeTarget("testEqualsSchemasOK"); + } + + public void testFileset() throws Exception { + executeTarget("testFileset"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/TraXLiaisonTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/TraXLiaisonTest.java new file mode 100644 index 000000000..55427ab5e --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/TraXLiaisonTest.java @@ -0,0 +1,100 @@ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.taskdefs.XSLTLiaison; +import org.apache.tools.ant.taskdefs.XSLTLogger; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.util.JAXPUtils; + +import java.io.File; + +import junit.framework.AssertionFailedError; + +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/** + * TraX XSLTLiaison testcase + */ +public class TraXLiaisonTest extends AbstractXSLTLiaisonTest + implements XSLTLogger { + + public TraXLiaisonTest(String name){ + super(name); + } + + public void tearDown() { + File f = new File("xalan2-redirect-out.tmp"); + if (f.exists()) { + f.delete(); + } + } + + public XSLTLiaison createLiaison() throws Exception { + TraXLiaison l = new TraXLiaison(); + l.setLogger(this); + return l; + } + + public void testXalan2Redirect() throws Exception { + File xsl = getFile("/taskdefs/optional/xalan-redirect-in.xsl"); + liaison.setStylesheet(xsl); + File out = new File("xalan2-redirect-out-dummy.tmp"); + File in = getFile("/taskdefs/optional/xsltliaison-in.xsl"); + try { + liaison.addParam("xalan-version", "2"); + liaison.transform(in, out); + } finally { + out.delete(); + } + } + + public void testMultipleTransform() throws Exception { + File xsl = getFile("/taskdefs/optional/xsltliaison-in.xsl"); + liaison.setStylesheet(xsl); + liaison.addParam("param", "value"); + File in = getFile("/taskdefs/optional/xsltliaison-in.xml"); + // test for 10 consecutives transform + for (int i = 0; i < 50; i++){ + File out = new File("xsltliaison" + i + ".tmp"); + try { + liaison.transform(in, out); + } catch (Exception e){ + throw new BuildException("failed in transform " + i, e); + } finally { + out.delete(); + } + } + } + + public void testSystemId(){ + File file = null; + if ( File.separatorChar == '\\' ){ + file = new File("d:\\jdk"); + } else { + file = new File("/user/local/bin"); + } + String systemid = JAXPUtils.getSystemId(file); + assertTrue("SystemIDs should start by file:/", systemid.startsWith("file:/")); + assertTrue("SystemIDs should not start with file:////", !systemid.startsWith("file:////")); + } + + public void log(String message) { + throw new AssertionFailedError("Liaison sent message: "+message); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/WsdlToDotnetTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/WsdlToDotnetTest.java new file mode 100644 index 000000000..9d3d4ea7f --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/WsdlToDotnetTest.java @@ -0,0 +1,201 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.taskdefs.optional.dotnet.WsdlToDotnet; + +/** + * Tests the WsdlToDotnet task. + * + * @since Ant 1.5 + */ +public class WsdlToDotnetTest extends BuildFileTest { + + /** + * dir for taskdefs + */ + private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/"; + + /** + * message from exec + */ + private static final String WSDL_FAILED = "WSDL returned:"; + + + /** + * Constructor + * + * @param name testname + */ + public WsdlToDotnetTest(String name) { + super(name); + } + + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject(TASKDEFS_DIR + "WsdlToDotnet.xml"); + } + + + /** + * The teardown method for JUnit + */ + public void tearDown() { + executeTarget("teardown"); + } + + + + /** + * A unit test for JUnit + */ + public void testNoParams() throws Exception { + expectBuildExceptionContaining("testNoParams", + "expected failure", + WsdlToDotnet.ERROR_NO_DEST_FILE); + } + + /** + * A unit test for JUnit + */ + public void testNoSrc() throws Exception { + expectBuildExceptionContaining("testNoSrc", + "expected failure", + WsdlToDotnet.Schema.ERROR_NONE_DECLARED); + } + + /** + * A unit test for JUnit + */ + public void testDestIsDir() throws Exception { + expectBuildExceptionContaining("testDestIsDir", + "expected failure", + WsdlToDotnet.ERROR_DEST_FILE_IS_DIR); + } + + /** + * A unit test for JUnit + */ + public void testBothSrc() throws Exception { + expectBuildExceptionContaining("testBothSrc", + "expected failure", + WsdlToDotnet.Schema.ERROR_BOTH_DECLARED); + } + /** + * A unit test for JUnit + */ + public void testSrcIsDir() throws Exception { + expectBuildExceptionContaining("testSrcIsDir", + "expected failure", + WsdlToDotnet.Schema.ERROR_FILE_IS_DIR); + } + + /** + * A unit test for JUnit + */ + public void testSrcIsMissing() throws Exception { + expectBuildExceptionContaining("testSrcIsMissing", + "expected failure", + WsdlToDotnet.Schema.ERROR_FILE_NOT_FOUND); + } + + /** + * A unit test for JUnit + */ + public void testLocalWsdl() throws Exception { + executeTarget("testLocalWsdl"); + } + /** + * A unit test for JUnit + */ + public void testLocalWsdlServer() throws Exception { + executeTarget("testLocalWsdlServer"); + } + /** + * A unit test for JUnit + */ + public void testInvalidExtraOps() throws Exception { + expectBuildExceptionContaining("testInvalidExtraOps", + "expected failure", + WSDL_FAILED); + } + + /** + * A unit test for JUnit + */ + public void testLocalWsdlVB() throws Exception { + executeTarget("testLocalWsdlVB"); + } + /** + * A unit test for JUnit + */ + public void testLocalWsdlServerVB() throws Exception { + executeTarget("testLocalWsdlServerVB"); + } + /** + * A unit test for JUnit + */ + public void testInvalidExtraOpsVB() throws Exception { + expectBuildExceptionContaining("testInvalidExtraOpsVB", + "expected failure", + WSDL_FAILED); + } + + /** + * as if parseable errors were not ignored, mono and WSE1.0 would + * crash and burn. So here we verify the property exists, + * and that it is not passed to the app when false + */ + public void testParseableErrorsIgnoredWhenFalse() throws Exception { + executeTarget("testLocalWsdl"); + } + + /** + * A unit test for JUnit + */ + public void testSchemaFileMustExist() throws Exception { + expectBuildExceptionContaining("testSchemaFileMustExist", + "expected failure", + WsdlToDotnet.Schema.ERROR_FILE_NOT_FOUND); + } + + /** + * A unit test for JUnit + */ + public void testSchemaFileMustHaveOneOptionOnly() throws Exception { + expectBuildExceptionContaining("testSchemaFileMustHaveOneOptionOnly", + "expected failure", + WsdlToDotnet.Schema.ERROR_BOTH_DECLARED); + } + + /** + * A unit test for JUnit + */ + public void testSchemaMustBeSet() throws Exception { + expectBuildExceptionContaining("testSchemaMustBeSet", + "expected failure", + WsdlToDotnet.Schema.ERROR_NONE_DECLARED); + } + + +} + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateCatalogTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateCatalogTest.java new file mode 100644 index 000000000..64db8e742 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateCatalogTest.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Tests the XMLValidate optional task with nested external catalogs. + * + * @see XmlValidateTest + * @since Ant 1.6 + */ +public class XmlValidateCatalogTest extends BuildFileTest { + + /** + * where tasks run + */ + private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/"; + + + /** + * Constructor + * + * @param name testname + */ + public XmlValidateCatalogTest(String name) { + super(name); + } + + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject(TASKDEFS_DIR + "xmlvalidate.xml"); + } + + + /** + * The teardown method for JUnit + */ + public void tearDown() { + + } + + /** + * catalogfiles fileset should be ignored + * if resolver.jar is not present, but will + * be used if it is. either way, test should + * work b/c we have a nested dtd with the same + * entity + */ + public void testXmlCatalogFiles() { + executeTarget("xmlcatalogfiles"); + } + + /** + * Test nested catalogpath. + * It should be ignored if resolver.jar is not + * present, but will be used if it is. either + * way, test should work b/c we have a nested + * dtd with the same entity + */ + public void testXmlCatalogPath() { + executeTarget("xmlcatalogpath"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java new file mode 100644 index 000000000..27be8a415 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java @@ -0,0 +1,189 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.BuildFileTest; + +/** + * Tests the XMLValidate optional task, by running targets in the test script + * src/etc/testcases/taskdefs/optional/xmlvalidate.xml + *

+ * + * @see XmlValidateCatalogTest + * @since Ant 1.5 + */ +public class XmlValidateTest extends BuildFileTest { + + /** + * where tasks run + */ + private final static String TASKDEFS_DIR = + "src/etc/testcases/taskdefs/optional/"; + + /** + * Constructor + * + * @param name testname + */ + public XmlValidateTest(String name) { + super(name); + } + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject(TASKDEFS_DIR + "xmlvalidate.xml"); + } + + /** + * The teardown method for JUnit + */ + public void tearDown() {} + + /** + * Basic inline 'dtd' element test. + */ + public void testValidate() throws Exception { + executeTarget("testValidate"); + } + + /** + * Test indirect validation. + */ + public void testDeepValidate() throws Exception { + executeTarget("testDeepValidate"); + } + + /** + * + */ + public void testXmlCatalog() { + executeTarget("xmlcatalog"); + } + + /** + * + */ + public void testXmlCatalogViaRefid() { + executeTarget("xmlcatalogViaRefid"); + } + + /** + * Test that the nested dtd element is used when resolver.jar is not + * present. This test should pass either way. + */ + public void testXmlCatalogFiles() { + executeTarget("xmlcatalogfiles-override"); + } + + /** + * Test nested catalogpath. + * Test that the nested dtd element is used when resolver.jar is not + * present. This test should pass either way. + */ + public void testXmlCatalogPath() { + executeTarget("xmlcatalogpath-override"); + } + + /** + * Test nested xmlcatalog definitions + */ + public void testXmlCatalogNested() { + executeTarget("xmlcatalognested"); + } + + /** + * Test xml schema validation + */ + public void testXmlSchemaGood() throws BuildException { + try { + executeTarget("testSchemaGood"); + } catch (BuildException e) { + if (e + .getMessage() + .endsWith(" doesn't recognize feature http://apache.org/xml/features/validation/schema") + || e.getMessage().endsWith( + " doesn't support feature http://apache.org/xml/features/validation/schema")) { + System.err.println(" skipped, parser doesn't support schema"); + } else { + throw e; + } + } + } + /** + * Test xml schema validation + */ + public void testXmlSchemaBad() { + try { + executeTarget("testSchemaBad"); + fail("Should throw BuildException because 'Bad Schema Validation'"); + + expectBuildExceptionContaining( + "testSchemaBad", + "Bad Schema Validation", + "not a valid XML document"); + } catch (BuildException e) { + if (e + .getMessage() + .endsWith(" doesn't recognize feature http://apache.org/xml/features/validation/schema") + || e.getMessage().endsWith( + " doesn't support feature http://apache.org/xml/features/validation/schema")) { + System.err.println(" skipped, parser doesn't support schema"); + } else { + assertTrue( + e.getMessage().indexOf("not a valid XML document") > -1); + } + } + } + + /** + * iso-2022-jp.xml is valid but wouldn't get recognized on systems + * with a different native encoding. + * + * Bug 11279 + */ + public void testIso2022Jp() { + executeTarget("testIso2022Jp"); + } + + /** + * utf-8.xml is invalid as it contains non-UTF-8 characters, but + * would pass on systems with a native iso-8859-1 (or similar) + * encoding. + * + * Bug 11279 + */ + public void testUtf8() { + expectBuildException("testUtf8", "invalid characters in file"); + } + + // Tests property element, using XML schema properties as an example. + + public void testPropertySchemaForValidXML() { + executeTarget("testProperty.validXML"); + } + + public void testPropertySchemaForInvalidXML() { + expectBuildException( + "testProperty.invalidXML", + "XML file does not satisfy schema."); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java new file mode 100644 index 000000000..c28551dfd --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Tests the {@link XSLTProcess} task. + * XXX merge with {@link StyleTest}? + * @since Ant 1.5 + */ +public class XsltTest extends BuildFileTest { + + /** + * where tasks run + */ + private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/"; + + + /** + * Constructor + * + * @param name testname + */ + public XsltTest(String name) { + super(name); + } + + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject(TASKDEFS_DIR + "xslt.xml"); + } + + + /** + * The teardown method for JUnit + */ + public void tearDown() { + executeTarget("teardown"); + } + + + + /** + * A unit test for JUnit + */ + public void testCatchNoDtd() throws Exception { + expectBuildExceptionContaining("testCatchNoDtd", + "expected failure", + "Fatal error during transformation"); + } + + /** + * A unit test for JUnit + */ + public void testCatalog() throws Exception { + executeTarget("testCatalog"); + } + + public void testOutputProperty() throws Exception { + executeTarget("testOutputProperty"); + } + + public void testFactory() throws Exception { + executeTarget("testFactory"); + } + + public void testAttribute() throws Exception { + executeTarget("testAttribute"); + } + public void testXMLWithEntitiesInNonAsciiPath() throws Exception { + executeTarget("testXMLWithEntitiesInNonAsciiPath"); + } + + /** + * check that the system id gets set properly on stylesheets. + * @throws Exception if something goes wrong. + */ + public void testStyleSheetWithInclude() throws Exception { + executeTarget("testStyleSheetWithInclude"); + if (getLog().indexOf("java.io.FileNotFoundException") != -1) { + fail("xsl:include was not found"); + } + } +} + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/depend/DependTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/depend/DependTest.java new file mode 100644 index 000000000..82f301e8b --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/depend/DependTest.java @@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.depend; + +import java.util.Hashtable; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.DirectoryScanner; +import org.apache.tools.ant.types.FileSet; + +/** + * Testcase for the Depend optional task. + * + */ +public class DependTest extends BuildFileTest { + public static final String RESULT_FILESET = "result"; + + public static final String TEST_BUILD_FILE + = "src/etc/testcases/taskdefs/optional/depend/depend.xml"; + + public DependTest(String name) { + super(name); + } + + public void setUp() { + configureProject(TEST_BUILD_FILE); + } + + public void tearDown() { + executeTarget("clean"); + } + + /** + * Test direct dependency removal + */ + public void testDirect() { + executeTarget("testdirect"); + Hashtable files = getResultFiles(); + assertEquals("Depend did not leave correct number of files", 3, + files.size()); + assertTrue("Result did not contain A.class", + files.containsKey("A.class")); + assertTrue("Result did not contain D.class", + files.containsKey("D.class")); + } + + /** + * Test dependency traversal (closure) + */ + public void testClosure() { + executeTarget("testclosure"); + Hashtable files = getResultFiles(); + assertTrue("Depend did not leave correct number of files", + files.size() <= 2); + assertTrue("Result did not contain D.class", + files.containsKey("D.class")); + } + + /** + * Test that inner class dependencies trigger deletion of the outer class + */ + public void testInner() { + executeTarget("testinner"); + assertEquals("Depend did not leave correct number of files", 0, + getResultFiles().size()); + } + + /** + * Test that multi-leve inner class dependencies trigger deletion of + * the outer class + */ + public void testInnerInner() { + executeTarget("testinnerinner"); + assertEquals("Depend did not leave correct number of files", 0, + getResultFiles().size()); + } + + /** + * Test that an exception is thrown when there is no source + */ + public void testNoSource() { + expectBuildExceptionContaining("testnosource", + "No source specified", "srcdir attribute must be set"); + } + + /** + * Test that an exception is thrown when the source attribute is empty + */ + public void testEmptySource() { + expectBuildExceptionContaining("testemptysource", + "No source specified", "srcdir attribute must be non-empty"); + } + + /** + * Read the result fileset into a Hashtable + * + * @return a Hashtable containing the names of the files in the result + * fileset + */ + private Hashtable getResultFiles() { + FileSet resultFileSet = (FileSet) project.getReference(RESULT_FILESET); + DirectoryScanner scanner = resultFileSet.getDirectoryScanner(project); + String[] scannedFiles = scanner.getIncludedFiles(); + Hashtable files = new Hashtable(); + for (int i = 0; i < scannedFiles.length; ++i) { + files.put(scannedFiles[i], scannedFiles[i]); + } + return files; + } + + + /** + * Test mutual dependency between inner and outer do not cause both to be + * deleted + */ + public void testInnerClosure() { + executeTarget("testinnerclosure"); + assertEquals("Depend did not leave correct number of files", 4, + getResultFiles().size()); + } + + /** + * Test the operation of the cache + */ + public void testCache() { + executeTarget("testcache"); + } + + /** + * Test the detection and warning of non public classes + */ + public void testNonPublic() { + executeTarget("testnonpublic"); + String log = getLog(); + assertTrue("Expected warning about APrivate", + log.indexOf("The class APrivate in file") != -1); + assertTrue("but has not been deleted because its source file " + + "could not be determined", + log.indexOf("The class APrivate in file") != -1); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/i18n/TranslateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/i18n/TranslateTest.java new file mode 100644 index 000000000..64b588580 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/i18n/TranslateTest.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.i18n; + +import org.apache.tools.ant.BuildFileTest; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +/** + * Tests the Translate task. + * + * @since Ant 1.6 + */ +public class TranslateTest extends BuildFileTest { + static private final int BUF_SIZE = 32768; + + private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/i18n/translate"; + + public TranslateTest(String name) { + super(name); + } + + + public void setUp() { + configureProject(TASKDEFS_DIR + "/translate.xml"); + } + + public void tearDown() { + executeTarget("cleanup"); + } + + public void test1() { + executeTarget("test1"); + assertTrue("translation of "+ TASKDEFS_DIR + "/input/template.txt",compareFiles(TASKDEFS_DIR+"/expected/de/template.txt",TASKDEFS_DIR+"/output/de/template.txt")); + } + private boolean compareFiles(String name1, String name2) { + File file1 = new File(System.getProperty("root"), name1); + File file2 = new File(System.getProperty("root"), name2); + + try { + if (!file1.exists() || !file2.exists()) { + System.out.println("One or both files do not exist:" + name1 + ", " + name2); + return false; + } + + if (file1.length() != file2.length()) { + System.out.println("File size mismatch:" + name1 + "(" + file1.length() + "), " + + name2 + "(" + file2.length() + ")"); + return false; + } + + // byte - byte compare + byte[] buffer1 = new byte[BUF_SIZE]; + byte[] buffer2 = new byte[BUF_SIZE]; + + FileInputStream fis1 = new FileInputStream(file1); + FileInputStream fis2 = new FileInputStream(file2); + int index = 0; + int read = 0; + while ((read = fis1.read(buffer1)) != -1) { + fis2.read(buffer2); + for (int i = 0; i < read; ++i, ++index) { + if (buffer1[i] != buffer2[i]) { + System.out.println("Bytes mismatch:" + name1 + ", " + name2 + + " at byte " + index); + return false; + } + } + } + return true; + } + catch (IOException e) { + System.out.println("IOException comparing files: " + name1 + ", " + name2); + return false; + } + } +} + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java new file mode 100644 index 000000000..25b42457d --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java @@ -0,0 +1,119 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.image; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.util.FileUtils; + +import java.io.File; + + +/** + * Tests the Image task. + * + * @since Ant 1.5 + */ +public class ImageTest extends BuildFileTest { + + private final static String TASKDEFS_DIR = + "src/etc/testcases/taskdefs/optional/image/"; + private final static String LARGEIMAGE = "largeimage.jpg"; + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + + public ImageTest(String name) { + super(name); + } + + + public void setUp() { + configureProject(TASKDEFS_DIR + "image.xml"); + } + + + public void tearDown() { + executeTarget("cleanup"); + } + + public void testEchoToLog() { + expectLogContaining("testEchoToLog", "Processing File"); + } + + public void testSimpleScale(){ + expectLogContaining("testSimpleScale", "Processing File"); + File f = createRelativeFile("/dest/" + LARGEIMAGE); + assertTrue( + "Did not create "+f.getAbsolutePath(), + f.exists()); + + } + + public void testOverwriteTrue() { + expectLogContaining("testSimpleScale", "Processing File"); + File f = createRelativeFile("/dest/" + LARGEIMAGE); + long lastModified = f.lastModified(); + try { + Thread.sleep(FILE_UTILS + .getFileTimestampGranularity()); + } + catch (InterruptedException e) {} + expectLogContaining("testOverwriteTrue", "Processing File"); + f = createRelativeFile("/dest/" + LARGEIMAGE); + long overwrittenLastModified = f.lastModified(); + assertTrue("File was not overwritten.", + lastModified < overwrittenLastModified); + } + + public void testOverwriteFalse() { + expectLogContaining("testSimpleScale", "Processing File"); + File f = createRelativeFile("/dest/" + LARGEIMAGE); + long lastModified = f.lastModified(); + expectLogContaining("testOverwriteFalse", "Processing File"); + f = createRelativeFile("/dest/" + LARGEIMAGE); + long overwrittenLastModified = f.lastModified(); + assertTrue("File was overwritten.", + lastModified == overwrittenLastModified); + } + + + public void off_testFailOnError() { + try { + expectLogContaining("testFailOnError", + "Unable to process image stream"); + } + catch (RuntimeException re){ + assertTrue("Run time exception should say " + + "'Unable to process image stream'. :" + + re.toString(), + re.toString() + .indexOf("Unable to process image stream") > -1); + } + } + + + + protected File createRelativeFile(String filename) { + if (filename.equals(".")) { + return getProjectDir(); + } + // else + return new File(getProjectDir(), filename); + } +} + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTest.java new file mode 100644 index 000000000..4e91d9c60 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTest.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.jdepend; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Testcase for the JDepend optional task. + * + */ +public class JDependTest extends BuildFileTest { + public static final String RESULT_FILESET = "result"; + + public JDependTest(String name) { + super(name); + } + + public void setUp() { + configureProject( + "src/etc/testcases/taskdefs/optional/jdepend/jdepend.xml"); + } + + /** + * Test simple + */ + public void testSimple() { + expectOutputContaining( + "simple", "Package: org.apache.tools.ant.util.facade"); + } + + /** + * Test xml + */ + public void testXml() { + expectOutputContaining( + "xml", ""); + } + + /** + * Test fork + * - forked output goes to log + */ + public void testFork() { + expectLogContaining( + "fork", "Package: org.apache.tools.ant.util.facade"); + } + + /** + * Test fork xml + */ + public void testForkXml() { + expectLogContaining( + "fork-xml", ""); + } + + /** + * Test timeout + */ + public void testTimeout() { + expectLogContaining( + "fork-timeout", "JDepend FAILED - Timed out"); + } + + + /** + * Test timeout without timing out + */ + public void testTimeoutNot() { + expectLogContaining( + "fork-timeout-not", "Package: org.apache.tools.ant.util.facade"); + } + + /** + * Assert that the given message has been outputted + */ + protected void expectOutputContaining(String target, String substring) { + executeTarget(target); + assertOutputContaining(substring); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitClassLoaderTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitClassLoaderTest.java new file mode 100644 index 000000000..36f5d6efd --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitClassLoaderTest.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import junit.framework.TestCase; + +/** + * Test to ensure that the classloader loading JUnit testcase + * is also the context classloader. + * + */ +public class JUnitClassLoaderTest extends TestCase { + + public JUnitClassLoaderTest(String s) { + super(s); + } + + public void testContextClassLoader(){ + ClassLoader context = Thread.currentThread().getContextClassLoader(); + ClassLoader caller = getClass().getClassLoader(); + assertSame(context, caller); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitReportTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitReportTest.java new file mode 100644 index 000000000..d19529369 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitReportTest.java @@ -0,0 +1,206 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.junit; + +import java.io.File; +import java.io.FileReader; +import java.io.InputStream; +import java.net.URL; +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.util.FileUtils; + +/** + * Small testcase for the junitreporttask. + * First test added to reproduce an fault, still a lot to improve + * + */ +public class JUnitReportTest extends BuildFileTest { + + public JUnitReportTest(String name){ + super(name); + } + + protected void setUp() { + configureProject("src/etc/testcases/taskdefs/optional/junitreport.xml"); + } + + protected void tearDown() { + executeTarget("clean"); + } + + /** + * Verifies that no empty junit-noframes.html is generated when frames + * output is selected via the default. + * Needs reports1 task from junitreport.xml. + */ + public void testNoFileJUnitNoFrames() { + executeTarget("reports1"); + if (new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/junit-noframes.html").exists()) + { + fail("No file junit-noframes.html expected"); + } + } + + public void assertIndexCreated() { + if (!new File(System.getProperty("root"), + "src/etc/testcases/taskdefs/optional/junitreport/test/html/index.html").exists()) { + fail("No file index file found"); + } + + } + + /** + * run a target, assert the index file is there, look for text in the log + * @param targetName target + * @param text optional text to look for + */ + private void expectReportWithText(String targetName, String text) { + executeTarget(targetName); + assertIndexCreated(); + if(text!=null) { + assertLogContaining(text); + } + } + + + public void testEmptyFile() throws Exception { + expectReportWithText("testEmptyFile", + XMLResultAggregator.WARNING_EMPTY_FILE); + } + + public void testIncompleteFile() throws Exception { + expectReportWithText("testIncompleteFile", + XMLResultAggregator.WARNING_IS_POSSIBLY_CORRUPTED); + } + public void testWrongElement() throws Exception { + expectReportWithText("testWrongElement", + XMLResultAggregator.WARNING_INVALID_ROOT_ELEMENT); + } + + // Bugzilla Report 34963 + public void testStackTraceLineBreaks() throws Exception { + expectReportWithText("testStackTraceLineBreaks", null); + FileReader r = null; + try { + r = new FileReader(new File(System.getProperty("root"), + "src/etc/testcases/taskdefs/optional/junitreport/test/html/sampleproject/coins/0_CoinTest.html")); + String report = FileUtils.readFully(r); + assertTrue("output must contain
", + report.indexOf("junit.framework.AssertionFailedError: DOEG
") + > -1); + } finally { + FileUtils.close(r); + } + } + + + // Bugzilla Report 38477 + public void testSpecialSignsInSrcPath() throws Exception { + executeTarget("testSpecialSignsInSrcPath"); + File reportFile = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/index.html"); + // tests one the file object + assertTrue("No index.html present. Not generated?", reportFile.exists() ); + assertTrue("Cant read the report file.", reportFile.canRead() ); + assertTrue("File shouldnt be empty.", reportFile.length() > 0 ); + // conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report + URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) ); + InputStream reportStream = reportUrl.openStream(); + assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0); + } + + public void testSpecialSignsInHtmlPath() throws Exception { + executeTarget("testSpecialSignsInHtmlPath"); + File reportFile = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html# $%\u00A7&-!report/index.html"); + // tests one the file object + assertTrue("No index.html present. Not generated?", reportFile.exists() ); + assertTrue("Cant read the report file.", reportFile.canRead() ); + assertTrue("File shouldnt be empty.", reportFile.length() > 0 ); + // conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report + URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) ); + InputStream reportStream = reportUrl.openStream(); + assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0); + } + + //Bugzilla Report 39708 + public void testWithStyleFromDir() throws Exception { + executeTarget("testWithStyleFromDir"); + File reportFile = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/index.html"); + // tests one the file object + assertTrue("No index.html present. Not generated?", reportFile.exists() ); + assertTrue("Cant read the report file.", reportFile.canRead() ); + assertTrue("File shouldnt be empty.", reportFile.length() > 0 ); + // conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report + URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) ); + InputStream reportStream = reportUrl.openStream(); + assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0); + } + + //Bugzilla Report 40021 + public void testNoFrames() throws Exception { + executeTarget("testNoFrames"); + File reportFile = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/junit-noframes.html"); + // tests one the file object + assertTrue("No junit-noframes.html present. Not generated?", reportFile.exists() ); + assertTrue("Cant read the report file.", reportFile.canRead() ); + assertTrue("File shouldnt be empty.", reportFile.length() > 0 ); + // conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report + URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) ); + InputStream reportStream = reportUrl.openStream(); + assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0); + } + //Bugzilla Report 39708 + public void testWithStyleFromDirAndXslImport() throws Exception { + executeTarget("testWithStyleFromDirAndXslImport"); + File reportFile = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/index.html"); + // tests one the file object + assertTrue("No index.html present. Not generated?", reportFile.exists() ); + assertTrue("Cant read the report file.", reportFile.canRead() ); + assertTrue("File shouldnt be empty.", reportFile.length() > 0 ); + // conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report + URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) ); + InputStream reportStream = reportUrl.openStream(); + assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0); + } + + public void testWithStyleFromClasspath() throws Exception { + executeTarget("testWithStyleFromClasspath"); + File reportFile = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/index.html"); + // tests one the file object + assertTrue("No index.html present. Not generated?", reportFile.exists() ); + assertTrue("Cant read the report file.", reportFile.canRead() ); + assertTrue("File shouldnt be empty.", reportFile.length() > 0 ); + // conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report + URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) ); + InputStream reportStream = reportUrl.openStream(); + assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0); + } + + public void testWithParams() throws Exception { + expectLogContaining("testWithParams", "key1=value1,key2=value2"); + File reportFile = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/index.html"); + // tests one the file object + assertTrue("No index.html present. Not generated?", reportFile.exists() ); + assertTrue("Cant read the report file.", reportFile.canRead() ); + assertTrue("File shouldnt be empty.", reportFile.length() > 0 ); + // conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report + URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) ); + InputStream reportStream = reportUrl.openStream(); + assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java new file mode 100644 index 000000000..bce4d3791 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import org.apache.tools.ant.BuildFileTest; +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class JUnitTaskTest extends BuildFileTest { + + /** + * Constructor for the JUnitTaskTest object + */ + public JUnitTaskTest(String name) { + super(name); + } + + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject("src/etc/testcases/taskdefs/optional/junit.xml"); + } + + + /** + * The teardown method for JUnit + */ + public void tearDown() { + executeTarget("cleanup"); + } + + public void testCrash() { + expectPropertySet("crash", "crashed"); + } + + public void testNoCrash() { + expectPropertyUnset("nocrash", "crashed"); + } + + public void testTimeout() { + expectPropertySet("timeout", "timeout"); + } + + public void testNoTimeout() { + expectPropertyUnset("notimeout", "timeout"); + } + + public void testNonForkedCapture() throws IOException { + executeTarget("capture"); + assertNoPrint(getLog(), "log"); + assertNoPrint(getFullLog(), "debug log"); + } + + public void testForkedCapture() throws IOException { + getProject().setProperty("fork", "true"); + testNonForkedCapture(); + // those would fail because of the way BuildFileTest captures output + assertNoPrint(getOutput(), "output"); + assertNoPrint(getError(), "error output"); + assertOutput(); + } + + public void testBatchTestForkOnceToDir() { + assertResultFilesExist("testBatchTestForkOnceToDir", ".xml"); + } + + /** Bugzilla Report 32973 */ + public void testBatchTestForkOnceExtension() { + assertResultFilesExist("testBatchTestForkOnceExtension", ".foo"); + } + + public void testBatchTestForkOnceCustomFormatter() { + assertResultFilesExist("testBatchTestForkOnceCustomFormatter", "foo"); + } + + private void assertResultFilesExist(String target, String extension) { + executeTarget(target); + assertResultFileExists("JUnitClassLoader", extension); + assertResultFileExists("JUnitTestRunner", extension); + assertResultFileExists("JUnitVersionHelper", extension); + } + + private void assertResultFileExists(String classNameFragment, String ext) { + assertTrue("result for " + classNameFragment + "Test" + ext + " exists", + getProject().resolveFile("out/TEST-org.apache.tools.ant." + + "taskdefs.optional.junit." + + classNameFragment + "Test" + ext) + .exists()); + } + + private void assertNoPrint(String result, String where) { + assertTrue(where + " '" + result + "' must not contain print statement", + result.indexOf("print to System.") == -1); + } + + private void assertOutput() throws IOException { + FileReader inner = new FileReader(getProject() + .resolveFile("testlog.txt")); + BufferedReader reader = new BufferedReader(inner); + try { + String line = reader.readLine(); + assertEquals("Testsuite: org.apache.tools.ant.taskdefs.optional.junit.Printer", + line); + line = reader.readLine(); + assertNotNull(line); + assertTrue(line.startsWith("Tests run: 1, Failures: 0, Errors: 0, Time elapsed:")); + line = reader.readLine(); + assertEquals("------------- Standard Output ---------------", + line); + assertPrint(reader.readLine(), "static", "out"); + assertPrint(reader.readLine(), "constructor", "out"); + assertPrint(reader.readLine(), "method", "out"); + line = reader.readLine(); + assertEquals("------------- ---------------- ---------------", + line); + line = reader.readLine(); + assertEquals("------------- Standard Error -----------------", + line); + assertPrint(reader.readLine(), "static", "err"); + assertPrint(reader.readLine(), "constructor", "err"); + assertPrint(reader.readLine(), "method", "err"); + line = reader.readLine(); + assertEquals("------------- ---------------- ---------------", + line); + line = reader.readLine(); + assertEquals("", line); + line = reader.readLine(); + assertNotNull(line); + assertTrue(line.startsWith("Testcase: testNoCrash took ")); + } finally { + inner.close(); + } + } + + private void assertPrint(String line, String from, String to) { + String search = from + " print to System." + to; + assertEquals(search, line); + } + +} + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestListenerTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestListenerTest.java new file mode 100644 index 000000000..ac36af226 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestListenerTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.junit; + +import org.apache.tools.ant.BuildFileTest; + +public class JUnitTestListenerTest extends BuildFileTest { + + // The captureToSummary test writes to stdout and stderr, good for + // verifying that the TestListener support doesn't break anything. + private static final String PASS_TEST_TARGET = "captureToSummary"; + + // testNoCrash is the test invoked by the captureToSummary's junit task + private static final String PASS_TEST = "testNoCrash"; + + public JUnitTestListenerTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/taskdefs/optional/junit.xml"); + } + + public void testFullLogOutput() { + executeTarget(PASS_TEST_TARGET); + assertTrue("expecting full log to have BuildListener events", + hasBuildListenerEvents(getFullLog())); + } + + public void testNoLogOutput() { + executeTarget(PASS_TEST_TARGET); + assertFalse("expecting log to not have BuildListener events", + hasBuildListenerEvents(getLog())); + } + + public void testTestCountFired() { + executeTarget(PASS_TEST_TARGET); + assertTrue("expecting test count message", + hasEventMessage(JUnitTask.TESTLISTENER_PREFIX + + "tests to run: ")); + } + + public void testStartTestFired() { + executeTarget(PASS_TEST_TARGET); + assertTrue("expecting test started message", + hasEventMessage(JUnitTask.TESTLISTENER_PREFIX + + "startTest(" + PASS_TEST + ")")); + } + + public void testEndTestFired() { + executeTarget(PASS_TEST_TARGET); + assertTrue("expecting test ended message", + hasEventMessage(JUnitTask.TESTLISTENER_PREFIX + + "endTest(" + PASS_TEST + ")")); + } + + private boolean hasBuildListenerEvents(String log) { + return log.indexOf(JUnitTask.TESTLISTENER_PREFIX) >= 0; + } + + private boolean hasEventMessage(String eventPrefix) { + return getFullLog().indexOf(eventPrefix) >= 0; + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java new file mode 100644 index 000000000..a06bdb8cd --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java @@ -0,0 +1,153 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import java.io.*; +import junit.framework.*; +import org.apache.tools.ant.BuildException; + +/** + * Small testcase for the runner, tests are very very very basics. + * They must be enhanced with time. + * + */ +public class JUnitTestRunnerTest extends TestCase { + + // mandatory constructor + public JUnitTestRunnerTest(String name){ + super(name); + } + + // check that having no suite generates no errors + public void testNoSuite(){ + TestRunner runner = createRunner(NoSuiteTestCase.class); + runner.run(); + assertEquals(runner.getFormatter().getError(), JUnitTestRunner.SUCCESS, runner.getRetCode()); + } + + // check that a suite generates no errors + public void testSuite(){ + TestRunner runner = createRunner(SuiteTestCase.class); + runner.run(); + assertEquals(runner.getFormatter().getError(), JUnitTestRunner.SUCCESS, runner.getRetCode()); + } + + // check that an invalid suite generates an error. + public void testInvalidSuite(){ + TestRunner runner = createRunner(InvalidSuiteTestCase.class); + runner.run(); + String error = runner.getFormatter().getError(); + assertEquals(error, JUnitTestRunner.ERRORS, runner.getRetCode()); + assertTrue(error, error.indexOf("thrown on purpose") != -1); + } + + // check that something which is not a testcase generates no errors + // at first even though this is incorrect. + public void testNoTestCase(){ + TestRunner runner = createRunner(NoTestCase.class); + runner.run(); + assertEquals(runner.getFormatter().getError(), JUnitTestRunner.FAILURES, runner.getRetCode()); + } + + // check that an exception in the constructor is noticed + public void testInvalidTestCase(){ + TestRunner runner = createRunner(InvalidTestCase.class); + runner.run(); + String error = runner.getFormatter().getError(); + assertEquals(error, JUnitTestRunner.FAILURES, runner.getRetCode()); + //@fixme as of now does not report the original stacktrace. + //assertTrue(error, error.indexOf("thrown on purpose") != -1); + } + + protected TestRunner createRunner(Class clazz){ + return new TestRunner(new JUnitTest(clazz.getName()), true, true, true); + } + + // the test runner that wrap the dummy formatter that interests us + private final static class TestRunner extends JUnitTestRunner { + private ResultFormatter formatter = new ResultFormatter(); + TestRunner(JUnitTest test, boolean haltonerror, boolean filtertrace, boolean haltonfailure){ + super(test, haltonerror, filtertrace, haltonfailure, TestRunner.class.getClassLoader()); + // use the classloader that loaded this class otherwise + // it will not be able to run inner classes if this test + // is ran in non-forked mode. + addFormatter(formatter); + } + ResultFormatter getFormatter(){ + return formatter; + } + } + + // dummy formatter just to catch the error + private final static class ResultFormatter implements JUnitResultFormatter { + private Throwable error; + public void setSystemOutput(String output){} + public void setSystemError(String output){} + public void startTestSuite(JUnitTest suite) throws BuildException{} + public void endTestSuite(JUnitTest suite) throws BuildException{} + public void setOutput(java.io.OutputStream out){} + public void startTest(Test t) {} + public void endTest(Test test) {} + public void addFailure(Test test, Throwable t) { } + public void addFailure(Test test, AssertionFailedError t) { } + public void addError(Test test, Throwable t) { + error = t; + } + String getError(){ + if (error == null){ + return ""; + } + StringWriter sw = new StringWriter(); + error.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + } + + public static class NoTestCase { + } + + public static class InvalidTestCase extends TestCase { + public InvalidTestCase(String name){ + super(name); + throw new NullPointerException("thrown on purpose"); + } + } + + public static class NoSuiteTestCase extends TestCase { + public NoSuiteTestCase(String name){ super(name); } + public void testA(){} + } + + public static class SuiteTestCase extends NoSuiteTestCase { + public SuiteTestCase(String name){ super(name); } + public static Test suite(){ + return new TestSuite(SuiteTestCase.class); + } + } + + public static class InvalidSuiteTestCase extends NoSuiteTestCase { + public InvalidSuiteTestCase(String name){ super(name); } + public static Test suite(){ + throw new NullPointerException("thrown on purpose"); + } + } + public static void main(String[] args){ + junit.textui.TestRunner.run(JUnitTestRunnerTest.class); + } +} + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelperTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelperTest.java new file mode 100644 index 000000000..a23b840b7 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelperTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestResult; + +/** + */ +public class JUnitVersionHelperTest extends TestCase { + + public JUnitVersionHelperTest(String name) { + super(name); + } + + public void testMyOwnName() { + assertEquals("testMyOwnName", + JUnitVersionHelper.getTestCaseName(this)); + } + + public void testNonTestCaseName() { + assertEquals("I'm a foo", + JUnitVersionHelper.getTestCaseName(new Foo1())); + } + + public void testNoStringReturn() { + assertEquals("unknown", + JUnitVersionHelper.getTestCaseName(new Foo2())); + } + + public void testNoGetName() { + assertEquals("unknown", + JUnitVersionHelper.getTestCaseName(new Foo3())); + } + + public void testNameNotGetName() { + assertEquals("I'm a foo, too", + JUnitVersionHelper.getTestCaseName(new Foo4())); + } + + public void testNull() { + assertEquals("unknown", JUnitVersionHelper.getTestCaseName(null)); + } + + public void testTestCaseSubClass() { + assertEquals("overridden getName", + JUnitVersionHelper.getTestCaseName(new Foo5())); + } + + public static class Foo implements Test { + public int countTestCases() {return 0;} + public void run(TestResult result) {} + } + + public static class Foo1 extends Foo { + public String getName() {return "I'm a foo";} + } + + public static class Foo2 extends Foo { + public int getName() {return 1;} + } + + public static class Foo3 extends Foo { + } + + public static class Foo4 extends Foo { + public String name() {return "I'm a foo, too";} + } + + public static class Foo5 extends TestCase { + public String getName() {return "overridden getName";} + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/NoVmCrash.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/NoVmCrash.java new file mode 100644 index 000000000..601eab2b9 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/NoVmCrash.java @@ -0,0 +1,33 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import junit.framework.TestCase; + +/** + */ +public class NoVmCrash extends TestCase { + + public NoVmCrash(String name) { + super(name); + } + + public void testNoCrash() { + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Printer.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Printer.java new file mode 100644 index 000000000..c0acc1cf7 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Printer.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import junit.framework.TestCase; + +/** + */ +public class Printer extends TestCase { + + public Printer(String name) { + super(name); + System.err.println("constructor print to System.err"); + System.out.println("constructor print to System.out"); + } + + static { + System.err.println("static print to System.err"); + System.out.println("static print to System.out"); + } + + public void testNoCrash() { + System.err.println("method print to System.err"); + System.out.println("method print to System.out"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Sleeper.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Sleeper.java new file mode 100644 index 000000000..cabc76370 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Sleeper.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import junit.framework.TestCase; + +/** + */ +public class Sleeper extends TestCase { + + public Sleeper(String name) { + super(name); + } + + public void testSleep() { + try { + Thread.sleep(5 * 1000); + } catch (InterruptedException e) { + } // end of try-catch + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/SuiteMethodTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/SuiteMethodTest.java new file mode 100644 index 000000000..5f8fd917d --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/SuiteMethodTest.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import junit.framework.Test; +import junit.framework.TestCase; + +/** + * validates that the suite() method works in classes that don't + * implement Test. + */ +public class SuiteMethodTest { + + public static Test suite() { + return new Nested("testMethod"); + } + + public static class Nested extends TestCase { + public Nested(String name) { + super(name); + } + + public void testMethod() { + assertTrue(true); + } + } +} \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/TestFormatter.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/TestFormatter.java new file mode 100644 index 000000000..27420d6f4 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/TestFormatter.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.junit; + +import java.io.IOException; +import java.io.OutputStream; + +import junit.framework.AssertionFailedError; +import junit.framework.Test; + +import org.apache.tools.ant.BuildException; + +public class TestFormatter implements JUnitResultFormatter { + + private static final byte[] grafitto = new byte[] { + (byte) 'T', (byte) 'e', (byte) 's', (byte) 't', (byte) 'F', (byte) 'o', + (byte) 'r', (byte) 'm', (byte) 'a', (byte) 't', (byte) 't', (byte) 'e', + (byte) 'r', (byte) ' ', (byte) 'w', (byte) 'a', (byte) 's', (byte) ' ', + (byte) 'h', (byte) 'e', (byte) 'r', (byte) 'e', 10 + }; + + /** + * Where to write the log to. + */ + private OutputStream out; + + /** + * Empty + */ + public TestFormatter() { + } + + /** + * Empty + */ + public void startTestSuite(JUnitTest suite) { + } + /** + * Empty + */ + public void startTest(Test t) { + } + /** + * Empty + */ + public void endTest(Test test) { + } + /** + * Empty + */ + public void addFailure(Test test, Throwable t) { + } + /** + * Empty + */ + public void addFailure(Test test, AssertionFailedError t) { + } + /** + * Empty + */ + public void addError(Test test, Throwable t) { + } + /** + * Empty + */ + public void setSystemOutput(String out) { + } + /** + * Empty + */ + public void setSystemError(String err) { + } + + public void setOutput(OutputStream out) { + this.out = out; + } + + public void endTestSuite(JUnitTest suite) throws BuildException { + if (out != null) { + try { + out.write(grafitto); + out.flush(); + } catch (IOException ioex) { + throw new BuildException("Unable to write output", ioex); + } finally { + if (out != System.out && out != System.err) { + try { + out.close(); + } catch (IOException e) { + // ignore + } + } + } + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/VmCrash.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/VmCrash.java new file mode 100644 index 000000000..8ccf17abe --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/VmCrash.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import junit.framework.TestCase; + +/** + */ +public class VmCrash extends TestCase { + + public VmCrash(String name) { + super(name); + } + + public void testCrash() { + System.exit(0); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLFormatterWithCDATAOnSystemOut.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLFormatterWithCDATAOnSystemOut.java new file mode 100644 index 000000000..f93fb889a --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLFormatterWithCDATAOnSystemOut.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.junit; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.util.FileUtils; + +public class XMLFormatterWithCDATAOnSystemOut extends BuildFileTest { + + private static String DIR = "src/etc/testcases/taskdefs/optional/junit"; + private static String REPORT = + "TEST-" + XMLFormatterWithCDATAOnSystemOut.class.getName() + ".xml"; + + private static String TESTDATA = + "" + + "" + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + " " + + "]]>" + + ""; + + public XMLFormatterWithCDATAOnSystemOut(String name) { + super(name); + } + + public void testOutput() { + System.out.println(TESTDATA); + } + + public void testBuildfile() throws IOException { + configureProject(DIR + "/cdataoutput.xml"); + if (getProject().getProperty("cdata.inner") == null) { + // avoid endless loop + executeTarget("run-junit"); + File f = getProject().resolveFile(REPORT); + FileReader reader = null; + try { + reader = new FileReader(f); + String content = FileUtils.readFully(reader); + assertTrue(content.indexOf("]]>" + + "") > 0); + } finally { + if (reader != null) { + reader.close(); + } + f.delete(); + } + } + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java new file mode 100644 index 000000000..ffe7228f7 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java @@ -0,0 +1,895 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.net; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.Vector; + +import org.apache.commons.net.ftp.FTPClient; +import org.apache.tools.ant.BuildEvent; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.DefaultLogger; +import org.apache.tools.ant.DirectoryScanner; +import org.apache.tools.ant.taskdefs.condition.Os; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.util.RetryHandler; +import org.apache.tools.ant.util.Retryable; +import org.apache.tools.ant.util.regexp.RegexpMatcher; +import org.apache.tools.ant.util.regexp.RegexpMatcherFactory; + +public class FTPTest extends BuildFileTest{ + // keep track of what operating systems are supported here. + private boolean supportsSymlinks = Os.isFamily("unix"); + + private FTPClient ftp; + private boolean connectionSucceeded = true; + private boolean loginSuceeded = true; + private String tmpDir = null; + private String remoteTmpDir = null; + private String ftpFileSep = null; + private myFTP myFTPTask = new myFTP(); + + public FTPTest(String name) { + super(name); + } + public void setUp() { + configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml"); + getProject().executeTarget("setup"); + tmpDir = getProject().getProperty("tmp.dir"); + ftp = new FTPClient(); + ftpFileSep = getProject().getProperty("ftp.filesep"); + myFTPTask.setSeparator(ftpFileSep); + myFTPTask.setProject(getProject()); + remoteTmpDir = myFTPTask.resolveFile(tmpDir); + String remoteHost = getProject().getProperty("ftp.host"); + int port = Integer.parseInt(getProject().getProperty("ftp.port")); + String remoteUser = getProject().getProperty("ftp.user"); + String password = getProject().getProperty("ftp.password"); + try { + ftp.connect(remoteHost, port); + } catch (Exception ex) { + connectionSucceeded = false; + loginSuceeded = false; + System.out.println("could not connect to host " + remoteHost + " on port " + port); + } + if (connectionSucceeded) { + try { + ftp.login(remoteUser, password); + } catch (IOException ioe) { + loginSuceeded = false; + System.out.println("could not log on to " + remoteHost + " as user " + remoteUser); + } + } + } + + public void tearDown() { + try { + ftp.disconnect(); + } catch (IOException ioe) { + // do nothing + } + getProject().executeTarget("cleanup"); + } + private boolean changeRemoteDir(String remoteDir) { + boolean result = true; + try { + ftp.cwd(remoteDir); + } + catch (Exception ex) { + System.out.println("could not change directory to " + remoteTmpDir); + result = false; + } + return result; + } + public void test1() { + if (loginSuceeded) { + if (changeRemoteDir(remoteTmpDir)) { + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha"}); + ds.scan(); + compareFiles(ds, new String[] {} ,new String[] {"alpha"}); + } + } + } + + public void test2() { + if (loginSuceeded) { + if (changeRemoteDir(remoteTmpDir)) { + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/"}); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"}); + } + } + } + + public void test3() { + if (loginSuceeded) { + if (changeRemoteDir(remoteTmpDir)) { + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", + "alpha/beta/gamma"}); + } + } + } + + public void testFullPathMatchesCaseSensitive() { + if (loginSuceeded) { + if (changeRemoteDir(remoteTmpDir)) { + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"}); + ds.scan(); + compareFiles(ds, new String[] {}, new String[] {}); + } + } + } + + public void testFullPathMatchesCaseInsensitive() { + if (loginSuceeded) { + if (changeRemoteDir(remoteTmpDir)) { + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setCaseSensitive(false); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"}); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {}); + } + } + } + + public void test2ButCaseInsensitive() { + if (loginSuceeded) { + if (changeRemoteDir(remoteTmpDir)) { + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"ALPHA/"}); + ds.setCaseSensitive(false); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"}); + } + } + } + public void test2bisButCaseInsensitive() { + if (loginSuceeded) { + if (changeRemoteDir(remoteTmpDir)) { + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/BETA/gamma/"}); + ds.setCaseSensitive(false); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha/beta/gamma"}); + } + } + } + public void testGetWithSelector() { + expectLogContaining("ftp-get-with-selector", + "selectors are not supported in remote filesets"); + FileSet fsDestination = (FileSet) getProject().getReference("fileset-destination-without-selector"); + DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(getProject()); + dsDestination.scan(); + String [] sortedDestinationDirectories = dsDestination.getIncludedDirectories(); + String [] sortedDestinationFiles = dsDestination.getIncludedFiles(); + for (int counter = 0; counter < sortedDestinationDirectories.length; counter++) { + sortedDestinationDirectories[counter] = + sortedDestinationDirectories[counter].replace(File.separatorChar, '/'); + } + for (int counter = 0; counter < sortedDestinationFiles.length; counter++) { + sortedDestinationFiles[counter] = + sortedDestinationFiles[counter].replace(File.separatorChar, '/'); + } + FileSet fsSource = (FileSet) getProject().getReference("fileset-source-without-selector"); + DirectoryScanner dsSource = fsSource.getDirectoryScanner(getProject()); + dsSource.scan(); + compareFiles(dsSource, sortedDestinationFiles, sortedDestinationDirectories); + } + public void testGetFollowSymlinksTrue() { + if (!supportsSymlinks) { + return; + } + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + getProject().executeTarget("ftp-get-directory-symbolic-link"); + FileSet fsDestination = (FileSet) getProject().getReference("fileset-destination-without-selector"); + DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(getProject()); + dsDestination.scan(); + compareFiles(dsDestination, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"}); + } + public void testGetFollowSymlinksFalse() { + if (!supportsSymlinks) { + return; + } + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + getProject().executeTarget("ftp-get-directory-no-symbolic-link"); + FileSet fsDestination = (FileSet) getProject().getReference("fileset-destination-without-selector"); + DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(getProject()); + dsDestination.scan(); + compareFiles(dsDestination, new String[] {}, + new String[] {}); + } + public void testAllowSymlinks() { + if (!supportsSymlinks) { + return; + } + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + getProject().executeTarget("symlink-setup"); + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/beta/gamma/"}); + ds.setFollowSymlinks(true); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha/beta/gamma"}); + } + + public void testProhibitSymlinks() { + if (!supportsSymlinks) { + return; + } + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + getProject().executeTarget("symlink-setup"); + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/beta/gamma/"}); + ds.setFollowSymlinks(false); + ds.scan(); + compareFiles(ds, new String[] {}, new String[] {}); + } + public void testFileSymlink() { + if (!supportsSymlinks) { + return; + } + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + getProject().executeTarget("symlink-file-setup"); + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/beta/gamma/"}); + ds.setFollowSymlinks(true); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha/beta/gamma"}); + } + // father and child pattern test + public void testOrderOfIncludePatternsIrrelevant() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + String [] expectedFiles = {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}; + String [] expectedDirectories = {"alpha/beta", "alpha/beta/gamma" }; + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/be?a/**", "alpha/beta/gamma/"}); + ds.scan(); + compareFiles(ds, expectedFiles, expectedDirectories); + // redo the test, but the 2 include patterns are inverted + ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/beta/gamma/", "alpha/be?a/**"}); + ds.scan(); + compareFiles(ds, expectedFiles, expectedDirectories); + } + + public void testPatternsDifferInCaseScanningSensitive() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/", "ALPHA/"}); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"}); + } + + public void testPatternsDifferInCaseScanningInsensitive() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/", "ALPHA/"}); + ds.setCaseSensitive(false); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"}); + } + + public void testFullpathDiffersInCaseScanningSensitive() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] { + "alpha/beta/gamma/gamma.xml", + "alpha/beta/gamma/GAMMA.XML" + }); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {}); + } + + public void testFullpathDiffersInCaseScanningInsensitive() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] { + "alpha/beta/gamma/gamma.xml", + "alpha/beta/gamma/GAMMA.XML" + }); + ds.setCaseSensitive(false); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {}); + } + + public void testParentDiffersInCaseScanningSensitive() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"}); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"}); + } + + public void testParentDiffersInCaseScanningInsensitive() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"}); + ds.setCaseSensitive(false); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml"}, + new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"}); + } + + public void testExcludeOneFile() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] { + "**/*.xml" + }); + ds.setExcludes(new String[] { + "alpha/beta/b*xml" + }); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"}, + new String[] {}); + } + public void testExcludeHasPrecedence() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] { + "alpha/**" + }); + ds.setExcludes(new String[] { + "alpha/**" + }); + ds.scan(); + compareFiles(ds, new String[] {}, + new String[] {}); + + } + public void testAlternateIncludeExclude() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setIncludes(new String[] { + "alpha/**", + "alpha/beta/gamma/**" + }); + ds.setExcludes(new String[] { + "alpha/beta/**" + }); + ds.scan(); + compareFiles(ds, new String[] {}, + new String[] {"alpha"}); + + } + public void testAlternateExcludeInclude() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setExcludes(new String[] { + "alpha/**", + "alpha/beta/gamma/**" + }); + ds.setIncludes(new String[] { + "alpha/beta/**" + }); + ds.scan(); + compareFiles(ds, new String[] {}, + new String[] {}); + + } + /** + * Test inspired by Bug#1415. + */ + public void testChildrenOfExcludedDirectory() { + if (!loginSuceeded) { + return; + } + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + getProject().executeTarget("children-of-excluded-dir-setup"); + FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp); + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setExcludes(new String[] {"alpha/**"}); + ds.scan(); + compareFiles(ds, new String[] {"delta/delta.xml"}, + new String[] {"delta"}); + + ds = myFTPTask.newScanner(ftp); + if (!changeRemoteDir(remoteTmpDir)) { + return; + } + ds.setBasedir(new File(getProject().getBaseDir(), "tmp")); + ds.setExcludes(new String[] {"alpha"}); + ds.scan(); + compareFiles(ds, new String[] {"alpha/beta/beta.xml", + "alpha/beta/gamma/gamma.xml", + "delta/delta.xml"}, + new String[] {"alpha/beta", "alpha/beta/gamma", "delta"}); + + } + + /** + * This class enables the use of the log messages as a way of testing + * the number of files actually transferred. + * It uses the ant regular expression mechanism to get a regex parser + * to parse the log output. + */ + private class CountLogListener extends DefaultLogger { + private Vector lastMatchGroups = null; + private RegexpMatcher matcher = new RegexpMatcherFactory().newRegexpMatcher(); + + /** + * The only constructor for a CountLogListener + * @param pattern a regular expression pattern. It should have + * one parenthesized group and that group should contain the + * number desired. + */ + public CountLogListener(String pattern) { + super(); + this.matcher.setPattern(pattern); + } + + + /* + * @param event the build event that is being logged. + */ + public void messageLogged(BuildEvent event) { + String message = event.getMessage(); + if (this.matcher.matches(message)) { + lastMatchGroups = this.matcher.getGroups(message); + } + super.messageLogged(event); + } + + /** + * returns the desired number that results from parsing the log + * message + * @return the number of files indicated in the desired message or -1 + * if a matching log message was never found. + */ + public int getCount() { + if (this.lastMatchGroups == null) { + return -1; + } + return Integer.parseInt((String) this.lastMatchGroups.get(1)); + } + } + + /** + * This class enables the use of the log to count the number + * of times a message has been emitted. + */ + private class LogCounter extends DefaultLogger { + private Map searchMap = new HashMap(); + private int matchCount; + + public void addLogMessageToSearch(String message) { + searchMap.put(message, new Integer(0)); + } + + /* + * @param event the build event that is being logged. + */ + public void messageLogged(BuildEvent event) { + String message = event.getMessage(); + Integer mcnt = (Integer) searchMap.get(message); + if (null != mcnt) { + searchMap.put(message, new Integer(mcnt.intValue() + 1)); + } + super.messageLogged(event); + } + + /** + * @return the number of times that the looked for message was sent + * to the log + */ + public int getMatchCount(String message) { + Integer mcnt = (Integer) searchMap.get(message); + if (null != mcnt) { + return mcnt.intValue(); + } + return 0; + } + } + /** + * Tests the combination of the newer parameter and the + * serverTimezoneConfig parameter in the PUT action. The default + * configuration is an ftp server on localhost which formats + * timestamps as GMT. + */ + public void testTimezonePut() { + CountLogListener log = new CountLogListener("(\\d+) files? sent"); + getProject().executeTarget("timed.test.setup"); + getProject().addBuildListener(log); + getProject().executeTarget("timed.test.put.older"); + assertEquals(1, log.getCount()); + } + + /** + * Tests the combination of the newer parameter and the + * serverTimezoneConfig parameter in the GET action. The default + * configuration is an ftp server on localhost which formats + * timestamps as GMT. + */ + public void testTimezoneGet() { + CountLogListener log = new CountLogListener("(\\d+) files? retrieved"); + getProject().executeTarget("timed.test.setup"); + getProject().addBuildListener(log); + getProject().executeTarget("timed.test.get.older"); + assertEquals(3, log.getCount()); + } + + + /** + * Tests that the presence of one of the server config params forces + * the system type to Unix if not specified. + */ + public void testConfiguration1() { + int[] expectedCounts = { + 1,1,0,1,0,0,0 + }; + performConfigTest("configuration.1", expectedCounts); + + } + + /** + * Tests the systemTypeKey attribute. + */ + public void testConfiguration2() { + int[] expectedCounts = { + 1,0,0,1,1,0,0 + }; + performConfigTest("configuration.2", expectedCounts); + + } + + /** + * Tests the systemTypeKey attribute with UNIX specified. + */ + public void testConfiguration3() { + int[] expectedCounts = { + 1,0,1,0,0,1,0 + }; + performConfigTest("configuration.3", expectedCounts); + + } + + public void testConfigurationLang() { + int[] expectedCounts = { + 1,1,0,0,0,0,1 + }; + performConfigTest("configuration.lang.good", expectedCounts); + + try { + performConfigTest("configuration.lang.bad", expectedCounts); + fail("BuildException Expected"); + } catch (Exception bx) { + assertTrue(bx instanceof BuildException); + } + } + /** + * Tests the systemTypeKey attribute. + */ + public void testConfigurationNone() { + int[] expectedCounts = { + 0,0,0,0,0,0,0 + }; + performConfigTest("configuration.none", expectedCounts); + + } + + private void performConfigTest(String target, int[] expectedCounts) { + String[] messages = new String[]{ + "custom configuration", + "custom config: system key = default (UNIX)", + "custom config: system key = UNIX", + "custom config: server time zone ID = " + getProject().getProperty("ftp.server.timezone"), + "custom config: system key = WINDOWS", + "custom config: default date format = yyyy/MM/dd HH:mm", + "custom config: server language code = de" + + }; + LogCounter counter = new LogCounter(); + for (int i=0; i < messages.length; i++) { + counter.addLogMessageToSearch(messages[i]); + } + + getProject().addBuildListener(counter); + getProject().executeTarget(target); + for (int i=0; i < messages.length; i++) { + assertEquals("target "+target+":message "+ i, expectedCounts[i], counter.getMatchCount(messages[i])); + } + + } + + + /** + * this test is inspired by a user reporting that deletions of directories with the ftp task do not work + */ + public void testFTPDelete() { + getProject().executeTarget("ftp-delete"); + } + private void compareFiles(DirectoryScanner ds, String[] expectedFiles, + String[] expectedDirectories) { + String includedFiles[] = ds.getIncludedFiles(); + String includedDirectories[] = ds.getIncludedDirectories(); + assertEquals("file present: ", expectedFiles.length, + includedFiles.length); + assertEquals("directories present: ", expectedDirectories.length, + includedDirectories.length); + + for (int counter=0; counter < includedFiles.length; counter++) { + includedFiles[counter] = includedFiles[counter].replace(File.separatorChar, '/'); + } + Arrays.sort(includedFiles); + for (int counter=0; counter < includedDirectories.length; counter++) { + includedDirectories[counter] = includedDirectories[counter] + .replace(File.separatorChar, '/'); + } + Arrays.sort(includedDirectories); + for (int counter=0; counter < includedFiles.length; counter++) { + assertEquals(expectedFiles[counter], includedFiles[counter]); + } + for (int counter=0; counter < includedDirectories.length; counter++) { + assertEquals(expectedDirectories[counter], includedDirectories[counter]); + counter++; + } + } + private static class myFTP extends FTP { + public FTP.FTPDirectoryScanner newScanner(FTPClient client) { + return new FTP.FTPDirectoryScanner(client); + } + // provide public visibility + public String resolveFile(String file) { + return super.resolveFile(file); + } + } + + + public abstract static class myRetryableFTP extends FTP { + private final int numberOfFailuresToSimulate; + private int simulatedFailuresLeft; + + protected myRetryableFTP(int numberOfFailuresToSimulate) { + this.numberOfFailuresToSimulate = numberOfFailuresToSimulate; + this.simulatedFailuresLeft = numberOfFailuresToSimulate; + } + + protected void getFile(FTPClient ftp, String dir, String filename) + throws IOException, BuildException + { + if (this.simulatedFailuresLeft > 0) { + this.simulatedFailuresLeft--; + throw new IOException("Simulated failure for testing"); + } + super.getFile(ftp, dir, filename); + } + protected void executeRetryable(RetryHandler h, Retryable r, + String filename) throws IOException + { + this.simulatedFailuresLeft = this.numberOfFailuresToSimulate; + super.executeRetryable(h, r, filename); + } + } + public static class oneFailureFTP extends myRetryableFTP { + public oneFailureFTP() { + super(1); + } + } + public static class twoFailureFTP extends myRetryableFTP { + public twoFailureFTP() { + super(2); + } + } + public static class threeFailureFTP extends myRetryableFTP { + public threeFailureFTP() { + super(3); + } + } + + public static class randomFailureFTP extends myRetryableFTP { + public randomFailureFTP() { + super(new Random().nextInt(Short.MAX_VALUE)); + } + } + public void testGetWithSelectorRetryable1() { + getProject().addTaskDefinition("ftp", oneFailureFTP.class); + try { + getProject().executeTarget("ftp-get-with-selector-retryable"); + } catch (BuildException bx) { + fail("Two retries expected, failed after one."); + } + } + public void testGetWithSelectorRetryable2() { + getProject().addTaskDefinition("ftp", twoFailureFTP.class); + try { + getProject().executeTarget("ftp-get-with-selector-retryable"); + } catch (BuildException bx) { + fail("Two retries expected, failed after two."); + } + } + + public void testGetWithSelectorRetryable3() { + getProject().addTaskDefinition("ftp", threeFailureFTP.class); + try { + getProject().executeTarget("ftp-get-with-selector-retryable"); + fail("Two retries expected, continued after two."); + } catch (BuildException bx) { + } + } + public void testGetWithSelectorRetryableRandom() { + getProject().addTaskDefinition("ftp", randomFailureFTP.class); + try { + getProject().setProperty("ftp.retries", "forever"); + getProject().executeTarget("ftp-get-with-selector-retryable"); + } catch (BuildException bx) { + fail("Retry forever specified, but failed."); + } + } + + public void testInitialCommand() { + performCommandTest("test-initial-command", new int[] { 1,0 }); + } + public void testSiteAction() { + performCommandTest("test-site-action", new int[] { 1,0 }); + } + + private void performCommandTest(String target, int[] expectedCounts) { + String[] messages = new String[]{ + "Doing Site Command: umask 222", + "Failed to issue Site Command: umask 222", + + }; + LogCounter counter = new LogCounter(); + for (int i=0; i < messages.length; i++) { + counter.addLogMessageToSearch(messages[i]); + } + + getProject().addBuildListener(counter); + getProject().executeTarget(target); + for (int i=0; i < messages.length; i++) { + assertEquals("target "+target+":message "+ i, expectedCounts[i], counter.getMatchCount(messages[i])); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/perforce/P4ChangeTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/perforce/P4ChangeTest.java new file mode 100644 index 000000000..0a44ae815 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/perforce/P4ChangeTest.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.perforce; + +import junit.framework.TestCase; +import org.apache.oro.text.perl.Perl5Util; + +/** + * Basic testcase to ensure that backslashing is OK. + */ +public class P4ChangeTest extends TestCase { + + protected P4Change p4change; + + public P4ChangeTest(String s) { + super(s); + } + + protected void setUp() throws Exception { + p4change = new P4Change(); + } + + public void testBackslash(){ + String input = "comment with a / inside"; + String output = P4Change.backslash(input); + assertEquals("comment with a \\/ inside", output); + } + + public void testSubstitute(){ + Perl5Util util = new Perl5Util(); + String tosubstitute = "xxxx"; + String input = P4Change.backslash("/a/b/c/"); + String output = util.substitute("s//" + input + "/", tosubstitute); + assertEquals("xx/a/b/c/xx", output); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/perforce/p4integrate.xml b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/perforce/p4integrate.xml new file mode 100644 index 000000000..31001ddf8 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/perforce/p4integrate.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java new file mode 100644 index 000000000..07cb1eb49 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.script; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.FileSet; +import java.io.File; + +/** + * Tests the examples of the <scriptdef> task. + * + * @since Ant 1.6 + */ +public class ScriptDefTest extends BuildFileTest { + + public ScriptDefTest(String name) { + super(name); + } + + /** + * The JUnit setup method + */ + public void setUp() { + configureProject("src/etc/testcases/taskdefs/optional/script/scriptdef.xml"); + } + + public void testSimple() { + executeTarget("simple"); + // get the fileset and its basedir + Project p = getProject(); + FileSet fileset = (FileSet) p.getReference("testfileset"); + File baseDir = fileset.getDir(p); + String log = getLog(); + assertTrue("Expecting attribute value printed", + log.indexOf("Attribute attr1 = test") != -1); + + assertTrue("Expecting nested element value printed", + log.indexOf("Fileset basedir = " + baseDir.getAbsolutePath()) != -1); + } + + public void testNoLang() { + expectBuildExceptionContaining("nolang", + "Absence of language attribute not detected", + "requires a language attribute"); + } + + public void testNoName() { + expectBuildExceptionContaining("noname", + "Absence of name attribute not detected", + "scriptdef requires a name attribute"); + } + + public void testNestedByClassName() { + executeTarget("nestedbyclassname"); + // get the fileset and its basedir + Project p = getProject(); + FileSet fileset = (FileSet) p.getReference("testfileset"); + File baseDir = fileset.getDir(p); + String log = getLog(); + assertTrue("Expecting attribute value to be printed", + log.indexOf("Attribute attr1 = test") != -1); + + assertTrue("Expecting nested element value to be printed", + log.indexOf("Fileset basedir = " + baseDir.getAbsolutePath()) != -1); + } + + public void testNoElement() { + expectOutput("noelement", "Attribute attr1 = test"); + } + + public void testException() { + expectBuildExceptionContaining("exception", + "Should have thrown an exception in the script", + "TypeError"); + } + + public void testDoubleDef() { + executeTarget("doubledef"); + String log = getLog(); + assertTrue("Task1 did not execute", + log.indexOf("Task1") != -1); + assertTrue("Task2 did not execute", + log.indexOf("Task2") != -1); + } + + public void testDoubleAttribute() { + expectBuildExceptionContaining("doubleAttributeDef", + "Should have detected duplicate attribute definition", + "attr1 attribute more than once"); + } + + public void testProperty() { + executeTarget("property"); + // get the fileset and its basedir + String log = getLog(); + assertTrue("Expecting property in attribute value replaced", + log.indexOf("Attribute value = test") != -1); + } + + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/sos/SOSTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/sos/SOSTest.java new file mode 100644 index 000000000..d36de008c --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/sos/SOSTest.java @@ -0,0 +1,336 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.sos; + +import java.io.File; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Commandline; +import org.apache.tools.ant.types.Path; + +/** + * Testcase to ensure that command line generation and required attributes are + * correct. + * + */ +public class SOSTest extends BuildFileTest { + + private Commandline commandline; + + private static final String VSS_SERVER_PATH = "\\\\server\\vss\\srcsafe.ini"; + private static final String VSS_PROJECT_PATH = "/SourceRoot/Project"; + private static final String DS_VSS_PROJECT_PATH = "$/SourceRoot/Project"; + private static final String SOS_SERVER_PATH = "192.168.0.1:8888"; + private static final String SOS_USERNAME = "ant"; + private static final String SOS_PASSWORD = "rocks"; + private static final String LOCAL_PATH = "testdir"; + private static final String SRC_FILE = "Class1.java"; + private static final String SRC_LABEL = "label1"; + private static final String SRC_COMMENT = "I fixed a bug"; + private static final String SOS_HOME = "/home/user/.sos"; + private static final String VERSION = "007"; + + /** + * Constructor for the SOSTest object + * + * @param s Test name + */ + public SOSTest(String s) { + super(s); + } + + /** + * The JUnit setup method + * + * @throws Exception + */ + protected void setUp() + throws Exception { + project = new Project(); + project.setBasedir("."); + } + + /** + * The teardown method for JUnit + * + * @throws Exception + */ + protected void tearDown() + throws Exception { + File file = new File(project.getBaseDir(), LOCAL_PATH); + if (file.exists()) { + file.delete(); + } + } + + /** Test SOSGetFile flags & commandline generation */ + public void testGetFileFlags() { + String[] sTestCmdLine = {"soscmd", "-command", "GetFile", "-file", + SRC_FILE, "-revision", "007", "-server", SOS_SERVER_PATH, "-name", + SOS_USERNAME, "-password", SOS_PASSWORD, "-database", VSS_SERVER_PATH, + "-project", DS_VSS_PROJECT_PATH, "-verbose", "-nocompress", + "-nocache", "-workdir", project.getBaseDir().getAbsolutePath() + + File.separator + LOCAL_PATH}; + + // Set up a SOSGet task + SOSGet sosGet = new SOSGet(); + sosGet.setProject(project); + sosGet.setVssServerPath(VSS_SERVER_PATH); + sosGet.setSosServerPath(SOS_SERVER_PATH); + sosGet.setProjectPath(VSS_PROJECT_PATH); + sosGet.setFile(SRC_FILE); + sosGet.setUsername(SOS_USERNAME); + sosGet.setPassword(SOS_PASSWORD); + sosGet.setVersion(VERSION); + sosGet.setLocalPath(new Path(project, LOCAL_PATH)); + sosGet.setNoCache(true); + sosGet.setNoCompress(true); + sosGet.setVerbose(true); + sosGet.setRecursive(true); + + commandline = sosGet.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Test SOSGetProject flags & commandline generation */ + public void testGetProjectFlags() { + String[] sTestCmdLine = {"soscmd", "-command", "GetProject", "-recursive", + "-label", SRC_LABEL, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME, + "-password", "", "-database", VSS_SERVER_PATH, "-project", + DS_VSS_PROJECT_PATH, "", "", "-soshome", SOS_HOME, "-workdir", + project.getBaseDir().getAbsolutePath()}; + + // Set up a SOSGet task + SOSGet sosGet = new SOSGet(); + sosGet.setProject(project); + sosGet.setVssServerPath(VSS_SERVER_PATH); + sosGet.setSosServerPath(SOS_SERVER_PATH); + sosGet.setProjectPath(DS_VSS_PROJECT_PATH); + sosGet.setLabel(SRC_LABEL); + sosGet.setUsername(SOS_USERNAME); + sosGet.setSosHome(SOS_HOME); + sosGet.setNoCache(true); + sosGet.setNoCompress(false); + sosGet.setVerbose(false); + sosGet.setRecursive(true); + + commandline = sosGet.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Tests SOSGet required attributes. */ + public void testGetExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml"); + expectSpecificBuildException("sosget.1", "some cause", "sosserverpath attribute must be set!"); + expectSpecificBuildException("sosget.2", "some cause", "username attribute must be set!"); + expectSpecificBuildException("sosget.3", "some cause", "vssserverpath attribute must be set!"); + expectSpecificBuildException("sosget.4", "some cause", "projectpath attribute must be set!"); + } + + /** Test CheckInFile option flags */ + public void testCheckinFileFlags() { + String[] sTestCmdLine = {"soscmd", "-command", "CheckInFile", "-file", + SRC_FILE, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME, + "-password", SOS_PASSWORD, "-database", VSS_SERVER_PATH, "-project", + DS_VSS_PROJECT_PATH, "-verbose", "-nocompress", "-nocache", + "-workdir", project.getBaseDir().getAbsolutePath() + File.separator + + LOCAL_PATH, "-log", SRC_COMMENT}; + + // Set up a SOSCheckin task + SOSCheckin sosCheckin = new SOSCheckin(); + sosCheckin.setProject(project); + sosCheckin.setVssServerPath(VSS_SERVER_PATH); + sosCheckin.setSosServerPath(SOS_SERVER_PATH); + sosCheckin.setProjectPath(VSS_PROJECT_PATH); + sosCheckin.setFile(SRC_FILE); + sosCheckin.setComment(SRC_COMMENT); + sosCheckin.setUsername(SOS_USERNAME); + sosCheckin.setPassword(SOS_PASSWORD); + sosCheckin.setLocalPath(new Path(project, LOCAL_PATH)); + sosCheckin.setNoCache(true); + sosCheckin.setNoCompress(true); + sosCheckin.setVerbose(true); + sosCheckin.setRecursive(true); + + commandline = sosCheckin.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Test CheckInProject option flags */ + public void testCheckinProjectFlags() { + String[] sTestCmdLine = {"soscmd", "-command", "CheckInProject", + "-recursive", "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME, + "-password", "", "-database", VSS_SERVER_PATH, "-project", + DS_VSS_PROJECT_PATH, "", "", "-soshome", SOS_HOME, "-workdir", + project.getBaseDir().getAbsolutePath(), "-log", SRC_COMMENT,}; + + // Set up a SOSCheckin task + SOSCheckin sosCheckin = new SOSCheckin(); + sosCheckin.setProject(project); + sosCheckin.setVssServerPath(VSS_SERVER_PATH); + sosCheckin.setSosServerPath(SOS_SERVER_PATH); + sosCheckin.setProjectPath(DS_VSS_PROJECT_PATH); + sosCheckin.setComment(SRC_COMMENT); + sosCheckin.setUsername(SOS_USERNAME); + sosCheckin.setSosHome(SOS_HOME); + sosCheckin.setNoCache(true); + sosCheckin.setNoCompress(false); + sosCheckin.setVerbose(false); + sosCheckin.setRecursive(true); + + commandline = sosCheckin.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Test SOSCheckIn required attributes. */ + public void testCheckinExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml"); + expectSpecificBuildException("soscheckin.1", "some cause", "sosserverpath attribute must be set!"); + expectSpecificBuildException("soscheckin.2", "some cause", "username attribute must be set!"); + expectSpecificBuildException("soscheckin.3", "some cause", "vssserverpath attribute must be set!"); + expectSpecificBuildException("soscheckin.4", "some cause", "projectpath attribute must be set!"); + } + + /** Test CheckOutFile option flags */ + public void testCheckoutFileFlags() { + String[] sTestCmdLine = {"soscmd", "-command", "CheckOutFile", "-file", + SRC_FILE, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME, + "-password", SOS_PASSWORD, "-database", VSS_SERVER_PATH, "-project", + DS_VSS_PROJECT_PATH, "-verbose", "-nocompress", "-nocache", + "-workdir", project.getBaseDir().getAbsolutePath() + + File.separator + LOCAL_PATH}; + + // Set up a SOSCheckout task + SOSCheckout sosCheckout = new SOSCheckout(); + sosCheckout.setProject(project); + sosCheckout.setVssServerPath(VSS_SERVER_PATH); + sosCheckout.setSosServerPath(SOS_SERVER_PATH); + sosCheckout.setProjectPath(DS_VSS_PROJECT_PATH); + sosCheckout.setFile(SRC_FILE); + sosCheckout.setUsername(SOS_USERNAME); + sosCheckout.setPassword(SOS_PASSWORD); + sosCheckout.setLocalPath(new Path(project, LOCAL_PATH)); + sosCheckout.setNoCache(true); + sosCheckout.setNoCompress(true); + sosCheckout.setVerbose(true); + sosCheckout.setRecursive(true); + + commandline = sosCheckout.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Test CheckOutProject option flags */ + public void testCheckoutProjectFlags() { + String[] sTestCmdLine = {"soscmd", "-command", "CheckOutProject", + "-recursive", "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME, + "-password", "", "-database", VSS_SERVER_PATH, "-project", + DS_VSS_PROJECT_PATH, "", "", "-soshome", SOS_HOME, "-workdir", + project.getBaseDir().getAbsolutePath()}; + + // Set up a sosCheckout task + SOSCheckout sosCheckout = new SOSCheckout(); + sosCheckout.setProject(project); + sosCheckout.setVssServerPath(VSS_SERVER_PATH); + sosCheckout.setSosServerPath(SOS_SERVER_PATH); + sosCheckout.setProjectPath(VSS_PROJECT_PATH); + sosCheckout.setUsername(SOS_USERNAME); + sosCheckout.setSosHome(SOS_HOME); + sosCheckout.setNoCache(true); + sosCheckout.setNoCompress(false); + sosCheckout.setVerbose(false); + sosCheckout.setRecursive(true); + + commandline = sosCheckout.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Test SOSCheckout required attributes. */ + public void testCheckoutExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml"); + expectSpecificBuildException("soscheckout.1", "some cause", "sosserverpath attribute must be set!"); + expectSpecificBuildException("soscheckout.2", "some cause", "username attribute must be set!"); + expectSpecificBuildException("soscheckout.3", "some cause", "vssserverpath attribute must be set!"); + expectSpecificBuildException("soscheckout.4", "some cause", "projectpath attribute must be set!"); + } + + /** Test Label option flags */ + public void testLabelFlags() { + String[] sTestCmdLine = {"soscmd", "-command", "AddLabel", "-server", + SOS_SERVER_PATH, "-name", SOS_USERNAME, "-password", "", "-database", + VSS_SERVER_PATH, "-project", DS_VSS_PROJECT_PATH, "-label", + SRC_LABEL, "-verbose", "-log", SRC_COMMENT}; + + // Set up a sosCheckout task + SOSLabel sosLabel = new SOSLabel(); + sosLabel.setVssServerPath(VSS_SERVER_PATH); + sosLabel.setSosServerPath(SOS_SERVER_PATH); + sosLabel.setProjectPath(DS_VSS_PROJECT_PATH); + sosLabel.setUsername(SOS_USERNAME); + sosLabel.setSosHome(SOS_HOME); + sosLabel.setComment(SRC_COMMENT); + sosLabel.setLabel(SRC_LABEL); + sosLabel.setNoCache(true); + sosLabel.setNoCompress(false); + sosLabel.setVerbose(true); + + commandline = sosLabel.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Test SOSLabel required attributes. */ + public void testLabelExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml"); + expectSpecificBuildException("soslabel.1", "some cause", "sosserverpath attribute must be set!"); + expectSpecificBuildException("soslabel.2", "some cause", "username attribute must be set!"); + expectSpecificBuildException("soslabel.3", "some cause", "vssserverpath attribute must be set!"); + expectSpecificBuildException("soslabel.4", "some cause", "projectpath attribute must be set!"); + expectSpecificBuildException("soslabel.5", "some cause", "label attribute must be set!"); + } + + /** + * Iterate through the generated command line comparing it to reference + * one. + * + * @param sTestCmdLine The reference command line; + * @param sGeneratedCmdLine The generated command line; + */ + private void checkCommandLines(String[] sTestCmdLine, String[] sGeneratedCmdLine) { + int length = sTestCmdLine.length; + for (int i = 0; i < length; i++) { + try { + assertEquals("arg # " + String.valueOf(i), + sTestCmdLine[i], + sGeneratedCmdLine[i]); + } catch (ArrayIndexOutOfBoundsException aioob) { + fail("missing arg " + sTestCmdLine[i]); + } + } + if (sGeneratedCmdLine.length > sTestCmdLine.length) { + // We have extra elements + fail("extra args"); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/splash/SplashScreenTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/splash/SplashScreenTest.java new file mode 100644 index 000000000..81da89385 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/splash/SplashScreenTest.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.splash; + +import org.apache.tools.ant.Project; + +/** + * This is an "interactive" test, it passes if the splash screen + * disappears after the "finished" but before the "exiting" message. + * + * This even isn't a JUnit test case. + * + * @since Ant 1.5.2 + */ +public class SplashScreenTest { + + public static void main(String[] args) { + Project p = new Project(); + SplashTask t = new SplashTask(); + t.setProject(p); + t.execute(); + + // give it some time to display + try { + Thread.currentThread().sleep(2000); + } catch (InterruptedException e) { + } // end of try-catch + + p.fireBuildFinished(null); + System.err.println("finished"); + + try { + Thread.currentThread().sleep(2000); + } catch (InterruptedException e) { + } // end of try-catch + System.err.println("exiting"); + System.exit(0); + } +} + diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java new file mode 100644 index 000000000..8c21c8d0f --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java @@ -0,0 +1,166 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.taskdefs.optional.ssh; + +import junit.framework.TestCase; + +import java.io.*; +import java.util.List; +import java.util.ArrayList; +import java.util.Iterator; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.condition.FilesMatch; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.ant.types.selectors.FilenameSelector; + +/** + * This is a unit test for the Scp task in Ant. It must be + * configured with command line options in order for it to work. + * Here are the options: + * + * scp.tmp This is a local path to a temporary + * directory for this task to use. + * scp.host This is the remote location of the form: + * "user:password@host:/path/to/directory" + * scp.port The port of the listening SSH service. + * Defaults to 22. (optional) + * scp.known.hosts The file containing the public keys of known + * hosts. Must be a SSH2 version file, but + * supports RSA and DSA keys. If it is not present + * this task setTrust() to true. (optional) + */ +public class ScpTest extends TestCase { + + private File tempDir = new File( System.getProperty("scp.tmp") ); + private String sshHostUri = System.getProperty("scp.host"); + private int port = Integer.parseInt( System.getProperty( "scp.port", "22" ) ); + private String knownHosts = System.getProperty("scp.known.hosts"); + + private List cleanUpList = new ArrayList(); + + public ScpTest(String testname) { + super(testname); + } + + protected void setUp() { + cleanUpList.clear(); + } + + protected void tearDown() { + for( Iterator i = cleanUpList.iterator(); i.hasNext(); ) { + File file = (File) i.next(); + file.delete(); + } + } + + public void testSingleFileUploadAndDownload() throws IOException { + File uploadFile = createTemporaryFile(); + + Scp scpTask = createTask(); + scpTask.setFile( uploadFile.getPath() ); + scpTask.setTodir( sshHostUri ); + scpTask.execute(); + + File testFile = new File( tempDir.getPath() + File.separator + + "download-testSingleFileUploadAndDownload.test" ); + addCleanup( testFile ); + assertTrue( "Assert that the testFile does not exist.", + !testFile.exists() ); + + scpTask.setFile( sshHostUri + "/" + uploadFile.getName() ); + scpTask.setTodir( testFile.getPath() ); + scpTask.execute(); + + assertTrue( "Assert that the testFile exists.", testFile.exists() ); + compareFiles( uploadFile, testFile ); + } + + public void testMultiUploadAndDownload() throws IOException { + List uploadList = new ArrayList(); + for( int i = 0; i < 5; i++ ) { + uploadList.add( createTemporaryFile() ); + } + + Scp scp = createTask(); + FilenameSelector selector = new FilenameSelector(); + selector.setName( "scp*" ); + FileSet fileset = new FileSet(); + fileset.setDir( tempDir ); + fileset.addFilename( selector ); + scp.addFileset( fileset ); + scp.setTodir( sshHostUri ); + scp.execute(); + + File multi = new File( tempDir, "multi" ); + multi.mkdir(); + addCleanup( multi ); + + Scp scp2 = createTask(); + scp2.setFile( sshHostUri + "/scp*" ); + scp2.setTodir( multi.getPath() ); + scp2.execute(); + + FilesMatch match = new FilesMatch(); + for( Iterator i = uploadList.iterator(); i.hasNext(); ) { + File f = (File)i.next(); + match.setFile1( f ); + File f2 = new File( multi, f.getName() ); + match.setFile2( f2 ); + assertTrue("Assert file '" + f.getPath() + "' and file '" + + f2.getPath() + "'", match.eval() ); + } + } + + public void addCleanup( File file ) { + cleanUpList.add( file ); + } + + private void compareFiles(File src, File dest) { + FilesMatch match = new FilesMatch(); + match.setFile1( src ); + match.setFile2( dest ); + + assertTrue( "Assert files are equal.", match.eval() ); + } + + private File createTemporaryFile() throws IOException { + File uploadFile; + uploadFile = File.createTempFile( "scp", "test", tempDir ); + FileWriter writer = new FileWriter( uploadFile ); + writer.write("Can you hear me now?\n"); + writer.close(); + addCleanup( uploadFile ); + return uploadFile; + } + + private Scp createTask() { + Scp scp = new Scp(); + Project p = new Project(); + p.init(); + scp.setProject( p ); + if( knownHosts != null ) { + scp.setKnownhosts( knownHosts ); + } else { + scp.setTrust( true ); + } + scp.setPort( port ); + return scp; + } +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/unix/SymlinkTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/unix/SymlinkTest.java new file mode 100644 index 000000000..83f65a399 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/unix/SymlinkTest.java @@ -0,0 +1,190 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* + * Since the initial version of this file was deveolped on the clock on + * an NSF grant I should say the following boilerplate: + * + * This material is based upon work supported by the National Science + * Foundaton under Grant No. EIA-0196404. Any opinions, findings, and + * conclusions or recommendations expressed in this material are those + * of the author and do not necessarily reflect the views of the + * National Science Foundation. + */ + +package org.apache.tools.ant.taskdefs.optional.unix; + +import org.apache.tools.ant.taskdefs.condition.Os; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; + +/** + * Test cases for the Symlink task. Link creation, link deletion, recording + * of links in multiple directories, and restoration of links recorded are + * all tested. A separate test for the utility method Symlink.deleteSymlink + * is not included because action="delete" only prints a message and calls + * Symlink.deleteSymlink, making a separate test redundant. + * + */ + +public class SymlinkTest extends BuildFileTest { + + private Project p; + private boolean supportsSymlinks = Os.isFamily("unix"); + + public SymlinkTest(String name) { + super(name); + } + + public void setUp() { + if (supportsSymlinks) { + configureProject("src/etc/testcases/taskdefs/optional/unix/symlink.xml"); + executeTarget("setup"); + } + } + + + public void testSingle() { + if (supportsSymlinks) { + executeTarget("test-single"); + p = getProject(); + assertNotNull("Failed to create file", + p.getProperty("test.single.file.created")); + assertNotNull("Failed to create link", + p.getProperty("test.single.link.created")); + } + } + + public void testDelete() { + if (supportsSymlinks) { + executeTarget("test-delete"); + p = getProject(); + String linkDeleted = p.getProperty("test.delete.link.still.there"); + assertNotNull("Actual file deleted by symlink", + p.getProperty("test.delete.file.still.there")); + if (linkDeleted != null) { + fail(linkDeleted); + } + } + } + + public void testRecord() { + if (supportsSymlinks) { + executeTarget("test-record"); + p = getProject(); + + assertNotNull("Failed to create dir1", + p.getProperty("test.record.dir1.created")); + + assertNotNull("Failed to create dir2", + p.getProperty("test.record.dir2.created")); + + assertNotNull("Failed to create file1", + p.getProperty("test.record.file1.created")); + + assertNotNull("Failed to create file2", + p.getProperty("test.record.file2.created")); + + assertNotNull("Failed to create fileA", + p.getProperty("test.record.fileA.created")); + + assertNotNull("Failed to create fileB", + p.getProperty("test.record.fileB.created")); + + assertNotNull("Failed to create fileC", + p.getProperty("test.record.fileC.created")); + + assertNotNull("Failed to create link1", + p.getProperty("test.record.link1.created")); + + assertNotNull("Failed to create link2", + p.getProperty("test.record.link2.created")); + + assertNotNull("Failed to create link3", + p.getProperty("test.record.link3.created")); + + assertNotNull("Failed to create dirlink", + p.getProperty("test.record.dirlink.created")); + + assertNotNull("Failed to create dirlink2", + p.getProperty("test.record.dirlink2.created")); + + assertNotNull("Couldn't record links in dir1", + p.getProperty("test.record.dir1.recorded")); + + assertNotNull("Couldn't record links in dir2", + p.getProperty("test.record.dir2.recorded")); + + String dir3rec = p.getProperty("test.record.dir3.recorded"); + + if (dir3rec != null) { + fail(dir3rec); + } + + } + } + + public void testRecreate() { + if (supportsSymlinks) { + executeTarget("test-recreate"); + p = getProject(); + String link1Rem = p.getProperty("test.recreate.link1.not.removed"); + String link2Rem = p.getProperty("test.recreate.link2.not.removed"); + String link3Rem = p.getProperty("test.recreate.link3.not.removed"); + String dirlinkRem = p.getProperty("test.recreate.dirlink.not.removed"); + if (link1Rem != null) { + fail(link1Rem); + } + if (link2Rem != null) { + fail(link2Rem); + } + if (link3Rem != null) { + fail(link3Rem); + } + if (dirlinkRem != null) { + fail(dirlinkRem); + } + assertNotNull("Failed to recreate link1", + p.getProperty("test.recreate.link1.recreated")); + assertNotNull("Failed to recreate link2", + p.getProperty("test.recreate.link2.recreated")); + assertNotNull("Failed to recreate link3", + p.getProperty("test.recreate.link3.recreated")); + assertNotNull("Failed to recreate dirlink", + p.getProperty("test.recreate.dirlink.recreated")); + + String doubleRecreate = p.getProperty("test.recreate.dirlink2.recreated.twice"); + + if (doubleRecreate != null) { + fail(doubleRecreate); + } + + assertNotNull("Failed to alter dirlink3", + p.getProperty("test.recreate.dirlink3.was.altered")); + + } + } + + public void tearDown() { + if (supportsSymlinks) { + executeTarget("teardown"); + } + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java new file mode 100644 index 000000000..7891d0b94 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java @@ -0,0 +1,453 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.taskdefs.optional.vss; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Location; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Tstamp; +import org.apache.tools.ant.types.Commandline; +import org.apache.tools.ant.types.Path; + +/** + * Testcase to ensure that command line generation and required attributes are correct. + * + */ +public class MSVSSTest extends BuildFileTest implements MSVSSConstants { + + private Commandline commandline; + + private static final String VSS_SERVER_PATH = "\\\\server\\vss\\srcsafe.ini"; + private static final String VSS_PROJECT_PATH = "/SourceRoot/Project"; + private static final String DS_VSS_PROJECT_PATH = "$/SourceRoot/Project"; + private static final String VSS_USERNAME = "ant"; + private static final String VSS_PASSWORD = "rocks"; + private static final String LOCAL_PATH = "testdir"; + private static final String SRC_FILE = "Class1.java"; + private static final String SRC_LABEL = "label1"; + private static final String LONG_LABEL = "123456789012345678901234567890"; + private static final String SRC_COMMENT = "I fixed a bug"; + private static final String VERSION = "007"; + private static final String DATE = "00-00-00"; + private static final String DATE2 = "01-01-01"; + private static final String OUTPUT = "output.log"; + private static final String SS_DIR = "c:/winnt".replace('/', File.separatorChar); + + /** + * Constructor for the MSVSSTest object + * + * @param s Test name + */ + public MSVSSTest(String s) { + super(s); + } + + /** + * The JUnit setup method + * + * @throws Exception + */ + protected void setUp() + throws Exception { + project = new Project(); + project.setBasedir("."); + } + + /** + * The teardown method for JUnit + * + * @throws Exception + */ + protected void tearDown() + throws Exception { + File file = new File(project.getBaseDir(), LOCAL_PATH); + if (file.exists()) { + file.delete(); + } + } + + /** Tests VSSGet commandline generation. */ + public void testGetCommandLine() { + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_GET, DS_VSS_PROJECT_PATH, + MSVSS.FLAG_OVERRIDE_WORKING_DIR + project.getBaseDir().getAbsolutePath() + + File.separator + LOCAL_PATH, MSVSS.FLAG_AUTORESPONSE_DEF, + MSVSS.FLAG_RECURSION, MSVSS.FLAG_VERSION + VERSION, MSVSS.FLAG_LOGIN + + VSS_USERNAME + "," + VSS_PASSWORD, FLAG_FILETIME_UPDATED, FLAG_SKIP_WRITABLE}; + + // Set up a VSSGet task + MSVSSGET vssGet = new MSVSSGET(); + vssGet.setProject(project); + vssGet.setRecursive(true); + vssGet.setLocalpath(new Path(project, LOCAL_PATH)); + vssGet.setLogin(VSS_USERNAME + "," + VSS_PASSWORD); + vssGet.setVersion(VERSION); + vssGet.setQuiet(false); + vssGet.setDate(DATE); + vssGet.setLabel(SRC_LABEL); + vssGet.setVsspath(VSS_PROJECT_PATH); + MSVSS.CurrentModUpdated cmu = new MSVSS.CurrentModUpdated(); + cmu.setValue(TIME_UPDATED); + vssGet.setFileTimeStamp(cmu); + MSVSS.WritableFiles wf = new MSVSS.WritableFiles(); + wf.setValue(WRITABLE_SKIP); + vssGet.setWritableFiles(wf); + + commandline = vssGet.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Tests VSSGet required attributes. */ + public void testGetExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vssget.1", "some cause", "vsspath attribute must be set!"); + } + + /** Tests Label commandline generation. */ + public void testLabelCommandLine1() { + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_LABEL, DS_VSS_PROJECT_PATH, + MSVSS.FLAG_COMMENT + SRC_COMMENT, MSVSS.FLAG_AUTORESPONSE_YES, + MSVSS.FLAG_LABEL + SRC_LABEL, MSVSS.FLAG_VERSION + VERSION, MSVSS.FLAG_LOGIN + + VSS_USERNAME + "," + VSS_PASSWORD}; + + // Set up a VSSLabel task + MSVSSLABEL vssLabel = new MSVSSLABEL(); + vssLabel.setProject(project); + vssLabel.setComment(SRC_COMMENT); + vssLabel.setLogin(VSS_USERNAME + "," + VSS_PASSWORD); + vssLabel.setVersion(VERSION); + vssLabel.setAutoresponse("Y"); + vssLabel.setLabel(SRC_LABEL); + vssLabel.setVsspath(VSS_PROJECT_PATH); + + commandline = vssLabel.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Tests Label commandline generation with a label of more than 31 chars. */ + public void testLabelCommandLine2() { + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_LABEL, DS_VSS_PROJECT_PATH, + MSVSS.FLAG_COMMENT + SRC_COMMENT, MSVSS.FLAG_AUTORESPONSE_DEF, + MSVSS.FLAG_LABEL + LONG_LABEL, + MSVSS.FLAG_LOGIN + VSS_USERNAME + "," + VSS_PASSWORD}; + + // Set up a VSSLabel task + MSVSSLABEL vssLabel = new MSVSSLABEL(); + vssLabel.setProject(project); + vssLabel.setComment(SRC_COMMENT); + vssLabel.setLogin(VSS_USERNAME + "," + VSS_PASSWORD); + vssLabel.setLabel(LONG_LABEL + "blahblah"); + vssLabel.setVsspath(VSS_PROJECT_PATH); + + commandline = vssLabel.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** + * Test VSSLabel required attributes. + */ + public void testLabelExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vsslabel.1", "some cause", "vsspath attribute must be set!"); + expectSpecificBuildException("vsslabel.2", "some cause", "label attribute must be set!"); + } + + /** Tests VSSHistory commandline generation with from label. */ + public void testHistoryCommandLine1() { + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_HISTORY, DS_VSS_PROJECT_PATH, + MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_VERSION_LABEL + LONG_LABEL + + MSVSS.VALUE_FROMLABEL + SRC_LABEL, MSVSS.FLAG_LOGIN + VSS_USERNAME + + "," + VSS_PASSWORD, MSVSS.FLAG_OUTPUT + project.getBaseDir().getAbsolutePath() + + File.separator + OUTPUT}; + + // Set up a VSSHistory task + MSVSSHISTORY vssHistory = new MSVSSHISTORY(); + vssHistory.setProject(project); + + vssHistory.setLogin(VSS_USERNAME + "," + VSS_PASSWORD); + + vssHistory.setFromLabel(SRC_LABEL); + vssHistory.setToLabel(LONG_LABEL + "blahblah"); + vssHistory.setVsspath(VSS_PROJECT_PATH); + vssHistory.setRecursive(false); + vssHistory.setOutput(new File(project.getBaseDir().getAbsolutePath(), OUTPUT)); + + commandline = vssHistory.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Tests VSSHistory commandline generation with from date. */ + public void testHistoryCommandLine2() { + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_HISTORY, DS_VSS_PROJECT_PATH, + MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_VERSION_DATE + DATE + MSVSS.VALUE_FROMDATE + + DATE2, MSVSS.FLAG_RECURSION, MSVSS.FLAG_LOGIN + VSS_USERNAME + "," + VSS_PASSWORD}; + + // Set up a VSSHistory task + MSVSSHISTORY vssHistory = new MSVSSHISTORY(); + vssHistory.setProject(project); + vssHistory.setLogin(VSS_USERNAME + "," + VSS_PASSWORD); + vssHistory.setFromDate(DATE2); + vssHistory.setToDate(DATE); + vssHistory.setVsspath(VSS_PROJECT_PATH); + vssHistory.setRecursive(true); + + commandline = vssHistory.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** Tests VSSHistory commandline generation with date calculation. */ + public void testHistoryCommandLine3() { + // Set up a Timestamp + Tstamp tstamp = new Tstamp(); + Location location = new Location("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + tstamp.setLocation(location); + tstamp.setProject(project); + Tstamp.CustomFormat format = tstamp.createFormat(); + format.setProperty("today"); + format.setPattern("HH:mm:ss z"); + format.setTimezone("GMT"); + Date date = Calendar.getInstance().getTime(); + format.execute(project, date, location); + String today = project.getProperty("today"); + + // Get today's date + SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z"); + sdf.setTimeZone( TimeZone.getTimeZone("GMT") ); + String expected = sdf.format(date); + + // Set up a VSSHistory task + MSVSSHISTORY vssHistory = new MSVSSHISTORY(); + vssHistory.setProject(project); + vssHistory.setLogin(VSS_USERNAME); + vssHistory.setToDate(today); + vssHistory.setVsspath(VSS_PROJECT_PATH); + + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_HISTORY, DS_VSS_PROJECT_PATH, + MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_VERSION_DATE + expected, MSVSS.FLAG_LOGIN + VSS_USERNAME}; + + commandline = vssHistory.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** + * Tests VSSHistory required attributes. + */ + public void testHistoryExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vsshistory.1", "some cause", "vsspath attribute must be set!"); + } + + /** Tests CheckIn commandline generation. */ + public void testCheckinCommandLine() { + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_CHECKIN, DS_VSS_PROJECT_PATH, + MSVSS.FLAG_AUTORESPONSE_NO, MSVSS.FLAG_WRITABLE, MSVSS.FLAG_LOGIN + VSS_USERNAME, + MSVSS.FLAG_COMMENT + SRC_COMMENT}; + + // Set up a VSSCheckIn task + MSVSSCHECKIN vssCheckin = new MSVSSCHECKIN(); + vssCheckin.setProject(project); + vssCheckin.setComment(SRC_COMMENT); + vssCheckin.setLogin(VSS_USERNAME); + vssCheckin.setAutoresponse("N"); + vssCheckin.setVsspath(VSS_PROJECT_PATH); + vssCheckin.setWritable(true); + + commandline = vssCheckin.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** + * Test VSSCheckIn required attributes. + */ + public void testCheckinExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vsscheckin.1", "some cause", "vsspath attribute must be set!"); + } + + /** Tests CheckOut commandline generation. */ + public void testCheckoutCommandLine() { + String[] sTestCmdLine = {SS_DIR + File.separator + MSVSS.SS_EXE, MSVSS.COMMAND_CHECKOUT, + DS_VSS_PROJECT_PATH, MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_RECURSION, + MSVSS.FLAG_VERSION_DATE + DATE, MSVSS.FLAG_LOGIN + VSS_USERNAME, + FLAG_FILETIME_MODIFIED, FLAG_NO_GET}; + + // Set up a VSSCheckOut task + MSVSSCHECKOUT vssCheckout = new MSVSSCHECKOUT(); + vssCheckout.setProject(project); + vssCheckout.setLogin(VSS_USERNAME); + vssCheckout.setVsspath(DS_VSS_PROJECT_PATH); + vssCheckout.setRecursive(true); + vssCheckout.setDate(DATE); + vssCheckout.setLabel(SRC_LABEL); + vssCheckout.setSsdir(SS_DIR); + MSVSS.CurrentModUpdated cmu = new MSVSS.CurrentModUpdated(); + cmu.setValue(TIME_MODIFIED); + vssCheckout.setFileTimeStamp(cmu); + vssCheckout.setGetLocalCopy(false); + + commandline = vssCheckout.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** + * Test VSSCheckout required attributes. + */ + public void testCheckoutExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vsscheckout.1", "some cause", "vsspath attribute must be set!"); + expectSpecificBuildException("vsscheckout.2", "some cause", "blah is not a legal value for this attribute"); + } + + /** Tests Add commandline generation. */ + public void testAddCommandLine() { + String[] sTestCmdLine = {SS_DIR + File.separator + MSVSS.SS_EXE, MSVSS.COMMAND_ADD, + project.getBaseDir().getAbsolutePath() + File.separator + LOCAL_PATH, + MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_RECURSION, + MSVSS.FLAG_LOGIN + VSS_USERNAME + "," + VSS_PASSWORD, MSVSS.FLAG_COMMENT + "-"}; + + // Set up a VSSAdd task + MSVSSADD vssAdd = new MSVSSADD(); + vssAdd.setProject(project); + vssAdd.setLogin(VSS_USERNAME + "," + VSS_PASSWORD); + vssAdd.setVsspath(DS_VSS_PROJECT_PATH); + vssAdd.setRecursive(true); + vssAdd.setSsdir(SS_DIR); + vssAdd.setWritable(false); + vssAdd.setLocalpath(new Path(project, LOCAL_PATH)); + + commandline = vssAdd.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** + * Test VSSAdd required attributes. + */ + public void testAddExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vssadd.1", "some cause", "localPath attribute must be set!"); + } + + /** Tests CP commandline generation. */ + public void testCpCommandLine() { + String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_CP, + DS_VSS_PROJECT_PATH, MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_LOGIN + + VSS_USERNAME}; + + // Set up a VSSCp task + MSVSSCP vssCp = new MSVSSCP(); + vssCp.setProject(project); + vssCp.setLogin(VSS_USERNAME); + vssCp.setVsspath(DS_VSS_PROJECT_PATH); + + commandline = vssCp.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** + * Test VSSCP required attributes. + */ + public void testCpExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vsscp.1", "some cause", "vsspath attribute must be set!"); + } + + /** Tests Create commandline generation. */ + public void testCreateCommandLine() { + String[] sTestCmdLine = { MSVSS.SS_EXE, MSVSS.COMMAND_CREATE, + DS_VSS_PROJECT_PATH, MSVSS.FLAG_COMMENT + SRC_COMMENT, MSVSS.FLAG_AUTORESPONSE_NO, + MSVSS.FLAG_QUIET, MSVSS.FLAG_LOGIN + VSS_USERNAME}; + + // Set up a VSSCreate task + MSVSSCREATE vssCreate = new MSVSSCREATE(); + vssCreate.setProject(project); + vssCreate.setComment(SRC_COMMENT); + vssCreate.setLogin(VSS_USERNAME); + vssCreate.setVsspath(DS_VSS_PROJECT_PATH); + vssCreate.setFailOnError(true); + vssCreate.setAutoresponse("N"); + vssCreate.setQuiet(true); + + commandline = vssCreate.buildCmdLine(); + + checkCommandLines(sTestCmdLine, commandline.getCommandline()); + } + + /** + * Test VSSCreate required attributes. + */ + public void testCreateExceptions() { + configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml"); + expectSpecificBuildException("vsscreate.1", "some cause", "vsspath attribute must be set!"); + } + + /** + * Iterate through the generated command line comparing it to reference one. + * @param sTestCmdLine The reference command line; + * @param sGeneratedCmdLine The generated command line; + */ + private void checkCommandLines(String[] sTestCmdLine, String[] sGeneratedCmdLine) { + int testLength = sTestCmdLine.length; + int genLength = sGeneratedCmdLine.length; + + int genIndex = 0; + int testIndex = 0; + + while (testIndex < testLength) { + try { + if (sGeneratedCmdLine[genIndex] == "") { + genIndex++; + continue; + } + assertEquals("arg # " + testIndex, + sTestCmdLine[testIndex], + sGeneratedCmdLine[genIndex]); + testIndex++; + genIndex++; + } catch (ArrayIndexOutOfBoundsException aioob) { + fail("missing arg " + sTestCmdLine[testIndex]); + } + } + + // Count the number of empty strings + int cnt = 0; + for (int i = 0; i < genLength; i++) { + if (sGeneratedCmdLine[i] == "") { + cnt++; + } + } + if (genLength - cnt > sTestCmdLine.length) { + // We have extra elements + fail("extra args"); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/AbstractFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/AbstractFileSetTest.java new file mode 100644 index 000000000..63adb615a --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/AbstractFileSetTest.java @@ -0,0 +1,245 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; + +/** + * Base class for FileSetTest and DirSetTest. + * + *

This doesn't actually test much, mainly reference handling. + * + */ + +public abstract class AbstractFileSetTest extends TestCase { + + private Project project; + + public AbstractFileSetTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.setBasedir("."); + } + + protected abstract AbstractFileSet getInstance(); + + protected final Project getProject() { + return project; + } + + public final void testEmptyElementIfIsReference() { + AbstractFileSet f = getInstance(); + f.setIncludes("**/*.java"); + try { + f.setRefid(new Reference("dummyref")); + fail("Can add reference to " + + f.getDataTypeName() + + " with elements from setIncludes"); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute " + + "when using refid", be.getMessage()); + } + + f = getInstance(); + f.createPatternSet(); + try { + f.setRefid(new Reference("dummyref")); + fail("Can add reference to " + + f.getDataTypeName() + + " with nested patternset element."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when " + + "using refid", be.getMessage()); + } + + f = getInstance(); + f.createInclude(); + try { + f.setRefid(new Reference("dummyref")); + fail("Can add reference to " + + f.getDataTypeName() + + " with nested include element."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute " + + "when using refid", be.getMessage()); + } + + f = getInstance(); + f.setRefid(new Reference("dummyref")); + try { + f.setIncludes("**/*.java"); + fail("Can set includes in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute " + + "when using refid", be.getMessage()); + } + try { + f.setIncludesfile(new File("/a")); + fail("Can set includesfile in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute " + + "when using refid", be.getMessage()); + } + try { + f.setExcludes("**/*.java"); + fail("Can set excludes in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute " + + "when using refid", be.getMessage()); + } + try { + f.setExcludesfile(new File("/a")); + fail("Can set excludesfile in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute " + + "when using refid", be.getMessage()); + } + try { + f.setDir(project.resolveFile(".")); + fail("Can set dir in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute " + + "when using refid", be.getMessage()); + } + try { + f.createInclude(); + fail("Can add nested include in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using " + + "refid", be.getMessage()); + } + try { + f.createExclude(); + fail("Can add nested exclude in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using " + + "refid", be.getMessage()); + } + try { + f.createIncludesFile(); + fail("Can add nested includesfile in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using " + + "refid", be.getMessage()); + } + try { + f.createExcludesFile(); + fail("Can add nested excludesfile in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using " + + "refid", be.getMessage()); + } + try { + f.createPatternSet(); + fail("Can add nested patternset in " + + f.getDataTypeName() + + " that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using " + + "refid", be.getMessage()); + } + } + + public void testCircularReferenceCheck() { + AbstractFileSet f = getInstance(); + project.addReference("dummy", f); + f.setRefid(new Reference("dummy")); + try { + f.getDir(project); + fail("Can make " + f.getDataTypeName() + + " a Reference to itself."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + try { + f.getDirectoryScanner(project); + fail("Can make " + f.getDataTypeName() + + " a Reference to itself."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 --> dummy1 + AbstractFileSet f1 = getInstance(); + project.addReference("dummy1", f1); + f1.setRefid(new Reference("dummy2")); + AbstractFileSet f2 = getInstance(); + project.addReference("dummy2", f2); + f2.setRefid(new Reference("dummy3")); + AbstractFileSet f3 = getInstance(); + project.addReference("dummy3", f3); + f3.setRefid(new Reference("dummy1")); + try { + f1.getDir(project); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + try { + f1.getDirectoryScanner(project); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 + // (which has the Project's basedir as root). + f1 = getInstance(); + project.addReference("dummy1", f1); + f1.setRefid(new Reference("dummy2")); + f2 = getInstance(); + project.addReference("dummy2", f2); + f2.setRefid(new Reference("dummy3")); + f3 = getInstance(); + project.addReference("dummy3", f3); + f3.setDir(project.resolveFile(".")); + File dir = f1.getDir(project); + assertEquals("Dir is basedir", dir, project.getBaseDir()); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/AddTypeTest.java b/src/tests/junit/org/apache/tools/ant/types/AddTypeTest.java new file mode 100644 index 000000000..715cbc1be --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/AddTypeTest.java @@ -0,0 +1,186 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.taskdefs.condition.Condition; + +public class AddTypeTest extends BuildFileTest { + + public AddTypeTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/addtype.xml"); + } + + public void testAddPath() { + executeTarget("addpath"); + } + + public void testAddCondition() { + executeTarget("addcondition"); + } + + public void testAddFilter() { + executeTarget("addfilter"); + } + + public void testAddSelector() { + executeTarget("addselector"); + } + + public void testNestedA() { + expectLogContaining("nested.a", "add A called"); + } + + public void testNestedB() { + expectLogContaining("nested.b", "add B called"); + } + + public void testNestedC() { + expectLogContaining("nested.c", "add C called"); + } + + public void testNestedAB() { + expectBuildExceptionContaining( + "nested.ab", "Should have got ambiguous", "ambiguous"); + } + + public void testConditionType() { + expectLogContaining("condition.type", "beforeafter"); + } + + public void testConditionTask() { + expectLogContaining("condition.task", "My Condition execution"); + } + public void testConditionConditionType() { + expectLogContaining("condition.condition.type", "My Condition eval"); + } + public void testConditionConditionTask() { + expectBuildExceptionContaining( + "condition.condition.task", "task masking condition", + "doesn't support the nested"); + } + + public void testAddConfigured() { + expectLogContaining( + "myaddconfigured", "value is Value Setexecute: value is Value Set"); + } + + public void testAddConfiguredValue() { + expectLogContaining( + "myaddconfiguredvalue", + "value is Value Setexecute: value is Value Set"); + } + + public void testNamespace() { + executeTarget("namespacetest"); + } + + // The following will be used as types and tasks + + public static interface A {} + public static interface B {} + public static interface C extends A {} + public static interface AB extends A, B {} + + public static class AImpl implements A{} + public static class BImpl implements B{} + public static class CImpl implements C{} + public static class ABImpl implements AB{} + + public static class NestedContainer + extends Task + { + public void add(A el) { + log("add A called"); + } + public void add(B el) { + log("add B called"); + } + public void add(C el) { + log("add C called"); + } + } + + public static class MyCondition + implements Condition + { + Project project; + public void setProject(Project project) { + this.project = project; + } + public boolean eval() { + project.log("My Condition eval"); + return true; + } + public void execute() { + project.log("My Condition execution"); + } + } + + public static class MyValue + { + private String text = "NOT SET YET"; + public void addText(String text) { + this.text = text; + } + public String toString() { + return text; + } + } + + public static class MyAddConfigured + extends Task + { + MyValue value; + public void addConfigured(MyValue value) { + log("value is " + value); + this.value = value; + } + public void add(MyValue value) { + throw new BuildException("Should not be called"); + } + public void execute() { + log("execute: value is " + value); + } + } + + public static class MyAddConfiguredValue + extends Task + { + MyValue value; + public void addConfiguredValue(MyValue value) { + log("value is " + value); + this.value = value; + } + public void addValue(MyValue value) { + throw new BuildException("Should not be called"); + } + public void execute() { + log("execute: value is " + value); + } + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/AssertionsTest.java b/src/tests/junit/org/apache/tools/ant/types/AssertionsTest.java new file mode 100644 index 000000000..d83018485 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/AssertionsTest.java @@ -0,0 +1,102 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; + +/** + * test assertion handling + */ +public class AssertionsTest extends BuildFileTest { + + public AssertionsTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + configureProject("src/etc/testcases/types/assertions.xml"); + } + + protected void tearDown() throws Exception { + executeTarget("teardown"); + } + + /** + * runs a test and expects an assertion thrown in forked code + * @param target + */ + protected void expectAssertion(String target) { + expectBuildExceptionContaining(target, + "assertion not thrown in "+target, + "Java returned: 1"); + } + + public void testClassname() { + expectAssertion("test-classname"); + } + + public void testPackage() { + expectAssertion("test-package"); + } + + public void testEmptyAssertions() { + executeTarget("test-empty-assertions"); + } + + public void testDisable() { + executeTarget("test-disable"); + } + + public void testOverride() { + expectAssertion("test-override"); + } + + public void testOverride2() { + executeTarget("test-override2"); + } + public void testReferences() { + expectAssertion("test-references"); + } + + public void testMultipleAssertions() { + expectBuildExceptionContaining("test-multiple-assertions", + "multiple assertions rejected", + "Only one assertion declaration is allowed"); + } + + public void testReferenceAbuse() { + expectBuildExceptionContaining("test-reference-abuse", + "reference abuse rejected", + "You must not specify more than one attribute when using refid"); + } + + public void testNofork() { + if (AssertionsTest.class.desiredAssertionStatus()) { + return; // ran Ant tests with -ea and this would fail spuriously + } + expectLogContaining("test-nofork", + "Assertion statements are currently ignored in non-forked mode"); + } + + + public void testJunit() { + executeTarget("test-junit"); + } +} + + diff --git a/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java b/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java new file mode 100644 index 000000000..8f2ebfcc8 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java @@ -0,0 +1,186 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import junit.framework.TestCase; + +import org.apache.tools.ant.MagicNames; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.util.JavaEnvUtils; + +/** + * JUnit 3 testcases for org.apache.tools.ant.CommandlineJava + * + */ +public class CommandlineJavaTest extends TestCase { + + private String cloneVm; + + public CommandlineJavaTest(String name) { + super(name); + } + + private Project project; + + public void setUp() { + project = new Project(); + project.setBasedir(System.getProperty("root")); + project.setProperty("build.sysclasspath", "ignore"); + cloneVm = System.getProperty("ant.build.clonevm"); + if (cloneVm != null) { + System.setProperty("ant.build.clonevm", "false"); + } + } + + public void tearDown() { + if (cloneVm != null) { + System.setProperty("ant.build.clonevm", cloneVm); + } + } + + public void testGetCommandline() throws Exception { + CommandlineJava c = new CommandlineJava(); + c.createArgument().setValue("org.apache.tools.ant.CommandlineJavaTest"); + c.setClassname("junit.textui.TestRunner"); + c.createVmArgument().setValue("-Djava.compiler=NONE"); + String[] s = c.getCommandline(); + assertEquals("no classpath", 4, s.length); + /* + * After changing CommandlineJava to search for the java + * executable, I don't know, how to tests the value returned + * here without using the same logic as applied in the class + * itself. + * + * assertTrue("no classpath", "java", s[0]); + */ + assertEquals("no classpath", "-Djava.compiler=NONE", s[1]); + assertEquals("no classpath", "junit.textui.TestRunner", s[2]); + assertEquals("no classpath", + "org.apache.tools.ant.CommandlineJavaTest", s[3]); + try { + CommandlineJava c2 = (CommandlineJava) c.clone(); + } catch (NullPointerException ex) { + fail("cloning should work without classpath specified"); + } + + c.createClasspath(project).setLocation(project.resolveFile("build.xml")); + c.createClasspath(project).setLocation(project.resolveFile( + System.getProperty(MagicNames.ANT_HOME)+"/lib/ant.jar")); + s = c.getCommandline(); + assertEquals("with classpath", 6, s.length); + // assertEquals("with classpath", "java", s[0]); + assertEquals("with classpath", "-Djava.compiler=NONE", s[1]); + assertEquals("with classpath", "-classpath", s[2]); + assertTrue("build.xml contained", + s[3].indexOf("build.xml"+java.io.File.pathSeparator) >= 0); + assertTrue("ant.jar contained", s[3].endsWith("ant.jar")); + assertEquals("with classpath", "junit.textui.TestRunner", s[4]); + assertEquals("with classpath", + "org.apache.tools.ant.CommandlineJavaTest", s[5]); + } + + public void testJarOption() throws Exception { + CommandlineJava c = new CommandlineJava(); + c.createArgument().setValue("arg1"); + c.setJar("myfile.jar"); + c.createVmArgument().setValue("-classic"); + c.createVmArgument().setValue("-Dx=y"); + String[] s = c.getCommandline(); + assertEquals("-classic", s[1]); + assertEquals("-Dx=y", s[2]); + assertEquals("-jar", s[3]); + assertEquals("myfile.jar", s[4]); + assertEquals("arg1", s[5]); + } + + public void testSysproperties() { + String currentClasspath = System.getProperty("java.class.path"); + assertNotNull(currentClasspath); + assertNull(System.getProperty("key")); + CommandlineJava c = new CommandlineJava(); + Environment.Variable v = new Environment.Variable(); + v.setKey("key"); + v.setValue("value"); + c.addSysproperty(v); + + project.setProperty("key2", "value2"); + PropertySet ps = new PropertySet(); + ps.setProject(project); + ps.appendName("key2"); + c.addSyspropertyset(ps); + + try { + c.setSystemProperties(); + String newClasspath = System.getProperty("java.class.path"); + assertNotNull(newClasspath); + assertEquals(currentClasspath, newClasspath); + assertNotNull(System.getProperty("key")); + assertEquals("value", System.getProperty("key")); + assertTrue(System.getProperties().containsKey("java.class.path")); + assertNotNull(System.getProperty("key2")); + assertEquals("value2", System.getProperty("key2")); + } finally { + c.restoreSystemProperties(); + } + assertNull(System.getProperty("key")); + assertNull(System.getProperty("key2")); + } + + public void testAssertions() throws Exception { + if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_2) + || JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_3)) { + return; + } + + CommandlineJava c = new CommandlineJava(); + c.createArgument().setValue("org.apache.tools.ant.CommandlineJavaTest"); + c.setClassname("junit.textui.TestRunner"); + c.createVmArgument().setValue("-Djava.compiler=NONE"); + Assertions a = new Assertions(); + a.setProject(project); + Assertions.EnabledAssertion ea = new Assertions.EnabledAssertion(); + ea.setClass("junit.textui.TestRunner"); + a.addEnable(ea); + c.setAssertions(a); + + String[] expected = new String[] { + null, + "-Djava.compiler=NONE", + "-ea:junit.textui.TestRunner", + "junit.textui.TestRunner", + "org.apache.tools.ant.CommandlineJavaTest", + }; + + // only the second iteration would pass because of PR 27218 + for (int i = 0; i < 3; i++) { + String[] s = c.getCommandline(); + assertEquals(expected.length, s.length); + for (int j = 1; j < expected.length; j++) { + assertEquals(expected[j], s[j]); + } + } + CommandlineJava c2 = (CommandlineJava) c.clone(); + String[] s = c2.getCommandline(); + assertEquals(expected.length, s.length); + for (int j = 1; j < expected.length; j++) { + assertEquals(expected[j], s[j]); + } + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/CommandlineTest.java b/src/tests/junit/org/apache/tools/ant/types/CommandlineTest.java new file mode 100644 index 000000000..559c5f76d --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/CommandlineTest.java @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; + +/** + * JUnit 3 testcases for org.apache.tools.ant.CommandLine + * + */ +public class CommandlineTest extends TestCase { + + public CommandlineTest(String name) { + super(name); + } + + public void testTokenizer() { + String[] s = Commandline.translateCommandline("1 2 3"); + assertEquals("Simple case", 3, s.length); + for (int i=0; i<3; i++) { + assertEquals(""+(i+1), s[i]); + } + + s = Commandline.translateCommandline(""); + assertEquals("empty string", 0, s.length); + + s = Commandline.translateCommandline(null); + assertEquals("null", 0, s.length); + + s = Commandline.translateCommandline("1 \'2\' 3"); + assertEquals("Simple case with single quotes", 3, s.length); + assertEquals("Single quotes have been stripped", "2", s[1]); + + s = Commandline.translateCommandline("1 \"2\" 3"); + assertEquals("Simple case with double quotes", 3, s.length); + assertEquals("Double quotes have been stripped", "2", s[1]); + + s = Commandline.translateCommandline("1 \"2 3\" 4"); + assertEquals("Case with double quotes and whitespace", 3, s.length); + assertEquals("Double quotes stripped, space included", "2 3", s[1]); + + s = Commandline.translateCommandline("1 \"2\'3\" 4"); + assertEquals("Case with double quotes around single quote", 3, s.length); + assertEquals("Double quotes stripped, single quote included", "2\'3", + s[1]); + + s = Commandline.translateCommandline("1 \'2 3\' 4"); + assertEquals("Case with single quotes and whitespace", 3, s.length); + assertEquals("Single quotes stripped, space included", "2 3", s[1]); + + s = Commandline.translateCommandline("1 \'2\"3\' 4"); + assertEquals("Case with single quotes around double quote", 3, s.length); + assertEquals("Single quotes stripped, double quote included", "2\"3", + s[1]); + + // \ doesn't have a special meaning anymore - this is different from + // what the Unix sh does but causes a lot of problems on DOS + // based platforms otherwise + s = Commandline.translateCommandline("1 2\\ 3 4"); + assertEquals("case with quoted whitespace", 4, s.length); + assertEquals("backslash included", "2\\", s[1]); + + // "" should become a single empty argument, same for '' + // PR 5906 + s = Commandline.translateCommandline("\"\" a"); + assertEquals("Doublequoted null arg prepend", 2, s.length); + assertEquals("Doublequoted null arg prepend", "", s[0]); + assertEquals("Doublequoted null arg prepend", "a", s[1]); + s = Commandline.translateCommandline("a \"\""); + assertEquals("Doublequoted null arg append", 2, s.length); + assertEquals("Doublequoted null arg append", "a", s[0]); + assertEquals("Doublequoted null arg append", "", s[1]); + s = Commandline.translateCommandline("\"\""); + assertEquals("Doublequoted null arg", 1, s.length); + assertEquals("Doublequoted null arg", "", s[0]); + + s = Commandline.translateCommandline("\'\' a"); + assertEquals("Singlequoted null arg prepend", 2, s.length); + assertEquals("Singlequoted null arg prepend", "", s[0]); + assertEquals("Singlequoted null arg prepend", "a", s[1]); + s = Commandline.translateCommandline("a \'\'"); + assertEquals("Singlequoted null arg append", 2, s.length); + assertEquals("Singlequoted null arg append", "a", s[0]); + assertEquals("Singlequoted null arg append", "", s[1]); + s = Commandline.translateCommandline("\'\'"); + assertEquals("Singlequoted null arg", 1, s.length); + assertEquals("Singlequoted null arg", "", s[0]); + + // now to the expected failures + + try { + s = Commandline.translateCommandline("a \'b c"); + fail("unbalanced single quotes undetected"); + } catch (BuildException be) { + assertEquals("unbalanced quotes in a \'b c", be.getMessage()); + } + + try { + s = Commandline.translateCommandline("a \"b c"); + fail("unbalanced double quotes undetected"); + } catch (BuildException be) { + assertEquals("unbalanced quotes in a \"b c", be.getMessage()); + } + } + + public void testToString() { + assertEquals("", Commandline.toString(new String[0])); + assertEquals("", Commandline.toString(null)); + assertEquals("1 2 3", Commandline.toString(new String[] {"1", "2", "3"})); + assertEquals("1 \"2 3\"", Commandline.toString(new String[] {"1", "2 3"})); + assertEquals("1 \"2\'3\"", Commandline.toString(new String[] {"1", "2\'3"})); + assertEquals("1 \'2\"3\'", Commandline.toString(new String[] {"1", "2\"3"})); + } + + public void testAwkCommand(){ + Commandline c = new Commandline(); + c.setExecutable("awk"); + c.createArgument().setValue("'NR == 2 { print $NF }'"); + String[] s = c.getCommandline(); + assertNotNull(s); + assertEquals(2, s.length); + assertEquals("awk", s[0]); + assertEquals("'NR == 2 { print $NF }'", s[1]); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/DescriptionTest.java b/src/tests/junit/org/apache/tools/ant/types/DescriptionTest.java new file mode 100644 index 000000000..966465dc0 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/DescriptionTest.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; + +/** + * FilterSet testing + * + */ +public class DescriptionTest extends BuildFileTest { + + public DescriptionTest(String name) { + super(name); + } + + public void setUp() { + } + + public void tearDown() { + } + + public void test1() { + configureProject("src/etc/testcases/types/description1.xml"); + assertEquals("Single description failed", "Test Project Description", project.getDescription()); + } + + public void test2() { + configureProject("src/etc/testcases/types/description2.xml"); + assertEquals("Multi line description failed", "Multi Line\nProject Description", project.getDescription()); + } + + public void test3() { + configureProject("src/etc/testcases/types/description3.xml"); + assertEquals("Multi instance description failed", "Multi Instance Project Description", project.getDescription()); + } + + public void test4() { + configureProject("src/etc/testcases/types/description4.xml"); + assertEquals("Multi instance nested description failed", "Multi Instance Nested Project Description", project.getDescription()); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/DirSetTest.java b/src/tests/junit/org/apache/tools/ant/types/DirSetTest.java new file mode 100644 index 000000000..c17ef55cb --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/DirSetTest.java @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; +import java.io.FileOutputStream; +import org.apache.tools.ant.BuildException; + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.DirSet. + * + */ +public class DirSetTest extends AbstractFileSetTest { + + public DirSetTest(String name) { + super(name); + } + + protected AbstractFileSet getInstance() { + return new DirSet(); + } + + public void testFileSetIsNoDirSet() { + DirSet ds = (DirSet) getInstance(); + ds.setProject(getProject()); + FileSet fs = new FileSet(); + fs.setProject(getProject()); + getProject().addReference("dummy", fs); + ds.setRefid(new Reference(getProject(), "dummy")); + try { + ds.getDir(getProject()); + fail("DirSet created from FileSet reference"); + } catch (BuildException e) { + assertEquals("dummy doesn\'t denote a DirSet", e.getMessage()); + } + + ds = (DirSet) getInstance(); + ds.setProject(getProject()); + getProject().addReference("dummy2", ds); + fs.setRefid(new Reference(getProject(), "dummy2")); + try { + fs.getDir(getProject()); + fail("FileSet created from DirSet reference"); + } catch (BuildException e) { + assertEquals("dummy2 doesn\'t denote a FileSet", e.getMessage()); + } + } + + public void testToString() throws Exception { + File tmp = File.createTempFile("DirSetTest", ""); + tmp.delete(); + File a = new File(tmp, "a"); + a.mkdirs(); + File b = new File(tmp, "b"); + File bc = new File(b, "c"); + bc.mkdirs(); + new FileOutputStream(new File(a, "x")).close(); + new FileOutputStream(new File(b, "x")).close(); + new FileOutputStream(new File(bc, "x")).close(); + DirSet ds = new DirSet(); + ds.setProject(getProject()); + ds.setDir(tmp); + ds.setIncludes("b/"); + assertEquals("b;b" + File.separator + "c", ds.toString()); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/EnumeratedAttributeTest.java b/src/tests/junit/org/apache/tools/ant/types/EnumeratedAttributeTest.java new file mode 100644 index 000000000..246686a4b --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/EnumeratedAttributeTest.java @@ -0,0 +1,86 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; + +/** + * JUnit 3 testcases for org.apache.tools.ant.EnumeratedAttribute. + * + */ + +public class EnumeratedAttributeTest extends TestCase { + + private static String[] expected = {"a", "b", "c"}; + + public EnumeratedAttributeTest(String name) { + super(name); + } + + public void testContains() { + EnumeratedAttribute t1 = new TestNormal(); + for (int i=0; i dummy2 --> dummy3 --> dummy1 + FileList f1 = new FileList(); + project.addReference("dummy1", f1); + f1.setRefid(new Reference("dummy2")); + FileList f2 = new FileList(); + project.addReference("dummy2", f2); + f2.setRefid(new Reference("dummy3")); + FileList f3 = new FileList(); + project.addReference("dummy3", f3); + f3.setRefid(new Reference("dummy1")); + try { + f1.getDir(project); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + try { + f1.getFiles(project); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 + // (which has the Project's basedir as root). + f1 = new FileList(); + project.addReference("dummy1", f1); + f1.setRefid(new Reference("dummy2")); + f2 = new FileList(); + project.addReference("dummy2", f2); + f2.setRefid(new Reference("dummy3")); + f3 = new FileList(); + project.addReference("dummy3", f3); + f3.setDir(project.resolveFile(".")); + File dir = f1.getDir(project); + assertEquals("Dir is basedir", dir, project.getBaseDir()); + } + + public void testSimple() { + expectLog("simple", "/abc/a"); + } + + public void testDouble() { + expectLog("double", "/abc/a:/abc/b"); + } + + public void testNested() { + expectLog("nested", "/abc/a:/abc/b"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/FileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/FileSetTest.java new file mode 100644 index 000000000..359598690 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/FileSetTest.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.FileSet. + * + *

This doesn't actually test much, mainly reference handling. + * + */ + +public class FileSetTest extends AbstractFileSetTest { + + public FileSetTest(String name) { + super(name); + } + + protected AbstractFileSet getInstance() { + return new FileSet(); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/FilterSetTest.java b/src/tests/junit/org/apache/tools/ant/types/FilterSetTest.java new file mode 100644 index 000000000..4f014285f --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/FilterSetTest.java @@ -0,0 +1,221 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Hashtable; + +import org.apache.tools.ant.BuildFileTest; + +/** + * FilterSet testing + * + */ +public class FilterSetTest extends BuildFileTest { + + static private final int BUF_SIZE = 32768; + + public FilterSetTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/filterset.xml"); + } + + public void tearDown() { + executeTarget("cleanup"); + } + + public void test1() { + executeTarget("test1"); + assertTrue("Filterset 1 failed", compareFiles("src/etc/testcases/types/gold/filterset1.txt", + "src/etc/testcases/types/dest1.txt")); + } + + public void test2() { + executeTarget("test2"); + assertTrue("Filterset 2 failed", compareFiles("src/etc/testcases/types/gold/filterset2.txt", + "src/etc/testcases/types/dest2.txt")); + } + + public void test3() { + executeTarget("test3"); + assertTrue("Filterset 3 failed", compareFiles("src/etc/testcases/types/gold/filterset3.txt", + "src/etc/testcases/types/dest3.txt")); + } + + /** + * This will test the recursive FilterSet. Which means that if + * the filter value @test@ contains another filter value, it will + * actually resolve. + */ + public void testRecursive() { + String result = "it works line"; + String line="@test@ line"; + FilterSet fs = new FilterSet(); + fs.addFilter("test", "@test1@"); + fs.addFilter("test1","@test2@"); + fs.addFilter("test2", "it works"); + fs.setBeginToken("@"); + fs.setEndToken("@"); + assertEquals(result, fs.replaceTokens(line)); + } + + /** + * Test to see what happens when the resolving occurs in an + * infinite loop. + */ + public void testInfinite() { + String result = "@test@ line testvalue"; + String line = "@test@ line @test3@"; + FilterSet fs = new FilterSet(); + fs.addFilter("test", "@test1@"); + fs.addFilter("test1","@test2@"); + fs.addFilter("test2", "@test@"); + fs.addFilter("test3", "testvalue"); + fs.setBeginToken("@"); + fs.setEndToken("@"); + assertEquals(result, fs.replaceTokens(line)); + } + + /** + * Test to see what happens when the resolving occurs in + * what would be an infinite loop, but with recursion disabled. + */ + public void testRecursionDisabled() { + String result = "@test1@ line testvalue"; + String line = "@test@ line @test2@"; + FilterSet fs = new FilterSet(); + fs.addFilter("test", "@test1@"); + fs.addFilter("test1","@test@"); + fs.addFilter("test2", "testvalue"); + fs.setBeginToken("@"); + fs.setEndToken("@"); + fs.setRecurse(false); + assertEquals(result, fs.replaceTokens(line)); + } + + public void testNonInfiniteRecursiveMultipleOnSingleLine() { + FilterSet filters = new FilterSet(); + + filters.setBeginToken("<"); + filters.setEndToken(">"); + + filters.addFilter("ul", ""); + filters.addFilter("/ul", ""); + filters.addFilter("li", ""); + filters.addFilter("/li", ""); + + String result = "Item 1 Item 2"; + String line = "

  • Item 1
  • Item 2
"; + + assertEquals(result, filters.replaceTokens(line)); + } + + public void testNestedFilterSets() { + executeTarget("test-nested-filtersets"); + + FilterSet fs = (FilterSet) getProject().getReference("1"); + Hashtable filters = fs.getFilterHash(); + assertEquals(1, filters.size()); + assertEquals("value1", filters.get("token1")); + + fs = (FilterSet) getProject().getReference("2"); + filters = fs.getFilterHash(); + assertEquals(2, filters.size()); + assertEquals("1111", filters.get("aaaa")); + assertEquals("2222", filters.get("bbbb")); + + fs = (FilterSet) getProject().getReference("3"); + filters = fs.getFilterHash(); + assertEquals(1, filters.size()); + assertEquals("value4", filters.get("token4")); + + fs = (FilterSet) getProject().getReference("5"); + filters = fs.getFilterHash(); + assertEquals(1, filters.size()); + assertEquals("value1", filters.get("token1")); + } + + public void testFiltersFileElement() { + executeTarget("testFiltersFileElement"); + } + + public void testFiltersFileAttribute() { + executeTarget("testFiltersFileAttribute"); + } + + public void testMultipleFiltersFiles() { + executeTarget("testMultipleFiltersFiles"); + } + + public void testMissingFiltersFile() { + expectBuildException("testMissingFiltersFile", + "should fail due to missing filtersfile"); + } + + public void testAllowMissingFiltersFile() { + executeTarget("testAllowMissingFiltersFile"); + } + + private boolean compareFiles(String name1, String name2) { + File file1 = new File(System.getProperty("root"), name1); + File file2 = new File(System.getProperty("root"), name2); + + try { + if (!file1.exists() || !file2.exists()) { + System.out.println("One or both files do not exist:" + name1 + ", " + name2); + return false; + } + + if (file1.length() != file2.length()) { + System.out.println("File size mismatch:" + name1 + "(" + file1.length() + "), " + + name2 + "(" + file2.length() + ")"); + return false; + } + + // byte - byte compare + byte[] buffer1 = new byte[BUF_SIZE]; + byte[] buffer2 = new byte[BUF_SIZE]; + + FileInputStream fis1 = new FileInputStream(file1); + FileInputStream fis2 = new FileInputStream(file2); + int index = 0; + int read = 0; + while ((read = fis1.read(buffer1)) != -1) { + fis2.read(buffer2); + for (int i = 0; i < read; ++i, ++index) { + if (buffer1[i] != buffer2[i]) { + System.out.println("Bytes mismatch:" + name1 + ", " + name2 + + " at byte " + index); + return false; + } + } + } + return true; + } + catch (IOException e) { + System.out.println("IOException comparing files: " + name1 + ", " + name2); + return false; + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java b/src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java new file mode 100644 index 000000000..d618b7692 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java @@ -0,0 +1,73 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.BuildException; + +public class FlexIntegerTest extends BuildFileTest { + + public FlexIntegerTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/flexinteger.xml"); + } + + public void testFlexInteger() { + executeTarget("test"); + assertEquals(project.getProperty("flexint.value1"), "10"); + assertEquals(project.getProperty("flexint.value2"), "8"); + } + + // This class acts as a custom Ant task also + // and uses these variables/methods in that mode + private Project taskProject; + String propName; + private FlexInteger value; + + /** + * To make taskdef happy + */ + public FlexIntegerTest() { + super("FlexIntegerTest"); + } + + public void setPropName(String propName) { + this.propName = propName; + } + + public void setValue(FlexInteger value) { + this.value = value; + } + + public void setProject(Project project) { + taskProject = project; + } + + public void execute() { + if (propName == null || value == null) { + throw new BuildException("name and value required"); + } + + taskProject.setNewProperty(propName, value.toString()); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/MapperTest.java b/src/tests/junit/org/apache/tools/ant/types/MapperTest.java new file mode 100644 index 000000000..6770c7826 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/MapperTest.java @@ -0,0 +1,246 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.util.Arrays; +import java.util.List; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.util.ChainedMapper; +import org.apache.tools.ant.util.FileNameMapper; +import org.apache.tools.ant.util.FlatFileNameMapper; +import org.apache.tools.ant.util.GlobPatternMapper; +import org.apache.tools.ant.util.MergingMapper; + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.Mapper. + * + */ + +public class MapperTest extends TestCase { + + private Project project; + + public MapperTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.setBasedir("."); + } + + public void testEmptyElementIfIsReference() { + Mapper m = new Mapper(project); + m.setFrom("*.java"); + try { + m.setRefid(new Reference("dummyref")); + fail("Can add reference to Mapper with from attribute set"); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + m = new Mapper(project); + m.setRefid(new Reference("dummyref")); + try { + m.setFrom("*.java"); + fail("Can set from in Mapper that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + m = new Mapper(project); + m.setRefid(new Reference("dummyref")); + try { + m.setTo("*.java"); + fail("Can set to in Mapper that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + try { + Mapper.MapperType mt = new Mapper.MapperType(); + mt.setValue("glob"); + m.setType(mt); + fail("Can set type in Mapper that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + } + + public void testCircularReferenceCheck() { + Mapper m = new Mapper(project); + project.addReference("dummy", m); + m.setRefid(new Reference("dummy")); + try { + m.getImplementation(); + fail("Can make Mapper a Reference to itself."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 --> dummy1 + Mapper m1 = new Mapper(project); + project.addReference("dummy1", m1); + m1.setRefid(new Reference("dummy2")); + Mapper m2 = new Mapper(project); + project.addReference("dummy2", m2); + m2.setRefid(new Reference("dummy3")); + Mapper m3 = new Mapper(project); + project.addReference("dummy3", m3); + m3.setRefid(new Reference("dummy1")); + try { + m1.getImplementation(); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 + // (which holds a glob mapper from "*.java" to "*.class" + m1 = new Mapper(project); + project.addReference("dummy1", m1); + m1.setRefid(new Reference("dummy2")); + m2 = new Mapper(project); + project.addReference("dummy2", m2); + m2.setRefid(new Reference("dummy3")); + m3 = new Mapper(project); + project.addReference("dummy3", m3); + Mapper.MapperType mt = new Mapper.MapperType(); + mt.setValue("glob"); + m3.setType(mt); + m3.setFrom("*.java"); + m3.setTo("*.class"); + FileNameMapper fmm = m1.getImplementation(); + assertTrue("should be glob", fmm instanceof GlobPatternMapper); + String[] result = fmm.mapFileName("a.java"); + assertEquals("a.java should match", 1, result.length); + assertEquals("a.class", result[0]); + } + + public void testNested() { + Mapper mapper1 = new Mapper(project); + Mapper.MapperType mt = new Mapper.MapperType(); + mt.setValue("glob"); + mapper1.setType(mt); + mapper1.setFrom("from*"); + mapper1.setTo("to*"); + + //mix element types + FileNameMapper mapper2 = new FlatFileNameMapper(); + FileNameMapper mapper3 = new MergingMapper(); + mapper3.setTo("mergefile"); + + Mapper container = new Mapper(project); + container.addConfiguredMapper(mapper1); + container.add(mapper2); + container.add(mapper3); + + FileNameMapper fileNameMapper = container.getImplementation(); + String[] targets = fileNameMapper.mapFileName("fromfilename"); + assertNotNull("no filenames mapped", targets); + assertEquals("wrong number of filenames mapped", 3, targets.length); + List list = Arrays.asList(targets); + assertTrue("cannot find expected target \"tofilename\"", + list.contains("tofilename")); + assertTrue("cannot find expected target \"fromfilename\"", + list.contains("fromfilename")); + assertTrue("cannot find expected target \"mergefile\"", + list.contains("mergefile")); + } + + public void testChained() { + + // a --> b --> c --- def + // \-- ghi + + FileNameMapper mapperAB = new GlobPatternMapper(); + mapperAB.setFrom("a"); + mapperAB.setTo("b"); + + FileNameMapper mapperBC = new GlobPatternMapper(); + mapperBC.setFrom("b"); + mapperBC.setTo("c"); + + //implicit composite + Mapper mapperCX = new Mapper(project); + + FileNameMapper mapperDEF = new GlobPatternMapper(); + mapperDEF.setFrom("c"); + mapperDEF.setTo("def"); + + FileNameMapper mapperGHI = new GlobPatternMapper(); + mapperGHI.setFrom("c"); + mapperGHI.setTo("ghi"); + + mapperCX.add(mapperDEF); + mapperCX.add(mapperGHI); + + Mapper chained = new Mapper(project); + chained.setClassname(ChainedMapper.class.getName()); + chained.add(mapperAB); + chained.add(mapperBC); + chained.addConfiguredMapper(mapperCX); + + FileNameMapper fileNameMapper = chained.getImplementation(); + String[] targets = fileNameMapper.mapFileName("a"); + assertNotNull("no filenames mapped", targets); + assertEquals("wrong number of filenames mapped", 2, targets.length); + List list = Arrays.asList(targets); + assertTrue("cannot find expected target \"def\"", list.contains("def")); + assertTrue("cannot find expected target \"ghi\"", list.contains("ghi")); + } + + public void testCopyTaskWithTwoFilesets() { + TaskdefForCopyTest t = new TaskdefForCopyTest("test1"); + try { + t.setUp(); + t.test1(); + } finally { + t.tearDown(); + } + } + + private class TaskdefForCopyTest extends BuildFileTest { + TaskdefForCopyTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/mapper.xml"); + } + + public void tearDown() { + executeTarget("cleanup"); + } + + public void test1() { + executeTarget("test1"); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/PathTest.java b/src/tests/junit/org/apache/tools/ant/types/PathTest.java new file mode 100644 index 000000000..25fd99349 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/PathTest.java @@ -0,0 +1,552 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; +import java.util.Locale; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.condition.Os; + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.Path + * + */ + +public class PathTest extends TestCase { + + public static boolean isUnixStyle = File.pathSeparatorChar == ':'; + public static boolean isNetWare = Os.isFamily("netware"); + + private Project project; + + public PathTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.setBasedir(System.getProperty("root")); + } + + // actually tests constructor as well as setPath + public void testConstructorUnixStyle() { + Path p = new Path(project, "/a:/b"); + String[] l = p.list(); + assertEquals("two items, Unix style", 2, l.length); + if (isUnixStyle) { + assertEquals("/a", l[0]); + assertEquals("/b", l[1]); + } else if (isNetWare) { + assertEquals("\\a", l[0]); + assertEquals("\\b", l[1]); + } else { + String base = new File(File.separator).getAbsolutePath().toUpperCase(); + assertEquals(base + "a", l[0]); + assertEquals(base + "b", l[1]); + } + } + + public void testRelativePathUnixStyle() { + project.setBasedir(new File(System.getProperty("root"), "src/etc").getAbsolutePath()); + Path p = new Path(project, "..:testcases"); + String[] l = p.list(); + assertEquals("two items, Unix style", 2, l.length); + if (isUnixStyle) { + assertTrue("test resolved relative to src/etc", + l[0].endsWith("/src")); + assertTrue("test resolved relative to src/etc", + l[1].endsWith("/src/etc/testcases")); + } else if (isNetWare) { + assertTrue("test resolved relative to src/etc", + l[0].endsWith("\\src")); + assertTrue("test resolved relative to src/etc", + l[1].endsWith("\\src\\etc\\testcases")); + } else { + assertTrue("test resolved relative to src/etc", + l[0].endsWith("\\src")); + assertTrue("test resolved relative to src/etc", + l[1].endsWith("\\src\\etc\\testcases")); + } + } + + public void testConstructorWindowsStyle() { + Path p = new Path(project, "\\a;\\b"); + String[] l = p.list(); + assertEquals("two items, DOS style", 2, l.length); + if (isUnixStyle) { + assertEquals("/a", l[0]); + assertEquals("/b", l[1]); + } else if (isNetWare) { + assertEquals("\\a", l[0]); + assertEquals("\\b", l[1]); + } else { + String base = new File(File.separator).getAbsolutePath().toUpperCase(); + assertEquals(base + "a", l[0]); + assertEquals(base + "b", l[1]); + } + + p = new Path(project, "c:\\test"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 2, l.length); + assertTrue("c resolved relative to project\'s basedir", + l[0].endsWith("/c")); + assertEquals("/test", l[1]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 1, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + } else { + assertEquals("drives on DOS", 1, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + } + + p = new Path(project, "c:\\test;d:\\programs"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 4, l.length); + assertTrue("c resolved relative to project\'s basedir", + l[0].endsWith("/c")); + assertEquals("/test", l[1]); + assertTrue("d resolved relative to project\'s basedir", + l[2].endsWith("/d")); + assertEquals("/programs", l[3]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 2, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + assertEquals("d:\\programs", l[1].toLowerCase(Locale.US)); + } else { + assertEquals("drives on DOS", 2, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + assertEquals("d:\\programs", l[1].toLowerCase(Locale.US)); + } + + p = new Path(project, "c:/test"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 2, l.length); + assertTrue("c resolved relative to project\'s basedir", + l[0].endsWith("/c")); + assertEquals("/test", l[1]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 1, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + } else { + assertEquals("drives on DOS", 1, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + } + + p = new Path(project, "c:/test;d:/programs"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 4, l.length); + assertTrue("c resolved relative to project\'s basedir", + l[0].endsWith("/c")); + assertEquals("/test", l[1]); + assertTrue("d resolved relative to project\'s basedir", + l[2].endsWith("/d")); + assertEquals("/programs", l[3]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 2, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + assertEquals("d:\\programs", l[1].toLowerCase(Locale.US)); + } else { + assertEquals("drives on DOS", 2, l.length); + assertEquals("c:\\test", l[0].toLowerCase(Locale.US)); + assertEquals("d:\\programs", l[1].toLowerCase(Locale.US)); + } + } + + public void testConstructorNetWareStyle() { + // try a netware-volume length path, see how it is handled + Path p = new Path(project, "sys:\\test"); + String[] l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 2, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("/sys")); + assertEquals("/test", l[1]); + } else if (isNetWare) { + assertEquals("sys:\\test", l[0].toLowerCase(Locale.US)); + assertEquals("volumes on NetWare", 1, l.length); + } else { + assertEquals("no multiple character-length volumes on Windows", 2, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("\\sys")); + assertTrue("test resolved relative to project\'s basedir", + l[1].endsWith("\\test")); + } + + // try a multi-part netware-volume length path, see how it is handled + p = new Path(project, "sys:\\test;dev:\\temp"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 4, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("/sys")); + assertEquals("/test", l[1]); + assertTrue("dev resolved relative to project\'s basedir", + l[2].endsWith("/dev")); + assertEquals("/temp", l[3]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 2, l.length); + assertEquals("sys:\\test", l[0].toLowerCase(Locale.US)); + assertEquals("dev:\\temp", l[1].toLowerCase(Locale.US)); + } else { + assertEquals("no multiple character-length volumes on Windows", 4, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("\\sys")); + assertTrue("test resolved relative to project\'s basedir", + l[1].endsWith("\\test")); + assertTrue("dev resolved relative to project\'s basedir", + l[2].endsWith("\\dev")); + assertTrue("temp resolved relative to project\'s basedir", + l[3].endsWith("\\temp")); + } + + // try a netware-volume length path w/forward slash, see how it is handled + p = new Path(project, "sys:/test"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 2, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("/sys")); + assertEquals("/test", l[1]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 1, l.length); + assertEquals("sys:\\test", l[0].toLowerCase(Locale.US)); + } else { + assertEquals("no multiple character-length volumes on Windows", 2, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("\\sys")); + assertTrue("test resolved relative to project\'s basedir", + l[1].endsWith("\\test")); + } + + // try a multi-part netware-volume length path w/forward slash, see how it is handled + p = new Path(project, "sys:/test;dev:/temp"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 4, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("/sys")); + assertEquals("/test", l[1]); + assertTrue("dev resolved relative to project\'s basedir", + l[2].endsWith("/dev")); + assertEquals("/temp", l[3]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 2, l.length); + assertEquals("sys:\\test", l[0].toLowerCase(Locale.US)); + assertEquals("dev:\\temp", l[1].toLowerCase(Locale.US)); + } else { + assertEquals("no multiple character-length volumes on Windows", 4, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("\\sys")); + assertTrue("test resolved relative to project\'s basedir", + l[1].endsWith("\\test")); + assertTrue("dev resolved relative to project\'s basedir", + l[2].endsWith("\\dev")); + assertTrue("temp resolved relative to project\'s basedir", + l[3].endsWith("\\temp")); + } + + // try a multi-part netware-volume length path with UNIX + // separator (this testcase if from an actual bug that was + // found, in AvailableTest, which uses PathTokenizer) + p = new Path(project, + "SYS:\\JAVA/lib/rt.jar:SYS:\\JAVA/lib/classes.zip"); + l = p.list(); + if (isUnixStyle) { + assertEquals("no drives on Unix", 3, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("/SYS")); + assertEquals("/JAVA/lib/rt.jar", l[1]); + assertEquals("/JAVA/lib/classes.zip", l[2]); + } else if (isNetWare) { + assertEquals("volumes on NetWare", 2, l.length); + assertEquals("sys:\\java\\lib\\rt.jar", l[0].toLowerCase(Locale.US)); + assertEquals("sys:\\java\\lib\\classes.zip", l[1].toLowerCase(Locale.US)); + } else { + assertEquals("no multiple character-length volumes on Windows", 3, l.length); + assertTrue("sys resolved relative to project\'s basedir", + l[0].endsWith("\\SYS")); + assertTrue("java/lib/rt.jar resolved relative to project\'s basedir", + l[1].endsWith("\\JAVA\\lib\\rt.jar")); + assertTrue("java/lib/classes.zip resolved relative to project\'s basedir", + l[2].endsWith("\\JAVA\\lib\\classes.zip")); + } + } + + public void testConstructorMixedStyle() { + Path p = new Path(project, "\\a;\\b:/c"); + String[] l = p.list(); + assertEquals("three items, mixed style", 3, l.length); + if (isUnixStyle) { + assertEquals("/a", l[0]); + assertEquals("/b", l[1]); + assertEquals("/c", l[2]); + } else if (isNetWare) { + assertEquals("\\a", l[0]); + assertEquals("\\b", l[1]); + assertEquals("\\c", l[2]); + } else { + String base = new File(File.separator).getAbsolutePath().toUpperCase(); + assertEquals(base + "a", l[0]); + assertEquals(base + "b", l[1]); + assertEquals(base + "c", l[2]); + } + } + + public void testSetLocation() { + Path p = new Path(project); + p.setLocation(new File(File.separatorChar+"a")); + String[] l = p.list(); + if (isUnixStyle) { + assertEquals(1, l.length); + assertEquals("/a", l[0]); + } else if (isNetWare) { + assertEquals(1, l.length); + assertEquals("\\a", l[0]); + } else { + assertEquals(1, l.length); + assertEquals(":\\a", l[0].substring(1)); + } + } + + public void testAppending() { + Path p = new Path(project, "/a:/b"); + String[] l = p.list(); + assertEquals("2 after construction", 2, l.length); + p.setLocation(new File("/c")); + l = p.list(); + assertEquals("3 after setLocation", 3, l.length); + p.setPath("\\d;\\e"); + l = p.list(); + assertEquals("5 after setPath", 5, l.length); + p.append(new Path(project, "\\f")); + l = p.list(); + assertEquals("6 after append", 6, l.length); + p.createPath().setLocation(new File("/g")); + l = p.list(); + assertEquals("7 after append", 7, l.length); + } + + public void testEmpyPath() { + Path p = new Path(project, ""); + String[] l = p.list(); + assertEquals("0 after construction", 0, l.length); + p.setPath(""); + l = p.list(); + assertEquals("0 after setPath", 0, l.length); + p.append(new Path(project)); + l = p.list(); + assertEquals("0 after append", 0, l.length); + p.createPath(); + l = p.list(); + assertEquals("0 after append", 0, l.length); + } + + public void testUnique() { + Path p = new Path(project, "/a:/a"); + String[] l = p.list(); + assertEquals("1 after construction", 1, l.length); + String base = new File(File.separator).getAbsolutePath().toUpperCase(); + p.setLocation(new File(base, "a")); + l = p.list(); + assertEquals("1 after setLocation", 1, l.length); + p.setPath("\\a;/a"); + l = p.list(); + assertEquals("1 after setPath", 1, l.length); + p.append(new Path(project, "/a;\\a:\\a")); + l = p.list(); + assertEquals("1 after append", 1, l.length); + p.createPath().setPath("\\a:/a"); + l = p.list(); + assertEquals("1 after append", 1, l.length); + } + + public void testEmptyElementIfIsReference() { + Path p = new Path(project, "/a:/a"); + try { + p.setRefid(new Reference("dummyref")); + fail("Can add reference to Path with elements from constructor"); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + p = new Path(project); + p.setLocation(new File("/a")); + try { + p.setRefid(new Reference("dummyref")); + fail("Can add reference to Path with elements from setLocation"); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + Path another = new Path(project, "/a:/a"); + project.addReference("dummyref", another); + p = new Path(project); + p.setRefid(new Reference("dummyref")); + try { + p.setLocation(new File("/a")); + fail("Can set location in Path that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + try { + p.setPath("/a;\\a"); + fail("Can set path in Path that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + try { + p.createPath(); + fail("Can create nested Path in Path that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + + try { + p.createPathElement(); + fail("Can create nested PathElement in Path that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + + try { + p.addFileset(new FileSet()); + fail("Can add nested FileSet in Path that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + + try { + p.addFilelist(new FileList()); + fail("Can add nested FileList in Path that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + + try { + p.addDirset(new DirSet()); + fail("Can add nested Dirset in Path that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + } + + public void testCircularReferenceCheck() { + Path p = new Path(project); + project.addReference("dummy", p); + p.setRefid(new Reference("dummy")); + try { + p.list(); + fail("Can make Path a Reference to itself."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 --> dummy1 + Path p1 = new Path(project); + project.addReference("dummy1", p1); + Path p2 = p1.createPath(); + project.addReference("dummy2", p2); + Path p3 = p2.createPath(); + project.addReference("dummy3", p3); + p3.setRefid(new Reference("dummy1")); + try { + p1.list(); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 (with Path "/a") + p1 = new Path(project); + project.addReference("dummy1", p1); + p2 = p1.createPath(); + project.addReference("dummy2", p2); + p3 = p2.createPath(); + project.addReference("dummy3", p3); + p3.setLocation(new File("/a")); + String[] l = p1.list(); + assertEquals("One element buried deep inside a nested path structure", + 1, l.length); + if (isUnixStyle) { + assertEquals("/a", l[0]); + } else if (isNetWare) { + assertEquals("\\a", l[0]); + } else { + assertEquals(":\\a", l[0].substring(1)); + } + } + + public void testFileList() { + Path p = new Path(project); + FileList f = new FileList(); + f.setProject(project); + f.setDir(project.resolveFile(".")); + f.setFiles("build.xml"); + p.addFilelist(f); + String[] l = p.list(); + assertEquals(1, l.length); + assertEquals(project.resolveFile("build.xml").getAbsolutePath(), l[0]); + } + + public void testFileSet() { + Path p = new Path(project); + FileSet f = new FileSet(); + f.setProject(project); + f.setDir(project.resolveFile(".")); + f.setIncludes("build.xml"); + p.addFileset(f); + String[] l = p.list(); + assertEquals(1, l.length); + assertEquals(project.resolveFile("build.xml").getAbsolutePath(), l[0]); + } + + public void testDirSet() { + Path p = new Path(project); + DirSet d = new DirSet(); + d.setProject(project); + d.setDir(project.resolveFile(".")); + d.setIncludes("build"); + p.addDirset(d); + String[] l = p.list(); + assertEquals(1, l.length); + assertEquals(project.resolveFile("build").getAbsolutePath(), l[0]); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/PatternSetTest.java b/src/tests/junit/org/apache/tools/ant/types/PatternSetTest.java new file mode 100644 index 000000000..45cda7d4e --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/PatternSetTest.java @@ -0,0 +1,203 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.PatternSet. + * + *

This doesn't actually test much, mainly reference handling.

+ * + */ + +public class PatternSetTest extends TestCase { + + private Project project; + + public PatternSetTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.setBasedir("."); + } + + public void testEmptyElementIfIsReference() { + PatternSet p = new PatternSet(); + p.setIncludes("**/*.java"); + try { + p.setRefid(new Reference("dummyref")); + fail("Can add reference to PatternSet with elements from setIncludes"); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + p = new PatternSet(); + p.setRefid(new Reference("dummyref")); + try { + p.setIncludes("**/*.java"); + fail("Can set includes in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + + p = new PatternSet(); + p.setRefid(new Reference("dummyref")); + try { + p.setIncludesfile(new File("/a")); + fail("Can set includesfile in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + try { + p.setExcludes("**/*.java"); + fail("Can set excludes in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + try { + p.setExcludesfile(new File("/a")); + fail("Can set excludesfile in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify more than one attribute when using refid", + be.getMessage()); + } + try { + p.createInclude(); + fail("Can add nested include in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + try { + p.createExclude(); + fail("Can add nested exclude in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + try { + p.createIncludesFile(); + fail("Can add nested includesfile in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + try { + p.createExcludesFile(); + fail("Can add nested excludesfile in PatternSet that is a reference."); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + } + + public void testCircularReferenceCheck() { + PatternSet p = new PatternSet(); + project.addReference("dummy", p); + p.setRefid(new Reference("dummy")); + try { + p.getIncludePatterns(project); + fail("Can make PatternSet a Reference to itself."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + try { + p.getExcludePatterns(project); + fail("Can make PatternSet a Reference to itself."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 --> dummy1 + PatternSet p1 = new PatternSet(); + project.addReference("dummy1", p1); + p1.setRefid(new Reference("dummy2")); + PatternSet p2 = new PatternSet(); + project.addReference("dummy2", p2); + p2.setRefid(new Reference("dummy3")); + PatternSet p3 = new PatternSet(); + project.addReference("dummy3", p3); + p3.setRefid(new Reference("dummy1")); + try { + p1.getIncludePatterns(project); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + try { + p1.getExcludePatterns(project); + fail("Can make circular reference."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } + + // dummy1 --> dummy2 --> dummy3 + // (which holds patterns "include" and "exclude") + p1 = new PatternSet(); + project.addReference("dummy1", p1); + p1.setRefid(new Reference("dummy2")); + p2 = new PatternSet(); + project.addReference("dummy2", p2); + p2.setRefid(new Reference("dummy3")); + p3 = new PatternSet(); + project.addReference("dummy3", p3); + p3.setIncludes("include"); + p3.createExclude().setName("exclude"); + String[] i = p1.getIncludePatterns(project); + assertEquals("One include pattern buried deep inside a nested patternset structure", + 1, i.length); + assertEquals("include", i[0]); + i = p3.getExcludePatterns(project); + assertEquals("One exclude pattern buried deep inside a nested patternset structure", + 1, i.length); + assertEquals("exclude", i[0]); + } + + public void testNestedPatternset() { + PatternSet p = new PatternSet(); + p.setIncludes("**/*.java"); + + PatternSet nested = new PatternSet(); + nested.setExcludes("**/*.class"); + + p.addConfiguredPatternset(nested); + + String[] excludes = p.getExcludePatterns(project); + String[] includes = p.getIncludePatterns(project); + + assertEquals("Includes","**/*.java", includes[0]); + assertEquals("Excludes","**/*.class", excludes[0]); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/PermissionsTest.java b/src/tests/junit/org/apache/tools/ant/types/PermissionsTest.java new file mode 100644 index 000000000..7c6e062c6 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/PermissionsTest.java @@ -0,0 +1,156 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import junit.framework.TestCase; + +import org.apache.tools.ant.ExitException; + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.Permissions. + * + */ +public class PermissionsTest extends TestCase { + + Permissions perms; + + public PermissionsTest(String name) { + super(name); + } + + public void setUp() { + perms = new Permissions(); + Permissions.Permission perm = new Permissions.Permission(); + // Grant extra permissions to read and write the user.* properties and read to the + // java.home property + perm.setActions("read, write"); + perm.setName("user.*"); + perm.setClass("java.util.PropertyPermission"); + perms.addConfiguredGrant(perm); + + perm = new Permissions.Permission(); + perm.setActions("read"); + perm.setName("java.home"); + perm.setClass("java.util.PropertyPermission"); + perms.addConfiguredGrant(perm); + + perm = new Permissions.Permission(); + perm.setActions("read"); + perm.setName("file.encoding"); + perm.setClass("java.util.PropertyPermission"); + perms.addConfiguredGrant(perm); + + // Revoke permission to write user.home (granted above via user.*), still able to read though. + // and the default granted permission to read os.name. + perm = new Permissions.Permission(); + perm.setActions("write"); + perm.setName("user.home"); + perm.setClass("java.util.PropertyPermission"); + perms.addConfiguredRevoke(perm); + + perm = new Permissions.Permission(); + perm.setActions("read"); + perm.setName("os.*"); + perm.setClass("java.util.PropertyPermission"); + perms.addConfiguredRevoke(perm); + } + + /** Tests a permission that is granted per default. */ + public void testDefaultGranted() { + perms.setSecurityManager(); + try { + String s = System.getProperty("line.separator"); + } finally { + perms.restoreSecurityManager(); + } + } + + /** Tests a permission that has been granted later via wildcard. */ + public void testGranted() { + perms.setSecurityManager(); + try { + String s = System.getProperty("user.name"); + System.setProperty("user.name", s); + } finally { + perms.restoreSecurityManager(); + } + } + + /** Tests a permission that has been granted and revoked later. */ + public void testGrantedAndRevoked() { + perms.setSecurityManager(); + try { + String s = System.getProperty("user.home"); + System.setProperty("user.home", s); + fail("Could perform an action that should have been forbidden."); + } catch (SecurityException e){ + // Was expected, test passes + } finally { + perms.restoreSecurityManager(); + } + } + + /** Tests a permission that is granted as per default but revoked later via wildcard. */ + public void testDefaultRevoked() { + perms.setSecurityManager(); + try { + System.getProperty("os.name"); + fail("Could perform an action that should have been forbidden."); + } catch (SecurityException e){ + // Was expected, test passes + } finally { + perms.restoreSecurityManager(); + } + } + /** Tests a permission that has not been granted or revoked. */ + public void testOther() { + String ls = System.getProperty("line.separator"); + perms.setSecurityManager(); + try { + String s = System.setProperty("line.separator",ls); + fail("Could perform an action that should have been forbidden."); + } catch (SecurityException e){ + // Was expected, test passes + } finally { + perms.restoreSecurityManager(); + } + } + + /** Tests an exit condition. */ + public void testExit() { + perms.setSecurityManager(); + try { + System.out.println("If this is the last line on standard out the testExit f.a.i.l.e.d"); + System.exit(3); + fail("Totaly impossible that this fail is ever executed. Please let me know if it is!"); + } catch (ExitException e) { + if (e.getStatus() != 3) { + fail("Received wrong exit status in Exit Exception."); + } + System.out.println("testExit successful."); + } finally { + perms.restoreSecurityManager(); + } + } + + + public void tearDown() { + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/PolyTest.java b/src/tests/junit/org/apache/tools/ant/types/PolyTest.java new file mode 100644 index 000000000..fe6d28616 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/PolyTest.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; + +public class PolyTest extends BuildFileTest { + + public PolyTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/poly.xml"); + } + + public void testFileSet() { + expectLogContaining("fileset", "types.FileSet"); + } + + public void testFileSetAntType() { + expectLogContaining("fileset-ant-type", "types.PolyTest$MyFileSet"); + } + + public void testPath() { + expectLogContaining("path", "types.Path"); + } + + public void testPathAntType() { + expectLogContaining("path-ant-type", "types.PolyTest$MyPath"); + } + + public static class MyFileSet extends FileSet {} + + public static class MyPath extends Path { + public MyPath(Project project) { + super(project); + } + } + + public static class MyTask extends Task { + public void addPath(Path path) { + log("class of path is " + path.getClass()); + } + public void addFileset(FileSet fileset) { + log("class of fileset is " + fileset.getClass()); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/PropertySetTest.java b/src/tests/junit/org/apache/tools/ant/types/PropertySetTest.java new file mode 100644 index 000000000..aea7f9215 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/PropertySetTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; + +public class PropertySetTest extends BuildFileTest { + + public PropertySetTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/propertyset.xml"); + } + + public void testReferenceToTwoReferences() { + executeTarget("reference-to-two-references"); + } + + public void testNestedMapped() { + executeTarget("nested-mapped"); + } + + public void testNestedMappedMapped() { + executeTarget("nested-mapped-mapped"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java b/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java new file mode 100755 index 000000000..678b7b21e --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java @@ -0,0 +1,64 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.types; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.BuildFileTest; + +public class RedirectorElementTest extends BuildFileTest { + + public RedirectorElementTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/redirector.xml", Project.MSG_VERBOSE); + } + + public void test1() { + executeTarget("test1"); + assertTrue((getProject().getReference("test1") + instanceof RedirectorElement)); + } + + public void test2() { + expectBuildException("test2", "You must not specify more than one " + + "attribute when using refid"); + } + + public void test3() { + expectBuildException("test3", "You must not specify nested elements " + + "when using refid"); + } + + public void test4() { + executeTarget("test4"); + } + + public void testLogInputString() { + executeTarget("testLogInputString"); + if (super.getLog().indexOf("testLogInputString can-cat") >=0 ) { + assertDebuglogContaining("Using input string"); + } + } + + public void testRefid() { + executeTarget("testRefid"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/ResourceCollectionsTest.java b/src/tests/junit/org/apache/tools/ant/types/ResourceCollectionsTest.java new file mode 100755 index 000000000..eaf47a454 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/ResourceCollectionsTest.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; + +public class ResourceCollectionsTest extends BuildFileTest { + + public ResourceCollectionsTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/resources/build.xml"); + } + + public void tearDown() { + executeTarget("tearDown"); + } + + public void testdifference() { + executeTarget("testdifference"); + } + + public void testdirset() { + executeTarget("testdirset"); + } + + public void testfile() { + executeTarget("testfile"); + } + + public void testfilelist() { + executeTarget("testfilelist"); + } + + public void testfiles1() { + executeTarget("testfiles1"); + } + + public void testfiles2() { + executeTarget("testfiles2"); + } + + public void testfiles3() { + executeTarget("testfiles3"); + } + + public void testfileset() { + executeTarget("testfileset"); + } + + public void testfileurl() { + executeTarget("testfileurl"); + } + + public void testfileurlref() { + executeTarget("testfileurlref"); + } + + public void testfirst1() { + executeTarget("testfirst1"); + } + + public void testfirst2() { + executeTarget("testfirst2"); + } + + public void testhttpurl1() { + executeTarget("testhttpurl1"); + } + + public void testhttpurl2() { + executeTarget("testhttpurl2"); + } + + public void testintersect() { + executeTarget("testintersect"); + } + + public void testjarurl() { + executeTarget("testjarurl"); + } + + public void testnestedresources() { + executeTarget("testnestedresources"); + } + + public void testpath() { + executeTarget("testpath"); + } + + public void testpropertyset() { + executeTarget("testpropertyset"); + } + + public void testresource() { + executeTarget("testresource"); + } + + public void testresourcesref() { + executeTarget("testresourcesref"); + } + + public void teststring1() { + executeTarget("teststring1"); + } + + public void teststring2() { + executeTarget("teststring2"); + } + + public void testunion() { + executeTarget("testunion"); + } + + public void testzipentry() { + executeTarget("testzipentry"); + } + + public void testzipfileset() { + executeTarget("testzipfileset"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/ResourceComparatorsTest.java b/src/tests/junit/org/apache/tools/ant/types/ResourceComparatorsTest.java new file mode 100755 index 000000000..0b39a60e5 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/ResourceComparatorsTest.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; + +public class ResourceComparatorsTest extends BuildFileTest { + + public ResourceComparatorsTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/resources/comparators/build.xml"); + } + + public void tearDown() { + executeTarget("tearDown"); + } + + public void testcompoundsort1() { + executeTarget("testcompoundsort1"); + } + + public void testcompoundsort2() { + executeTarget("testcompoundsort2"); + } + + public void testcontent() { + executeTarget("testcontent"); + } + + public void testexists() { + executeTarget("testexists"); + } + + public void testdate() { + executeTarget("testdate"); + } + + public void testname() { + executeTarget("testname"); + } + + public void testrvcontent() { + executeTarget("testrvcontent"); + } + + public void testrvdefault() { + executeTarget("testrvdefault"); + } + + public void testrvexists() { + executeTarget("testrvexists"); + } + + public void testrvdate() { + executeTarget("testrvdate"); + } + + public void testrvname() { + executeTarget("testrvname"); + } + + public void testrvsize() { + executeTarget("testrvsize"); + } + + public void testrvtype() { + executeTarget("testrvtype"); + } + + public void testsize() { + executeTarget("testsize"); + } + + public void testsortdefault() { + executeTarget("testsortdefault"); + } + + public void testtype() { + executeTarget("testtype"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/ResourceOutputTest.java b/src/tests/junit/org/apache/tools/ant/types/ResourceOutputTest.java new file mode 100755 index 000000000..f0ec5e428 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/ResourceOutputTest.java @@ -0,0 +1,152 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; +import java.io.IOException; +import java.net.UnknownServiceException; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Zip; +import org.apache.tools.ant.types.resources.ImmutableResourceException; +import org.apache.tools.ant.types.resources.PropertyResource; +import org.apache.tools.ant.types.resources.StringResource; +import org.apache.tools.ant.types.resources.URLResource; +import org.apache.tools.ant.types.resources.ZipResource; +import org.apache.tools.ant.util.FileUtils; +import org.apache.tools.ant.util.ResourceUtils; + +public class ResourceOutputTest extends BuildFileTest { + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + private static final File basedir = new File(System.getProperty("root"), + "src/etc/testcases/types/resources"); + + public ResourceOutputTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.init(); + project.setUserProperty("basedir" , basedir.getAbsolutePath()); + } + + public void testresourceoutput() { + try { + testoutputbe(new Resource("foo")); + fail("should have caught UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } + } + + public void teststringoutput1() { + StringResource r = new StringResource(); + testoutputbe(r); + assertEquals("foo", r.getValue()); + } + + public void teststringoutput2() { + StringResource r = new StringResource("bar"); + try { + testoutput(r); + fail("should have caught ImmutableResourceException"); + } catch (ImmutableResourceException e) { + } catch (IOException e) { + fail("caught some other IOException: " + e); + } + assertEquals("bar", r.getValue()); + } + + public void testpropertyoutput1() { + PropertyResource r = new PropertyResource(getProject(), "bar"); + testoutputbe(r); + assertPropertyEquals("bar", "foo"); + } + + public void testpropertyoutput2() { + getProject().setNewProperty("bar", "bar"); + PropertyResource r = new PropertyResource(getProject(), "bar"); + try { + testoutput(r); + fail("should have caught ImmutableResourceException"); + } catch (ImmutableResourceException e) { + } catch (IOException e) { + fail("caught some other IOException: " + e); + } + assertPropertyEquals("bar", "bar"); + } + + public void testurloutput() { + File f = getProject().resolveFile("testurloutput"); + try { + FILE_UTILS.createNewFile(f); + testoutput(new URLResource(f)); + fail("should have caught UnknownServiceException"); + } catch (UnknownServiceException e) { + } catch (IOException e) { + e.printStackTrace(System.err); + fail("caught some other IOException: " + e); + } finally { + if (!f.delete()) { + f.deleteOnExit(); + } + } + } + + public void testzipentryoutput() { + Zip z = new Zip(); + z.setProject(getProject()); + Zip.WhenEmpty create = new Zip.WhenEmpty(); + create.setValue("create"); + z.setWhenempty(create); + z.setBasedir(basedir); + z.setExcludes("**/*"); + File f = getProject().resolveFile("foo"); + z.setDestFile(f); + z.execute(); + ZipResource r = new ZipResource(); + r.setZipfile(f); + r.setName("foo"); + try { + testoutputbe(r); + fail("should have caught UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + } finally { + if (!f.delete()) { + f.deleteOnExit(); + } + } + } + + private void testoutputbe(Resource dest) { + try { + testoutput(dest); + } catch (IOException e) { + throw new BuildException(e); + } + } + + private void testoutput(Resource dest) throws IOException { + ResourceUtils.copyResource(new StringResource("foo"), dest, null); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/ResourceSelectorsTest.java b/src/tests/junit/org/apache/tools/ant/types/ResourceSelectorsTest.java new file mode 100755 index 000000000..6c129c889 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/ResourceSelectorsTest.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; + +public class ResourceSelectorsTest extends BuildFileTest { + + public ResourceSelectorsTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/resources/selectors/build.xml"); + } + + public void testname1() { + executeTarget("testname1"); + } + + public void testname2() { + executeTarget("testname2"); + } + + public void testexists() { + executeTarget("testexists"); + } + + public void testinstanceoftype1() { + executeTarget("testinstanceoftype1"); + } + + public void testinstanceoftype2() { + executeTarget("testinstanceoftype2"); + } + + public void testinstanceofclass() { + executeTarget("testinstanceofclass"); + } + + public void testtype() { + executeTarget("testtype"); + } + + public void testdate() { + executeTarget("testdate"); + } + + public void testsize() { + executeTarget("testsize"); + } + + public void testand() { + executeTarget("testand"); + } + + public void testor() { + executeTarget("testor"); + } + + public void testnot() { + executeTarget("testnot"); + } + + public void testnone() { + executeTarget("testnone"); + } + + public void testmajority1() { + executeTarget("testmajority1"); + } + + public void testmajority2() { + executeTarget("testmajority2"); + } + + public void testmajority3() { + executeTarget("testmajority3"); + } + + public void testmajority4() { + executeTarget("testmajority4"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/TarFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/TarFileSetTest.java new file mode 100755 index 000000000..8a5680bec --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/TarFileSetTest.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; + +import org.apache.tools.ant.BuildException; + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.TarFileSet. + * + *

This doesn't actually test much, mainly reference handling. + * + */ + +public class TarFileSetTest extends AbstractFileSetTest { + + public TarFileSetTest(String name) { + super(name); + } + + protected AbstractFileSet getInstance() { + return new TarFileSet(); + } + public final void testAttributes() { + TarFileSet f = (TarFileSet)getInstance(); + //check that dir and src are incompatible + f.setSrc(new File("example.tar")); + try { + f.setDir(new File("examples")); + fail("can add dir to " + + f.getDataTypeName() + + " when a src is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both dir and src attributes",be.getMessage()); + } + f = (TarFileSet)getInstance(); + //check that dir and src are incompatible + f.setDir(new File("examples")); + try { + f.setSrc(new File("example.tar")); + fail("can add src to " + + f.getDataTypeName() + + " when a dir is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both dir and src attributes",be.getMessage()); + } + //check that fullpath and prefix are incompatible + f = (TarFileSet)getInstance(); + f.setSrc(new File("example.tar")); + f.setPrefix("/examples"); + try { + f.setFullpath("/doc/manual/index.html"); + fail("Can add fullpath to " + + f.getDataTypeName() + + " when a prefix is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both fullpath and prefix attributes", be.getMessage()); + } + f = (TarFileSet)getInstance(); + f.setSrc(new File("example.tar")); + f.setFullpath("/doc/manual/index.html"); + try { + f.setPrefix("/examples"); + fail("Can add prefix to " + + f.getDataTypeName() + + " when a fullpath is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both fullpath and prefix attributes", be.getMessage()); + } + // check that reference tarfilesets cannot have specific attributes + f = (TarFileSet)getInstance(); + f.setRefid(new Reference("test")); + try { + f.setSrc(new File("example.tar")); + fail("Can add src to " + + f.getDataTypeName() + + " when a refid is already present"); + } catch (BuildException be) { + assertEquals("You must not specify more than one " + + "attribute when using refid", be.getMessage()); + } + // check that a reference tarfileset gets the same attributes as the original + f = (TarFileSet)getInstance(); + f.setSrc(new File("example.tar")); + f.setPrefix("/examples"); + f.setFileMode("600"); + f.setDirMode("530"); + getProject().addReference("test",f); + TarFileSet zid=(TarFileSet)getInstance(); + zid.setRefid(new Reference("test")); + assertTrue("src attribute copied by copy constructor",zid.getSrc(getProject()).equals(f.getSrc(getProject()))); + assertTrue("prefix attribute copied by copy constructor",f.getPrefix(getProject()).equals(zid.getPrefix(getProject()))); + assertTrue("file mode attribute copied by copy constructor",f.getFileMode(getProject())==zid.getFileMode(getProject())); + assertTrue("dir mode attribute copied by copy constructor",f.getDirMode(getProject())==zid.getDirMode(getProject())); + } + + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/XMLCatalogBuildFileTest.java b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogBuildFileTest.java new file mode 100644 index 000000000..6d487affc --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogBuildFileTest.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import org.apache.tools.ant.BuildFileTest; + +/** + * BuildFileTest testcases for org.apache.tools.ant.types.XMLCatalog + * + * @see org.apache.tools.ant.types.XMLCatalogTest + * + */ +public class XMLCatalogBuildFileTest extends BuildFileTest { + + public XMLCatalogBuildFileTest(String name) { + super(name); + } + + public void setUp() { + } + + public void tearDown() { + } + + // + // Ensure that an external entity resolves as expected with NO + // XMLCatalog involvement: + // + // Transform an XML file that refers to the entity into a text + // file, stuff result into property: val1 + // + public void testEntityNoCatalog() { + configureProject("src/etc/testcases/types/xmlcatalog.xml"); + expectPropertySet("testentitynocatalog", "val1", + "A stitch in time saves nine"); + } + + // + // Ensure that an external entity resolves as expected Using an + // XMLCatalog: + // + // Transform an XML file that refers to the entity into a text + // file, entity is listed in the XMLCatalog pointing to a + // different file. Stuff result into property: val2 + // + public void testEntityWithCatalog() { + configureProject("src/etc/testcases/types/xmlcatalog.xml"); + expectPropertySet("testentitywithcatalog", "val2", + "No news is good news"); + } + + // + // Ensure that an external entity resolves as expected with NO + // XMLCatalog involvement: + // + // Transform an XML file that contains a reference to a _second_ XML file + // via the document() function. The _second_ XML file refers to an entity. + // Stuff result into the property: val3 + // + public void testDocumentNoCatalog() { + configureProject("src/etc/testcases/types/xmlcatalog.xml"); + expectPropertySet("testdocumentnocatalog", "val3", + "A stitch in time saves nine"); + } + + // + // Ensure that an external entity resolves as expected Using an + // XMLCatalog: + // + // Transform an XML file that contains a reference to a _second_ XML file + // via the document() function. The _second_ XML file refers to an entity. + // The entity is listed in the XMLCatalog pointing to a different file. + // Stuff result into the property: val4 + // + public void testDocumentWithCatalog() { + configureProject("src/etc/testcases/types/xmlcatalog.xml"); + expectPropertySet("testdocumentwithcatalog", "val4", + "No news is good news"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/XMLCatalogTest.java b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogTest.java new file mode 100644 index 000000000..532174bbb --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogTest.java @@ -0,0 +1,411 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; + +import javax.xml.transform.Source; +import javax.xml.transform.sax.SAXSource; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.util.JAXPUtils; +import org.xml.sax.InputSource; + +/** + * JUnit testcases for org.apache.tools.ant.types.XMLCatalog + * + */ +public class XMLCatalogTest extends TestCase { + + private Project project; + private XMLCatalog catalog; + + private XMLCatalog newCatalog() { + XMLCatalog cat = new XMLCatalog(); + cat.setProject(project); + return cat; + } + + private String toURLString(File file) throws MalformedURLException { + return JAXPUtils.getSystemId(file); + } + + public XMLCatalogTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.setBasedir(System.getProperty("root")); + + // This causes XMLCatalog to print out detailed logging + // messages for debugging + // + // DefaultLogger logger = new DefaultLogger(); + // logger.setMessageOutputLevel(Project.MSG_DEBUG); + // logger.setOutputPrintStream(System.out); + // logger.setErrorPrintStream(System.err); + // project.addBuildListener(logger); + + catalog = newCatalog(); + } + + public void tearDown() { + project = null; + catalog = null; + } + + public void testEmptyCatalog() { + try { + InputSource result = catalog.resolveEntity("PUBLIC ID ONE", + "i/dont/exist.dtd"); + assertNull("Empty catalog should return null", result); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + + try { + Source result = catalog.resolve("i/dont/exist.dtd", null); + String expected = toURLString(new File(project.getBaseDir() + + "/i/dont/exist.dtd")); + // + // These shenanigans are necessary b/c Norm Walsh's resolver + // has a different idea of how file URLs are created on windoze + // ie file://c:/foo instead of file:///c:/foo + // + String resultStr = new URL(((SAXSource)result).getInputSource().getSystemId()).getFile(); + assertTrue("Empty catalog should return input", + expected.endsWith(resultStr)); + } catch (Exception e) { + fail("resolve() failed!" + e.toString()); + } + } + + public void testNonExistentEntry() { + + ResourceLocation dtd = new ResourceLocation(); + dtd.setPublicId("PUBLIC ID ONE"); + dtd.setLocation("i/dont/exist.dtd"); + + try { + InputSource result = catalog.resolveEntity("PUBLIC ID ONE", + "i/dont/exist.dtd"); + assertNull("Nonexistent Catalog entry should not be returned", result); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + + try { + Source result = catalog.resolve("i/dont/exist.dtd", null); + String expected = toURLString(new File(project.getBaseDir().toURL() + + "/i/dont/exist.dtd")); + String resultStr = new URL(((SAXSource)result).getInputSource().getSystemId()).getFile(); + assertTrue("Nonexistent Catalog entry return input", + expected.endsWith(resultStr)); + } catch (Exception e) { + fail("resolve() failed!" + e.toString()); + } + } + + public void testEmptyElementIfIsReference() { + ResourceLocation dtd = new ResourceLocation(); + dtd.setPublicId("PUBLIC ID ONE"); + dtd.setLocation("i/dont/exist.dtd"); + catalog.addDTD(dtd); + project.addReference("catalog", catalog); + + try { + catalog.setRefid(new Reference("dummyref")); + fail("Can add reference to nonexistent XMLCatalog"); + } catch (BuildException be) { + assertEquals("You must not specify more than one " + + "attribute when using refid", be.getMessage()); + } + + XMLCatalog catalog2 = newCatalog(); + catalog2.setRefid(new Reference("catalog")); + + try { + catalog2.addConfiguredXMLCatalog(catalog); + fail("Can add nested XMLCatalog to XMLCatalog that is a reference"); + } catch (BuildException be) { + assertEquals("You must not specify nested elements when using refid", + be.getMessage()); + } + } + + public void testCircularReferenceCheck() { + + // catalog <--> catalog + project.addReference("catalog", catalog); + catalog.setRefid(new Reference("catalog")); + + try { + InputSource result = catalog.resolveEntity("PUBLIC ID ONE", + "i/dont/exist.dtd"); + fail("Can make XMLCatalog a Reference to itself."); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + + // catalog1 --> catalog2 --> catalog3 --> catalog1 + XMLCatalog catalog1 = newCatalog(); + project.addReference("catalog1", catalog1); + XMLCatalog catalog2 = newCatalog(); + project.addReference("catalog2", catalog2); + XMLCatalog catalog3 = newCatalog(); + project.addReference("catalog3", catalog3); + + catalog3.setRefid(new Reference("catalog1")); + catalog2.setRefid(new Reference("catalog3")); + catalog1.setRefid(new Reference("catalog2")); + + try { + InputSource result = catalog1.resolveEntity("PUBLIC ID ONE", + "i/dont/exist.dtd"); + fail("Can make circular reference"); + } catch (BuildException be) { + assertEquals("This data type contains a circular reference.", + be.getMessage()); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + } + // inspired by Bugzilla Report 23913 + // a problem used to happen under Windows when the location of the DTD was given as an absolute path + // possibly with a mixture of file separators + public void testAbsolutePath() { + ResourceLocation dtd = new ResourceLocation(); + dtd.setPublicId("-//stevo//DTD doc 1.0//EN"); + + String sysid = System.getProperty("root") + File.separator + "src/etc/testcases/taskdefs/optional/xml/doc.dtd"; + dtd.setLocation(sysid); + catalog.addDTD(dtd); + File dtdFile = project.resolveFile(sysid); + + try { + InputSource result = catalog.resolveEntity("-//stevo//DTD doc 1.0//EN", + "nap:chemical+brothers"); + assertNotNull(result); + assertEquals(toURLString(dtdFile), + result.getSystemId()); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + + } + + public void testSimpleEntry() { + + ResourceLocation dtd = new ResourceLocation(); + dtd.setPublicId("-//stevo//DTD doc 1.0//EN"); + String sysid = "src/etc/testcases/taskdefs/optional/xml/doc.dtd"; + dtd.setLocation(sysid); + catalog.addDTD(dtd); + File dtdFile = project.resolveFile(sysid); + + try { + InputSource result = catalog.resolveEntity("-//stevo//DTD doc 1.0//EN", + "nap:chemical+brothers"); + assertNotNull(result); + assertEquals(toURLString(dtdFile), + result.getSystemId()); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + } + + public void testEntryReference() { + + String publicId = "-//stevo//DTD doc 1.0//EN"; + String sysid = "src/etc/testcases/taskdefs/optional/xml/doc.dtd"; + + // catalog2 --> catalog1 --> catalog + ResourceLocation dtd = new ResourceLocation(); + dtd.setPublicId(publicId); + dtd.setLocation(sysid); + catalog.addDTD(dtd); + File dtdFile = project.resolveFile(sysid); + + String uri = "http://foo.com/bar/blah.xml"; + String uriLoc = "src/etc/testcases/taskdefs/optional/xml/about.xml"; + + ResourceLocation entity = new ResourceLocation(); + entity.setPublicId(uri); + entity.setLocation(uriLoc); + catalog.addEntity(entity); + File xmlFile = project.resolveFile(uriLoc); + + project.addReference("catalog", catalog); + + XMLCatalog catalog1 = newCatalog(); + project.addReference("catalog1", catalog1); + XMLCatalog catalog2 = newCatalog(); + project.addReference("catalog2", catalog1); + + catalog1.setRefid(new Reference("catalog")); + catalog2.setRefid(new Reference("catalog1")); + + try { + InputSource result = catalog2.resolveEntity(publicId, + "nap:chemical+brothers"); + + assertNotNull(result); + assertEquals(toURLString(dtdFile), + result.getSystemId()); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + + try { + Source result = catalog.resolve(uri, null); + assertNotNull(result); + assertEquals(toURLString(xmlFile), + result.getSystemId()); + } catch (Exception e) { + fail("resolve() failed!" + e.toString()); + } + } + + public void testNestedCatalog() { + + String publicId = "-//stevo//DTD doc 1.0//EN"; + String dtdLoc = "src/etc/testcases/taskdefs/optional/xml/doc.dtd"; + + ResourceLocation dtd = new ResourceLocation(); + dtd.setPublicId(publicId); + dtd.setLocation(dtdLoc); + catalog.addDTD(dtd); + File dtdFile = project.resolveFile(dtdLoc); + + String uri = "http://foo.com/bar/blah.xml"; + String uriLoc = "src/etc/testcases/taskdefs/optional/xml/about.xml"; + + ResourceLocation entity = new ResourceLocation(); + entity.setPublicId(uri); + entity.setLocation(uriLoc); + catalog.addEntity(entity); + File xmlFile = project.resolveFile(uriLoc); + + XMLCatalog catalog1 = newCatalog(); + catalog1.addConfiguredXMLCatalog(catalog); + + try { + InputSource result = catalog1.resolveEntity(publicId, + "nap:chemical+brothers"); + assertNotNull(result); + assertEquals(toURLString(dtdFile), + result.getSystemId()); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + + try { + Source result = catalog.resolve(uri, null); + assertNotNull(result); + assertEquals(toURLString(xmlFile), + result.getSystemId()); + } catch (Exception e) { + fail("resolve() failed!" + e.toString()); + } + + } + + public void testResolverBase() { + + String uri = "http://foo.com/bar/blah.xml"; + String uriLoc = "etc/testcases/taskdefs/optional/xml/about.xml"; + String base = null; + try { + base = toURLString(project.getBaseDir()) + "/src/"; + } catch (MalformedURLException ex) { + fail (ex.toString()); + } + + ResourceLocation entity = new ResourceLocation(); + entity.setPublicId(uri); + entity.setLocation(uriLoc); + catalog.addEntity(entity); + File xmlFile = project.resolveFile("src/" + uriLoc); + + try { + Source result = catalog.resolve(uri, base); + assertNotNull(result); + assertEquals(toURLString(xmlFile), + result.getSystemId()); + } catch (Exception e) { + fail("resolve() failed!" + e.toString()); + } + } + + public void testClasspath() { + + + String publicId = "-//stevo//DTD doc 1.0//EN"; + String dtdLoc = "testcases/taskdefs/optional/xml/doc.dtd"; + String path1 = project.getBaseDir().toString() + "/src/etc"; + + ResourceLocation dtd = new ResourceLocation(); + dtd.setPublicId(publicId); + dtd.setLocation(dtdLoc); + catalog.addDTD(dtd); + File dtdFile = project.resolveFile("src/etc/" + dtdLoc); + + String uri = "http://foo.com/bar/blah.xml"; + String uriLoc = "etc/testcases/taskdefs/optional/xml/about.xml"; + String path2 = project.getBaseDir().toString() + "/src"; + + ResourceLocation entity = new ResourceLocation(); + entity.setPublicId(uri); + entity.setLocation(uriLoc); + catalog.addEntity(entity); + File xmlFile = project.resolveFile("src/" + uriLoc); + + Path aPath = new Path(project, path1); + aPath.append(new Path(project, path2)); + catalog.setClasspath(aPath); + + try { + InputSource result = catalog.resolveEntity(publicId, + "nap:chemical+brothers"); + assertNotNull(result); + String resultStr = new URL(result.getSystemId()).getFile(); + assertTrue(toURLString(dtdFile).endsWith(resultStr)); + } catch (Exception e) { + fail("resolveEntity() failed!" + e.toString()); + } + + try { + Source result = catalog.resolve(uri, null); + assertNotNull(result); + String resultStr = new URL(result.getSystemId()).getFile(); + assertTrue(toURLString(xmlFile).endsWith(resultStr)); + } catch (Exception e) { + fail("resolve() failed!" + e.toString()); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/ZipFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/ZipFileSetTest.java new file mode 100644 index 000000000..665dedda7 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/ZipFileSetTest.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types; + +import java.io.File; + +import org.apache.tools.ant.BuildException; + +/** + * JUnit 3 testcases for org.apache.tools.ant.types.ZipFileSet. + * + *

This doesn't actually test much, mainly reference handling. + * + */ + +public class ZipFileSetTest extends AbstractFileSetTest { + + public ZipFileSetTest(String name) { + super(name); + } + + protected AbstractFileSet getInstance() { + return new ZipFileSet(); + } + public final void testAttributes() { + ZipFileSet f = (ZipFileSet)getInstance(); + //check that dir and src are incompatible + f.setSrc(new File("example.zip")); + try { + f.setDir(new File("examples")); + fail("can add dir to " + + f.getDataTypeName() + + " when a src is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both dir and src attributes",be.getMessage()); + } + f = (ZipFileSet)getInstance(); + //check that dir and src are incompatible + f.setDir(new File("examples")); + try { + f.setSrc(new File("example.zip")); + fail("can add src to " + + f.getDataTypeName() + + " when a dir is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both dir and src attributes",be.getMessage()); + } + //check that fullpath and prefix are incompatible + f = (ZipFileSet)getInstance(); + f.setSrc(new File("example.zip")); + f.setPrefix("/examples"); + try { + f.setFullpath("/doc/manual/index.html"); + fail("Can add fullpath to " + + f.getDataTypeName() + + " when a prefix is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both fullpath and prefix attributes", be.getMessage()); + } + f = (ZipFileSet)getInstance(); + f.setSrc(new File("example.zip")); + f.setFullpath("/doc/manual/index.html"); + try { + f.setPrefix("/examples"); + fail("Can add prefix to " + + f.getDataTypeName() + + " when a fullpath is already present"); + } catch (BuildException be) { + assertEquals("Cannot set both fullpath and prefix attributes", be.getMessage()); + } + // check that reference zipfilesets cannot have specific attributes + f = (ZipFileSet)getInstance(); + f.setRefid(new Reference("test")); + try { + f.setSrc(new File("example.zip")); + fail("Can add src to " + + f.getDataTypeName() + + " when a refid is already present"); + } catch (BuildException be) { + assertEquals("You must not specify more than one " + + "attribute when using refid", be.getMessage()); + } + // check that a reference zipfileset gets the same attributes as the original + f = (ZipFileSet)getInstance(); + f.setSrc(new File("example.zip")); + f.setPrefix("/examples"); + f.setFileMode("600"); + f.setDirMode("530"); + getProject().addReference("test",f); + ZipFileSet zid=(ZipFileSet)getInstance(); + zid.setRefid(new Reference("test")); + assertTrue("src attribute copied by copy constructor",zid.getSrc(getProject()).equals(f.getSrc(getProject()))); + assertTrue("prefix attribute copied by copy constructor",f.getPrefix(getProject()).equals(zid.getPrefix(getProject()))); + assertTrue("file mode attribute copied by copy constructor",f.getFileMode(getProject())==zid.getFileMode(getProject())); + assertTrue("dir mode attribute copied by copy constructor",f.getDirMode(getProject())==zid.getDirMode(getProject())); + } + + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/mappers/GlobMapperTest.java b/src/tests/junit/org/apache/tools/ant/types/mappers/GlobMapperTest.java new file mode 100644 index 000000000..71a79d378 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/mappers/GlobMapperTest.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.mappers; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Testcase for the <globmapper> mapper. + * + */ +public class GlobMapperTest extends BuildFileTest { + public GlobMapperTest(String name) { + super(name); + } + public void setUp() { + configureProject("src/etc/testcases/types/mappers/globmapper.xml"); + } + + public void testIgnoreCase() { + executeTarget("ignore.case"); + } + public void testHandleDirSep() { + executeTarget("handle.dirsep"); + } +} + + diff --git a/src/tests/junit/org/apache/tools/ant/types/mappers/MapperResult.java b/src/tests/junit/org/apache/tools/ant/types/mappers/MapperResult.java new file mode 100644 index 000000000..43a7b2962 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/mappers/MapperResult.java @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.mappers; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.Mapper; +import org.apache.tools.ant.util.FileNameMapper; + +/** + * This is a test task to show the result of a mapper + * on a specific input. + * (Test is not in the name of the class, to make sure that + * it is not treated as a unit test. + */ + +public class MapperResult extends Task { + + private String failMessage = ""; + private String input; + private String output; + private FileNameMapper fileNameMapper; + + /** + * The output on an empty string array + */ + private static final String NULL_MAPPER_RESULT = ""; + + public void setFailMessage(String failMessage) { + this.failMessage = failMessage; + } + + public void setInput(String input) { + this.input = input; + } + + public void setOutput(String output) { + this.output = output; + } + + public void addConfiguredMapper(Mapper mapper) { + add(mapper.getImplementation()); + } + + public void add(FileNameMapper fileNameMapper) { + if (this.fileNameMapper != null) { + throw new BuildException("Only one mapper type nested element allowed"); + } + this.fileNameMapper = fileNameMapper; + } + + public void execute() { + if (input == null) { + throw new BuildException("Missing attribute 'input'"); + } + if (output == null) { + throw new BuildException("Missing attribute 'output'"); + } + if (fileNameMapper == null) { + throw new BuildException("Missing a nested file name mapper type element"); + } + String[] result = fileNameMapper.mapFileName(input); + String flattened; + if (result == null) { + flattened = NULL_MAPPER_RESULT; + } else { + StringBuffer b = new StringBuffer(); + for (int i = 0; i < result.length; ++i) { + if (i != 0) { + b.append("|"); + } + b.append(result[i]); + } + flattened = b.toString(); + } + if (!flattened.equals(output)) { + throw new BuildException( + failMessage + + " " + + "got " + + flattened + + " " + + "expected " + + output); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/mappers/RegexpPatternMapperTest.java b/src/tests/junit/org/apache/tools/ant/types/mappers/RegexpPatternMapperTest.java new file mode 100644 index 000000000..a3c1c3a09 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/mappers/RegexpPatternMapperTest.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.mappers; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Testcase for the <regexpmapper> mapper. + * + */ +public class RegexpPatternMapperTest extends BuildFileTest { + public RegexpPatternMapperTest(String name) { + super(name); + } + public void setUp() { + configureProject("src/etc/testcases/types/mappers/regexpmapper.xml"); + } + + public void testIgnoreCase() { + executeTarget("ignore.case"); + } + public void testHandleDirSep() { + executeTarget("handle.dirsep"); + } +} + + diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/ScriptConditionTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptConditionTest.java new file mode 100644 index 000000000..e4d160d37 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptConditionTest.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.types.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + */ +public class ScriptConditionTest extends BuildFileTest { + /** + * Constructor for the BuildFileTest object + * + * @param name string to pass up to TestCase constructor + */ + public ScriptConditionTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/scriptcondition.xml"); + } + + public void testNolanguage() { + expectBuildExceptionContaining("testNolanguage", + "Absence of language attribute not detected", + "script language must be specified"); + } + + public void testMacro() { + executeTarget("testMacro"); + } + public void testClearByDefault() { + executeTarget("testClearByDefault"); + } + public void testValueWorks() { + executeTarget("testValueWorks"); + } + + public void testSetWorks() { + executeTarget("testSetWorks"); + } + + public void testClearWorks() { + executeTarget("testClearWorks"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/ScriptMapperTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptMapperTest.java new file mode 100644 index 000000000..208e7a1f9 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptMapperTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Test our script mapping + */ +public class ScriptMapperTest extends BuildFileTest { + public ScriptMapperTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/mappers/scriptmapper.xml"); + } + + public void testClear() { + executeTarget("testClear"); + } + public void testSetMultiple() { + executeTarget("testSetMultiple"); + } + public void testPassthrough() { + executeTarget("testPassthrough"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/ScriptSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptSelectorTest.java new file mode 100644 index 000000000..1052669e2 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptSelectorTest.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.types.optional; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Test that scripting selection works. Needs scripting support to work + */ +public class ScriptSelectorTest extends BuildFileTest { + + + public ScriptSelectorTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/selectors/scriptselector.xml"); + } + + public void testNolanguage() { + expectBuildExceptionContaining("testNolanguage", + "Absence of language attribute not detected", + "script language must be specified"); + } + + public void testSelectionSetByDefault() { + executeTarget("testSelectionSetByDefault"); + } + public void testSelectionSetWorks() { + executeTarget("testSelectionSetWorks"); + } + public void testSelectionClearWorks() { + executeTarget("testSelectionClearWorks"); + } + public void testFilenameAttribute() { + executeTarget("testFilenameAttribute"); + } + public void testFileAttribute() { + executeTarget("testFileAttribute"); + } + public void testBasedirAttribute() { + executeTarget("testBasedirAttribute"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java new file mode 100644 index 000000000..0f97b8857 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java @@ -0,0 +1,177 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.optional.depend; + +import java.io.File; +import java.util.Hashtable; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.DirectoryScanner; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.FileSet; + +/** + * Testcase for the Classfileset optional type. + * + */ +public class ClassFileSetTest extends BuildFileTest { + public static final String RESULT_FILESET = "result"; + + public ClassFileSetTest(String name) { + super(name); + } + + public void setUp() { + // share the setup for testing the depend task + configureProject("src/etc/testcases/taskdefs/optional/depend/depend.xml"); + } + + public void tearDown() { + executeTarget("clean"); + } + + /** + * Test basic classfileset + */ + public void testBasicSet() { + Project p = getProject(); + executeTarget("testbasicset"); + FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET); + DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); + String[] scannedFiles = scanner.getIncludedFiles(); + Hashtable files = new Hashtable(); + for (int i = 0; i < scannedFiles.length; ++i) { + files.put(scannedFiles[i], scannedFiles[i]); + } + assertEquals("Classfileset did not pick up expected number of " + + "class files", 4, files.size()); + assertTrue("Result did not contain A.class", + files.containsKey("A.class")); + assertTrue("Result did not contain B.class", + files.containsKey("B.class")); + assertTrue("Result did not contain C.class", + files.containsKey("C.class")); + assertTrue("Result did not contain D.class", + files.containsKey("D.class")); + } + + /** + * Test small classfileset + */ + public void testSmallSet() { + Project p = getProject(); + executeTarget("testsmallset"); + FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET); + DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); + String[] scannedFiles = scanner.getIncludedFiles(); + Hashtable files = new Hashtable(); + for (int i = 0; i < scannedFiles.length; ++i) { + files.put(scannedFiles[i], scannedFiles[i]); + } + assertEquals("Classfileset did not pick up expected number of " + + "class files", 2, files.size()); + assertTrue("Result did not contain B.class", + files.containsKey("B.class")); + assertTrue("Result did not contain C.class", + files.containsKey("C.class")); + } + + /** + * Test combo classfileset + */ + public void testComboSet() { + Project p = getProject(); + executeTarget("testcomboset"); + FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET); + DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); + String[] scannedFiles = scanner.getIncludedFiles(); + Hashtable files = new Hashtable(); + for (int i = 0; i < scannedFiles.length; ++i) { + files.put(scannedFiles[i], scannedFiles[i]); + } + assertEquals("Classfileset did not pick up expected number of " + + "class files", 1, files.size()); + assertTrue("Result did not contain C.class", + files.containsKey("C.class")); + } + + /** + * Test that you can pass a classfileset by reference to a fileset. + */ + public void testByReference() { + executeTarget("testbyreference"); + } + + /** + * Test that classes included in a method "System.out.println(MyClass.class)" are included. + */ + public void testMethodParam() { + Project p = getProject(); + executeTarget("testmethodparam"); + FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET); + DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); + String[] scannedFiles = scanner.getIncludedFiles(); + Hashtable files = new Hashtable(); + for (int i = 0; i < scannedFiles.length; ++i) { + files.put(scannedFiles[i], scannedFiles[i]); + } + assertEquals("Classfileset did not pick up expected number of " + + "class files", 5, files.size()); + assertTrue("Result did not contain A.class", + files.containsKey("A.class")); + assertTrue("Result did not contain B.class", + files.containsKey("B.class")); + assertTrue("Result did not contain C.class", + files.containsKey("C.class")); + assertTrue("Result did not contain D.class", + files.containsKey("D.class")); + assertTrue("Result did not contain E.class", + files.containsKey("E.class")); + } + + /** + * Test that classes included in a method "System.out.println(Outer.Inner.class)" are included. + */ + public void testMethodParamInner() { + Project p = getProject(); + executeTarget("testmethodparaminner"); + FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET); + DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p); + String[] scannedFiles = scanner.getIncludedFiles(); + Hashtable files = new Hashtable(); + for (int i = 0; i < scannedFiles.length; ++i) { + files.put(scannedFiles[i], scannedFiles[i]); + } + assertEquals("Classfileset did not pick up expected number of " + + "class files", 4, files.size()); + assertTrue("Result did not contain test" + File.separator + "Outer$Inner.class", + files.containsKey("test" + File.separator + "Outer$Inner.class")); + assertTrue("Result did not contain test" + File.separator + "Outer.class", + files.containsKey("test" + File.separator + "Outer.class")); + assertTrue("Result did not contain test" + File.separator + "ContainsOnlyInner.class", + files.containsKey("test" + File.separator + "ContainsOnlyInner.class")); + assertTrue("Result did not contain test" + File.separator + "ContainsOnlyInner.class", + files.containsKey("test" + File.separator + "MethodParam.class")); + } + + public void testResourceCollection() { + executeTarget("testresourcecollection"); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/JavaResourceTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/JavaResourceTest.java new file mode 100755 index 000000000..77a16be81 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/resources/JavaResourceTest.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.types.resources; + +import org.apache.tools.ant.BuildFileTest; + +public class JavaResourceTest extends BuildFileTest { + + public JavaResourceTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/resources/javaresource.xml"); + } + + public void testLoadManifest() { + executeTarget("loadManifest"); + assertNotNull(getProject().getProperty("manifest")); + + // this actually relies on the first manifest being found on + // the classpath (probably rt.jar's) being valid + assertTrue(getProject().getProperty("manifest") + .startsWith("Manifest-Version:")); + } +} \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/TarResourceTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/TarResourceTest.java new file mode 100755 index 000000000..a247bf604 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/resources/TarResourceTest.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.types.resources; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.util.FileUtils; + +public class TarResourceTest extends BuildFileTest { + + private static final FileUtils FU = FileUtils.getFileUtils(); + + public TarResourceTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + configureProject("src/etc/testcases/types/resources/tarentry.xml"); + } + + protected void tearDown() throws Exception { + executeTarget("tearDown"); + } + + public void testUncompressSource() throws java.io.IOException { + executeTarget("uncompressSource"); + assertTrue(FU.contentEquals(project.resolveFile("../../asf-logo.gif"), + project.resolveFile("testout/asf-logo.gif"))); + } +} \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorTest.java new file mode 100644 index 000000000..ca0ae51fc --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorTest.java @@ -0,0 +1,289 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import java.io.File; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; + +/** + * Base test case for Selectors. Provides a shared test as well as + * a test bed for selecting on, and a helper method for determining + * whether selections are correct. + * + */ +public abstract class BaseSelectorTest extends TestCase { + + private Project project; + private TaskdefForMakingBed tbed = null; + protected String basedirname = "src/etc/testcases/types"; + protected String beddirname = basedirname + "/selectortest"; + protected String mirrordirname = basedirname + "/selectortest2"; + protected File basedir = new File(System.getProperty("root"), basedirname); + protected File beddir = new File(System.getProperty("root"), beddirname); + protected File mirrordir = new File(System.getProperty("root"), mirrordirname); + protected String[] filenames = {".","asf-logo.gif.md5","asf-logo.gif.bz2", + "asf-logo.gif.gz","copy.filterset.filtered","zip/asf-logo.gif.zip", + "tar/asf-logo.gif.tar","tar/asf-logo-huge.tar.gz", + "tar/gz/asf-logo.gif.tar.gz","tar/bz2/asf-logo.gif.tar.bz2", + "tar/bz2/asf-logo-huge.tar.bz2","tar/bz2"}; + protected File[] files = new File[filenames.length]; + protected File[] mirrorfiles = new File[filenames.length]; + + public BaseSelectorTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.init(); + project.setBaseDir(basedir); + for (int x = 0; x < files.length; x++) { + files[x] = new File(beddir,filenames[x]); + mirrorfiles[x] = new File(mirrordir,filenames[x]); + } + } + + /** + * Override this in child classes to return a specific Selector + */ + public abstract BaseSelector getInstance(); + + + /** + * Return a preconfigured selector (with a set reference to + * project instance). + * @return the selector + */ + public BaseSelector getSelector() { + BaseSelector selector = getInstance(); + selector.setProject( getProject() ); + return selector; + } + + + public Project getProject() { + return project; + } + + /** + * This is a test that all Selectors derived from BaseSelector can + * use. It calls the setError() method and checks to ensure that a + * BuildException is thrown as a result. + */ + public void testRespondsToError() { + BaseSelector s = getInstance(); + if (s == null) { + return; + } + s.setError("test error"); + try { + s.isSelected(beddir,filenames[0],files[0]); + fail("Cannot cause BuildException when setError() is called"); + } catch (BuildException be) { + assertEquals("test error", + be.getMessage()); + } + } + + + /** + * This is a helper method that takes a selector and calls its + * isSelected() method on each file in the testbed. It returns + * a string of "T"s amd "F"s + */ + public String selectionString(FileSelector selector) { + return selectionString(beddir,files,selector); + } + + /** + * This is a helper method that takes a selector and calls its + * isSelected() method on each file in the mirror testbed. This + * variation is used for dependency checks and to get around the + * limitations in the touch task when running JDK 1.1. It returns + * a string of "T"s amd "F"s. + */ + public String mirrorSelectionString(FileSelector selector) { + return selectionString(mirrordir,mirrorfiles,selector); + } + + /** + * Worker method for the two convenience methods above. Applies a + * selector on a set of files passed in and returns a string of + * "T"s amd "F"s from applying the selector to each file. + */ + public String selectionString(File basedir, File[] files, FileSelector selector) { + StringBuffer buf = new StringBuffer(); + for (int x = 0; x < files.length; x++) { + if (selector.isSelected(basedir,filenames[x],files[x])) { + buf.append('T'); + } + else { + buf.append('F'); + } + } + return buf.toString(); + } + + /** + * Does the selection test for a given selector and prints the + * filenames of the differing files (selected but shouldn't, + * not selected but should). + * @param selector The selector to test + * @param expected The expected result + */ + public void performTests(FileSelector selector, String expected) { + String result = selectionString(selector); + String diff = diff(expected, result); + String resolved = resolve(diff); + assertEquals("Differing files: " + resolved, result, expected); + } + + /** + * Checks which files are selected and shouldn't be or which + * are not selected but should. + * @param expected String containing 'F's and 'T's + * @param result String containing 'F's and 'T's + * @return Difference as String containing '-' (equal) and + * 'X' (difference). + */ + public String diff(String expected, String result) { + int length1 = expected.length(); + int length2 = result.length(); + int min = (length1 > length2) ? length2 : length1; + StringBuffer sb = new StringBuffer(); + for (int i=0; i filelist.length()) + ? filelist.length() + : filenames.length; + for (int i=0; iCreates a testbed. We avoid the dreaded "test" word so that we + * don't falsely identify this as a test to be run. The actual + * setting up of the testbed is done in the + * src/etc/testcases/types/selectors.xml build file.

+ * + *

Note that the right way to call this is within a try block, + * with a finally clause that calls cleanupBed(). You place tests of + * the isSelected() method within the try block.

+ */ + protected void makeBed() { + tbed = new TaskdefForMakingBed("setupfiles"); + tbed.setUp(); + tbed.makeTestbed(); + } + + /** + * Cleans up the testbed by calling a target in the + * src/etc/testcases/types/selectors.xml file. + */ + protected void cleanupBed() { + if (tbed != null) { + tbed.tearDown(); + tbed = null; + } + } + + + /** + *

Creates a mirror of the testbed for use in dependency checks.

+ * + *

Note that the right way to call this is within a try block, + * with a finally clause that calls cleanupMirror(). You place tests of + * the isSelected() method within the try block.

+ */ + protected void makeMirror() { + tbed = new TaskdefForMakingBed("mirrorfiles"); + tbed.setUp(); + tbed.makeMirror(); + } + + /** + * Cleans up the mirror testbed by calling a target in the + * src/etc/testcases/types/selectors.xml file. + */ + protected void cleanupMirror() { + if (tbed != null) { + tbed.deleteMirror(); + tbed = null; + } + } + + private class TaskdefForMakingBed extends BuildFileTest { + + TaskdefForMakingBed(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/selectors.xml"); + } + + public void tearDown() { + executeTarget("cleanup"); + } + + public void makeTestbed() { + executeTarget("setupfiles"); + } + + public void makeMirror() { + executeTarget("mirrorfiles"); + } + + public void deleteMirror() { + executeTarget("cleanup.mirrorfiles"); + } + } + + + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsRegexpTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsRegexpTest.java new file mode 100644 index 000000000..b3ba47cbe --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsRegexpTest.java @@ -0,0 +1,84 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import java.io.File; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildFileTest; +import org.apache.tools.ant.Project; + + +public class ContainsRegexpTest extends TestCase { + + private Project project; + + public ContainsRegexpTest(String name) { + super(name); + } + + public void setUp() { + project = new Project(); + project.setBasedir("."); + } + + public void testContainsRegexp() { + TaskdefForRegexpTest MyTask = + new TaskdefForRegexpTest("containsregexp"); + try { + MyTask.setUp(); + MyTask.test(); + } finally { + MyTask.tearDown(); + } + } + + private class TaskdefForRegexpTest extends BuildFileTest { + TaskdefForRegexpTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/selectors.xml"); + } + + public void tearDown() { + executeTarget("cleanupregexp"); + } + + public void test() { + File dir = null; + File[] files = null; + int filecount; + + executeTarget("containsregexp"); + + dir = new File(getProjectDir() + "/regexpseltestdest/"); + files = dir.listFiles(); + filecount = files.length; + + if (filecount != 1) + assertEquals("ContainsRegexp test should have copied 1 file", + 1, files.length); + + } + } +} + diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsSelectorTest.java new file mode 100644 index 000000000..bde5ecef8 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsSelectorTest.java @@ -0,0 +1,123 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Parameter; + +/** + * Tests Contains Selectors. + * + */ +public class ContainsSelectorTest extends BaseSelectorTest { + + private Project project; + + public ContainsSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new ContainsSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + ContainsSelector s = (ContainsSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("ContainsSelector did not check for required field 'text'"); + } catch (BuildException be1) { + assertEquals("The text attribute is required", be1.getMessage()); + } + + s = (ContainsSelector)getInstance(); + Parameter param = new Parameter(); + param.setName("garbage in"); + param.setValue("garbage out"); + Parameter[] params = {param}; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("ContainsSelector did not check for valid parameter element"); + } catch (BuildException be2) { + assertEquals("Invalid parameter garbage in", be2.getMessage()); + } + + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + ContainsSelector s; + String results; + + try { + makeBed(); + + s = (ContainsSelector)getInstance(); + s.setText("no such string in test files"); + results = selectionString(s); + assertEquals("TFFFFFFFFFFT", results); + + s = (ContainsSelector)getInstance(); + s.setText("Apache Ant"); + results = selectionString(s); + assertEquals("TFFFTFFFFFFT", results); + + s = (ContainsSelector)getInstance(); + s.setText("apache ant"); + s.setCasesensitive(true); + results = selectionString(s); + assertEquals("TFFFFFFFFFFT", results); + + s = (ContainsSelector)getInstance(); + s.setText("apache ant"); + s.setCasesensitive(false); + results = selectionString(s); + assertEquals("TFFFTFFFFFFT", results); + + s = (ContainsSelector)getInstance(); + s.setText("ApacheAnt"); + s.setIgnorewhitespace(true); + results = selectionString(s); + assertEquals("TFFFTFFFFFFT", results); + + s = (ContainsSelector)getInstance(); + s.setText("A p a c h e A n t"); + s.setIgnorewhitespace(true); + results = selectionString(s); + assertEquals("TFFFTFFFFFFT", results); + + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/DateSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/DateSelectorTest.java new file mode 100644 index 000000000..2126d4334 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/DateSelectorTest.java @@ -0,0 +1,239 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Parameter; + +import java.text.SimpleDateFormat; +import java.text.ParsePosition; +import java.util.Date; + + +/** + * Tests Date Selectors. + * + */ +public class DateSelectorTest extends BaseSelectorTest { + + private Project project; + + public DateSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new DateSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + DateSelector s = (DateSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DateSelector did not check for required fields"); + } catch (BuildException be1) { + assertEquals("You must provide a datetime or the number of " + + "milliseconds.", be1.getMessage()); + } + + s = (DateSelector)getInstance(); + s.setDatetime("01/01/1969 01:01 AM"); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DateSelector did not check for Datetime being in the " + + "allowable range"); + } catch (BuildException be2) { + assertEquals("Date of 01/01/1969 01:01 AM results in negative " + + "milliseconds value relative to epoch (January 1, " + + "1970, 00:00:00 GMT).", be2.getMessage()); + } + + s = (DateSelector)getInstance(); + s.setDatetime("this is not a date"); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DateSelector did not check for Datetime being in a " + + "valid format"); + } catch (BuildException be3) { + assertEquals("Date of this is not a date" + + " Cannot be parsed correctly. It should be in" + + " MM/DD/YYYY HH:MM AM_PM format.", be3.getMessage()); + } + + s = (DateSelector)getInstance(); + Parameter param = new Parameter(); + param.setName("garbage in"); + param.setValue("garbage out"); + Parameter[] params = new Parameter[1]; + params[0] = param; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DateSelector did not check for valid parameter element"); + } catch (BuildException be4) { + assertEquals("Invalid parameter garbage in", be4.getMessage()); + } + + s = (DateSelector)getInstance(); + param = new Parameter(); + param.setName("millis"); + param.setValue("garbage out"); + params[0] = param; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DateSelector did not check for valid millis parameter"); + } catch (BuildException be5) { + assertEquals("Invalid millisecond setting garbage out", + be5.getMessage()); + } + + s = (DateSelector)getInstance(); + param = new Parameter(); + param.setName("granularity"); + param.setValue("garbage out"); + params[0] = param; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DateSelector did not check for valid granularity parameter"); + } catch (BuildException be6) { + assertEquals("Invalid granularity setting garbage out", + be6.getMessage()); + } + + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + DateSelector s; + String results; + + DateSelector.TimeComparisons before = new + DateSelector.TimeComparisons(); + before.setValue("before"); + DateSelector.TimeComparisons equal = new + DateSelector.TimeComparisons(); + equal.setValue("equal"); + DateSelector.TimeComparisons after = new + DateSelector.TimeComparisons(); + after.setValue("after"); + + try { + makeBed(); + + s = (DateSelector)getInstance(); + s.setDatetime("10/10/1999 1:45 PM"); + s.setWhen(before); + results = selectionString(s); + assertEquals("TFFFFFFFFFFT", results); + + s = (DateSelector)getInstance(); + s.setDatetime("10/10/1999 1:45 PM"); + s.setWhen(before); + s.setCheckdirs(true); + results = selectionString(s); + assertEquals("FFFFFFFFFFFF", results); + + s = (DateSelector)getInstance(); + s.setDatetime("10/10/1999 1:45 PM"); + s.setWhen(after); + results = selectionString(s); + assertEquals("TTTTTTTTTTTT", results); + + s = (DateSelector)getInstance(); + s.setDatetime("11/21/2001 4:54 AM"); + s.setWhen(before); + results = selectionString(s); + assertEquals("TFTFFFFFFFFT", results); + + s = (DateSelector)getInstance(); + s.setDatetime("11/21/2001 4:55 AM"); + SimpleDateFormat formatter = new SimpleDateFormat(); + Date d = formatter.parse("11/21/2001 4:55 AM",new ParsePosition(0)); + + long milliseconds = s.getMillis(); + s.setWhen(equal); + results = selectionString(s); + assertEquals("TTFFTFFFTTTT", results); + + s = (DateSelector)getInstance(); + s.setMillis(milliseconds); + s.setWhen(equal); + results = selectionString(s); + assertEquals("TTFFTFFFTTTT", results); + + s = (DateSelector)getInstance(); + s.setDatetime("11/21/2001 4:56 AM"); + s.setWhen(after); + results = selectionString(s); + assertEquals("TFFTFTTTFFFT", results); + + s = (DateSelector)getInstance(); + Parameter param1 = new Parameter(); + Parameter param2 = new Parameter(); + param1.setName("datetime"); + param1.setValue("11/21/2001 4:56 AM"); + param2.setName("when"); + param2.setValue("after"); + Parameter[] params = {param1,param2}; + s.setParameters(params); + results = selectionString(s); + assertEquals("TFFTFTTTFFFT", results); + try { + makeMirror(); + + s = (DateSelector)getInstance(); + long testtime = mirrorfiles[5].lastModified(); + s.setMillis(testtime); + s.setWhen(after); + s.setGranularity(2); + results = mirrorSelectionString(s); + assertEquals("TFFFFTTTTTTT", results); + + s = (DateSelector)getInstance(); + testtime = mirrorfiles[6].lastModified(); + s.setMillis(testtime); + s.setWhen(before); + s.setGranularity(2); + results = mirrorSelectionString(s); + assertEquals("TTTTTTTFFFFT", results); + } + finally { + cleanupMirror(); + } + + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/DependSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/DependSelectorTest.java new file mode 100644 index 000000000..6dc9e8950 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/DependSelectorTest.java @@ -0,0 +1,172 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Mapper; + +import java.io.File; + + +/** + * Tests Depend Selectors + * + */ +public class DependSelectorTest extends BaseSelectorTest { + + private Project project; + + public DependSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new DependSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + DependSelector s = (DependSelector)getInstance(); + try { + s.createMapper(); + s.createMapper(); + fail("DependSelector allowed more than one nested mapper."); + } catch (BuildException be1) { + assertEquals("Cannot define more than one mapper", + be1.getMessage()); + } + + s = (DependSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DependSelector did not check for required fields"); + } catch (BuildException be2) { + assertEquals("The targetdir attribute is required.", + be2.getMessage()); + } + + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + DependSelector s; + String results; + File subdir; + Mapper m; + Mapper.MapperType identity = new Mapper.MapperType(); + identity.setValue("identity"); + Mapper.MapperType glob = new Mapper.MapperType(); + glob.setValue("glob"); + Mapper.MapperType merge = new Mapper.MapperType(); + merge.setValue("merge"); + + try { + makeBed(); + + s = (DependSelector)getInstance(); + s.setTargetdir(beddir); + results = selectionString(s); + assertEquals("FFFFFFFFFFFF", results); + + s = (DependSelector)getInstance(); + s.setTargetdir(beddir); + m = s.createMapper(); + m.setType(identity); + results = selectionString(s); + assertEquals("FFFFFFFFFFFF", results); + + s = (DependSelector)getInstance(); + s.setTargetdir(beddir); + m = s.createMapper(); + m.setType(merge); + m.setTo("asf-logo.gif.gz"); + results = selectionString(s); + assertEquals("TFFFFTTTFFF", results.substring(0,11)); + + s = (DependSelector)getInstance(); + s.setTargetdir(beddir); + m = s.createMapper(); + m.setType(merge); + m.setTo("asf-logo.gif.bz2"); + results = selectionString(s); + assertEquals("TTFTTTTTTTTT", results); + + // Test for path relative to project base directory + s = (DependSelector)getInstance(); + subdir = new File("selectortest/tar/bz2"); + s.setTargetdir(subdir); + m = s.createMapper(); + m.setType(glob); + m.setFrom("*.bz2"); + m.setTo("*.tar.bz2"); + results = selectionString(s); + assertEquals("FFTFFFFFFTTF", results); + + s = (DependSelector)getInstance(); + subdir = new File(beddir,"tar/bz2"); + s.setTargetdir(subdir); + m = s.createMapper(); + m.setType(glob); + m.setFrom("*.bz2"); + m.setTo("*.tar.bz2"); + results = selectionString(s); + assertEquals("FFFFFFFFFTTF", results); + + try { + makeMirror(); + + s = (DependSelector)getInstance(); + File testdir = getProject().resolveFile("selectortest2"); + s.setTargetdir(testdir); + results = selectionString(s); + assertEquals("FFFTTFFFFFFF", results); + + s = (DependSelector)getInstance(); + testdir = getProject().resolveFile("selectortest2/tar/bz2"); + s.setTargetdir(testdir); + m = s.createMapper(); + m.setType(glob); + m.setFrom("*.bz2"); + m.setTo("*.tar.bz2"); + results = mirrorSelectionString(s); + assertEquals("FFFFFFFFFTTF", results); + results = selectionString(s); + assertEquals("FFFFFFFFFTTF", results); + } + finally { + cleanupMirror(); + } + + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/DepthSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/DepthSelectorTest.java new file mode 100644 index 000000000..64c260fe9 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/DepthSelectorTest.java @@ -0,0 +1,158 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Parameter; + +/** + * Tests Depth Selectors + * + */ +public class DepthSelectorTest extends BaseSelectorTest { + + private Project project; + + public DepthSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new DepthSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + DepthSelector s = (DepthSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DepthSelector did not check for required fields"); + } catch (BuildException be1) { + assertEquals("You must set at least one of the min or the " + + "max levels.", be1.getMessage()); + } + + s = (DepthSelector)getInstance(); + s.setMin(5); + s.setMax(2); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DepthSelector did not check for maximum being higher " + + "than minimum"); + } catch (BuildException be2) { + assertEquals("The maximum depth is lower than the minimum.", + be2.getMessage()); + } + + s = (DepthSelector)getInstance(); + Parameter param = new Parameter(); + param.setName("garbage in"); + param.setValue("garbage out"); + Parameter[] params = new Parameter[1]; + params[0] = param; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DepthSelector did not check for valid parameter element"); + } catch (BuildException be3) { + assertEquals("Invalid parameter garbage in", be3.getMessage()); + } + + s = (DepthSelector)getInstance(); + param = new Parameter(); + param.setName("min"); + param.setValue("garbage out"); + params[0] = param; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DepthSelector accepted bad minimum as parameter"); + } catch (BuildException be4) { + assertEquals("Invalid minimum value garbage out", + be4.getMessage()); + } + + s = (DepthSelector)getInstance(); + param = new Parameter(); + param.setName("max"); + param.setValue("garbage out"); + params[0] = param; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("DepthSelector accepted bad maximum as parameter"); + } catch (BuildException be5) { + assertEquals("Invalid maximum value garbage out", + be5.getMessage()); + } + + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + DepthSelector s; + String results; + + try { + makeBed(); + + s = (DepthSelector)getInstance(); + s.setMin(20); + s.setMax(25); + results = selectionString(s); + assertEquals("FFFFFFFFFFFF", results); + + s = (DepthSelector)getInstance(); + s.setMin(0); + results = selectionString(s); + assertEquals("TTTTTTTTTTTT", results); + + s = (DepthSelector)getInstance(); + s.setMin(1); + results = selectionString(s); + assertEquals("FFFFFTTTTTTT", results); + + s = (DepthSelector)getInstance(); + s.setMax(0); + results = selectionString(s); + assertEquals("TTTTTFFFFFFF", results); + + s = (DepthSelector)getInstance(); + s.setMin(1); + s.setMax(1); + results = selectionString(s); + assertEquals("FFFFFTTTFFFT", results); + + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/FilenameSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/FilenameSelectorTest.java new file mode 100644 index 000000000..2083d6341 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/FilenameSelectorTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Parameter; + +/** + * Tests Filename Selectors + * + */ +public class FilenameSelectorTest extends BaseSelectorTest { + + private Project project; + + public FilenameSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new FilenameSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + FilenameSelector s = (FilenameSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("FilenameSelector did not check for required fields"); + } catch (BuildException be1) { + assertEquals("The name attribute is required", be1.getMessage()); + } + + s = (FilenameSelector)getInstance(); + Parameter param = new Parameter(); + param.setName("garbage in"); + param.setValue("garbage out"); + Parameter[] params = {param}; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("FilenameSelector did not check for valid parameter element"); + } catch (BuildException be2) { + assertEquals("Invalid parameter garbage in", be2.getMessage()); + } + + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + FilenameSelector s; + String results; + + try { + makeBed(); + + s = (FilenameSelector)getInstance(); + s.setName("no match possible"); + results = selectionString(s); + assertEquals("FFFFFFFFFFFF", results); + + s = (FilenameSelector)getInstance(); + s.setName("*.gz"); + results = selectionString(s); + // This is turned off temporarily. There appears to be a bug + // in SelectorUtils.matchPattern() where it is recursive on + // Windows even if no ** is in pattern. + //assertEquals("FFFTFFFFFFFF", results); // Unix + // vs + //assertEquals("FFFTFFFFTFFF", results); // Windows + + s = (FilenameSelector)getInstance(); + s.setName("**/*.gz"); + s.setNegate(true); + results = selectionString(s); + assertEquals("TTTFTTTFFTTT", results); + + s = (FilenameSelector)getInstance(); + s.setName("**/*.GZ"); + s.setCasesensitive(false); + results = selectionString(s); + assertEquals("FFFTFFFTTFFF", results); + + s = (FilenameSelector)getInstance(); + Parameter param1 = new Parameter(); + param1.setName("name"); + param1.setValue("**/*.bz2"); + Parameter[] params = {param1}; + s.setParameters(params); + results = selectionString(s); + assertEquals("FFTFFFFFFTTF", results); + + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/MockAlgorithm.java b/src/tests/junit/org/apache/tools/ant/types/selectors/MockAlgorithm.java new file mode 100644 index 000000000..12c9f0828 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/MockAlgorithm.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + + +import java.io.File; +import org.apache.tools.ant.types.selectors.modifiedselector.Algorithm; + +public class MockAlgorithm implements Algorithm { + public boolean isValid() { + return true; + } + + public String getValue(File file) { + return "TEST"; + } + + public String toString() { + return "MockAlgorithm@" + hashCode(); + } +} \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/MockCache.java b/src/tests/junit/org/apache/tools/ant/types/selectors/MockCache.java new file mode 100644 index 000000000..e60def23d --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/MockCache.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + + +import java.util.Iterator; +import org.apache.tools.ant.types.selectors.modifiedselector.Cache; + +public class MockCache implements Cache { + + public boolean debug = false; + public boolean saved = false; + + + public MockCache() { + log("()"); + } + + public boolean isValid() { + log(".isValid()"); + return true; + } + public void delete() { + log(".delete()"); + } + public void load() { + log(".load()"); + } + public void save() { + log(".save()"); + saved = true; + } + public Object get(Object key) { + log(".get("+key+")"); + return key; + } + public void put(Object key, Object value) { + log(".put("+key+", "+value+")"); + saved = false; + } + public Iterator iterator() { + log("iterator()"); + return null; + } + public String toString() { + return "MockCache@" + hashCode(); + } + + private void log(String msg) { + if (debug) System.out.println(this+msg); + } +}//class-MockCache \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/MockComparator.java b/src/tests/junit/org/apache/tools/ant/types/selectors/MockComparator.java new file mode 100644 index 000000000..e77ec854f --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/MockComparator.java @@ -0,0 +1,32 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import java.util.Comparator; + +public class MockComparator implements Comparator { + + public int compare(Object o1, Object o2) { + return 0; + } + + public String toString() { + return "MockComparator"; + } +}//class-MockCache \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java new file mode 100644 index 000000000..adfa7ea8c --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java @@ -0,0 +1,1017 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + + +// Java +import java.io.File; +import java.text.RuleBasedCollator; +import java.util.Comparator; +import java.util.Iterator; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Target; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.Parameter; +import org.apache.tools.ant.types.Path; +import org.apache.tools.ant.types.selectors.modifiedselector.Algorithm; +import org.apache.tools.ant.types.selectors.modifiedselector.Cache; +import org.apache.tools.ant.types.selectors.modifiedselector.ChecksumAlgorithm; +import org.apache.tools.ant.types.selectors.modifiedselector.DigestAlgorithm; +import org.apache.tools.ant.types.selectors.modifiedselector.EqualComparator; +import org.apache.tools.ant.types.selectors.modifiedselector.HashvalueAlgorithm; +import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector; +import org.apache.tools.ant.types.selectors.modifiedselector.PropertiesfileCache; +import org.apache.tools.ant.util.FileUtils; + + +/** + * Unit tests for ModifiedSelector. + * + * @since Ant 1.6 + */ +public class ModifiedSelectorTest extends BaseSelectorTest { + + /** Utilities used for file operations */ + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + + // ===================== attributes ===================== + + + /** Package of the CacheSelector classes. */ + private static String pkg = "org.apache.tools.ant.types.selectors.modifiedselector"; + + /** Path where the testclasses are. */ + private Path testclasses = null; + + + // ===================== constructors, factories ===================== + + + public ModifiedSelectorTest(String name) { + super(name); + } + + + /** + * Factory method from base class. This should be overriden in child + * classes to return a specific Selector class (like here). + */ + public BaseSelector getInstance() { + return new ModifiedSelector(); + } + + + // ===================== JUnit stuff ===================== + + + public void setUp() { + // project reference is set in super.setUp() + super.setUp(); + // init the testclasses path object + Project prj = getProject(); + if (prj != null) { + testclasses = new Path(prj, prj.getProperty("build.tests.value")); + } + } + + + /* * / + // for test only - ignore tests where we arent work at the moment + public static junit.framework.Test suite() { + junit.framework.TestSuite suite= new junit.framework.TestSuite(); + suite.addTest(new ModifiedSelectorTest("testValidateWrongCache")); + return suite; + } + /* */ + + + // ======= testcases for the attributes and nested elements of the selector ===== + + + /** Test right use of cache names. */ + public void testValidateWrongCache() { + String name = "this-is-not-a-valid-cache-name"; + try { + ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName(); + cacheName.setValue(name); + fail("CacheSelector.CacheName accepted invalid value."); + } catch (BuildException be) { + assertEquals(name + " is not a legal value for this attribute", + be.getMessage()); + } + } + + + /** Test right use of cache names. */ + public void testValidateWrongAlgorithm() { + String name = "this-is-not-a-valid-algorithm-name"; + try { + ModifiedSelector.AlgorithmName algoName + = new ModifiedSelector.AlgorithmName(); + algoName.setValue(name); + fail("CacheSelector.AlgorithmName accepted invalid value."); + } catch (BuildException be) { + assertEquals(name + " is not a legal value for this attribute", + be.getMessage()); + } + } + + + /** Test right use of comparator names. */ + public void testValidateWrongComparator() { + String name = "this-is-not-a-valid-comparator-name"; + try { + ModifiedSelector.ComparatorName compName + = new ModifiedSelector.ComparatorName(); + compName.setValue(name); + fail("ModifiedSelector.ComparatorName accepted invalid value."); + } catch (BuildException be) { + assertEquals(name + " is not a legal value for this attribute", + be.getMessage()); + } + } + + + public void testIllegalCustomAlgorithm() { + try { + String algo = getAlgoName("java.lang.Object"); + fail("Illegal classname used."); + } catch (Exception e) { + assertTrue("Wrong exception type: " + e.getClass().getName(), e instanceof BuildException); + assertEquals("Wrong exception message.", + "Specified class (java.lang.Object) is not an Algorithm.", + e.getMessage()); + + } + } + + + public void testNonExistentCustomAlgorithm() { + boolean noExcThrown = false; + try { + String algo = getAlgoName("non.existent.custom.Algorithm"); + noExcThrown = true; + } catch (Exception e) { + if (noExcThrown) { + fail("does 'non.existent.custom.Algorithm' really exist?"); + } + assertTrue("Wrong exception type: " + e.getClass().getName(), e instanceof BuildException); + assertEquals("Wrong exception message.", + "Specified class (non.existent.custom.Algorithm) not found.", + e.getMessage()); + + } + } + + + public void testCustomAlgorithm() { + String algo = getAlgoName("org.apache.tools.ant.types.selectors.modifiedselector.HashvalueAlgorithm"); + assertTrue("Wrong algorithm used: "+algo, algo.startsWith("HashvalueAlgorithm")); + } + + + public void testCustomAlgorithm2() { + String algo = getAlgoName("org.apache.tools.ant.types.selectors.MockAlgorithm"); + assertTrue("Wrong algorithm used: "+algo, algo.startsWith("MockAlgorithm")); + } + + + public void testCustomClasses() { + BFT bft = new BFT(); + bft.setUp(); + try { + // do the actions + bft.doTarget("modifiedselectortest-customClasses"); + // do the checks - the buildfile stores the fileset as property + String fsFullValue = bft.getProperty("fs.full.value"); + String fsModValue = bft.getProperty("fs.mod.value"); + + assertNotNull("'fs.full.value' must be set.", fsFullValue); + assertTrue("'fs.full.value' must not be null.", !"".equals(fsFullValue)); + assertTrue("'fs.full.value' must contain ant.bat.", fsFullValue.indexOf("ant.bat")>-1); + + assertNotNull("'fs.mod.value' must be set.", fsModValue); + // must be empty according to the Mock* implementations + assertTrue("'fs.mod.value' must be empty.", "".equals(fsModValue)); + // don't catch the JUnit exceptions + } finally { + bft.doTarget("modifiedselectortest-scenario-clean"); + bft.deletePropertiesfile(); + bft.tearDown(); + } + } + + + public void testDelayUpdateTaskFinished() { + doDelayUpdateTest(1); + } + + + public void testDelayUpdateTargetFinished() { + doDelayUpdateTest(2); + } + + + public void testDelayUpdateBuildFinished() { + doDelayUpdateTest(3); + } + + + public void doDelayUpdateTest(int kind) { + // no check for 1<=kind<=3 - only internal use therefore check it + // while development + + // readable form of parameter kind + String[] kinds = {"task", "target", "build"}; + + // setup the "Ant project" + MockProject project = new MockProject(); + File base = new File("base"); + File file1 = new File("file1"); + File file2 = new File("file2"); + + // setup the selector + ModifiedSelector sel = new ModifiedSelector(); + sel.setProject(project); + sel.setUpdate(true); + sel.setDelayUpdate(true); + // sorry - otherwise we will get a ClassCastException because the MockCache + // is loaded by two different classloader ... + sel.setClassLoader(this.getClass().getClassLoader()); + sel.addClasspath(testclasses); + + sel.setAlgorithmClass("org.apache.tools.ant.types.selectors.MockAlgorithm"); + sel.setCacheClass("org.apache.tools.ant.types.selectors.MockCache"); + sel.configure(); + + // get the cache, so we can check our things + MockCache cache = (MockCache)sel.getCache(); + + // the test + assertFalse("Cache must not be saved before 1st selection.", cache.saved); + sel.isSelected(base, "file1", file1); + assertFalse("Cache must not be saved after 1st selection.", cache.saved); + sel.isSelected(base, "file2", file2); + assertFalse("Cache must not be saved after 2nd selection.", cache.saved); + switch (kind) { + case 1 : project.fireTaskFinished(); break; + case 2 : project.fireTargetFinished(); break; + case 3 : project.fireBuildFinished(); break; + } + assertTrue("Cache must be saved after " + kinds[kind-1] + "Finished-Event.", cache.saved); + + // MockCache doesnt create a file - therefore no cleanup needed + } + + + /** + * Extracts the real used algorithm name from the ModifiedSelector using + * its toString() method. + * @param classname the classname from the algorithm to use + * @return the algorithm part from the toString() (without brackets) + */ + private String getAlgoName(String classname) { + ModifiedSelector sel = new ModifiedSelector(); + // add the test classes to its classpath + sel.addClasspath(testclasses); + sel.setAlgorithmClass(classname); + // let the selector do its checks + sel.validate(); + // extract the algorithm name (and config) from the selectors output + String s1 = sel.toString(); + int posStart = s1.indexOf("algorithm=") + 10; + int posEnd = s1.indexOf(" comparator="); + String algo = s1.substring(posStart, posEnd); + // '<' and '>' are only used if the algorithm has properties + if (algo.startsWith("<")) algo = algo.substring(1); + if (algo.endsWith(">")) algo = algo.substring(0, algo.length()-1); + // return the clean value + return algo; + } + + + // ================ testcases for the cache implementations ================ + + + /** + * Propertycache must have a set 'cachefile' attribute. + * The default in ModifiedSelector "cache.properties" is set by the selector. + */ + public void testPropcacheInvalid() { + Cache cache = new PropertiesfileCache(); + if (cache.isValid()) + fail("PropertyfilesCache does not check its configuration."); + } + + + public void testPropertyfileCache() { + PropertiesfileCache cache = new PropertiesfileCache(); + File cachefile = new File("cache.properties"); + cache.setCachefile(cachefile); + doTest(cache); + assertFalse("Cache file not deleted.", cachefile.exists()); + } + + + /** Checks whether a cache file is created. */ + public void testCreatePropertiesCacheDirect() { + File cachefile = new File(basedir, "cachefile.properties"); + + PropertiesfileCache cache = new PropertiesfileCache(); + cache.setCachefile(cachefile); + + cache.put("key", "value"); + cache.save(); + + assertTrue("Cachefile not created.", cachefile.exists()); + + cache.delete(); + assertFalse("Cachefile not deleted.", cachefile.exists()); + } + + + /** Checks whether a cache file is created. */ + public void testCreatePropertiesCacheViaModifiedSelector() { + File cachefile = new File(basedir, "cachefile.properties"); + try { + + // initialize test environment (called "bed") + makeBed(); + + // Configure the selector + ModifiedSelector s = (ModifiedSelector)getSelector(); + s.setDelayUpdate(false); + s.addParam("cache.cachefile", cachefile); + + ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName(); + cacheName.setValue("propertyfile"); + s.setCache(cacheName); + + s.setUpdate(true); + + // does the selection + String results = selectionString(s); + + // evaluate correctness + assertTrue("Cache file is not created.", cachefile.exists()); + } finally { + cleanupBed(); + if (cachefile!=null) cachefile.delete(); + } + } + + + /** + * In earlier implementations there were problems with the order + * of the s. The scenario was
+     *   
+     *       
+     *       
+     *   
+     * 
It was important first to set the cache and then to set + * the cache's configuration parameters. That results in the reorganized + * configure() method of ModifiedSelector. This testcase tests that. + */ + public void testCreatePropertiesCacheViaCustomSelector() { + File cachefile = FILE_UTILS.createTempFile("tmp-cache-", ".properties", null); + try { + // initialize test environment (called "bed") + makeBed(); + + // Configure the selector + + ExtendSelector s = new ExtendSelector(); + s.setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector"); + s.addParam(createParam("update", "true")); + s.addParam(createParam("cache.cachefile", cachefile.getAbsolutePath())); + s.addParam(createParam("cache", "propertyfile")); + + // does the selection + String results = selectionString(s); + + // evaluate correctness + assertTrue("Cache file is not created.", cachefile.exists()); + } finally { + cleanupBed(); + if (cachefile!=null) cachefile.delete(); + } + } + + + public void _testCustomCache() { + // same logic as on algorithm, no testcases created + } + + + /** + * Test the interface semantic of Caches. + * This method does some common test for cache implementations. + * A cache must return a stored value and a valid iterator. + * After calling the delete() the cache must be empty. + * + * @param algo configured test object + */ + protected void doTest(Cache cache) { + assertTrue("Cache not proper configured.", cache.isValid()); + + String key1 = "key1"; + String value1 = "value1"; + String key2 = "key2"; + String value2 = "value2"; + + // given cache must be empty + Iterator it1 = cache.iterator(); + assertFalse("Cache is not empty", it1.hasNext()); + + // cache must return a stored value + cache.put(key1, value1); + cache.put(key2, value2); + assertEquals("cache returned wrong value", value1, cache.get(key1)); + assertEquals("cache returned wrong value", value2, cache.get(key2)); + + // test the iterator + Iterator it2 = cache.iterator(); + Object returned = it2.next(); + boolean ok = (key1.equals(returned) || key2.equals(returned)); + String msg = "Iterator returned unexpected value." + + " key1.equals(returned)="+key1.equals(returned) + + " key2.equals(returned)="+key2.equals(returned) + + " returned="+returned + + " ok="+ok; + assertTrue(msg, ok); + + // clear the cache + cache.delete(); + Iterator it3 = cache.iterator(); + assertFalse("Cache is not empty", it1.hasNext()); + } + + + // ============== testcases for the algorithm implementations ============== + + + public void testHashvalueAlgorithm() { + HashvalueAlgorithm algo = new HashvalueAlgorithm(); + doTest(algo); + } + + + public void testDigestAlgorithmMD5() { + DigestAlgorithm algo = new DigestAlgorithm(); + algo.setAlgorithm("MD5"); + doTest(algo); + } + + + public void testDigestAlgorithmSHA() { + DigestAlgorithm algo = new DigestAlgorithm(); + algo.setAlgorithm("SHA"); + doTest(algo); + } + + + public void testChecksumAlgorithm() { + ChecksumAlgorithm algo = new ChecksumAlgorithm(); + doTest(algo); + } + + + public void testChecksumAlgorithmCRC() { + ChecksumAlgorithm algo = new ChecksumAlgorithm(); + algo.setAlgorithm("CRC"); + doTest(algo); + } + + + public void testChecksumAlgorithmAdler() { + ChecksumAlgorithm algo = new ChecksumAlgorithm(); + algo.setAlgorithm("Adler"); + doTest(algo); + } + + + /** + * Test the interface semantic of Algorithms. + * This method does some common test for algorithm implementations. + * An algorithm must return always the same value for the same file and + * it must not return null. + * + * @param algo configured test object + */ + protected void doTest(Algorithm algo) { + assertTrue("Algorithm not proper configured.", algo.isValid()); + try { + makeBed(); + + for (int i=0; i + *
  • try fist time --> should select all
  • + *
  • try second time --> should select no files (only directories)
  • + *
  • modify timestamp of one file and content of a nother one
  • + *
  • try third time --> should select only the file with modified + * content
  • + */ + public void testScenario1() { + BFT bft = null; + ModifiedSelector s = null; + try { + // + // ***** initialize test environment (called "bed") ***** + // + makeBed(); + String results = null; + + // Configure the selector - only defaults are used + s = (ModifiedSelector)getSelector(); + + // + // ***** First Run ***** + // the first call should get all files, because nothing is in + // the cache + // + performTests(s, "TTTTTTTTTTTT"); + + // + // ***** Second Run ***** + // the second call should get no files, because no content + // has changed + // + performTests(s, "TFFFFFFFFFFT"); + + // + // ***** make some files dirty ***** + // + + // these files are made dirty --> 3+4 with different content + String f2name = "tar/bz2/asf-logo-huge.tar.bz2"; + String f3name = "asf-logo.gif.md5"; + String f4name = "copy.filterset.filtered"; + + // AccessObject to the test-Ant-environment + bft = new BFT(); + // give some values (via property file) to that environment + bft.writeProperties("f2name="+f2name); + bft.writeProperties("f3name="+f3name); + bft.writeProperties("f4name="+f4name); + // call the target for making the files dirty + bft.doTarget("modifiedselectortest-makeDirty"); + + // + // ***** Third Run ***** + // third call should get only those files, which CONTENT changed + // (no timestamp changes required!) + results = selectionString(s); + + // + // ***** Check the result ***** + // + + // Mark all files which should be selected as (T)rue and all others + // as (F)alse. Directories are always selected so they always are + // (T)rue. + StringBuffer expected = new StringBuffer(); + for (int i=0; i selector. Used values are:
      + *
    • Cache: Propertyfile, + * cachefile={java.io.tmpdir}/mycache.txt
    • + *
    • Algorithm: Digest + * algorithm=SHA, Provider=null
    • + *
    • Comparator: java.text.RuleBasedCollator + *
    • Update: true
    • + */ + public void _testScenario2() { // RuleBasedCollator not yet supported - see Selector:375 note + ExtendSelector s = new ExtendSelector(); + BFT bft = new BFT(); + String cachefile = System.getProperty("java.io.tmpdir")+"/mycache.txt"; + try { + makeBed(); + + s.setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector"); + + s.addParam(createParam("cache.cachefile", cachefile)); + //s.addParam(createParam("algorithm.provider","---")); // i don't know any valid + s.addParam(createParam("cache","propertyfile")); + s.addParam(createParam("update","true")); + s.addParam(createParam("comparator","rule")); + s.addParam(createParam("algorithm.name","sha")); + s.addParam(createParam("algorithm","digest")); + + // first and second run + performTests(s, "TTTTTTTTTTTT"); + performTests(s, "TFFFFFFFFFFT"); + // make dirty + String f2name = "tar/bz2/asf-logo-huge.tar.bz2"; + String f3name = "asf-logo.gif.md5"; + String f4name = "copy.filterset.filtered"; + bft.writeProperties("f2name="+f2name); + bft.writeProperties("f3name="+f3name); + bft.writeProperties("f4name="+f4name); + bft.doTarget("modifiedselectortest-makeDirty"); + // third run + String results = selectionString(s); + StringBuffer expected = new StringBuffer(); + for (int i=0; i5); + assertTrue("Too much files copied on second time.", to2.list().length==0); + assertTrue("Too much files copied on third time.", to3.list().length==2); + // don't catch the JUnit exceptions + } finally { + bft.doTarget("modifiedselectortest-scenario-clean"); + bft.deletePropertiesfile(); + bft.tearDown(); + cachefile.delete(); + } + } + + + // ===================== helper methods and classes ==================== + + + /** + * Creates a configured parameter object. + * @param name name of the parameter + * @param value value of the parameter + * @return the parameter object + */ + private Parameter createParam(String name, String value) { + Parameter p = new Parameter(); + p.setName(name); + p.setValue(value); + return p; + } + + + /** + * The BFT class wrapps the selector test-builfile inside an + * ant project (BuildFileTest). It supports target execution + * and property transfer to that project. + */ + private class BFT extends org.apache.tools.ant.BuildFileTest { + String buildfile = "src/etc/testcases/types/selectors.xml"; + + BFT() { super("nothing"); } + BFT(String name) { + super(name); + } + + String propfile = "ModifiedSelectorTest.properties"; + + boolean isConfigured = false; + + public void setUp() { + configureProject(buildfile); + isConfigured = true; + } + + + /** + * This stub teardown is here because the outer class needs to call the + * tearDown method, and in the superclass it is protected. + */ + public void tearDown() { + try { + super.tearDown(); + } catch (Exception e) { + // ignore + } + } + + public void doTarget(String target) { + if (!isConfigured) setUp(); + executeTarget(target); + } + + public String getProperty(String property) { + return project.getProperty(property); + } + + public void writeProperties(String line) { + if (!isConfigured) setUp(); + File dir = getProject().getBaseDir(); + File file = new File(dir, propfile); + try { + java.io.FileWriter out = + new java.io.FileWriter(file.getAbsolutePath(), true); + out.write(line); + out.write(System.getProperty("line.separator")); + out.flush(); + out.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void deletePropertiesfile() { + if (!isConfigured) setUp(); + new File(getProject().getBaseDir(), propfile).delete(); + } + + public void deleteCachefile() { + File basedir = new File(buildfile).getParentFile(); + File cacheFile = new File(basedir, "cache.properties"); + cacheFile.delete(); + } + + public String getBuildfile() { + return buildfile; + } + public void setBuildfile(String buildfile) { + this.buildfile = buildfile; + } + }//class-BFT + + + /** + * MockProject wrappes a very small ant project (one target, one task) + * but provides public methods to fire the build events. + */ + private class MockProject extends Project { + private Task task; + private Target target; + + public MockProject() { + task = new Task(){ + public void execute() { + } + }; + task.setTaskName("testTask"); + target = new Target(); + target.setName("testTarget"); + target.setProject(this); + target.addTask(task); + task.setOwningTarget(target); + } + + public void fireBuildFinished() { + super.fireBuildFinished(null); + } + public void fireSubBuildFinished() { + super.fireSubBuildFinished(null); + } + public void fireTargetStarted() { + super.fireTargetStarted(target); + } + public void fireTargetFinished() { + super.fireTargetFinished(target, null); + } + public void fireTaskStarted() { + super.fireTaskStarted(task); + } + public void fireTaskFinished() { + super.fireTaskFinished(task, null); + } + }//class-MockProject + + +}//class-ModifiedSelectorTest \ No newline at end of file diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/PresentSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/PresentSelectorTest.java new file mode 100644 index 000000000..180faf3c1 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/PresentSelectorTest.java @@ -0,0 +1,154 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Mapper; + +import java.io.File; + + +/** + * Tests Present Selectors + * + */ +public class PresentSelectorTest extends BaseSelectorTest { + + private Project project; + + public PresentSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new PresentSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + PresentSelector s = (PresentSelector)getInstance(); + try { + s.createMapper(); + s.createMapper(); + fail("PresentSelector allowed more than one nested mapper."); + } catch (BuildException be1) { + assertEquals("Cannot define more than one mapper", + be1.getMessage()); + } + + s = (PresentSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("PresentSelector did not check for required fields"); + } catch (BuildException be2) { + assertEquals("The targetdir attribute is required.", + be2.getMessage()); + } + + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + PresentSelector s; + String results; + Mapper m; + Mapper.MapperType identity = new Mapper.MapperType(); + identity.setValue("identity"); + Mapper.MapperType glob = new Mapper.MapperType(); + glob.setValue("glob"); + Mapper.MapperType merge = new Mapper.MapperType(); + merge.setValue("merge"); + Mapper.MapperType flatten = new Mapper.MapperType(); + flatten.setValue("flatten"); + + try { + makeBed(); + + s = (PresentSelector)getInstance(); + s.setTargetdir(beddir); + results = selectionString(s); + assertEquals("TTTTTTTTTTTT", results); + + s = (PresentSelector)getInstance(); + s.setTargetdir(beddir); + m = s.createMapper(); + m.setType(identity); + results = selectionString(s); + assertEquals("TTTTTTTTTTTT", results); + + s = (PresentSelector)getInstance(); + File subdir = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/expected"); + s.setTargetdir(subdir); + m = s.createMapper(); + m.setType(flatten); + results = selectionString(s); + assertEquals("TTTTTTTTTTTF", results); + + s = (PresentSelector)getInstance(); + s.setTargetdir(beddir); + m = s.createMapper(); + m.setType(merge); + m.setTo("asf-logo.gif.gz"); + results = selectionString(s); + assertEquals("TTTTTTTTTTTT", results); + + s = (PresentSelector)getInstance(); + subdir = new File(beddir, "tar/bz2"); + s.setTargetdir(subdir); + m = s.createMapper(); + m.setType(glob); + m.setFrom("*.bz2"); + m.setTo("*.tar.bz2"); + results = selectionString(s); + assertEquals("FFTFFFFFFFFF", results); + + try { + makeMirror(); + + s = (PresentSelector)getInstance(); + subdir = getProject().resolveFile("selectortest2"); + s.setTargetdir(subdir); + results = mirrorSelectionString(s); + assertEquals("TTTFFTTTTTTT", results); + results = selectionString(s); + assertEquals("TTTFFTTTTTTT", results); + + + } + finally { + cleanupMirror(); + } + + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/README b/src/tests/junit/org/apache/tools/ant/types/selectors/README new file mode 100755 index 000000000..eb48f6bbc --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/README @@ -0,0 +1,96 @@ +A DESCRIPTION OF THE SELECTOR TEST FRAMEWORK + +When writing tests for selectors, I found that I wanted to have some +standard way of working with a set of files and testing whether one or +another of them was selected. To that end, I created a base class called +BaseSelectorTest that does most of the heavy lifting. Of course, you can +test your selectors any way you want, but if you want to reuse this code, +read on. + +What BaseSelectorTest does is use an ant build file +"src/etc/testcases/types/selector.xml" to copy a tree of files out of +"src/etc/testcases/taskdefs/expected" into a "selectortest" directories. +Then it takes a list of 12 of the files and directories in this tree, and +applies whatever selector you pass in to each one. It passes back to your +test a 12 character long string indicating which of the 12 files and +directories was selected, using 'T' for selected and 'F' for not selected. +In the Test class for your selector, you override the getInstance() method +to create your own type of selector, and set the elements of your selector +a variety of ways to ensure that the string of T's and F's returned when +the selector is applied to those 12 files is correct. + +So, for example, DepthSelectorTest.java extends BaseSelectorTest and has +the following code: + + + public BaseSelector getInstance() { + return new DepthSelector(); + } + + + public void testSelectionBehaviour() { + DepthSelector s; + String results; + + + try { + makeBed(); + + + s = (DepthSelector)getInstance(); + s.setMin(20); + s.setMax(25); + results = selectionString(s); + assertEquals("FFFFFFFFFFFF", results); + + + s = (DepthSelector)getInstance(); + s.setMin(0); + results = selectionString(s); + assertEquals("TTTTTTTTTTTT", results); + + + s = (DepthSelector)getInstance(); + s.setMin(1); + results = selectionString(s); + assertEquals("FFFFFTTTTTTT", results); + + +The first test says that none of the 12 files or directories will match if +the depth range for the selector is between 20 and 25 (that would be one +deep directory tree!). The second says that all files and directories +match if the minimum depth is set to 0 and the maximum isn't specified. The +third test says that if the minumum depth is 1, the first 5 entries in the +list of 12 will not be selected and the rest will. + + +You can find the 12 files and directories that are tested for selection in +the BaseSelectorTest class. I used a fixed list so that if someone added +new files to the src/etc/testcases/types directory it wouldn't break my +tests: + + + protected String[] filenames = {".","asf-logo.gif.md5","asf- + logo.gif.bz2", + "asf-logo.gif.gz","copy.filterset.filtered","zip/asf- + logo.gif.zip", + "tar/asf-logo.gif.tar","tar/asf-logo-huge.tar.gz", + "tar/gz/asf-logo.gif.tar.gz","tar/bz2/asf-logo.gif.tar.bz2", + "tar/bz2/asf-logo-huge.tar.bz2","tar/bz2"}; + + +If you wish to use this set of files and directories to test your selector, +you can reuse the BaseSelectorTest with no change to it. + +You may find you need to alter the build file so that you get some +variation in the files that your selector can work with. Most of the core +selectors have required that kind of modification. If you do that, make +sure that it doesn't alter the output strings on the other selector test, +or if it does that you update their expected return results. + +You may also want to alter the set of files you look at in a particular +selector test. Since the filelist in BaseSelectorTest is protected, you +should be able to override it as you need to. Or you can alter the fileset +in BaseSelectorTest itself, provided you update the test strings in all the +other unit tests. + diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/SignedSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/SignedSelectorTest.java new file mode 100644 index 000000000..8b938b9c0 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/SignedSelectorTest.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildFileTest; + +/** + * Testcase for the <signedselector> selector. + * + */ +public class SignedSelectorTest extends BuildFileTest { + + public SignedSelectorTest(String name) { + super(name); + } + public void setUp() { + configureProject("src/etc/testcases/types/selectors/signedselector.xml"); + } + + public void testSelectSigned() { + executeTarget("selectsigned"); + } + public void testNotSelected() { + executeTarget("notselected"); + } + public void testName() { + executeTarget("name"); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/SizeSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/SizeSelectorTest.java new file mode 100644 index 000000000..52fcf4c50 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/SizeSelectorTest.java @@ -0,0 +1,201 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Parameter; + +/** + * Tests Size Selectors + * + */ +public class SizeSelectorTest extends BaseSelectorTest { + + private Project project; + + public SizeSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new SizeSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + SizeSelector s = (SizeSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("SizeSelector did not check for required fields"); + } catch (BuildException be1) { + assertEquals("The value attribute is required, and must " + + "be positive", be1.getMessage()); + } + + s = (SizeSelector)getInstance(); + s.setValue(-10); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("SizeSelector did not check for value being in the " + + "allowable range"); + } catch (BuildException be2) { + assertEquals("The value attribute is required, and must " + + "be positive", be2.getMessage()); + } + + s = (SizeSelector)getInstance(); + Parameter param = new Parameter(); + param.setName("garbage in"); + param.setValue("garbage out"); + Parameter[] params = {param}; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("SizeSelector did not check for valid parameter element"); + } catch (BuildException be3) { + assertEquals("Invalid parameter garbage in", be3.getMessage()); + } + + s = (SizeSelector)getInstance(); + param = new Parameter(); + param.setName("value"); + param.setValue("garbage out"); + params[0] = param; + s.setParameters(params); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("SizeSelector accepted bad value as parameter"); + } catch (BuildException be4) { + assertEquals("Invalid size setting garbage out", + be4.getMessage()); + } + + s = (SizeSelector)getInstance(); + Parameter param1 = new Parameter(); + Parameter param2 = new Parameter(); + param1.setName("value"); + param1.setValue("5"); + param2.setName("units"); + param2.setValue("garbage out"); + params = new Parameter[2]; + params[0] = param1; + params[1] = param2; + try { + s.setParameters(params); + s.isSelected(basedir,filenames[0],files[0]); + fail("SizeSelector accepted bad units as parameter"); + } catch (BuildException be5) { + assertEquals("garbage out is not a legal value for this attribute", + be5.getMessage()); + } + + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + SizeSelector s; + String results; + + SizeSelector.ByteUnits kilo = new SizeSelector.ByteUnits(); + kilo.setValue("K"); + SizeSelector.ByteUnits kibi = new SizeSelector.ByteUnits(); + kibi.setValue("Ki"); + SizeSelector.ByteUnits tibi = new SizeSelector.ByteUnits(); + tibi.setValue("Ti"); + SizeSelector.SizeComparisons less = new SizeSelector.SizeComparisons(); + less.setValue("less"); + SizeSelector.SizeComparisons equal = new SizeSelector.SizeComparisons(); + equal.setValue("equal"); + SizeSelector.SizeComparisons more = new SizeSelector.SizeComparisons(); + more.setValue("more"); + + + try { + makeBed(); + + s = (SizeSelector)getInstance(); + s.setValue(10); + s.setWhen(less); + results = selectionString(s); + assertEquals("TFFFFFFFFFFT", results); + + s = (SizeSelector)getInstance(); + s.setValue(10); + s.setWhen(more); + results = selectionString(s); + assertEquals("TTTTTTTTTTTT", results); + + s = (SizeSelector)getInstance(); + s.setValue(32); + s.setWhen(equal); + results = selectionString(s); + assertEquals("TFFFTFFFFFFT", results); + + s = (SizeSelector)getInstance(); + s.setValue(7); + s.setWhen(more); + s.setUnits(kilo); + results = selectionString(s); + assertEquals("TFTFFTTTTTTT", results); + + s = (SizeSelector)getInstance(); + s.setValue(7); + s.setWhen(more); + s.setUnits(kibi); + results = selectionString(s); + assertEquals("TFTFFFTTFTTT", results); + + s = (SizeSelector)getInstance(); + s.setValue(99999); + s.setWhen(more); + s.setUnits(tibi); + results = selectionString(s); + assertEquals("TFFFFFFFFFFT", results); + + s = (SizeSelector)getInstance(); + Parameter param1 = new Parameter(); + Parameter param2 = new Parameter(); + Parameter param3 = new Parameter(); + param1.setName("value"); + param1.setValue("20"); + param2.setName("units"); + param2.setValue("Ki"); + param3.setName("when"); + param3.setValue("more"); + Parameter[] params = {param1,param2,param3}; + s.setParameters(params); + results = selectionString(s); + assertEquals("TFFFFFFTFFTT", results); + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/TypeSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/TypeSelectorTest.java new file mode 100644 index 000000000..1158177f3 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/types/selectors/TypeSelectorTest.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.types.selectors; + +import org.apache.tools.ant.BuildException; + +/** + * Tests Type Selectors. + * + */ +public class TypeSelectorTest extends BaseSelectorTest { + + public TypeSelectorTest(String name) { + super(name); + } + + /** + * Factory method from base class. This is overriden in child + * classes to return a specific Selector class. + */ + public BaseSelector getInstance() { + return new TypeSelector(); + } + + /** + * Test the code that validates the selector. + */ + public void testValidate() { + TypeSelector s = (TypeSelector)getInstance(); + try { + s.isSelected(basedir,filenames[0],files[0]); + fail("TypeSelector did not check for required fields"); + } catch (BuildException be1) { + assertEquals("The type attribute is required" + , be1.getMessage()); + } + } + + /** + * Tests to make sure that the selector is selecting files correctly. + */ + public void testSelectionBehaviour() { + TypeSelector s; + String results; + + TypeSelector.FileType directory = new + TypeSelector.FileType(); + directory.setValue("dir"); + TypeSelector.FileType file = new + TypeSelector.FileType(); + file.setValue("file"); + + try { + makeBed(); + + s = (TypeSelector)getInstance(); + s.setType(directory); + results = selectionString(s); + assertEquals("TFFFFFFFFFFT", results); + + s = (TypeSelector)getInstance(); + s.setType(file); + results = selectionString(s); + assertEquals("FTTTTTTTTTTF", results); + + + } + finally { + cleanupBed(); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/util/ClasspathUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/ClasspathUtilsTest.java new file mode 100644 index 000000000..b975f6566 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/ClasspathUtilsTest.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import java.io.IOException; +import java.util.Enumeration; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.Path; + + +/** + * Test case for ClasspathUtils + * + */ +public class ClasspathUtilsTest extends TestCase { + + private Project p; + + public ClasspathUtilsTest(String name) { + super(name); + } + + public void setUp() { + p = new Project(); + p.init(); + } + + + public void testOnlyOneInstance() { + Enumeration enumeration; + String list = ""; + ClassLoader c = ClasspathUtils.getUniqueClassLoaderForPath(p, (Path) null, false); + try { + enumeration = c.getResources( + "org/apache/tools/ant/taskdefs/defaults.properties"); + } catch (IOException e) { + throw new BuildException( + "Could not get the defaults.properties resource"); + } + int count = 0; + while (enumeration.hasMoreElements()) { + list = list + " " + enumeration.nextElement(); + count++; + } + assertTrue("Should be only one and not " + count + " " + list, count == 1); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/CollectionUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/CollectionUtilsTest.java new file mode 100644 index 000000000..340c357b2 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/CollectionUtilsTest.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import java.util.Hashtable; +import java.util.Properties; +import java.util.Stack; +import java.util.Vector; + +import junit.framework.TestCase; + +/** + * Tests for org.apache.tools.ant.util.CollectionUtils. + * + */ +public class CollectionUtilsTest extends TestCase { + + public CollectionUtilsTest(String name) { + super(name); + } + + public void testVectorEquals() { + assertTrue(!CollectionUtils.equals(null, new Vector())); + assertTrue(!CollectionUtils.equals(new Vector(), null)); + assertTrue(CollectionUtils.equals(new Vector(), new Vector())); + Vector v1 = new Vector(); + Stack s2 = new Stack(); + v1.addElement("foo"); + s2.push("foo"); + assertTrue(CollectionUtils.equals(v1, s2)); + assertTrue(CollectionUtils.equals(s2, v1)); + v1.addElement("bar"); + assertTrue(!CollectionUtils.equals(v1, s2)); + assertTrue(!CollectionUtils.equals(s2, v1)); + s2.push("bar"); + assertTrue(CollectionUtils.equals(v1, s2)); + assertTrue(CollectionUtils.equals(s2, v1)); + s2.push("baz"); + assertTrue(!CollectionUtils.equals(v1, s2)); + assertTrue(!CollectionUtils.equals(s2, v1)); + v1.addElement("baz"); + assertTrue(CollectionUtils.equals(v1, s2)); + assertTrue(CollectionUtils.equals(s2, v1)); + v1.addElement("zyzzy"); + s2.push("zyzzy2"); + assertTrue(!CollectionUtils.equals(v1, s2)); + assertTrue(!CollectionUtils.equals(s2, v1)); + } + + public void testDictionaryEquals() { + assertTrue(!CollectionUtils.equals(null, new Hashtable())); + assertTrue(!CollectionUtils.equals(new Hashtable(), null)); + assertTrue(CollectionUtils.equals(new Hashtable(), new Properties())); + Hashtable h1 = new Hashtable(); + Properties p2 = new Properties(); + h1.put("foo", ""); + p2.put("foo", ""); + assertTrue(CollectionUtils.equals(h1, p2)); + assertTrue(CollectionUtils.equals(p2, h1)); + h1.put("bar", ""); + assertTrue(!CollectionUtils.equals(h1, p2)); + assertTrue(!CollectionUtils.equals(p2, h1)); + p2.put("bar", ""); + assertTrue(CollectionUtils.equals(h1, p2)); + assertTrue(CollectionUtils.equals(p2, h1)); + p2.put("baz", ""); + assertTrue(!CollectionUtils.equals(h1, p2)); + assertTrue(!CollectionUtils.equals(p2, h1)); + h1.put("baz", ""); + assertTrue(CollectionUtils.equals(h1, p2)); + assertTrue(CollectionUtils.equals(p2, h1)); + h1.put("zyzzy", ""); + p2.put("zyzzy2", ""); + assertTrue(!CollectionUtils.equals(h1, p2)); + assertTrue(!CollectionUtils.equals(p2, h1)); + p2.put("zyzzy", ""); + h1.put("zyzzy2", ""); + assertTrue(CollectionUtils.equals(h1, p2)); + assertTrue(CollectionUtils.equals(p2, h1)); + h1.put("dada", "1"); + p2.put("dada", "2"); + assertTrue(!CollectionUtils.equals(h1, p2)); + assertTrue(!CollectionUtils.equals(p2, h1)); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/DOMElementWriterTest.java b/src/tests/junit/org/apache/tools/ant/util/DOMElementWriterTest.java new file mode 100644 index 000000000..0e6d62996 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/DOMElementWriterTest.java @@ -0,0 +1,257 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import java.io.IOException; +import java.io.StringWriter; + +import junit.framework.TestCase; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Tests for org.apache.tools.ant.util.DOMElementWriter. + * + */ +public class DOMElementWriterTest extends TestCase { + + private DOMElementWriter w = new DOMElementWriter(); + + public DOMElementWriterTest(String name) { + super(name); + } + + public void testIsReference() { + assertTrue("", w.isReference("")); + assertTrue(" ", w.isReference(" ")); + assertTrue(" ", w.isReference(" ")); + assertTrue("&#A0;", !w.isReference("&#A0;")); + assertTrue("20;", !w.isReference("20;")); + assertTrue("", !w.isReference("")); + assertTrue(""", w.isReference(""")); + assertTrue("'", w.isReference("'")); + assertTrue(">", w.isReference(">")); + assertTrue("<", w.isReference("<")); + assertTrue("&", w.isReference("&")); + } + + public void testEncode() { + assertEquals("", w.encode("")); + assertEquals(" ", w.encode(" ")); + assertEquals(" ", w.encode(" ")); + assertEquals("&#A0;", w.encode("&#A0;")); + assertEquals("20;", w.encode("20;")); + assertEquals("&#20", w.encode("")); + assertEquals(""", w.encode(""")); + assertEquals("'", w.encode("'")); + assertEquals(">", w.encode(">")); + assertEquals("<", w.encode("<")); + assertEquals("&", w.encode("&")); + assertEquals(""", w.encode("\"")); + assertEquals("<", w.encode("<")); + assertEquals("&", w.encode("&")); + assertEquals("", w.encode("\u0017")); + assertEquals("\"20;&", w.encodedata("\"20;&")); + assertEquals("", w.encodedata("\u0017")); + } + + public void testIsLegalCharacter() { + assertTrue("0x00", !w.isLegalCharacter('\u0000')); + assertTrue("0x09", w.isLegalCharacter('\t')); + assertTrue("0x0A", w.isLegalCharacter('\n')); + assertTrue("0x0C", w.isLegalCharacter('\r')); + assertTrue("0x1F", !w.isLegalCharacter('\u001F')); + assertTrue("0x20", w.isLegalCharacter('\u0020')); + assertTrue("0xD7FF", w.isLegalCharacter('\uD7FF')); + assertTrue("0xD800", !w.isLegalCharacter('\uD800')); + assertTrue("0xDFFF", !w.isLegalCharacter('\uDFFF')); + assertTrue("0xE000", w.isLegalCharacter('\uE000')); + assertTrue("0xFFFD", w.isLegalCharacter('\uFFFD')); + assertTrue("0xFFFE", !w.isLegalCharacter('\uFFFE')); + } + + public void testCDATAEndEncoding() { + assertEquals("]>", w.encodedata("]>")); + assertEquals("]]", w.encodedata("]]")); + assertEquals("]]>", w.encodedata("]]>")); + assertEquals("]]>A", w.encodedata("]]>A")); + assertEquals("A]]>", w.encodedata("A]]>")); + assertEquals("A]]>A", w.encodedata("A]]>A")); + assertEquals("A]]>B]]>C", + w.encodedata("A]]>B]]>C")); + } + + public void testNoAdditionalWhiteSpaceForText() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElement("root"); + DOMUtils.appendTextElement(root, "textElement", "content"); + + StringWriter sw = new StringWriter(); + DOMElementWriter w = new DOMElementWriter(); + w.write(root, sw, 0, " "); + assertEquals("" + StringUtils.LINE_SEP + + " content" + + StringUtils.LINE_SEP + + "" + StringUtils.LINE_SEP, + sw.toString()); + } + + public void testNoAdditionalWhiteSpaceForCDATA() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElement("root"); + DOMUtils.appendCDATAElement(root, "cdataElement", "content"); + + StringWriter sw = new StringWriter(); + DOMElementWriter w = new DOMElementWriter(); + w.write(root, sw, 0, " "); + assertEquals("" + StringUtils.LINE_SEP + + " " + + StringUtils.LINE_SEP + + "" + StringUtils.LINE_SEP, + sw.toString()); + } + + public void testNoAdditionalWhiteSpaceForEmptyElement() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElement("root"); + DOMUtils.createChildElement(root, "emptyElement"); + + StringWriter sw = new StringWriter(); + DOMElementWriter w = new DOMElementWriter(); + w.write(root, sw, 0, " "); + assertEquals("" + StringUtils.LINE_SEP + // + " " + + " " + + StringUtils.LINE_SEP + + "" + StringUtils.LINE_SEP, + sw.toString()); + } + + public void testNoNSPrefixByDefault() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElementNS("urn:foo", "root"); + root.setAttributeNS("urn:foo2", "bar", "baz"); + + StringWriter sw = new StringWriter(); + DOMElementWriter w = new DOMElementWriter(); + w.write(root, sw, 0, " "); + assertEquals("" + + StringUtils.LINE_SEP, sw.toString()); + } + + public void testNSOnElement() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElementNS("urn:foo", "root"); + root.setAttributeNS("urn:foo2", "bar", "baz"); + + StringWriter sw = new StringWriter(); + DOMElementWriter w = + new DOMElementWriter(false, + DOMElementWriter.XmlNamespacePolicy + .ONLY_QUALIFY_ELEMENTS); + w.write(root, sw, 0, " "); + assertEquals("" + + StringUtils.LINE_SEP, sw.toString()); + } + + public void testNSPrefixOnAttribute() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElementNS("urn:foo", "root"); + root.setAttributeNS("urn:foo2", "bar", "baz"); + + StringWriter sw = new StringWriter(); + DOMElementWriter w = + new DOMElementWriter(false, + DOMElementWriter.XmlNamespacePolicy + .QUALIFY_ALL); + w.write(root, sw, 0, " "); + assertEquals("" + + StringUtils.LINE_SEP, sw.toString()); + } + + public void testNSPrefixOnAttributeEvenWithoutElement() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElementNS("urn:foo", "root"); + root.setAttributeNS("urn:foo2", "bar", "baz"); + + StringWriter sw = new StringWriter(); + DOMElementWriter w = + new DOMElementWriter(false, + new DOMElementWriter.XmlNamespacePolicy(false, + true) + ); + w.write(root, sw, 0, " "); + assertEquals("" + + StringUtils.LINE_SEP, sw.toString()); + } + + public void testNSGetsReused() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElementNS("urn:foo", "root"); + Element child = d.createElementNS("urn:foo", "child"); + root.appendChild(child); + StringWriter sw = new StringWriter(); + DOMElementWriter w = + new DOMElementWriter(false, + DOMElementWriter.XmlNamespacePolicy + .ONLY_QUALIFY_ELEMENTS); + w.write(root, sw, 0, " "); + assertEquals("" + + StringUtils.LINE_SEP + + " " + + StringUtils.LINE_SEP + + "" + + StringUtils.LINE_SEP, sw.toString()); + } + + public void testNSGoesOutOfScope() throws IOException { + Document d = DOMUtils.newDocument(); + Element root = d.createElementNS("urn:foo", "root"); + Element child = d.createElementNS("urn:foo2", "child"); + root.appendChild(child); + Element child2 = d.createElementNS("urn:foo2", "child"); + root.appendChild(child2); + Element grandChild = d.createElementNS("urn:foo2", "grandchild"); + child2.appendChild(grandChild); + Element child3 = d.createElementNS("urn:foo2", "child"); + root.appendChild(child3); + StringWriter sw = new StringWriter(); + DOMElementWriter w = + new DOMElementWriter(false, + DOMElementWriter.XmlNamespacePolicy + .ONLY_QUALIFY_ELEMENTS); + w.write(root, sw, 0, " "); + assertEquals("" + + StringUtils.LINE_SEP + + " " + + StringUtils.LINE_SEP + + " " + + StringUtils.LINE_SEP + + " " + + StringUtils.LINE_SEP + + " " + + StringUtils.LINE_SEP + + " " + + StringUtils.LINE_SEP + + "" + + StringUtils.LINE_SEP, sw.toString()); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/DateUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/DateUtilsTest.java new file mode 100644 index 000000000..ede0b4355 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/DateUtilsTest.java @@ -0,0 +1,91 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import java.util.Calendar; +import java.util.TimeZone; + +import junit.framework.TestCase; + +/** + * TestCase for DateUtils. + * + */ +public class DateUtilsTest extends TestCase { + public DateUtilsTest(String s) { + super(s); + } + + public void testElapsedTime(){ + String text = DateUtils.formatElapsedTime(50*1000); + assertEquals("50 seconds", text); + text = DateUtils.formatElapsedTime(65*1000); + assertEquals("1 minute 5 seconds", text); + text = DateUtils.formatElapsedTime(120*1000); + assertEquals("2 minutes 0 seconds", text); + text = DateUtils.formatElapsedTime(121*1000); + assertEquals("2 minutes 1 second", text); + } + + public void testDateTimeISO(){ + TimeZone timeZone = TimeZone.getTimeZone("GMT+1"); + Calendar cal = Calendar.getInstance(timeZone); + cal.set(2002,1,23,10,11,12); + String text = DateUtils.format(cal.getTime(), + DateUtils.ISO8601_DATETIME_PATTERN); + assertEquals("2002-02-23T09:11:12", text); + } + + public void testDateISO(){ + TimeZone timeZone = TimeZone.getTimeZone("GMT"); + Calendar cal = Calendar.getInstance(timeZone); + cal.set(2002,1,23); + String text = DateUtils.format(cal.getTime(), + DateUtils.ISO8601_DATE_PATTERN); + assertEquals("2002-02-23", text); + } + + public void testTimeISODate(){ + // make sure that elapsed time in set via date works + TimeZone timeZone = TimeZone.getTimeZone("GMT+1"); + Calendar cal = Calendar.getInstance(timeZone); + cal.set(2002,1,23, 21, 11, 12); + String text = DateUtils.format(cal.getTime(), + DateUtils.ISO8601_TIME_PATTERN); + assertEquals("20:11:12", text); + } + + public void testTimeISO(){ + // make sure that elapsed time in ms works + long ms = (20*3600 + 11*60 + 12)*1000; + String text = DateUtils.format(ms, + DateUtils.ISO8601_TIME_PATTERN); + assertEquals("20:11:12", text); + } + + public void testPhaseOfMoon() { + TimeZone timeZone = TimeZone.getTimeZone("GMT"); + Calendar cal = Calendar.getInstance(timeZone); + // should be full moon + cal.set(2002, 2, 27); + assertEquals(4, DateUtils.getPhaseOfMoon(cal)); + // should be new moon + cal.set(2002, 2, 12); + assertEquals(0, DateUtils.getPhaseOfMoon(cal)); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/FileUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/FileUtilsTest.java new file mode 100644 index 000000000..e1f4092e6 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/FileUtilsTest.java @@ -0,0 +1,574 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +import junit.framework.TestCase; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.taskdefs.condition.Os; + +/** + * Tests for org.apache.tools.ant.util.FileUtils. + * + */ +public class FileUtilsTest extends TestCase { + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + private File removeThis; + private String root; + + public FileUtilsTest(String name) { + super(name); + } + + public void setUp() { + // Windows adds the drive letter in uppercase, unless you run Cygwin + root = new File(File.separator).getAbsolutePath().toUpperCase(); + } + + public void tearDown() { + if (removeThis != null && removeThis.exists()) { + removeThis.delete(); + } + } + + /** + * test modification. + * Since Ant1.7, the method being tested no longer uses + * reflection to provide backwards support to Java1.1, so this + * test is not so critical. But it does explore file system + * behaviour and will help catch any regression in Java itself, + * so is worth retaining. + * @see FileUtils#setFileLastModified(java.io.File, long) + * @throws IOException + */ + public void testSetLastModified() throws IOException { + removeThis = new File("dummy"); + FileOutputStream fos = new FileOutputStream(removeThis); + fos.write(new byte[0]); + fos.close(); + long modTime = removeThis.lastModified(); + assertTrue(modTime != 0); + + /* + * Sleep for some time to make sure a touched file would get a + * more recent timestamp according to the file system's + * granularity (should be > 2s to account for Windows FAT). + */ + try { + Thread.sleep(5000); + } catch (InterruptedException ie) { + fail(ie.getMessage()); + } + + FILE_UTILS.setFileLastModified(removeThis, -1); + long secondModTime = removeThis.lastModified(); + assertTrue(secondModTime > modTime); + + // number of milliseconds in a day + final int millisperday=24 * 3600 * 1000; + // in a previous version, the date of the file was set to 123456 + // milliseconds since 01.01.1970 + // it did not work on a computer running JDK 1.4.1_02 + Windows 2000 + FILE_UTILS.setFileLastModified(removeThis, secondModTime + millisperday); + long thirdModTime = removeThis.lastModified(); + /* + * I would love to compare this with 123456, but depending on + * the filesystems granularity it can take an arbitrary value. + * + * Just assert the time has changed. + */ + assertTrue(thirdModTime != secondModTime); + } + + public void testResolveFile() { + if (!(Os.isFamily("dos") || Os.isFamily("netware"))) { + /* + * Start with simple absolute file names. + */ + assertEquals(File.separator, + FILE_UTILS.resolveFile(null, "/").getPath()); + assertEquals(File.separator, + FILE_UTILS.resolveFile(null, "\\").getPath()); + } else { + assertEqualsIgnoreDriveCase(localize(File.separator), + FILE_UTILS.resolveFile(null, "/").getPath()); + assertEqualsIgnoreDriveCase(localize(File.separator), + FILE_UTILS.resolveFile(null, "\\").getPath()); + /* + * throw in drive letters + */ + String driveSpec = "C:"; + assertEquals(driveSpec + "\\", + FILE_UTILS.resolveFile(null, driveSpec + "/").getPath()); + assertEquals(driveSpec + "\\", + FILE_UTILS.resolveFile(null, driveSpec + "\\").getPath()); + String driveSpecLower = "c:"; + assertEquals(driveSpec + "\\", + FILE_UTILS.resolveFile(null, driveSpecLower + "/").getPath()); + assertEquals(driveSpec + "\\", + FILE_UTILS.resolveFile(null, driveSpecLower + "\\").getPath()); + /* + * promised to eliminate consecutive slashes after drive letter. + */ + assertEquals(driveSpec + "\\", + FILE_UTILS.resolveFile(null, driveSpec + "/////").getPath()); + assertEquals(driveSpec + "\\", + FILE_UTILS.resolveFile(null, driveSpec + "\\\\\\\\\\\\").getPath()); + } + if (Os.isFamily("netware")) { + /* + * throw in NetWare volume names + */ + String driveSpec = "SYS:"; + assertEquals(driveSpec, + FILE_UTILS.resolveFile(null, driveSpec + "/").getPath()); + assertEquals(driveSpec, + FILE_UTILS.resolveFile(null, driveSpec + "\\").getPath()); + String driveSpecLower = "sys:"; + assertEquals(driveSpec, + FILE_UTILS.resolveFile(null, driveSpecLower + "/").getPath()); + assertEquals(driveSpec, + FILE_UTILS.resolveFile(null, driveSpecLower + "\\").getPath()); + /* + * promised to eliminate consecutive slashes after drive letter. + */ + assertEquals(driveSpec, + FILE_UTILS.resolveFile(null, driveSpec + "/////").getPath()); + assertEquals(driveSpec, + FILE_UTILS.resolveFile(null, driveSpec + "\\\\\\\\\\\\").getPath()); + } else if (!(Os.isFamily("dos"))) { + /* + * drive letters must be considered just normal filenames. + */ + String driveSpec = "C:"; + String udir = System.getProperty("user.dir"); + assertEquals(udir + File.separator + driveSpec, + FILE_UTILS.resolveFile(null, driveSpec + "/").getPath()); + assertEquals(udir + File.separator + driveSpec, + FILE_UTILS.resolveFile(null, driveSpec + "\\").getPath()); + String driveSpecLower = "c:"; + assertEquals(udir + File.separator + driveSpecLower, + FILE_UTILS.resolveFile(null, driveSpecLower + "/").getPath()); + assertEquals(udir + File.separator + driveSpecLower, + FILE_UTILS.resolveFile(null, driveSpecLower + "\\").getPath()); + } + + /* + * Now test some relative file name magic. + */ + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), "4").getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), "./4").getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), ".\\4").getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), "./.\\4").getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), "../3/4").getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), "..\\3\\4").getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), "../../5/.././2/./3/6/../4").getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.resolveFile(new File(localize("/1/2/3")), "..\\../5/..\\./2/./3/6\\../4").getPath()); + + assertEquals("meaningless result but no exception", + new File(localize("/1/../../b")), + FILE_UTILS.resolveFile(new File(localize("/1")), "../../b")); + + } + + public void testNormalize() { + if (!(Os.isFamily("dos") || Os.isFamily("netware"))) { + /* + * Start with simple absolute file names. + */ + assertEquals(File.separator, + FILE_UTILS.normalize("/").getPath()); + assertEquals(File.separator, + FILE_UTILS.normalize("\\").getPath()); + } else { + try { + FILE_UTILS.normalize("/").getPath(); + fail("normalized \"/\" on dos or netware"); + } catch (Exception e) { + } + try { + FILE_UTILS.normalize("\\").getPath(); + fail("normalized \"\\\" on dos or netware"); + } catch (Exception e) { + } + } + + if (Os.isFamily("dos")) { + /* + * throw in drive letters + */ + String driveSpec = "C:"; + try { + FILE_UTILS.normalize(driveSpec).getPath(); + fail(driveSpec + " is not an absolute path"); + } catch (Exception e) { + } + assertEquals(driveSpec + "\\", + FILE_UTILS.normalize(driveSpec + "/").getPath()); + assertEquals(driveSpec + "\\", + FILE_UTILS.normalize(driveSpec + "\\").getPath()); + String driveSpecLower = "c:"; + assertEquals(driveSpec + "\\", + FILE_UTILS.normalize(driveSpecLower + "/").getPath()); + assertEquals(driveSpec + "\\", + FILE_UTILS.normalize(driveSpecLower + "\\").getPath()); + /* + * promised to eliminate consecutive slashes after drive letter. + */ + assertEquals(driveSpec + "\\", + FILE_UTILS.normalize(driveSpec + "/////").getPath()); + assertEquals(driveSpec + "\\", + FILE_UTILS.normalize(driveSpec + "\\\\\\\\\\\\").getPath()); + } else if (Os.isFamily("netware")) { + /* + * throw in NetWare volume names + */ + String driveSpec = "SYS:"; + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpec).getPath()); + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpec + "/").getPath()); + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpec + "\\").getPath()); + String driveSpecLower = "sys:"; + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpecLower).getPath()); + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpecLower + "/").getPath()); + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpecLower + "\\").getPath()); + assertEquals(driveSpec + "\\junk", + FILE_UTILS.normalize(driveSpecLower + "\\junk").getPath()); + /* + * promised to eliminate consecutive slashes after drive letter. + */ + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpec + "/////").getPath()); + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpec + "\\\\\\\\\\\\").getPath()); + } else { + try { + String driveSpec = "C:"; + assertEquals(driveSpec, + FILE_UTILS.normalize(driveSpec).getPath()); + fail("Expected failure, C: isn't an absolute path on other os's"); + } catch (BuildException e) { + // Passed test + } + } + + /* + * Now test some relative file name magic. + */ + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/4")).getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/./4")).getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/.\\4")).getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/./.\\4")).getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/../3/4")).getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/..\\3\\4")).getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/../../5/.././2/./3/6/../4")).getPath()); + assertEquals(localize("/1/2/3/4"), + FILE_UTILS.normalize(localize("/1/2/3/..\\../5/..\\./2/./3/6\\../4")).getPath()); + + try { + FILE_UTILS.normalize("foo"); + fail("foo is not an absolute path"); + } catch (BuildException e) { + // Expected exception caught + } + + assertEquals("will not go outside FS root (but will not throw an exception either)", + new File(localize("/1/../../b")), + FILE_UTILS.normalize(localize("/1/../../b"))); + } + + /** + * Test handling of null arguments. + */ + public void testNullArgs() { + try { + FILE_UTILS.normalize(null); + fail("successfully normalized a null-file"); + } catch (NullPointerException npe) { + // Expected exception caught + } + + File f = FILE_UTILS.resolveFile(null, "a"); + assertEquals(f, new File("a").getAbsoluteFile()); + } + + /** + * Test createTempFile + */ + public void testCreateTempFile() { + File parent = new File((new File("/tmp")).getAbsolutePath()); + File tmp1 = FILE_UTILS.createTempFile("pre", ".suf", parent); + assertTrue("new file", !tmp1.exists()); + + String name = tmp1.getName(); + assertTrue("starts with pre", name.startsWith("pre")); + assertTrue("ends with .suf", name.endsWith(".suf")); + assertEquals("is inside parent dir", + parent.getAbsolutePath(), + tmp1.getParent()); + + File tmp2 = FILE_UTILS.createTempFile("pre", ".suf", parent); + assertTrue("files are different", + !tmp1.getAbsolutePath().equals(tmp2.getAbsolutePath())); + + // null parent dir + File tmp3 = FILE_UTILS.createTempFile("pre", ".suf", null); + String tmploc = System.getProperty("java.io.tmpdir"); + assertEquals((new File(tmploc, tmp3.getName())).getAbsolutePath(), + tmp3.getAbsolutePath()); + } + + /** + * Test contentEquals + */ + public void testContentEquals() throws IOException { + assertTrue("Non existing files", FILE_UTILS.contentEquals(new File(System.getProperty("root"), "foo"), + new File(System.getProperty("root"), "bar"))); + assertTrue("One exists, the other one doesn\'t", + !FILE_UTILS.contentEquals(new File(System.getProperty("root"), "foo"), new File(System.getProperty("root"), "build.xml"))); + assertTrue("Don\'t compare directories", + !FILE_UTILS.contentEquals(new File(System.getProperty("root"), "src"), new File(System.getProperty("root"), "src"))); + assertTrue("File equals itself", + FILE_UTILS.contentEquals(new File(System.getProperty("root"), "build.xml"), + new File(System.getProperty("root"), "build.xml"))); + assertTrue("Files are different", + !FILE_UTILS.contentEquals(new File(System.getProperty("root"), "build.xml"), + new File(System.getProperty("root"), "docs.xml"))); + } + + /** + * Test createNewFile + */ + public void testCreateNewFile() throws IOException { + removeThis = new File("dummy"); + assertTrue(!removeThis.exists()); + FILE_UTILS.createNewFile(removeThis); + assertTrue(removeThis.exists()); + } + + /** + * Test removeLeadingPath. + */ + public void testRemoveLeadingPath() { + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("/foo"), + new File("/foo/bar"))); + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("/foo/"), + new File("/foo/bar"))); + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("\\foo"), + new File("\\foo\\bar"))); + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("\\foo\\"), + new File("\\foo\\bar"))); + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("c:/foo"), + new File("c:/foo/bar"))); + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("c:/foo/"), + new File("c:/foo/bar"))); + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("c:\\foo"), + new File("c:\\foo\\bar"))); + assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("c:\\foo\\"), + new File("c:\\foo\\bar"))); + if (!(Os.isFamily("dos") || Os.isFamily("netware"))) { + assertEquals(FILE_UTILS.normalize("/bar").getAbsolutePath(), + FILE_UTILS.removeLeadingPath(new File("/foo"), new File("/bar"))); + assertEquals(FILE_UTILS.normalize("/foobar").getAbsolutePath(), + FILE_UTILS.removeLeadingPath(new File("/foo"), new File("/foobar"))); + } + // bugzilla report 19979 + assertEquals("", FILE_UTILS.removeLeadingPath(new File("/foo/bar"), + new File("/foo/bar"))); + assertEquals("", FILE_UTILS.removeLeadingPath(new File("/foo/bar"), + new File("/foo/bar/"))); + assertEquals("", FILE_UTILS.removeLeadingPath(new File("/foo/bar/"), + new File("/foo/bar/"))); + assertEquals("", FILE_UTILS.removeLeadingPath(new File("/foo/bar/"), + new File("/foo/bar"))); + + String expected = "foo/bar".replace('\\', File.separatorChar) + .replace('/', File.separatorChar); + assertEquals(expected, FILE_UTILS.removeLeadingPath(new File("/"), + new File("/foo/bar"))); + assertEquals(expected, FILE_UTILS.removeLeadingPath(new File("c:/"), + new File("c:/foo/bar"))); + assertEquals(expected, FILE_UTILS.removeLeadingPath(new File("c:\\"), + new File("c:\\foo\\bar"))); + } + + /** + * test toUri + */ + public void testToURI() { + String dosRoot = null; + if (Os.isFamily("dos") || Os.isFamily("netware")) { + dosRoot = System.getProperty("user.dir") + .substring(0, 3).replace(File.separatorChar, '/'); + + //preserve case on Cygwin when using 1.4 toURI: + Class uriClazz = null; + try { + uriClazz = Class.forName("java.net.URI"); + } catch (ClassNotFoundException e) { + // OK, Java 1.3. + dosRoot = dosRoot.toUpperCase(); + } + } + else + { + dosRoot = ""; + } + if (Os.isFamily("dos")) { + assertEquals("file:/c:/foo", removeExtraneousAuthority(FILE_UTILS.toURI("c:\\foo"))); + } + if (Os.isFamily("netware")) { + assertEquals("file:/SYS:/foo", removeExtraneousAuthority(FILE_UTILS.toURI("sys:\\foo"))); + } + if (File.pathSeparatorChar == '/') { + assertEquals("file:/foo", removeExtraneousAuthority(FILE_UTILS.toURI("/foo"))); + assertTrue("file: URIs must name absolute paths", FILE_UTILS.toURI("./foo").startsWith("file:/")); + assertTrue(FILE_UTILS.toURI("./foo").endsWith("/foo")); + assertEquals("file:/" + dosRoot + "foo%20bar", removeExtraneousAuthority(FILE_UTILS.toURI("/foo bar"))); + assertEquals("file:/" + dosRoot + "foo%23bar", removeExtraneousAuthority(FILE_UTILS.toURI("/foo#bar"))); + } else if (File.pathSeparatorChar == '\\') { + assertEquals("file:/" + dosRoot + "foo", removeExtraneousAuthority(FILE_UTILS.toURI("\\foo"))); + assertTrue("file: URIs must name absolute paths", FILE_UTILS.toURI(".\\foo").startsWith("file:/")); + assertTrue(FILE_UTILS.toURI(".\\foo").endsWith("/foo")); + assertEquals("file:/" + dosRoot + "foo%20bar", removeExtraneousAuthority(FILE_UTILS.toURI("\\foo bar"))); + assertEquals("file:/" + dosRoot + "foo%23bar", removeExtraneousAuthority(FILE_UTILS.toURI("\\foo#bar"))); + } + // a test with ant for germans + // the escaped character used for the test is the "a umlaut" + // this is the fix for the bug 37348 + assertEquals("file:/" + dosRoot + "%C3%A4nt", removeExtraneousAuthority(FILE_UTILS.toURI("/\u00E4nt"))); + } + + /** + * Authority field is unnecessary, but harmless, in file: URIs. + * Java 1.4 does not produce it when using File.toURI. + */ + private static String removeExtraneousAuthority(String uri) { + String prefix = "file:///"; + if (uri.startsWith(prefix)) { + return "file:/" + uri.substring(prefix.length()); + } else { + return uri; + } + } + /** + * test fromUri + */ + public void testFromURI() { + String dosRoot = null; + if (Os.isFamily("dos") || Os.isFamily("netware")) { + dosRoot = Character.toUpperCase( + System.getProperty("user.dir").charAt(0)) + ":"; + } + else + { + dosRoot = ""; + } + if (Os.isFamily("netware")) { + assertEqualsIgnoreDriveCase("SYS:\\foo", FILE_UTILS.fromURI("file:///sys:/foo")); + } + if (Os.isFamily("dos")) { + assertEqualsIgnoreDriveCase("C:\\foo", FILE_UTILS.fromURI("file:///c:/foo")); + } + assertEqualsIgnoreDriveCase(dosRoot + File.separator + "foo", FILE_UTILS.fromURI("file:///foo")); + assertEquals("." + File.separator + "foo", + FILE_UTILS.fromURI("file:./foo")); + assertEquals(dosRoot + File.separator + "foo bar", FILE_UTILS.fromURI("file:///foo%20bar")); + assertEquals(dosRoot + File.separator + "foo#bar", FILE_UTILS.fromURI("file:///foo%23bar")); + } + + public void testModificationTests() { + + //get a time + long firstTime=System.currentTimeMillis(); + //add some time. We assume no OS has a granularity this bad + long secondTime=firstTime+60000; +/* + assertTrue("same timestamp is up to date", + fu.isUpToDate(firstTime, firstTime)); + */ + + //check that older is up to date with a newer dest + assertTrue("older source files are up to date", + FILE_UTILS.isUpToDate(firstTime,secondTime)); + //check that older is up to date with a newer dest + assertFalse("newer source files are no up to date", + FILE_UTILS.isUpToDate(secondTime, firstTime)); + + assertTrue("-1 dest timestamp implies nonexistence", + !FILE_UTILS.isUpToDate(firstTime,-1L)); + } + + public void testGetDefaultEncoding() { + // This just tests that the function does not blow up + FILE_UTILS.getDefaultEncoding(); + } + + /** + * adapt file separators to local conventions + */ + private String localize(String path) { + path = root + path.substring(1); + return path.replace('\\', File.separatorChar).replace('/', File.separatorChar); + } + + /** + * convenience method + * normalize brings the drive in uppercase + * the drive letter is in lower case under cygwin + * calling this method allows tests where normalize is called to pass under cygwin + */ + private void assertEqualsIgnoreDriveCase(String s1, String s2) { + if ((Os.isFamily("dos") || Os.isFamily("netware")) + && s1.length() > 0 && s2.length() > 0) { + StringBuffer sb1 = new StringBuffer(s1); + StringBuffer sb2 = new StringBuffer(s2); + sb1.setCharAt(0, Character.toUpperCase(s1.charAt(0))); + sb2.setCharAt(0, Character.toUpperCase(s2.charAt(0))); + assertEquals(sb1.toString(), sb2.toString()); + } else { + assertEquals(s1, s2); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/GlobPatternMapperTest.java b/src/tests/junit/org/apache/tools/ant/util/GlobPatternMapperTest.java new file mode 100644 index 000000000..bca05b2e3 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/GlobPatternMapperTest.java @@ -0,0 +1,98 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import junit.framework.TestCase; + +/** + * Tests for org.apache.tools.ant.util;GlobPatternMapper. + * + */ +public class GlobPatternMapperTest extends TestCase { + + public GlobPatternMapperTest(String name) { + super(name); + } + + public void testNoPatternAtAll() { + GlobPatternMapper m = new GlobPatternMapper(); + m.setFrom("foobar"); + m.setTo("baz"); + assertNull("Shouldn\'t match foobar", m.mapFileName("plonk")); + String[] result = m.mapFileName("foobar"); + assertNotNull("Should match foobar", result); + assertEquals("only one result for foobar", 1, result.length); + assertEquals("baz", result[0]); + } + + public void testPostfixOnly() { + GlobPatternMapper m = new GlobPatternMapper(); + m.setFrom("*foo"); + m.setTo("*plonk"); + assertNull("Shouldn\'t match *foo", m.mapFileName("bar.baz")); + String[] result = m.mapFileName("bar.foo"); + assertNotNull("Should match *.foo", result); + assertEquals("only one result for bar.foo", 1, result.length); + assertEquals("bar.plonk", result[0]); + + // Try a silly case + m.setTo("foo*"); + result = m.mapFileName("bar.foo"); + assertEquals("foobar.", result[0]); + } + + public void testPrefixOnly() { + GlobPatternMapper m = new GlobPatternMapper(); + m.setFrom("foo*"); + m.setTo("plonk*"); + assertNull("Shouldn\'t match foo*", m.mapFileName("bar.baz")); + String[] result = m.mapFileName("foo.bar"); + assertNotNull("Should match foo*", result); + assertEquals("only one result for foo.bar", 1, result.length); + assertEquals("plonk.bar", result[0]); + + // Try a silly case + m.setTo("*foo"); + result = m.mapFileName("foo.bar"); + assertEquals(".barfoo", result[0]); + } + + public void testPreAndPostfix() { + GlobPatternMapper m = new GlobPatternMapper(); + m.setFrom("foo*bar"); + m.setTo("plonk*pling"); + assertNull("Shouldn\'t match foo*bar", m.mapFileName("bar.baz")); + String[] result = m.mapFileName("foo.bar"); + assertNotNull("Should match foo*bar", result); + assertEquals("only one result for foo.bar", 1, result.length); + assertEquals("plonk.pling", result[0]); + + // and a little longer + result = m.mapFileName("foo.baz.bar"); + assertNotNull("Should match foo*bar", result); + assertEquals("only one result for foo.baz.bar", 1, result.length); + assertEquals("plonk.baz.pling", result[0]); + + // and a little shorter + result = m.mapFileName("foobar"); + assertNotNull("Should match foo*bar", result); + assertEquals("only one result for foobar", 1, result.length); + assertEquals("plonkpling", result[0]); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/JAXPUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/JAXPUtilsTest.java new file mode 100644 index 000000000..e5a3b7f57 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/JAXPUtilsTest.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import junit.framework.TestCase; + +import java.io.File; + +/** + * JAXPUtils test case + */ +public class JAXPUtilsTest extends TestCase { + public JAXPUtilsTest(String name){ + super(name); + } + + public void testGetSystemId(){ + File file = null; + if ( File.separatorChar == '\\' ){ + file = new File("d:\\jdk"); + } else { + file = new File("/user/local/bin"); + } + String systemid = JAXPUtils.getSystemId(file); + assertTrue("SystemIDs should start by file:/", systemid.startsWith("file:/")); + assertTrue("SystemIDs should not start with file:////", !systemid.startsWith("file:////")); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/JavaEnvUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/JavaEnvUtilsTest.java new file mode 100644 index 000000000..4ee47ea77 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/JavaEnvUtilsTest.java @@ -0,0 +1,130 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import java.io.File; + +import junit.framework.AssertionFailedError; +import junit.framework.TestCase; + +import org.apache.tools.ant.taskdefs.condition.Os; + +/** + * TestCase for JavaEnvUtils. + * + */ +public class JavaEnvUtilsTest extends TestCase { + + private static final FileUtils FILE_UTILS = FileUtils.getFileUtils(); + + public JavaEnvUtilsTest(String s) { + super(s); + } + + public void testGetExecutableNetware() { + if (Os.isName("netware")) { + assertEquals("java", JavaEnvUtils.getJreExecutable("java")); + assertEquals("javac", JavaEnvUtils.getJdkExecutable("javac")); + assertEquals("foo", JavaEnvUtils.getJreExecutable("foo")); + assertEquals("foo", JavaEnvUtils.getJdkExecutable("foo")); + } + } + + public void testGetExecutableWindows() { + if (Os.isFamily("windows")) { + String javaHome = + FILE_UTILS.normalize(System.getProperty("java.home")) + .getAbsolutePath(); + + String j = JavaEnvUtils.getJreExecutable("java"); + assertTrue(j.endsWith(".exe")); + assertTrue(j+" is absolute", (new File(j)).isAbsolute()); + try { + assertTrue(j+" is normalized and in the JRE dir", + j.startsWith(javaHome)); + } catch (AssertionFailedError e) { + // java.home is bogus + assertEquals("java.exe", j); + } + + j = JavaEnvUtils.getJdkExecutable("javac"); + assertTrue(j.endsWith(".exe")); + try { + assertTrue(j+" is absolute", (new File(j)).isAbsolute()); + String javaHomeParent = + FILE_UTILS.normalize(javaHome+"/..").getAbsolutePath(); + assertTrue(j+" is normalized and in the JDK dir", + j.startsWith(javaHomeParent)); + assertTrue(j+" is normalized and not in the JRE dir", + !j.startsWith(javaHome)); + + } catch (AssertionFailedError e) { + // java.home is bogus + assertEquals("javac.exe", j); + } + + assertEquals("foo.exe", JavaEnvUtils.getJreExecutable("foo")); + assertEquals("foo.exe", JavaEnvUtils.getJdkExecutable("foo")); + } + } + + public void testGetExecutableMostPlatforms() { + if (!Os.isName("netware") && !Os.isFamily("windows")) { + String javaHome = + FILE_UTILS.normalize(System.getProperty("java.home")) + .getAbsolutePath(); + + // could still be OS/2 + String extension = Os.isFamily("dos") ? ".exe" : ""; + + String j = JavaEnvUtils.getJreExecutable("java"); + if (!extension.equals("")) { + assertTrue(j.endsWith(extension)); + } + assertTrue(j+" is absolute", (new File(j)).isAbsolute()); + assertTrue(j+" is normalized and in the JRE dir", + j.startsWith(javaHome)); + + j = JavaEnvUtils.getJdkExecutable("javac"); + if (!extension.equals("")) { + assertTrue(j.endsWith(extension)); + } + assertTrue(j+" is absolute", (new File(j)).isAbsolute()); + + String javaHomeParent = + FILE_UTILS.normalize(javaHome+"/..").getAbsolutePath(); + assertTrue(j+" is normalized and in the JDK dir", + j.startsWith(javaHomeParent)); + + if (Os.isFamily("mac")) { + assertTrue(j+" is normalized and in the JRE dir", + j.startsWith(javaHome)); + } else { + assertTrue(j+" is normalized and not in the JRE dir", + !j.startsWith(javaHome)); + } + + assertEquals("foo"+extension, + JavaEnvUtils.getJreExecutable("foo")); + assertEquals("foo"+extension, + JavaEnvUtils.getJdkExecutable("foo")); + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/util/LazyFileOutputStreamTest.java b/src/tests/junit/org/apache/tools/ant/util/LazyFileOutputStreamTest.java new file mode 100644 index 000000000..394669ebe --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/LazyFileOutputStreamTest.java @@ -0,0 +1,69 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import java.io.File; +import java.io.IOException; +import junit.framework.TestCase; + +/** + * @since Ant 1.6 + */ +public class LazyFileOutputStreamTest extends TestCase { + private LazyFileOutputStream los; + private final static File f = new File("test.txt"); + + public LazyFileOutputStreamTest(String s) { + super(s); + } + + public void setUp() { + los = new LazyFileOutputStream(f); + } + + public void tearDown() throws IOException { + try { + los.close(); + } finally { + f.delete(); + } + } + + public void testNoFileWithoutWrite() throws IOException { + los.close(); + assertTrue(f + " has not been written.", !f.exists()); + } + + public void testOpen() throws IOException { + los.open(); + los.close(); + assertTrue(f + " has been written.", f.exists()); + } + + public void testSingleByte() throws IOException { + los.write(0); + los.close(); + assertTrue(f + " has been written.", f.exists()); + } + + public void testByteArray() throws IOException { + los.write(new byte[] {0}); + los.close(); + assertTrue(f + " has been written.", f.exists()); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/LineOrientedOutputStreamTest.java b/src/tests/junit/org/apache/tools/ant/util/LineOrientedOutputStreamTest.java new file mode 100644 index 000000000..7bcb4dcb1 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/LineOrientedOutputStreamTest.java @@ -0,0 +1,139 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import java.io.IOException; +import junit.framework.TestCase; + +/** + */ + +public class LineOrientedOutputStreamTest extends TestCase { + + private static String LINE = "This is a line"; + private DummyStream stream; + + public LineOrientedOutputStreamTest(String name) { + super(name); + } + + public void setUp() { + stream = new DummyStream(); + } + + public void tearDown() throws IOException { + if (stream != null) { + stream.close(); + } + } + + public void testLineWithLinefeedArray() throws IOException { + writeByteArray(); + writeAsArray('\n'); + stream.assertInvoked(); + } + + public void testLineWithLinefeedSingleBytes() throws IOException { + writeSingleBytes(); + stream.write('\n'); + stream.assertInvoked(); + } + + public void testLineWithCariagereturnArray() throws IOException { + writeByteArray(); + writeAsArray('\r'); + stream.assertInvoked(); + } + + public void testLineWithCariagereturnSingleBytes() throws IOException { + writeSingleBytes(); + stream.write('\r'); + stream.assertInvoked(); + } + + public void testLineWithCariagereturnLinefeedArray() throws IOException { + writeByteArray(); + writeAsArray('\r'); + writeAsArray('\n'); + stream.assertInvoked(); + } + + public void testLineWithCariagereturnLinefeedSingleBytes() throws IOException { + writeSingleBytes(); + stream.write('\r'); + stream.write('\n'); + stream.assertInvoked(); + } + + public void testFlushArray() throws IOException { + writeByteArray(); + stream.flush(); + stream.assertInvoked(); + } + + public void testFlushSingleBytes() throws IOException { + writeSingleBytes(); + stream.flush(); + stream.assertInvoked(); + } + + public void testCloseArray() throws IOException { + writeByteArray(); + stream.close(); + stream.assertInvoked(); + stream = null; + } + + public void testCloseSingleBytes() throws IOException { + writeSingleBytes(); + stream.close(); + stream.assertInvoked(); + stream = null; + } + + private void writeByteArray() throws IOException { + stream.write(LINE.getBytes(), 0, LINE.length()); + } + + private void writeSingleBytes() throws IOException { + byte[] b = LINE.getBytes(); + for (int i = 0; i < b.length; i++) { + stream.write(b[i]); + } + } + + private void writeAsArray(char c) throws IOException { + stream.write(new byte[] {(byte) c}, 0, 1); + } + + private class DummyStream extends LineOrientedOutputStream { + private boolean invoked; + protected void processLine(String line) { + LineOrientedOutputStreamTest.this.assertFalse("Only one line", + invoked); + LineOrientedOutputStreamTest.this.assertEquals(LINE, line); + invoked = true; + } + + private void assertInvoked() { + LineOrientedOutputStreamTest.this.assertTrue("At least one line", + invoked); + } + } +}// LineOrientedOutputStreamTest diff --git a/src/tests/junit/org/apache/tools/ant/util/LoaderUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/LoaderUtilsTest.java new file mode 100644 index 000000000..49518ea3d --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/LoaderUtilsTest.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import java.io.File; +import junit.framework.TestCase; + +/** + * @since Ant 1.6 + */ +public class LoaderUtilsTest extends TestCase { + + public LoaderUtilsTest(String name) { + super(name); + } + + public void testGetXyzSource() { + File f1 = LoaderUtils.getClassSource(LoaderUtils.class); + assertNotNull(f1); + + File f2 = LoaderUtils.getResourceSource(null, + "org/apache/tools/ant/taskdefs/defaults.properties"); + assertNotNull(f2); + + assertEquals(f1.getAbsolutePath(), f2.getAbsolutePath()); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/util/PackageNameMapperTest.java b/src/tests/junit/org/apache/tools/ant/util/PackageNameMapperTest.java new file mode 100644 index 000000000..f6c859f17 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/PackageNameMapperTest.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + package org.apache.tools.ant.util; + +import java.io.File; +import junit.framework.TestCase; + +public class PackageNameMapperTest extends TestCase { + public PackageNameMapperTest(String name) { super(name); } + + public void testMapping() { + PackageNameMapper mapper = new PackageNameMapper(); + mapper.setFrom("*.java"); + mapper.setTo("TEST-*.xml"); + String file = fixupPath("org/apache/tools/ant/util/PackageNameMapperTest.java"); + String result = mapper.mapFileName(file)[0]; + + assertEquals("TEST-org.apache.tools.ant.util.PackageNameMapperTest.xml", + result); + } + + private String fixupPath(String file) { + return file.replace('/', File.separatorChar); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/ReaderInputStreamTest.java b/src/tests/junit/org/apache/tools/ant/util/ReaderInputStreamTest.java new file mode 100644 index 000000000..a7648cbde --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/ReaderInputStreamTest.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import java.io.*; + +import junit.framework.TestCase; + +/** + * Test for ReaderInputStream + */ +public class ReaderInputStreamTest extends TestCase { + public ReaderInputStreamTest(String s) { + super(s); + } + + public void testSimple() throws Exception { + compareBytes("abc", "utf-8"); + } + + public void testSimple16() throws Exception { + compareBytes("a", "utf-16"); + } + + public void testSimpleAbc16() throws Exception { + // THIS WILL FAIL. + //compareBytes("abc", "utf-16"); + byte[] bytes = new byte[40]; + int pos = 0; + ReaderInputStream r = new ReaderInputStream( + new StringReader("abc"), "utf-16"); + for (int i = 0; true; ++i) { + int res = r.read(); + if (res == -1) { + break; + } + bytes[pos++] = (byte) res; + } + bytes = "abc".getBytes("utf-16"); + // String n = new String(bytes, 0, pos, "utf-16"); + String n = new String(bytes, 0, bytes.length, "utf-16"); + System.out.println(n); + } + + public void testReadZero() throws Exception { + ReaderInputStream r = new ReaderInputStream( + new StringReader("abc")); + byte[] bytes = new byte[30]; + // First read in zero bytes + r.read(bytes, 0, 0); + // Now read in the string + int readin = r.read(bytes, 0, 10); + // Make sure that the counts are the same + assertEquals("abc".getBytes().length, readin); + } + + public void testPreample() throws Exception { + byte[] bytes = "".getBytes("utf-16"); + System.out.println("Preample len is " + bytes.length); + } + + private void compareBytes(String s, String encoding) throws Exception { + byte[] expected = s.getBytes(encoding); + + ReaderInputStream r = new ReaderInputStream( + new StringReader(s), encoding); + for (int i = 0; i < expected.length; ++i) { + int expect = expected[i] & 0xFF; + int read = r.read(); + if (expect != read) { + fail("Mismatch in ReaderInputStream at index " + i + + " expecting " + expect + " got " + read + " for string " + + s + " with encoding " + encoding); + } + } + if (r.read() != -1) { + fail("Mismatch in ReaderInputStream - EOF not seen for string " + + s + " with encoding " + encoding); + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/ResourceUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/ResourceUtilsTest.java new file mode 100644 index 000000000..072718c44 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/ResourceUtilsTest.java @@ -0,0 +1,61 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import junit.framework.TestCase; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Echo; +import org.apache.tools.ant.types.Resource; +import org.apache.tools.ant.types.ResourceFactory; + +/** + * Tests for org.apache.tools.ant.util.ResourceUtils. + */ +public class ResourceUtilsTest extends TestCase + implements ResourceFactory, FileNameMapper { + + private Echo taskINeedForLogging = new Echo(); + + public ResourceUtilsTest(String name) { + super(name); + taskINeedForLogging.setProject(new Project()); + } + + public void testNoDuplicates() { + Resource r = new Resource("samual vimes", true, 1, false); + Resource[] toNew = + ResourceUtils.selectOutOfDateSources(taskINeedForLogging, + new Resource[] {r}, + this, this); + assertEquals(1, toNew.length); + } + + /* ============ ResourceFactory interface ====================== */ + public Resource getResource(String name) { + return new Resource(name); // implies lastModified == 0 + } + + /* ============ FileNameMapper interface ======================= */ + public void setFrom(String s) {} + public void setTo(String s) {} + public String[] mapFileName(String s) { + return new String[] {"fred colon", "carrot ironfoundersson"}; + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/StringUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/StringUtilsTest.java new file mode 100644 index 000000000..5f934e590 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/StringUtilsTest.java @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import java.util.Vector; + +import junit.framework.TestCase; + +/** + * Test for StringUtils + */ +public class StringUtilsTest extends TestCase { + public StringUtilsTest(String s) { + super(s); + } + + public void testSplit(){ + final String data = "a,b,,"; + Vector res = StringUtils.split(data, ','); + assertEquals(4, res.size()); + assertEquals("a", res.elementAt(0)); + assertEquals("b", res.elementAt(1)); + assertEquals("", res.elementAt(2)); + assertEquals("", res.elementAt(3)); + } + + public void testSplitLines(){ + final String data = "a\r\nb\nc\nd\ne"; + Vector res = StringUtils.lineSplit(data); + assertEquals(5, res.size()); + assertEquals("a\r", res.elementAt(0)); + assertEquals("b", res.elementAt(1)); + assertEquals("c", res.elementAt(2)); + assertEquals("d", res.elementAt(3)); + assertEquals("e", res.elementAt(4)); + } + + public void testReplace() { + final String data = "abcabcabca"; + String res = StringUtils.replace(data, "a", ""); + assertEquals("bcbcbc", res); + } + + public void testEndsWithBothEmpty() { + assertTrue( StringUtils.endsWith( new StringBuffer(), "") ); + } + + public void testEndsWithEmptyString() { + assertTrue( StringUtils.endsWith( new StringBuffer("12234545"), "") ); + } + + public void testEndsWithShorterString() { + assertTrue( StringUtils.endsWith( new StringBuffer("12345678"), "78")); + } + + public void testEndsWithSameString() { + assertTrue( StringUtils.endsWith( new StringBuffer("123"), "123")); + } + + public void testEndsWithLongerString() { + assertFalse( StringUtils.endsWith( new StringBuffer("12"), "1245")); + } + + public void testEndsWithNoMatch() { + assertFalse( StringUtils.endsWith( new StringBuffer("12345678"), "789")); + } + + public void testEndsWithEmptyBuffer() { + assertFalse( StringUtils.endsWith( new StringBuffer(""), "12345667") ); + } + + public void testEndsWithJDKPerf() { + StringBuffer buf = getFilledBuffer(1024*300, 'a'); + for (int i = 0; i < 1000; i++) { + assertTrue(buf.toString().endsWith("aa")); + } + } + + public void testEndsWithPerf() { + StringBuffer buf = getFilledBuffer(1024*300, 'a'); + for (int i = 0; i < 1000; i++) { + assertTrue(StringUtils.endsWith(buf, "aa")); + } + } + + private StringBuffer getFilledBuffer(int size, char ch) { + StringBuffer buf = new StringBuffer(size); + for (int i = 0; i < size; i++) { buf.append(ch); }; + return buf; + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/UnPackageNameMapperTest.java b/src/tests/junit/org/apache/tools/ant/util/UnPackageNameMapperTest.java new file mode 100644 index 000000000..c78e1d351 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/UnPackageNameMapperTest.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.ant.util; + +import java.io.File; +import junit.framework.TestCase; + +public class UnPackageNameMapperTest extends TestCase { + public UnPackageNameMapperTest(String name) { super(name); } + + public void testMapping() { + UnPackageNameMapper mapper = new UnPackageNameMapper(); + mapper.setFrom("TEST-*.xml"); + mapper.setTo("*.java"); + String file ="TEST-org.apache.tools.ant.util.UnPackageNameMapperTest.xml"; + String result = mapper.mapFileName(file)[0]; + String expected = fixupPath("org/apache/tools/ant/util/UnPackageNameMapperTest.java"); + + assertEquals(expected, result); + } + + private String fixupPath(String file) { + return file.replace('/', File.separatorChar); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/XMLFragmentTest.java b/src/tests/junit/org/apache/tools/ant/util/XMLFragmentTest.java new file mode 100644 index 000000000..f139d605a --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/XMLFragmentTest.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util; + +import org.apache.tools.ant.BuildFileTest; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class XMLFragmentTest extends BuildFileTest { + + public XMLFragmentTest(String name) { + super(name); + } + + public void setUp() { + configureProject("src/etc/testcases/types/xmlfragment.xml"); + } + + public void testNestedText() { + XMLFragment x = (XMLFragment) getProject().getReference("nested-text"); + assertNotNull(x); + Node n = x.getFragment(); + assertTrue("No attributes", !n.hasAttributes()); + NodeList nl = n.getChildNodes(); + assertEquals(1, nl.getLength()); + assertEquals(Node.TEXT_NODE, nl.item(0).getNodeType()); + assertEquals("foo", nl.item(0).getNodeValue()); + } + + public void testNestedChildren() { + XMLFragment x = + (XMLFragment) getProject().getReference("with-children"); + assertNotNull(x); + Node n = x.getFragment(); + assertTrue("No attributes", !n.hasAttributes()); + NodeList nl = n.getChildNodes(); + assertEquals(3, nl.getLength()); + + assertEquals(Node.ELEMENT_NODE, nl.item(0).getNodeType()); + Element child1 = (Element) nl.item(0); + assertEquals("child1", child1.getTagName()); + assertTrue(!child1.hasAttributes()); + NodeList nl2 = child1.getChildNodes(); + assertEquals(1, nl2.getLength()); + assertEquals(Node.TEXT_NODE, nl2.item(0).getNodeType()); + assertEquals("foo", nl2.item(0).getNodeValue()); + + assertEquals(Node.ELEMENT_NODE, nl.item(1).getNodeType()); + Element child2 = (Element) nl.item(1); + assertEquals("child2", child2.getTagName()); + assertTrue(child2.hasAttributes()); + nl2 = child2.getChildNodes(); + assertEquals(0, nl2.getLength()); + assertEquals("bar", child2.getAttribute("foo")); + + assertEquals(Node.ELEMENT_NODE, nl.item(2).getNodeType()); + Element child3 = (Element) nl.item(2); + assertEquals("child3", child3.getTagName()); + assertTrue(!child3.hasAttributes()); + nl2 = child3.getChildNodes(); + assertEquals(1, nl2.getLength()); + assertEquals(Node.ELEMENT_NODE, nl2.item(0).getNodeType()); + assertEquals("child4", ((Element) nl2.item(0)).getTagName()); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/facade/FacadeTaskHelperTest.java b/src/tests/junit/org/apache/tools/ant/util/facade/FacadeTaskHelperTest.java new file mode 100644 index 000000000..f80b4d9af --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/facade/FacadeTaskHelperTest.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.facade; + +import junit.framework.TestCase; + +/** + * @since Ant 1.5 + */ +public class FacadeTaskHelperTest extends TestCase { + + public FacadeTaskHelperTest(String name) { + super(name); + } + + public void testPrecedenceRules() { + FacadeTaskHelper fth = new FacadeTaskHelper("foo"); + assertEquals("foo", fth.getImplementation()); + + fth.setMagicValue("bar"); + assertEquals("bar", fth.getImplementation()); + + fth = new FacadeTaskHelper("foo", "bar"); + assertEquals("bar", fth.getImplementation()); + + fth = new FacadeTaskHelper("foo", null); + assertEquals("foo", fth.getImplementation()); + + fth = new FacadeTaskHelper("foo"); + fth.setMagicValue("bar"); + fth.setImplementation("baz"); + assertEquals("baz", fth.getImplementation()); + } + + public void testHasBeenSet() { + FacadeTaskHelper fth = new FacadeTaskHelper("foo"); + assertTrue("nothing set", !fth.hasBeenSet()); + fth.setMagicValue(null); + assertTrue("magic has not been set", !fth.hasBeenSet()); + fth.setMagicValue("foo"); + assertTrue("magic has been set", fth.hasBeenSet()); + fth.setMagicValue(null); + assertTrue(!fth.hasBeenSet()); + fth.setImplementation("baz"); + assertTrue("set explicitly", fth.hasBeenSet()); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/facade/ImplementationSpecificArgumentTest.java b/src/tests/junit/org/apache/tools/ant/util/facade/ImplementationSpecificArgumentTest.java new file mode 100644 index 000000000..e4e7a2ae5 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/facade/ImplementationSpecificArgumentTest.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.facade; + +import junit.framework.TestCase; + +/** + * @since Ant 1.5 + */ +public class ImplementationSpecificArgumentTest extends TestCase { + + public ImplementationSpecificArgumentTest(String name) { + super(name); + } + + public void testDependsOnImplementation() { + ImplementationSpecificArgument ia = + new ImplementationSpecificArgument(); + ia.setLine("A B"); + String[] parts = ia.getParts(); + assertNotNull(parts); + assertEquals(2, parts.length); + assertEquals("A", parts[0]); + assertEquals("B", parts[1]); + + parts = ia.getParts(null); + assertNotNull(parts); + assertEquals(2, parts.length); + assertEquals("A", parts[0]); + assertEquals("B", parts[1]); + + ia.setImplementation("foo"); + parts = ia.getParts(null); + assertNotNull(parts); + assertEquals(0, parts.length); + + parts = ia.getParts("foo"); + assertNotNull(parts); + assertEquals(2, parts.length); + assertEquals("A", parts[0]); + assertEquals("B", parts[1]); + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaOroMatcherTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaOroMatcherTest.java new file mode 100644 index 000000000..d1405f4ad --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaOroMatcherTest.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +/** + * Tests for the jakarta-oro implementation of the RegexpMatcher interface. + * + */ +public class JakartaOroMatcherTest extends RegexpMatcherTest { + + public RegexpMatcher getImplementation() { + return new JakartaOroMatcher(); + } + + public JakartaOroMatcherTest(String name) { + super(name); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaOroRegexpTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaOroRegexpTest.java new file mode 100644 index 000000000..e869c62e1 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaOroRegexpTest.java @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +/** + * Tests for the jakarta-oro implementation of the Regexp interface. + * + */ +public class JakartaOroRegexpTest extends RegexpTest { + + public Regexp getRegexpImplementation() { + return new JakartaOroRegexp(); + } + + public JakartaOroRegexpTest(String name) { + super(name); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaRegexpMatcherTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaRegexpMatcherTest.java new file mode 100644 index 000000000..3340b59cf --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaRegexpMatcherTest.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +import java.io.IOException; + +import junit.framework.AssertionFailedError; + +/** + * Tests for the jakarta-regexp implementation of the RegexpMatcher interface. + * + */ +public class JakartaRegexpMatcherTest extends RegexpMatcherTest { + + public RegexpMatcher getImplementation() { + return new JakartaRegexpMatcher(); + } + + public JakartaRegexpMatcherTest(String name) { + super(name); + } + + public void testWindowsLineSeparator2() throws IOException { + try { + super.testWindowsLineSeparator2(); + fail("Should trigger when this bug is fixed. {@since 1.2}"); + } catch (AssertionFailedError e) { + } + } + + /** + * Fails for the same reason as "default" mode in doEndTest2. + */ + public void testUnixLineSeparator() throws IOException { + try { + super.testUnixLineSeparator(); + fail("Should trigger once this bug is fixed. {@since 1.2}"); + } catch (AssertionFailedError e) { + } + } + + + /** + * Fails for "default" mode. + */ + protected void doEndTest2(String text) {} +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaRegexpRegexpTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaRegexpRegexpTest.java new file mode 100644 index 000000000..078fbb1bd --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/JakartaRegexpRegexpTest.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +import java.io.IOException; + +import junit.framework.AssertionFailedError; + +/** + * Tests for the jakarta-regexp implementation of the Regexp interface. + * + */ +public class JakartaRegexpRegexpTest extends RegexpTest { + + public Regexp getRegexpImplementation() { + return new JakartaRegexpRegexp(); + } + + public JakartaRegexpRegexpTest(String name) { + super(name); + } + + public void testWindowsLineSeparator2() throws IOException { + try { + super.testWindowsLineSeparator2(); + fail("Should trigger when this bug is fixed. {@since 1.2}"); + } catch (AssertionFailedError e){ + } + } + + /** + * Fails for the same reason as "default" mode in doEndTest2. + */ + public void testUnixLineSeparator() throws IOException { + try { + super.testUnixLineSeparator(); + fail("Should trigger once this bug is fixed. {@since 1.2}"); + } catch (AssertionFailedError e){ + } + } + + /** + * Fails for "default" mode. + */ + protected void doEndTest2(String text) {} +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/Jdk14RegexpMatcherTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/Jdk14RegexpMatcherTest.java new file mode 100644 index 000000000..c042e7157 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/Jdk14RegexpMatcherTest.java @@ -0,0 +1,70 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +import java.io.IOException; + +import junit.framework.AssertionFailedError; + +/** + * Tests for the JDK 1.4 implementation of the RegexpMatcher interface. + * + */ +public class Jdk14RegexpMatcherTest extends RegexpMatcherTest { + + public RegexpMatcher getImplementation() { + return new Jdk14RegexpMatcher(); + } + + public Jdk14RegexpMatcherTest(String name) { + super(name); + } + + public void testParagraphCharacter() throws IOException { + try { + super.testParagraphCharacter(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } + + public void testLineSeparatorCharacter() throws IOException { + try { + super.testLineSeparatorCharacter(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } + + public void testStandaloneCR() throws IOException { + try { + super.testStandaloneCR(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } + + public void testWindowsLineSeparator() throws IOException { + try { + super.testWindowsLineSeparator(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/Jdk14RegexpRegexpTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/Jdk14RegexpRegexpTest.java new file mode 100644 index 000000000..2b60406a3 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/Jdk14RegexpRegexpTest.java @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +import java.io.IOException; + +import junit.framework.AssertionFailedError; + +/** + * Tests for the JDK 1.4 implementation of the Regexp interface. + * + */ +public class Jdk14RegexpRegexpTest extends RegexpTest { + + public Regexp getRegexpImplementation() { + return new Jdk14RegexpRegexp(); + } + + public Jdk14RegexpRegexpTest(String name) { + super(name); + } + + public void testParagraphCharacter() throws IOException { + try { + super.testParagraphCharacter(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } + + public void testLineSeparatorCharacter() throws IOException { + try { + super.testLineSeparatorCharacter(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } + + public void testStandaloneCR() throws IOException { + try { + super.testStandaloneCR(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } + + public void testWindowsLineSeparator() throws IOException { + try { + super.testWindowsLineSeparator(); + fail("Should trigger once fixed. {@since JDK 1.4RC1}"); + } catch (AssertionFailedError e){ + } + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/RegexpMatcherTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/RegexpMatcherTest.java new file mode 100644 index 000000000..095082740 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/RegexpMatcherTest.java @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +import java.io.IOException; +import java.util.Vector; + +import junit.framework.TestCase; + +/** + * Tests for all implementations of the RegexpMatcher interface. + * + */ +public abstract class RegexpMatcherTest extends TestCase { + + public final static String UNIX_LINE = "\n"; + + private RegexpMatcher reg; + + public abstract RegexpMatcher getImplementation(); + + protected final RegexpMatcher getReg() {return reg;} + + public RegexpMatcherTest(String name) { + super(name); + } + + public void setUp() { + reg = getImplementation(); + } + + public void testMatches() { + reg.setPattern("aaaa"); + assertTrue("aaaa should match itself", reg.matches("aaaa")); + assertTrue("aaaa should match xaaaa", reg.matches("xaaaa")); + assertTrue("aaaa shouldn\'t match xaaa", !reg.matches("xaaa")); + reg.setPattern("^aaaa"); + assertTrue("^aaaa shouldn\'t match xaaaa", !reg.matches("xaaaa")); + assertTrue("^aaaa should match aaaax", reg.matches("aaaax")); + reg.setPattern("aaaa$"); + assertTrue("aaaa$ shouldn\'t match aaaax", !reg.matches("aaaax")); + assertTrue("aaaa$ should match xaaaa", reg.matches("xaaaa")); + reg.setPattern("[0-9]+"); + assertTrue("[0-9]+ should match 123", reg.matches("123")); + assertTrue("[0-9]+ should match 1", reg.matches("1")); + assertTrue("[0-9]+ shouldn\'t match \'\'", !reg.matches("")); + assertTrue("[0-9]+ shouldn\'t match a", !reg.matches("a")); + reg.setPattern("[0-9]*"); + assertTrue("[0-9]* should match 123", reg.matches("123")); + assertTrue("[0-9]* should match 1", reg.matches("1")); + assertTrue("[0-9]* should match \'\'", reg.matches("")); + assertTrue("[0-9]* should match a", reg.matches("a")); + reg.setPattern("([0-9]+)=\\1"); + assertTrue("([0-9]+)=\\1 should match 1=1", reg.matches("1=1")); + assertTrue("([0-9]+)=\\1 shouldn\'t match 1=2", !reg.matches("1=2")); + } + + public void testGroups() { + reg.setPattern("aaaa"); + Vector v = reg.getGroups("xaaaa"); + assertEquals("No parens -> no extra groups", 1, v.size()); + assertEquals("Trivial match with no parens", "aaaa", + (String) v.elementAt(0)); + + reg.setPattern("(aaaa)"); + v = reg.getGroups("xaaaa"); + assertEquals("Trivial match with single paren", 2, v.size()); + assertEquals("Trivial match with single paren, full match", "aaaa", + (String) v.elementAt(0)); + assertEquals("Trivial match with single paren, matched paren", "aaaa", + (String) v.elementAt(0)); + + reg.setPattern("(a+)b(b+)"); + v = reg.getGroups("xaabb"); + assertEquals(3, v.size()); + assertEquals("aabb", (String) v.elementAt(0)); + assertEquals("aa", (String) v.elementAt(1)); + assertEquals("b", (String) v.elementAt(2)); + } + + public void testBugzillaReport14619() { + reg.setPattern("^(.*)/src/((.*/)*)([a-zA-Z0-9_\\.]+)\\.java$"); + Vector v = reg.getGroups("de/tom/src/Google.java"); + assertEquals(5, v.size()); + assertEquals("de/tom", v.elementAt(1)); + assertEquals("", v.elementAt(2)); + assertEquals("", v.elementAt(3)); + assertEquals("Google", v.elementAt(4)); + } + + public void testCaseInsensitiveMatch() { + reg.setPattern("aaaa"); + assertTrue("aaaa doesn't match AAaa", !reg.matches("AAaa")); + assertTrue("aaaa matches AAaa ignoring case", + reg.matches("AAaa", RegexpMatcher.MATCH_CASE_INSENSITIVE)); + } + + +// make sure there are no issues concerning line separator interpretation +// a line separator for regex (perl) is always a unix line (ie \n) + + public void testParagraphCharacter() throws IOException { + reg.setPattern("end of text$"); + assertTrue("paragraph character", !reg.matches("end of text\u2029")); + } + + public void testLineSeparatorCharacter() throws IOException { + reg.setPattern("end of text$"); + assertTrue("line-separator character", !reg.matches("end of text\u2028")); + } + + public void testNextLineCharacter() throws IOException { + reg.setPattern("end of text$"); + assertTrue("next-line character", !reg.matches("end of text\u0085")); + } + + public void testStandaloneCR() throws IOException { + reg.setPattern("end of text$"); + assertTrue("standalone CR", !reg.matches("end of text\r")); + } + + public void testWindowsLineSeparator() throws IOException { + reg.setPattern("end of text$"); + assertTrue("Windows line separator", !reg.matches("end of text\r\n")); + } + + public void testWindowsLineSeparator2() throws IOException { + reg.setPattern("end of text\r$"); + assertTrue("Windows line separator", reg.matches("end of text\r\n")); + } + + public void testUnixLineSeparator() throws IOException { + reg.setPattern("end of text$"); + assertTrue("Unix line separator", reg.matches("end of text\n")); + } + + + public void testMultiVersusSingleLine() throws IOException { + StringBuffer buf = new StringBuffer(); + buf.append("Line1").append(UNIX_LINE); + buf.append("starttest Line2").append(UNIX_LINE); + buf.append("Line3 endtest").append(UNIX_LINE); + buf.append("Line4").append(UNIX_LINE); + String text = buf.toString(); + + doStartTest1(text); + doStartTest2(text); + doEndTest1(text); + doEndTest2(text); + } + + protected void doStartTest1(String text) { + reg.setPattern("^starttest"); + assertTrue("^starttest in default mode", !reg.matches(text)); + assertTrue("^starttest in single line mode", + !reg.matches(text, RegexpMatcher.MATCH_SINGLELINE)); + assertTrue("^starttest in multi line mode", + reg.matches(text, RegexpMatcher.MATCH_MULTILINE)); + } + + protected void doStartTest2(String text) { + reg.setPattern("^Line1"); + assertTrue("^Line1 in default mode", reg.matches(text)); + assertTrue("^Line1 in single line mode", + reg.matches(text, RegexpMatcher.MATCH_SINGLELINE)); + assertTrue("^Line1 in multi line mode", + reg.matches(text, RegexpMatcher.MATCH_MULTILINE)); + } + + protected void doEndTest1(String text) { + reg.setPattern("endtest$"); + assertTrue("endtest$ in default mode", !reg.matches(text)); + assertTrue("endtest$ in single line mode", + !reg.matches(text, RegexpMatcher.MATCH_SINGLELINE)); + assertTrue("endtest$ in multi line mode", + reg.matches(text, RegexpMatcher.MATCH_MULTILINE)); + } + + protected void doEndTest2(String text) { + reg.setPattern("Line4$"); + assertTrue("Line4$ in default mode", reg.matches(text)); + assertTrue("Line4$ in single line mode", + reg.matches(text, RegexpMatcher.MATCH_SINGLELINE)); + assertTrue("Line4$ in multi line mode", + reg.matches(text, RegexpMatcher.MATCH_MULTILINE)); + } + +} diff --git a/src/tests/junit/org/apache/tools/ant/util/regexp/RegexpTest.java b/src/tests/junit/org/apache/tools/ant/util/regexp/RegexpTest.java new file mode 100644 index 000000000..5cfe8c976 --- /dev/null +++ b/src/tests/junit/org/apache/tools/ant/util/regexp/RegexpTest.java @@ -0,0 +1,63 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.ant.util.regexp; + +/** + * Tests for all implementations of the Regexp interface. + * + */ +public abstract class RegexpTest extends RegexpMatcherTest { + + private static final String test = "abcdefg-abcdefg"; + private static final String pattern = "ab([^d]*)d([^f]*)f"; + + public RegexpTest(String name) { + super(name); + } + + public final RegexpMatcher getImplementation() { + return getRegexpImplementation(); + } + + public abstract Regexp getRegexpImplementation(); + + public void testSubstitution() { + Regexp reg = (Regexp) getReg(); + reg.setPattern(pattern); + assertTrue(reg.matches(test)); + assertEquals("abedcfg-abcdefg", reg.substitute(test, "ab\\2d\\1f", + Regexp.MATCH_DEFAULT)); + } + + public void testReplaceFirstSubstitution() { + Regexp reg = (Regexp) getReg(); + reg.setPattern(pattern); + assertTrue(reg.matches(test)); + assertEquals("abedcfg-abcdefg", reg.substitute(test, "ab\\2d\\1f", + Regexp.REPLACE_FIRST)); + } + + public void testReplaceAllSubstitution() { + Regexp reg = (Regexp) getReg(); + reg.setPattern(pattern); + assertTrue(reg.matches(test)); + assertEquals("abedcfg-abedcfg", reg.substitute(test, "ab\\2d\\1f", + Regexp.REPLACE_ALL)); + } +} diff --git a/src/tests/junit/org/apache/tools/mail/MailMessageTest.java b/src/tests/junit/org/apache/tools/mail/MailMessageTest.java new file mode 100644 index 000000000..a8e75308f --- /dev/null +++ b/src/tests/junit/org/apache/tools/mail/MailMessageTest.java @@ -0,0 +1,734 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.mail; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.PrintStream; +import java.net.InetAddress; +import java.net.Socket; +import java.net.ServerSocket; +import java.util.Enumeration; +import java.util.Vector; + +import org.apache.tools.mail.MailMessage; + +import junit.framework.TestCase; + +/** + * JUnit 3 testcases for org.apache.tools.mail.MailMessage. + * + * @since Ant 1.6 + */ +public class MailMessageTest extends TestCase { + + // 27224 = magic (a random port which is unlikely to be in use) + private static int TEST_PORT = 27224; + + private String local = null; + + public MailMessageTest(String name) { + super(name); + } + + public void setUp() { + try { + local = InetAddress.getLocalHost().getHostName(); + } catch (java.net.UnknownHostException uhe) { + // ignore + } + } + + /** + * Test an example that is similar to the one given in the API + * If this testcase takes >90s to complete, it is very likely that + * the two threads are blocked waiting for each other and Thread.join() + * timed out. + */ + public void testAPIExample() { + + ServerThread testMailServer = new ServerThread(); + Thread server = new Thread(testMailServer); + server.start(); + + ClientThread testMailClient = new ClientThread(); + + testMailClient.from("Mail Message "); + testMailClient.to("to@you.com"); + testMailClient.cc("cc1@you.com"); + testMailClient.cc("cc2@you.com"); + testMailClient.bcc("bcc@you.com"); + testMailClient.setSubject("Test subject"); + testMailClient.setMessage( "test line 1\n" + + "test line 2" ); + + Thread client = new Thread(testMailClient); + client.start(); + + try { + server.join(60 * 1000); // 60s + client.join(30 * 1000); // a further 30s + } catch (InterruptedException ie ) { + fail( "InterruptedException: " + ie ); + } + + String result = testMailServer.getResult(); + String expectedResult = "220 test SMTP EmailTaskTest\r\n" + + "HELO " + local + "\r\n" + + "250 " + local + " Hello " + local + " [127.0.0.1], pleased to meet you\r\n" + + "MAIL FROM: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "DATA\r\n" + + "354\r\n" + + "Subject: Test subject\r\n" + + "From: Mail Message \r\n" + + "To: to@you.com\r\n" + + "Cc: cc1@you.com, cc2@you.com\r\n" + + "X-Mailer: org.apache.tools.mail.MailMessage (ant.apache.org)\r\n" + + "\r\n" + + "test line 1\r\n" + + "test line 2\r\n" + + "\r\n" + + ".\r\n" + + "250\r\n" + + "QUIT\r\n" + + "221\r\n"; + for (int icounter = 0; icounterresult.length()) { + System.out.println("excedent of expected result " + + expectedResult.substring(result.length())); + } + if (expectedResult.length()"); + testMailClient.to("to@you.com"); + testMailClient.setSubject("Test subject"); + testMailClient.setMessage( "test line 1\n" + + "test line 2" ); + + Thread client = new Thread(testMailClient); + client.start(); + + try { + server.join(60 * 1000); // 60s + client.join(30 * 1000); // a further 30s + } catch (InterruptedException ie ) { + fail("InterruptedException: " + ie); + } + + String result = testMailServer.getResult(); + String expectedResult = "220 test SMTP EmailTaskTest\r\n" + + "HELO " + local + "\r\n" + + "250 " + local + " Hello " + local + " [127.0.0.1], pleased to meet you\r\n" + + "MAIL FROM: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "DATA\r\n" + + "354\r\n" + + "Subject: Test subject\r\n" + + "From: Mail Message \r\n" + + "To: to@you.com\r\n" + + "X-Mailer: org.apache.tools.mail.MailMessage (ant.apache.org)\r\n" + + "\r\n" + + "test line 1\r\n" + + "test line 2\r\n" + + "\r\n" + + ".\r\n" + + "250\r\n" + + "QUIT\r\n" + + "221\r\n"; + assertEquals(expectedResult.length(), result.length()); + assertEquals(expectedResult, result); // order of headers cannot be guaranteed + if (testMailClient.isFailed()) { + fail(testMailClient.getFailMessage()); + } + } + + + /** + * Test a MailMessage with no to or bcc lines + */ + public void testCcOnly() { + ServerThread testMailServer = new ServerThread(); + Thread server = new Thread(testMailServer); + server.start(); + + ClientThread testMailClient = new ClientThread(); + + testMailClient.from("Mail Message "); + testMailClient.cc("cc@you.com"); + testMailClient.setSubject("Test subject"); + testMailClient.setMessage( "test line 1\n" + + "test line 2" ); + + Thread client = new Thread(testMailClient); + client.start(); + + try { + server.join(60 * 1000); // 60s + client.join(30 * 1000); // a further 30s + } catch (InterruptedException ie ) { + fail( "InterruptedException: " + ie ); + } + + String result = testMailServer.getResult(); + String expectedResult = "220 test SMTP EmailTaskTest\r\n" + + "HELO " + local + "\r\n" + + "250 " + local + " Hello " + local + " [127.0.0.1], pleased to meet you\r\n" + + "MAIL FROM: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "DATA\r\n" + + "354\r\n" + + "Subject: Test subject\r\n" + + "From: Mail Message \r\n" + + "Cc: cc@you.com\r\n" + + "X-Mailer: org.apache.tools.mail.MailMessage (ant.apache.org)\r\n" + + "\r\n" + + "test line 1\r\n" + + "test line 2\r\n" + + "\r\n" + + ".\r\n" + + "250\r\n" + + "QUIT\r\n" + + "221\r\n"; + assertEquals(expectedResult.length(), result.length()); + assertEquals(expectedResult, result); + if (testMailClient.isFailed()) { + fail(testMailClient.getFailMessage()); + } + } + + + /** + * Test a MailMessage with no to or cc lines + */ + public void testBccOnly() { + ServerThread testMailServer = new ServerThread(); + Thread server = new Thread(testMailServer); + server.start(); + + ClientThread testMailClient = new ClientThread(); + + testMailClient.from("Mail Message "); + testMailClient.bcc("bcc@you.com"); + testMailClient.setSubject("Test subject"); + testMailClient.setMessage( "test line 1\n" + + "test line 2" ); + + Thread client = new Thread(testMailClient); + client.start(); + + try { + server.join(60 * 1000); // 60s + client.join(30 * 1000); // a further 30s + } catch (InterruptedException ie ) { + fail( "InterruptedException: " + ie ); + } + + String result = testMailServer.getResult(); + String expectedResult = "220 test SMTP EmailTaskTest\r\n" + + "HELO " + local + "\r\n" + + "250 " + local + " Hello " + local + " [127.0.0.1], pleased to meet you\r\n" + + "MAIL FROM: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "DATA\r\n" + + "354\r\n" + + "Subject: Test subject\r\n" + + "From: Mail Message \r\n" + + "X-Mailer: org.apache.tools.mail.MailMessage (ant.apache.org)\r\n" + + "\r\n" + + "test line 1\r\n" + + "test line 2\r\n" + + "\r\n" + + ".\r\n" + + "250\r\n" + + "QUIT\r\n" + + "221\r\n"; + assertEquals( expectedResult.length(), result.length() ); + assertEquals( expectedResult, result ); + if ( testMailClient.isFailed() ) { + fail( testMailClient.getFailMessage() ); + } + } + + + /** + * Test a MailMessage with no subject line + * Subject is an optional field (RFC 822 s4.1) + */ + public void testNoSubject() { + ServerThread testMailServer = new ServerThread(); + Thread server = new Thread(testMailServer); + server.start(); + + ClientThread testMailClient = new ClientThread(); + + testMailClient.from("Mail Message "); + testMailClient.to("to@you.com"); + testMailClient.setMessage( "test line 1\n" + + "test line 2" ); + + Thread client = new Thread(testMailClient); + client.start(); + + try { + server.join(60 * 1000); // 60s + client.join(30 * 1000); // a further 30s + } catch (InterruptedException ie ) { + fail( "InterruptedException: " + ie ); + } + + String result = testMailServer.getResult(); + String expectedResult = "220 test SMTP EmailTaskTest\r\n" + + "HELO " + local + "\r\n" + + "250 " + local + " Hello " + local + " [127.0.0.1], pleased to meet you\r\n" + + "MAIL FROM: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "DATA\r\n" + + "354\r\n" + + "From: Mail Message \r\n" + + "To: to@you.com\r\n" + + "X-Mailer: org.apache.tools.mail.MailMessage (ant.apache.org)\r\n" + + "\r\n" + + "test line 1\r\n" + + "test line 2\r\n" + + "\r\n" + + ".\r\n" + + "250\r\n" + + "QUIT\r\n" + + "221\r\n"; + assertEquals( expectedResult.length(), result.length() ); + assertEquals( expectedResult, result ); + if ( testMailClient.isFailed() ) { + fail( testMailClient.getFailMessage() ); + } + } + + + /** + * Test a MailMessage with empty body message + */ + public void testEmptyBody() { + ServerThread testMailServer = new ServerThread(); + Thread server = new Thread(testMailServer); + server.start(); + + ClientThread testMailClient = new ClientThread(); + + testMailClient.from("Mail Message "); + testMailClient.to("to@you.com"); + testMailClient.setSubject("Test subject"); + testMailClient.setMessage(""); + + Thread client = new Thread(testMailClient); + client.start(); + + try { + server.join(60 * 1000); // 60s + client.join(30 * 1000); // a further 30s + } catch (InterruptedException ie ) { + fail( "InterruptedException: " + ie ); + } + + String result = testMailServer.getResult(); + String expectedResult = "220 test SMTP EmailTaskTest\r\n" + + "HELO " + local + "\r\n" + + "250 " + local + " Hello " + local + " [127.0.0.1], pleased to meet you\r\n" + + "MAIL FROM: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "DATA\r\n" + + "354\r\n" + + "Subject: Test subject\r\n" + + "From: Mail Message \r\n" + + "To: to@you.com\r\n" + + "X-Mailer: org.apache.tools.mail.MailMessage (ant.apache.org)\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + ".\r\n" + + "250\r\n" + + "QUIT\r\n" + + "221\r\n"; + assertEquals(expectedResult.length(), result.length()); + assertEquals(expectedResult, result); + if (testMailClient.isFailed()) { + fail(testMailClient.getFailMessage()); + } + } + + + /** + * Test a MailMessage with US-ASCII character set + * The next four testcase can be kinda hard to debug as Ant will often + * print the junit failure in US-ASCII. + */ + public void testAsciiCharset() { + + ServerThread testMailServer = new ServerThread(); + Thread server = new Thread(testMailServer); + server.start(); + + ClientThread testMailClient = new ClientThread(); + + testMailClient.from("Mail Message "); + testMailClient.to("Ceki G\u00fclc\u00fc "); + testMailClient.setSubject("Test subject"); + testMailClient.setMessage(""); + + Thread client = new Thread(testMailClient); + client.start(); + + try { + server.join(60 * 1000); // 60s + client.join(30 * 1000); // a further 30s + } catch (InterruptedException ie ) { + fail("InterruptedException: " + ie); + } + + String result = testMailServer.getResult(); + String expectedResult = "220 test SMTP EmailTaskTest\r\n" + + "HELO " + local + "\r\n" + + "250 " + local + " Hello " + local + " [127.0.0.1], pleased to meet you\r\n" + + "MAIL FROM: \r\n" + + "250\r\n" + + "RCPT TO: \r\n" + + "250\r\n" + + "DATA\r\n" + + "354\r\n" + + "Subject: Test subject\r\n" + + "From: Mail Message \r\n" + + "To: Ceki G\u00fclc\u00fc \r\n" + + "X-Mailer: org.apache.tools.mail.MailMessage (ant.apache.org)\r\n" + + "\r\n" + + "\r\n" + + "\r\n" + + ".\r\n" + + "250\r\n" + + "QUIT\r\n" + + "221\r\n"; + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); + PrintStream bos1 = new PrintStream(baos1, true); + PrintStream bos2 = new PrintStream(baos2, true); + + bos1.print(expectedResult); + bos2.print(result); + + assertEquals( "expected message length != actual message length " + + "in testAsciiCharset()", expectedResult.length(), result.length() ); + assertEquals( "baos1 and baos2 should be the same in testAsciiCharset()", + baos1.toString(), baos2.toString() ); // order of headers cannot be guaranteed + if (testMailClient.isFailed()) { + fail(testMailClient.getFailMessage()); + } + } + + + + + /** + * A private test class that pretends to be a mail transfer agent + */ + private class ServerThread implements Runnable { + + private StringBuffer sb = null; + private boolean loop = false; + ServerSocket ssock = null; + Socket sock = null; + BufferedWriter out = null; + BufferedReader in = null; + private boolean data = false; // state engine: false=envelope, true=message + + public void run() { + + try { + ssock = new ServerSocket(TEST_PORT); + sock = ssock.accept(); // wait for connection + in = new BufferedReader( new InputStreamReader( + sock.getInputStream()) ); + out = new BufferedWriter( new OutputStreamWriter( + sock.getOutputStream() ) ); + sb = new StringBuffer(); + send( "220 test SMTP EmailTaskTest\r\n" ); + loop = true; + while ( loop ) { + String response = in.readLine(); + if ( response == null ) { + loop = false; + break; + } + sb.append( response + "\r\n" ); + + if ( !data && response.startsWith( "HELO" ) ) { + send( "250 " + local + " Hello " + local + " " + + "[127.0.0.1], pleased to meet you\r\n" ); + } else if ( !data && response.startsWith("MAIL") ) { + send( "250\r\n" ); + } else if ( !data && response.startsWith("RCPT")) { + send( "250\r\n" ); + } else if (!data && response.startsWith("DATA")) { + send( "354\r\n" ); + data = true; + } else if (data && response.equals(".") ) { + send( "250\r\n" ); + data = false; + } else if (!data && response.startsWith("QUIT")) { + send( "221\r\n" ); + loop = false; + } else if (!data) { + //throw new IllegalStateException("Command unrecognized: " + // + response); + send( "500 5.5.1 Command unrecognized: \"" + + response + "\"\r\n" ); + loop = false; + } else { + // sb.append( response + "\r\n" ); + } + + } // while + } catch (IOException ioe) { + fail(); + } finally { + disconnect(); + } + } + + private void send(String retmsg) throws IOException { + out.write( retmsg ); + out.flush(); + sb.append( retmsg ); + } + + private void disconnect() { + if (out != null) { + try { + out.flush(); + out.close(); + out = null; + } catch (IOException e) { + // ignore + } + } + if (in != null) { + try { + in.close(); + in = null; + } catch (IOException e) { + // ignore + } + } + if (sock != null) { + try { + sock.close(); + sock = null; + } catch (IOException e) { + // ignore + } + } + if (ssock != null) { + try { + ssock.close(); + ssock = null; + } catch (IOException e) { + // ignore + } + } + } + + public synchronized String getResult() { + loop = false; + return sb.toString(); + } + + } + + /** + * A private test class that wraps MailMessage + */ + private class ClientThread implements Runnable { + + private MailMessage msg; + private boolean fail = false; + private String failMessage = null; + + protected String from = null; + protected String subject = null; + protected String message = null; + + protected Vector replyToList = new Vector(); + protected Vector toList = new Vector(); + protected Vector ccList = new Vector(); + protected Vector bccList = new Vector(); + + + public void run() { + for (int i = 9; i > 0; i--) { + try { + msg = new MailMessage("localhost", TEST_PORT); + } catch (java.net.ConnectException ce) { + try { + Thread.sleep(10 * 1000); + } catch (InterruptedException ie) { + // ignore + } + } catch (IOException ioe) { + fail = true; + failMessage = "IOException: " + ioe; + return; + } + if (msg != null) { + break; + } + } + + if (msg == null) { + fail = true; + failMessage = "java.net.ConnectException: Connection refused"; + return; + } + + try { + msg.from(from); + + Enumeration e; + + e = replyToList.elements(); + while (e.hasMoreElements()) { + msg.replyto(e.nextElement().toString()); + } + + e = toList.elements(); + while (e.hasMoreElements()) { + msg.to(e.nextElement().toString()); + } + + e = ccList.elements(); + while (e.hasMoreElements()) { + msg.cc(e.nextElement().toString()); + } + + e = bccList.elements(); + while (e.hasMoreElements()) { + msg.bcc(e.nextElement().toString()); + } + + if (subject != null) { + msg.setSubject(subject); + } + + if (message != null ) { + PrintStream out = msg.getPrintStream(); + out.println( message ); + } + + msg.sendAndClose(); + } catch (IOException ioe) { + fail = true; + failMessage = "IOException: " + ioe; + return; + } + } + + public boolean isFailed() { + return fail; + } + + public String getFailMessage() { + return failMessage; + } + + public void replyTo(String replyTo) { + replyToList.add(replyTo); + } + + public void to(String to) { + toList.add(to); + } + + public void cc(String cc) { + ccList.add(cc); + } + + public void bcc(String bcc) { + bccList.add(bcc); + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public void from(String from) { + this.from = from; + } + + public void setMessage(String message) { + this.message = message; + } + + } + +} diff --git a/src/tests/junit/org/apache/tools/tar/TarEntryTest.java b/src/tests/junit/org/apache/tools/tar/TarEntryTest.java new file mode 100644 index 000000000..23f4185ec --- /dev/null +++ b/src/tests/junit/org/apache/tools/tar/TarEntryTest.java @@ -0,0 +1,38 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.tar; + +import junit.framework.TestCase; + +/** + * @since Ant 1.6 + */ +public class TarEntryTest extends TestCase { + + public TarEntryTest(String name) { + super(name); + } + + /** + * demonstrates bug 18105 on OSes with os.name shorter than 7. + */ + public void testFileConstructor() { + new TarEntry(new java.io.File("/foo")); + } +} diff --git a/src/tests/junit/org/apache/tools/tar/TarOutputStreamTest.java b/src/tests/junit/org/apache/tools/tar/TarOutputStreamTest.java new file mode 100644 index 000000000..be5311af8 --- /dev/null +++ b/src/tests/junit/org/apache/tools/tar/TarOutputStreamTest.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.tar; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import junit.framework.TestCase; + +public class TarOutputStreamTest extends TestCase { + + public void testClose() throws IOException { + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + TarOutputStream stream = new TarOutputStream(byteStream); + stream.close(); + stream.close(); + } +} diff --git a/src/tests/junit/org/apache/tools/tar/TarRoundTripTest.java b/src/tests/junit/org/apache/tools/tar/TarRoundTripTest.java new file mode 100644 index 000000000..6df0de845 --- /dev/null +++ b/src/tests/junit/org/apache/tools/tar/TarRoundTripTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.apache.tools.tar; + +import java.io.IOException; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import junit.framework.TestCase; + +public class TarRoundTripTest extends TestCase { + + private static final String LONG_NAME + = "this/path/name/contains/more/than/one/hundred/characters/in/order/" + + "to/test/the/GNU/long/file/name/capability/round/tripped"; + + public TarRoundTripTest(String name) { + super(name); + } + + /** + * test round-tripping long (GNU) entries + */ + public void testLongRoundTripping() throws IOException { + TarEntry original = new TarEntry(LONG_NAME); + assertEquals("over 100 chars", true, LONG_NAME.length() > 100); + assertEquals("original name", LONG_NAME, original.getName()); + + + ByteArrayOutputStream buff = new ByteArrayOutputStream(); + TarOutputStream tos = new TarOutputStream(buff); + tos.setLongFileMode(TarOutputStream.LONGFILE_GNU); + tos.putNextEntry(original); + tos.closeEntry(); + tos.close(); + + TarInputStream tis + = new TarInputStream(new ByteArrayInputStream(buff.toByteArray())); + TarEntry tripped = tis.getNextEntry(); + assertEquals("round-tripped name", LONG_NAME, tripped.getName()); + assertNull("no more entries", tis.getNextEntry()); + tis.close(); + } +} + + diff --git a/src/tests/junit/org/apache/tools/zip/AsiExtraFieldTest.java b/src/tests/junit/org/apache/tools/zip/AsiExtraFieldTest.java new file mode 100644 index 000000000..c8e4fe418 --- /dev/null +++ b/src/tests/junit/org/apache/tools/zip/AsiExtraFieldTest.java @@ -0,0 +1,141 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.zip; + +import junit.framework.TestCase; + +/** + * JUnit 3 testcases for org.apache.tools.zip.AsiExtraField. + * + */ +public class AsiExtraFieldTest extends TestCase implements UnixStat { + public AsiExtraFieldTest(String name) { + super(name); + } + + /** + * Test file mode magic. + */ + public void testModes() { + AsiExtraField a = new AsiExtraField(); + a.setMode(0123); + assertEquals("plain file", 0100123, a.getMode()); + a.setDirectory(true); + assertEquals("directory", 040123, a.getMode()); + a.setLinkedFile("test"); + assertEquals("symbolic link", 0120123, a.getMode()); + } + + /** + * Test content. + */ + public void testContent() { + AsiExtraField a = new AsiExtraField(); + a.setMode(0123); + a.setUserId(5); + a.setGroupId(6); + byte[] b = a.getLocalFileDataData(); + + // CRC manually calculated, sorry + byte[] expect = {(byte)0xC6, 0x02, 0x78, (byte)0xB6, // CRC + 0123, (byte)0x80, // mode + 0, 0, 0, 0, // link length + 5, 0, 6, 0}; // uid, gid + assertEquals("no link", expect.length, b.length); + for (int i=0; i> 16) & 0xFFFF); + assertEquals(0, ze.getExternalAttributes() & 0xFFFF); + + ze.setUnixMode(0444); + assertEquals(3, ze.getPlatform()); + assertEquals(0444, + (ze.getExternalAttributes() >> 16) & 0xFFFF); + assertEquals(1, ze.getExternalAttributes() & 0xFFFF); + + ze = new ZipEntry("foo/"); + assertEquals(0, ze.getPlatform()); + ze.setUnixMode(0777); + assertEquals(3, ze.getPlatform()); + assertEquals(0777, + (ze.getExternalAttributes() >> 16) & 0xFFFF); + assertEquals(0x10, ze.getExternalAttributes() & 0xFFFF); + + ze.setUnixMode(0577); + assertEquals(3, ze.getPlatform()); + assertEquals(0577, + (ze.getExternalAttributes() >> 16) & 0xFFFF); + assertEquals(0x11, ze.getExternalAttributes() & 0xFFFF); + } + +} diff --git a/src/tests/junit/org/apache/tools/zip/ZipLongTest.java b/src/tests/junit/org/apache/tools/zip/ZipLongTest.java new file mode 100644 index 000000000..e72aaaaef --- /dev/null +++ b/src/tests/junit/org/apache/tools/zip/ZipLongTest.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.zip; + +import junit.framework.TestCase; + +/** + * JUnit 3 testcases for org.apache.tools.zip.ZipLong. + * + */ +public class ZipLongTest extends TestCase { + + public ZipLongTest(String name) { + super(name); + } + + /** + * Test conversion to bytes. + */ + public void testToBytes() { + ZipLong zl = new ZipLong(0x12345678); + byte[] result = zl.getBytes(); + assertEquals("length getBytes", 4, result.length); + assertEquals("first byte getBytes", 0x78, result[0]); + assertEquals("second byte getBytes", 0x56, result[1]); + assertEquals("third byte getBytes", 0x34, result[2]); + assertEquals("fourth byte getBytes", 0x12, result[3]); + } + + /** + * Test conversion from bytes. + */ + public void testFromBytes() { + byte[] val = new byte[] {0x78, 0x56, 0x34, 0x12}; + ZipLong zl = new ZipLong(val); + assertEquals("value from bytes", 0x12345678, zl.getValue()); + } + + /** + * Test the contract of the equals method. + */ + public void testEquals() { + ZipLong zl = new ZipLong(0x12345678); + ZipLong zl2 = new ZipLong(0x12345678); + ZipLong zl3 = new ZipLong(0x87654321); + + assertTrue("reflexive", zl.equals(zl)); + + assertTrue("works", zl.equals(zl2)); + assertTrue("works, part two", !zl.equals(zl3)); + + assertTrue("symmetric", zl2.equals(zl)); + + assertTrue("null handling", !zl.equals(null)); + assertTrue("non ZipLong handling", !zl.equals(new Integer(0x1234))); + } + + /** + * Test sign handling. + */ + public void testSign() { + ZipLong zl = new ZipLong(new byte[] {(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF}); + assertEquals(0x00000000FFFFFFFFl, zl.getValue()); + } + +} diff --git a/src/tests/junit/org/apache/tools/zip/ZipOutputStreamTest.java b/src/tests/junit/org/apache/tools/zip/ZipOutputStreamTest.java new file mode 100644 index 000000000..19b7c0591 --- /dev/null +++ b/src/tests/junit/org/apache/tools/zip/ZipOutputStreamTest.java @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.zip; + +import java.util.Calendar; +import java.util.Date; + +import junit.framework.TestCase; + +public class ZipOutputStreamTest extends TestCase { + + private Date time; + private ZipLong zl; + + /** + * Constructor + */ + public ZipOutputStreamTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + time = new Date(); + Calendar cal = Calendar.getInstance(); + cal.setTime(time); + int year = cal.get(Calendar.YEAR); + int month = cal.get(Calendar.MONTH) + 1; + long value = ((year - 1980) << 25) + | (month << 21) + | (cal.get(Calendar.DAY_OF_MONTH) << 16) + | (cal.get(Calendar.HOUR_OF_DAY) << 11) + | (cal.get(Calendar.MINUTE) << 5) + | (cal.get(Calendar.SECOND) >> 1); + + byte[] result = new byte[4]; + result[0] = (byte) ((value & 0xFF)); + result[1] = (byte) ((value & 0xFF00) >> 8); + result[2] = (byte) ((value & 0xFF0000) >> 16); + result[3] = (byte) ((value & 0xFF000000L) >> 24); + zl = new ZipLong(result); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testZipLong() throws Exception { + ZipLong test = ZipOutputStream.toDosTime(time); + assertEquals(test.getValue(), zl.getValue()); + } + + public void testAdjustToLong() { + assertEquals((long) Integer.MAX_VALUE, + ZipOutputStream.adjustToLong(Integer.MAX_VALUE)); + assertEquals(((long) Integer.MAX_VALUE) + 1, + ZipOutputStream.adjustToLong(Integer.MAX_VALUE + 1)); + assertEquals(2 * ((long) Integer.MAX_VALUE), + ZipOutputStream.adjustToLong(2 * Integer.MAX_VALUE)); + } + +} diff --git a/src/tests/junit/org/apache/tools/zip/ZipShortTest.java b/src/tests/junit/org/apache/tools/zip/ZipShortTest.java new file mode 100644 index 000000000..3fb604f7d --- /dev/null +++ b/src/tests/junit/org/apache/tools/zip/ZipShortTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.apache.tools.zip; + +import junit.framework.TestCase; + +/** + * JUnit 3 testcases for org.apache.tools.zip.ZipShort. + * + */ +public class ZipShortTest extends TestCase { + + public ZipShortTest(String name) { + super(name); + } + + /** + * Test conversion to bytes. + */ + public void testToBytes() { + ZipShort zs = new ZipShort(0x1234); + byte[] result = zs.getBytes(); + assertEquals("length getBytes", 2, result.length); + assertEquals("first byte getBytes", 0x34, result[0]); + assertEquals("second byte getBytes", 0x12, result[1]); + } + + /** + * Test conversion from bytes. + */ + public void testFromBytes() { + byte[] val = new byte[] {0x34, 0x12}; + ZipShort zs = new ZipShort(val); + assertEquals("value from bytes", 0x1234, zs.getValue()); + } + + /** + * Test the contract of the equals method. + */ + public void testEquals() { + ZipShort zs = new ZipShort(0x1234); + ZipShort zs2 = new ZipShort(0x1234); + ZipShort zs3 = new ZipShort(0x5678); + + assertTrue("reflexive", zs.equals(zs)); + + assertTrue("works", zs.equals(zs2)); + assertTrue("works, part two", !zs.equals(zs3)); + + assertTrue("symmetric", zs2.equals(zs)); + + assertTrue("null handling", !zs.equals(null)); + assertTrue("non ZipShort handling", !zs.equals(new Integer(0x1234))); + } + + /** + * Test sign handling. + */ + public void testSign() { + ZipShort zs = new ZipShort(new byte[] {(byte)0xFF, (byte)0xFF}); + assertEquals(0x0000FFFF, zs.getValue()); + } + +} diff --git a/src/tests/junit/org/example/junit/Output.java b/src/tests/junit/org/example/junit/Output.java new file mode 100644 index 000000000..a7135f7b3 --- /dev/null +++ b/src/tests/junit/org/example/junit/Output.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.example.junit; + +import junit.framework.TestCase; + +/** + * Not really a test of Ant but a test that is run by the test of the + * junit task. Confused? + * + * @since Ant 1.5 + */ +public class Output extends TestCase { + + public Output(String s) { + super(s); + } + + public void testOutput() { + System.out.println("foo"); + } +} diff --git a/src/tests/junit/org/example/junit/ThreadedOutput.java b/src/tests/junit/org/example/junit/ThreadedOutput.java new file mode 100644 index 000000000..91f462a21 --- /dev/null +++ b/src/tests/junit/org/example/junit/ThreadedOutput.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.example.junit; + +import junit.framework.TestCase; + +/** + * Not really a test of Ant but a test that is run by the test of the + * junit task. Confused? + * + * @since Ant 1.5 + */ +public class ThreadedOutput extends TestCase { + + public ThreadedOutput(String s) { + super(s); + } + + public void testOutput() throws InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + System.out.println("foo"); + } + }); + t.start(); + t.join(); + } +} diff --git a/src/tests/junit/org/example/junit/XmlParserTest.java b/src/tests/junit/org/example/junit/XmlParserTest.java new file mode 100644 index 000000000..ddc766dd1 --- /dev/null +++ b/src/tests/junit/org/example/junit/XmlParserTest.java @@ -0,0 +1,56 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package org.example.junit; + +import junit.framework.TestCase; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.helpers.XMLReaderFactory; + +/** + * created Aug 12, 2004 1:39:59 PM + */ + +public class XmlParserTest extends TestCase { + + public XmlParserTest(String s) { + super(s); + } + + public void testXercesIsPresent() throws SAXException { + XMLReader xerces; + xerces = XMLReaderFactory.createXMLReader( + "org.apache.xerces.parsers.SAXParser"); + assertNotNull(xerces); + } + + public void testXercesHandlesSchema() throws SAXException { + XMLReader xerces; + xerces = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); + xerces.setFeature("http://apache.org/xml/features/validation/schema", + true); + } + + public void testParserHandlesSchema() throws SAXException { + XMLReader xerces; + xerces = XMLReaderFactory.createXMLReader(); + xerces.setFeature("http://apache.org/xml/features/validation/schema", + true); + } + +} diff --git a/src/tests/junit/org/example/tasks/TaskdefTestContainerTask.java b/src/tests/junit/org/example/tasks/TaskdefTestContainerTask.java new file mode 100644 index 000000000..a566d5c1f --- /dev/null +++ b/src/tests/junit/org/example/tasks/TaskdefTestContainerTask.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.example.tasks; + +import org.apache.tools.ant.taskdefs.Sequential; + +public class TaskdefTestContainerTask extends Sequential { + public TaskdefTestContainerTask() {} +} diff --git a/src/tests/junit/org/example/tasks/TaskdefTestSimpleTask.java b/src/tests/junit/org/example/tasks/TaskdefTestSimpleTask.java new file mode 100644 index 000000000..bce8cd503 --- /dev/null +++ b/src/tests/junit/org/example/tasks/TaskdefTestSimpleTask.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.example.tasks; + +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; + +public class TaskdefTestSimpleTask extends Task { + + public class Echo { + Echo() {} + private String message = null; + public void setMessage(String s) {message = s;} + } + + public TaskdefTestSimpleTask() {} + + private Echo echo; + public Echo createEcho() { + echo = new Echo(); + return echo; + } + + public void execute() { + log("simpletask: "+echo.message, Project.MSG_INFO); + } + +} + diff --git a/src/tests/junit/org/example/tasks/antlib.xml b/src/tests/junit/org/example/tasks/antlib.xml new file mode 100644 index 000000000..593ed604c --- /dev/null +++ b/src/tests/junit/org/example/tasks/antlib.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/tests/junit/org/example/tasks/antlib2.xml b/src/tests/junit/org/example/tasks/antlib2.xml new file mode 100644 index 000000000..593ed604c --- /dev/null +++ b/src/tests/junit/org/example/tasks/antlib2.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/tests/junit/org/example/types/TypedefTestType.java b/src/tests/junit/org/example/types/TypedefTestType.java new file mode 100644 index 000000000..235b76f61 --- /dev/null +++ b/src/tests/junit/org/example/types/TypedefTestType.java @@ -0,0 +1,25 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package org.example.types; + +import org.apache.tools.ant.ProjectComponent; + +public class TypedefTestType extends ProjectComponent { +} +