Browse Source

Restructuring to allow junit and antunit tests both.

git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@448636 13f79535-47bb-0310-9956-ffa450edef68
master
Matthew Jason Benson 19 years ago
parent
commit
73d66d2c6d
100 changed files with 13290 additions and 44 deletions
  1. +149
    -44
      build.xml
  2. +121
    -0
      src/tests/junit/org/apache/tools/ant/AntClassLoaderDelegationTest.java
  3. +101
    -0
      src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java
  4. +524
    -0
      src/tests/junit/org/apache/tools/ant/BuildFileTest.java
  5. +54
    -0
      src/tests/junit/org/apache/tools/ant/CaseTest.java
  6. +534
    -0
      src/tests/junit/org/apache/tools/ant/DirectoryScannerTest.java
  7. +36
    -0
      src/tests/junit/org/apache/tools/ant/DispatchTaskTest.java
  8. +32
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskAbstract.java
  9. +25
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskInterface.java
  10. +31
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskOk.java
  11. +29
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskOkNonTask.java
  12. +29
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskWithNonPublicExecute.java
  13. +30
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskWithNonVoidExecute.java
  14. +31
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskWithoutDefaultConstructor.java
  15. +29
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskWithoutExecute.java
  16. +31
    -0
      src/tests/junit/org/apache/tools/ant/DummyTaskWithoutPublicConstructor.java
  17. +129
    -0
      src/tests/junit/org/apache/tools/ant/ExecutorTest.java
  18. +65
    -0
      src/tests/junit/org/apache/tools/ant/ExtendedTaskdefTest.java
  19. +78
    -0
      src/tests/junit/org/apache/tools/ant/ImmutableTest.java
  20. +133
    -0
      src/tests/junit/org/apache/tools/ant/IncludeTest.java
  21. +683
    -0
      src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java
  22. +45
    -0
      src/tests/junit/org/apache/tools/ant/LoaderRefTest.java
  23. +77
    -0
      src/tests/junit/org/apache/tools/ant/LocationTest.java
  24. +63
    -0
      src/tests/junit/org/apache/tools/ant/MockBuildListener.java
  25. +31
    -0
      src/tests/junit/org/apache/tools/ant/PickOneTask.java
  26. +296
    -0
      src/tests/junit/org/apache/tools/ant/ProjectTest.java
  27. +90
    -0
      src/tests/junit/org/apache/tools/ant/PropertyExpansionTest.java
  28. +61
    -0
      src/tests/junit/org/apache/tools/ant/TaskContainerTest.java
  29. +49
    -0
      src/tests/junit/org/apache/tools/ant/TopLevelTaskTest.java
  30. +154
    -0
      src/tests/junit/org/apache/tools/ant/filters/ConcatFilterTest.java
  31. +112
    -0
      src/tests/junit/org/apache/tools/ant/filters/DynamicFilterTest.java
  32. +52
    -0
      src/tests/junit/org/apache/tools/ant/filters/EscapeUnicodeTest.java
  33. +131
    -0
      src/tests/junit/org/apache/tools/ant/filters/HeadTailTest.java
  34. +56
    -0
      src/tests/junit/org/apache/tools/ant/filters/LineContainsTest.java
  35. +49
    -0
      src/tests/junit/org/apache/tools/ant/filters/NoNewLineTest.java
  36. +59
    -0
      src/tests/junit/org/apache/tools/ant/filters/ReplaceTokensTest.java
  37. +52
    -0
      src/tests/junit/org/apache/tools/ant/filters/StripJavaCommentsTest.java
  38. +296
    -0
      src/tests/junit/org/apache/tools/ant/filters/TokenFilterTest.java
  39. +61
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/AbstractCvsTaskTest.java
  40. +62
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/AntLikeTasksAtTopLevelTest.java
  41. +97
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/AntStructureTest.java
  42. +512
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java
  43. +94
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/AntlibTest.java
  44. +77
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/AptTest.java
  45. +213
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/AvailableTest.java
  46. +63
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/BUnzip2Test.java
  47. +111
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/BZip2Test.java
  48. +83
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/BasenameTest.java
  49. +122
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/CVSPassTest.java
  50. +72
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/CallTargetTest.java
  51. +93
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ChecksumTest.java
  52. +284
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java
  53. +275
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ConditionTest.java
  54. +231
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java
  55. +68
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/CopydirTest.java
  56. +68
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/CopyfileTest.java
  57. +111
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DefaultExcludesTest.java
  58. +83
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DeleteTest.java
  59. +44
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DeltreeTest.java
  60. +75
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DemuxOutputTask.java
  61. +70
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DependSetTest.java
  62. +70
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DirnameTest.java
  63. +46
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTask.java
  64. +40
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTest.java
  65. +77
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/EchoTest.java
  66. +49
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/EchoXMLTest.java
  67. +491
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ExecTaskTest.java
  68. +136
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteJavaTest.java
  69. +599
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteOnTest.java
  70. +153
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteWatchdogTest.java
  71. +164
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/FailTest.java
  72. +114
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/FilterTest.java
  73. +219
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/FixCrLfTest.java
  74. +71
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/GUnzipTest.java
  75. +71
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/GetTest.java
  76. +76
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/GzipTest.java
  77. +172
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ImportTest.java
  78. +64
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/InitializeClassTest.java
  79. +106
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/InputTest.java
  80. +270
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java
  81. +328
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/JavaTest.java
  82. +245
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/JavacTest.java
  83. +134
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/JavadocTest.java
  84. +123
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/LengthTest.java
  85. +155
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java
  86. +60
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/LoadPropertiesTest.java
  87. +158
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java
  88. +137
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java
  89. +150
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ManifestClassPathTest.java
  90. +346
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java
  91. +51
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/MkdirTest.java
  92. +146
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/MoveTest.java
  93. +74
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/MultiMapTest.java
  94. +62
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/NiceTest.java
  95. +154
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java
  96. +56
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/PathConvertTest.java
  97. +117
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/PreSetDefTest.java
  98. +84
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ProcessDestroyerTest.java
  99. +111
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java
  100. +95
    -0
      src/tests/junit/org/apache/tools/ant/taskdefs/ProtectedJarMethodsTest.java

+ 149
- 44
build.xml View File

@@ -19,7 +19,7 @@
<project name="apache-ant" default="main" basedir=".">

<!-- Give user a chance to override without editing this file
(and without typing -D each time it compiles it) -->
(and without typing -D on each invocation) -->
<property file=".ant.properties"/>
<property file="${user.home}/.ant.properties"/>
<property environment="env"/>
@@ -80,7 +80,8 @@
<property name="lib.dir" value="lib"/>
<property name="docs.dir" value="docs"/>
<property name="etc.dir" value="${src.dir}/etc"/>
<property name="src.junit" value="${src.dir}/testcases"/>
<property name="src.junit" value="${src.dir}/tests/junit"/>
<property name="src.antunit" value="${src.dir}/tests/antunit"/>
<property name="tests.etc.dir" value="${src.dir}/etc/testcases"/>
<property name="manifest" value="${src.dir}/etc/manifest"/>
<property name="resource.dir" value="${src.dir}/resources"/>
@@ -97,8 +98,10 @@
<property name="build.javadocs" value="${build.dir}/javadocs"/>
<property name="build.tests" value="${build.dir}/testcases"/>
<property name="build.tests.javadocs" value="${build.dir}/javadocs.test/"/>
<property name="build.tests.xml" location="${build.tests}/xml"/>
<property name="build.tests.reports" location="${build.tests}/reports"/>
<property name="build.junit.xml" location="${build.tests}/xml"/>
<property name="antunit.xml" location="${build.dir}/antunit/xml"/>
<property name="antunit.reports" location="${build.dir}/antunit/reports"/>
<property name="build.junit.reports" location="${build.tests}/reports"/>
<property name="manifest.tmp" value="${build.dir}/optional.manifest"/>
<!-- the absolute path -->
<property name="build.tests.value" location="${build.tests}"/>
@@ -416,6 +419,9 @@
<available property="junit.present"
classname="junit.framework.TestCase"
classpathref="classpath"/>
<available property="antunit.present"
classname="org.apache.ant.antunit.AntUnit"
classpathref="classpath"/>
<available property="commons.net.present"
classname="org.apache.commons.net.ftp.FTPClient"
classpathref="classpath"/>
@@ -1542,52 +1548,116 @@
Run testcase
===================================================================
-->
<target name="test" depends="test-report" description="--> run JUnit tests">
<fail if="tests.failed">Unit tests failed see ${build.tests.reports}</fail>

<target name="tests-failed">
<condition property="tests.failed">
<or>
<isset property="junit.failed" />
<isset property="antunit.failed" />
</or>
</condition>
</target>

<target name="test" depends="junit-report,antunit-report,tests-failed"
description="--> run unit tests">
<fail if="tests.failed">Unit tests failed; see ${build.junit.reports} / ${antunit.reports}</fail>
</target>

<target name="test-init" depends="probe-offline">
<mkdir dir="${build.tests.xml}"/>
<mkdir dir="${build.tests.reports}" />

<presetdef name="test-junit">
<junit printsummary="${junit.summary}"
haltonfailure="${test.haltonfailure}"
fork="${junit.fork}"
forkmode="${junit.forkmode}"
failureproperty="tests.failed"
errorproperty="tests.failed"
filtertrace="${junit.filtertrace}">
<sysproperty key="ant.home" value="${ant.home}"/>
<sysproperty key="build.tests" file="${build.tests}"/>
<sysproperty key="build.tests.value" value="${build.tests.value}"/>
<sysproperty key="offline" value="${offline}"/>
<sysproperty key="tests-classpath.value"
value="${tests-classpath.value}"/>
<sysproperty key="root" file="${basedir}"/>
<sysproperty key="build.compiler" value="${build.compiler}"/>
<sysproperty key="tests.and.ant.share.classloader"
value="${tests.and.ant.share.classloader}"/>
<classpath refid="tests-classpath"/>
<formatter type="xml"/>
</junit>
</presetdef>
<target name="test-init" depends="probe-offline,check_for_optional_packages">
<macrodef name="test-junit">
<element name="junit-nested" implicit="true" />
<sequential>
<mkdir dir="${build.junit.xml}" />
<junit printsummary="${junit.summary}"
haltonfailure="${test.haltonfailure}"
fork="${junit.fork}"
forkmode="${junit.forkmode}"
failureproperty="junit.failed"
errorproperty="junit.failed"
filtertrace="${junit.filtertrace}">
<sysproperty key="ant.home" value="${ant.home}"/>
<sysproperty key="build.tests" file="${build.tests}"/>
<sysproperty key="build.tests.value" value="${build.tests.value}"/>
<sysproperty key="offline" value="${offline}"/>
<sysproperty key="tests-classpath.value"
value="${tests-classpath.value}"/>
<sysproperty key="root" file="${basedir}"/>
<sysproperty key="build.compiler" value="${build.compiler}"/>
<sysproperty key="tests.and.ant.share.classloader"
value="${tests.and.ant.share.classloader}"/>
<classpath refid="tests-classpath"/>
<formatter type="xml"/>
<junit-nested />
</junit>
</sequential>
</macrodef>

<condition property="antunit.testcase" value="${testcase}">
<available file="${src.antunit}/${testcase}" />
</condition>

<condition property="junit.testcase" value="${testcase}">
<available classname="${testcase}" classpathref="tests-classpath" />
</condition>

<condition property="run.junit">
<and>
<not><equals arg1="${testcase}" arg2="${antunit.testcase}" /></not>
<isset property="junit.present" />
<available file="${src.junit}" />
</and>
</condition>

<condition property="junit.single">
<and>
<isset property="junit.testcase" />
<isset property="run.junit" />
</and>
</condition>

<condition property="junit.batch">
<and>
<not><isset property="junit.testcase" /></not>
<isset property="run.junit" />
</and>
</condition>

<condition property="run.antunit">
<and>
<not><equals arg1="${testcase}" arg2="${junit.testcase}" /></not>
<isset property="antunit.present" />
<available file="${src.antunit}" />
</and>
</condition>

<condition property="run.antunit.report">
<and>
<isset property="run.antunit" />
<isset property="trax.impl.present" />
</and>
</condition>

<condition property="run.junit.report">
<and>
<isset property="run.junit" />
<isset property="trax.impl.present" />
</and>
</condition>
</target>

<!--if="run.junitreport"-->
<target name="test-report" depends="test-init,run-tests,run-single-test"
if="trax.impl.present">
<junitreport todir="${build.tests.reports}">
<fileset dir="${build.tests.xml}">
<target name="junit-report" depends="junit-tests,junit-single-test"
if="run.junit.report">
<mkdir dir="${build.junit.reports}" />
<junitreport todir="${build.junit.reports}">
<fileset dir="${build.junit.xml}">
<include name="TEST-*.xml"/>
</fileset>
<report format="frames" todir="${build.tests.reports}"/>
<report format="frames" todir="${build.junit.reports}"/>
</junitreport>
</target>

<target name="run-tests" depends="dump-info,compile-tests,probe-offline,test-init"
if="junit.present" unless="testcase">
<target name="junit-tests" depends="dump-info,compile-tests,test-init"
if="junit.batch">

<property name="junit.includes" value="**/*Test*" />
<property name="junit.excludes" value="" />
@@ -1595,7 +1665,7 @@
<test-junit>
<formatter type="brief" usefile="false"/>

<batchtest todir="${build.tests.xml}">
<batchtest todir="${build.junit.xml}">
<fileset dir="${src.junit}"
includes="${junit.includes}" excludes="${junit.excludes}">

@@ -1736,15 +1806,15 @@
</test-junit>
</target>

<target name="run-single-test" if="testcase" depends="compile-tests,run-single-test-only"
<target name="junit-single-test" depends="compile-tests,junit-single-test-only"
description="--> runs the single unit test defined in the testcase property"/>

<target name="run-single-test-only" if="testcase"
<target name="junit-single-test-only" if="junit.single"
description="--> runs the single unit test defined in the testcase property"
depends="test-init">
<test-junit>
<formatter type="plain" usefile="false"/>
<test name="${testcase}" todir="${build.tests.xml}"/>
<test name="${junit.testcase}" todir="${build.junit.xml}"/>
</test-junit>
</target>

@@ -1756,6 +1826,41 @@
fork="true"/>
</target>

<target name="antunit-tests" depends="dump-info,build,test-init"
if="run.antunit">

<condition property="antunit.includes" value="${antunit.testcase}"
else="**/*-test.xml">
<isset property="${antunit.testcase}" />
</condition>

<property name="antunit.excludes" value="" />

<mkdir dir="${antunit.xml}" />
<au:antunit xmlns:au="antlib:org.apache.ant.antunit"
failonerror="false" errorproperty="antunit.failed">
<fileset dir="${src.antunit}" includes="${antunit.includes}"
excludes="${antunit.excludes}" />
<au:plainlistener />
<au:xmllistener todir="${antunit.xml}" />
</au:antunit>
</target>

<target name="antunit-report" depends="antunit-tests" if="run.antunit.report">
<length>
<fileset dir="${antunit.xml}" includes="TEST-*.xml" />
</length>
<mkdir dir="${antunit.reports}" />
<junitreport todir="${antunit.reports}">
<fileset dir="${antunit.xml}" includes="TEST-*.xml" />
<report styledir="${src.antunit}" format="frames"
todir="${antunit.reports}"/>
</junitreport>
<length>
<fileset dir="${antunit.xml}" includes="TEST-*.xml" />
</length>
</target>

<!--
===================================================================
Main target - runs dist-lite by default


+ 121
- 0
src/tests/junit/org/apache/tools/ant/AntClassLoaderDelegationTest.java View File

@@ -0,0 +1,121 @@
/*
* 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;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import junit.framework.TestCase;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.FileUtils;

/**
* Test case for ant class loader
*
*/
public class AntClassLoaderDelegationTest extends TestCase {

/** Instance of a utility class to use for file operations. */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

private Project p;

public AntClassLoaderDelegationTest(String name) {
super(name);
}

public void setUp() {
p = new Project();
p.init();
}

/** Sample resource present in build/testcases/ */
private static final String TEST_RESOURCE = "org/apache/tools/ant/IncludeTest.class";
public void testFindResources() throws Exception {
//System.err.println("loading from: " + AntClassLoader.class.getProtectionDomain().getCodeSource().getLocation());
// See bug #30161.
// This path should contain the class files for these testcases:
String buildTestcases = System.getProperty("build.tests");
assertNotNull("defined ${build.tests}", buildTestcases);
assertTrue("have a dir " + buildTestcases, new File(buildTestcases).isDirectory());
Path path = new Path(p, buildTestcases);
// A special parent loader which is not the system class loader:
ClassLoader parent = new ParentLoader();
// An AntClassLoader which is supposed to delegate to the parent and then to the disk path:
ClassLoader acl = new AntClassLoader(parent, p, path, true);
// The intended result URLs:
URL urlFromPath = new URL(FILE_UTILS.toURI(buildTestcases) + TEST_RESOURCE);
URL urlFromParent = new URL("http://ant.apache.org/" + TEST_RESOURCE);
assertEquals("correct resources (regular delegation order)",
Arrays.asList(new URL[] {urlFromParent, urlFromPath}),
enum2List(acl.getResources(TEST_RESOURCE)));
acl = new AntClassLoader(parent, p, path, false);
assertEquals("correct resources (reverse delegation order)",
Arrays.asList(new URL[] {urlFromPath, urlFromParent}),
enum2List(acl.getResources(TEST_RESOURCE)));
}

public void testFindIsolateResources() throws Exception {
String buildTestcases = System.getProperty("build.tests");
assertNotNull("defined ${build.tests}", buildTestcases);
assertTrue("have a dir " + buildTestcases, new File(buildTestcases).isDirectory());
Path path = new Path(p, buildTestcases);
// A special parent loader which is not the system class loader:
ClassLoader parent = new ParentLoader();

URL urlFromPath = new URL(FILE_UTILS.toURI(buildTestcases) + TEST_RESOURCE);
AntClassLoader acl = new AntClassLoader(parent, p, path, false);
acl.setIsolated(true);
assertEquals("correct resources (reverse delegation order)",
Arrays.asList(new URL[] {urlFromPath}),
enum2List(acl.getResources(TEST_RESOURCE)));
}
private static List enum2List(Enumeration e) {
// JDK 1.4: return Collections.list(e);
List l = new ArrayList();
while (e.hasMoreElements()) {
l.add(e.nextElement());
}
return l;
}
/** Special loader that just knows how to find TEST_RESOURCE. */
private static final class ParentLoader extends ClassLoader {
public ParentLoader() {}
protected Enumeration findResources(String name) throws IOException {
if (name.equals(TEST_RESOURCE)) {
return Collections.enumeration(Collections.singleton(new URL("http://ant.apache.org/" + name)));
} else {
return Collections.enumeration(Collections.EMPTY_SET);
}
}
}
}

+ 101
- 0
src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java View File

@@ -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;

import java.io.File;
import org.apache.tools.ant.types.Path;

/**
* Test case for ant class loader
*
*/
public class AntClassLoaderTest extends BuildFileTest {

private Project p;

public AntClassLoaderTest(String name) {
super(name);
}

public void setUp() {
p = new Project();
p.init();
configureProject("src/etc/testcases/core/antclassloader.xml");
getProject().executeTarget("setup");
}

public void tearDown() {
getProject().executeTarget("cleanup");
}
//test inspired by bug report 37085
public void testJarWithManifestInDirWithSpace() {
String mainjarstring = getProject().getProperty("main.jar");
String extjarstring = getProject().getProperty("ext.jar");
Path myPath = new Path(getProject());
myPath.setLocation(new File(mainjarstring));
getProject().setUserProperty("build.sysclasspath","ignore");
AntClassLoader myLoader = getProject().createClassLoader(myPath);
String path = myLoader.getClasspath();
assertEquals(mainjarstring + File.pathSeparator + extjarstring, path);
}
public void testJarWithManifestInNonAsciiDir() {
String mainjarstring = getProject().getProperty("main.jar.nonascii");
String extjarstring = getProject().getProperty("ext.jar.nonascii");
Path myPath = new Path(getProject());
myPath.setLocation(new File(mainjarstring));
getProject().setUserProperty("build.sysclasspath","ignore");
AntClassLoader myLoader = getProject().createClassLoader(myPath);
String path = myLoader.getClasspath();
assertEquals(mainjarstring + File.pathSeparator + extjarstring, path);
}
public void testCleanup() throws BuildException {
Path path = new Path(p, ".");
AntClassLoader loader = p.createClassLoader(path);
try {
// we don't expect to find this
loader.findClass("fubar");
fail("Did not expect to find fubar class");
} catch (ClassNotFoundException e) {
// ignore expected
}

loader.cleanup();
try {
// we don't expect to find this
loader.findClass("fubar");
fail("Did not expect to find fubar class");
} catch (ClassNotFoundException e) {
// ignore expected
} catch (NullPointerException e) {
fail("loader should not fail even if cleaned up");
}

// tell the build it is finished
p.fireBuildFinished(null);
try {
// we don't expect to find this
loader.findClass("fubar");
fail("Did not expect to find fubar class");
} catch (ClassNotFoundException e) {
// ignore expected
} catch (NullPointerException e) {
fail("loader should not fail even if project finished");
}
}
}

+ 524
- 0
src/tests/junit/org/apache/tools/ant/BuildFileTest.java View File

@@ -0,0 +1,524 @@
/*
* 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;

import junit.framework.TestCase;
import java.io.File;
import java.io.PrintStream;
import java.net.URL;

/**
* A BuildFileTest is a TestCase which executes targets from an Ant buildfile
* for testing.
*
* This class provides a number of utility methods for particular build file
* tests which extend this class.
*
*/
public abstract class BuildFileTest extends TestCase {

protected Project project;

private StringBuffer logBuffer;
private StringBuffer fullLogBuffer;
private StringBuffer outBuffer;
private StringBuffer errBuffer;
private BuildException buildException;

/**
* Default constructor for the BuildFileTest object.
*/
public BuildFileTest() {
super();
}

/**
* Constructor for the BuildFileTest object.
*
* @param name string to pass up to TestCase constructor
*/
public BuildFileTest(String name) {
super(name);
}

/**
* Automatically calls the target called "tearDown"
* from the build file tested if it exits.
*
* This allows to use Ant tasks directly in the build file
* to clean up after each test. Note that no "setUp" target
* is automatically called, since it's trivial to have a
* test target depend on it.
*/
protected void tearDown() throws Exception {
final String tearDown = "tearDown";
if (project.getTargets().containsKey(tearDown)) {
project.executeTarget(tearDown);
}
}

/**
* run a target, expect for any build exception
*
* @param target target to run
* @param cause information string to reader of report
*/
public void expectBuildException(String target, String cause) {
expectSpecificBuildException(target, cause, null);
}

/**
* Assert that only the given message has been logged with a
* priority &lt;= INFO when running the given target.
*/
public void expectLog(String target, String log) {
executeTarget(target);
String realLog = getLog();
assertEquals(log, realLog);
}

/**
* Assert that the given substring is in the log messages.
*/
public void assertLogContaining(String substring) {
String realLog = getLog();
assertTrue("expecting log to contain \"" + substring + "\" log was \""
+ realLog + "\"",
realLog.indexOf(substring) >= 0);
}

/**
* Assert that the given substring is in the output messages.
* @since Ant1.7
*/
public void assertOutputContaining(String substring) {
String realOutput = getOutput();
assertTrue("expecting output to contain \"" + substring
+ "\" output was \"" + realOutput + "\"",
realOutput.indexOf(substring) >= 0);
}

/**
* Assert that the given message has been logged with a priority
* &lt;= INFO when running the given target.
*/
public void expectLogContaining(String target, String log) {
executeTarget(target);
assertLogContaining(log);
}

/**
* Gets the log the BuildFileTest object.
* Only valid if configureProject() has been called.
*
* @pre logBuffer!=null
* @return The log value
*/
public String getLog() {
return logBuffer.toString();
}

/**
* Assert that the given message has been logged with a priority
* &gt;= VERBOSE when running the given target.
*/
public void expectDebuglog(String target, String log) {
executeTarget(target);
String realLog = getFullLog();
assertEquals(log, realLog);
}

/**
* Assert that the given substring is in the log messages.
*/
public void assertDebuglogContaining(String substring) {
String realLog = getFullLog();
assertTrue("expecting debug log to contain \"" + substring
+ "\" log was \""
+ realLog + "\"",
realLog.indexOf(substring) >= 0);
}

/**
* Gets the log the BuildFileTest object.
*
* Only valid if configureProject() has been called.
*
* @pre fullLogBuffer!=null
* @return The log value
*/
public String getFullLog() {
return fullLogBuffer.toString();
}

/**
* execute the target, verify output matches expectations
*
* @param target target to execute
* @param output output to look for
*/
public void expectOutput(String target, String output) {
executeTarget(target);
String realOutput = getOutput();
assertEquals(output, realOutput.trim());
}

/**
* Executes the target, verify output matches expectations
* and that we got the named error at the end
*
* @param target target to execute
* @param output output to look for
* @param error Description of Parameter
*/
public void expectOutputAndError(String target, String output, String error) {
executeTarget(target);
String realOutput = getOutput();
assertEquals(output, realOutput);
String realError = getError();
assertEquals(error, realError);
}

public String getOutput() {
return cleanBuffer(outBuffer);
}

public String getError() {
return cleanBuffer(errBuffer);
}

public BuildException getBuildException() {
return buildException;
}

private String cleanBuffer(StringBuffer buffer) {
StringBuffer cleanedBuffer = new StringBuffer();
boolean cr = false;
for (int i = 0; i < buffer.length(); i++) {
char ch = buffer.charAt(i);
if (ch == '\r') {
cr = true;
continue;
}

if (!cr) {
cleanedBuffer.append(ch);
} else {
cleanedBuffer.append(ch);
}
}
return cleanedBuffer.toString();
}

/**
* Sets up to run the named project
*
* @param filename name of project file to run
*/
public void configureProject(String filename) throws BuildException {
configureProject(filename, Project.MSG_DEBUG);
}

/**
* Sets up to run the named project
*
* @param filename name of project file to run
*/
public void configureProject(String filename, int logLevel)
throws BuildException {
logBuffer = new StringBuffer();
fullLogBuffer = new StringBuffer();
project = new Project();
project.init();
File antFile = new File(System.getProperty("root"), filename);
project.setUserProperty("ant.file" , antFile.getAbsolutePath());
project.addBuildListener(new AntTestListener(logLevel));
ProjectHelper.configureProject(project, antFile);
}

/**
* Executes a target we have set up
*
* @pre configureProject has been called
* @param targetName target to run
*/
public void executeTarget(String targetName) {
PrintStream sysOut = System.out;
PrintStream sysErr = System.err;
try {
sysOut.flush();
sysErr.flush();
outBuffer = new StringBuffer();
PrintStream out = new PrintStream(new AntOutputStream(outBuffer));
System.setOut(out);
errBuffer = new StringBuffer();
PrintStream err = new PrintStream(new AntOutputStream(errBuffer));
System.setErr(err);
logBuffer = new StringBuffer();
fullLogBuffer = new StringBuffer();
buildException = null;
project.executeTarget(targetName);
} finally {
System.setOut(sysOut);
System.setErr(sysErr);
}

}

/**
* Get the project which has been configured for a test.
*
* @return the Project instance for this test.
*/
public Project getProject() {
return project;
}

/**
* Gets the directory of the project.
*
* @return the base dir of the project
*/
public File getProjectDir() {
return project.getBaseDir();
}

/**
* Runs a target, wait for a build exception.
*
* @param target target to run
* @param cause information string to reader of report
* @param msg the message value of the build exception we are waiting
* for set to null for any build exception to be valid
*/
public void expectSpecificBuildException(String target, String cause, String msg) {
try {
executeTarget(target);
} catch (org.apache.tools.ant.BuildException ex) {
buildException = ex;
if ((null != msg) && (!ex.getMessage().equals(msg))) {
fail("Should throw BuildException because '" + cause
+ "' with message '" + msg
+ "' (actual message '" + ex.getMessage() + "' instead)");
}
return;
}
fail("Should throw BuildException because: " + cause);
}

/**
* run a target, expect an exception string
* containing the substring we look for (case sensitive match)
*
* @param target target to run
* @param cause information string to reader of report
* @param contains substring of the build exception to look for
*/
public void expectBuildExceptionContaining(String target, String cause, String contains) {
try {
executeTarget(target);
} catch (org.apache.tools.ant.BuildException ex) {
buildException = ex;
if ((null != contains) && (ex.getMessage().indexOf(contains) == -1)) {
fail("Should throw BuildException because '" + cause + "' with message containing '" + contains + "' (actual message '" + ex.getMessage() + "' instead)");
}
return;
}
fail("Should throw BuildException because: " + cause);
}

/**
* call a target, verify property is as expected
*
* @param target build file target
* @param property property name
* @param value expected value
*/
public void expectPropertySet(String target, String property, String value) {
executeTarget(target);
assertPropertyEquals(property, value);
}

/**
* assert that a property equals a value; comparison is case sensitive.
*
* @param property property name
* @param value expected value
*/
public void assertPropertyEquals(String property, String value) {
String result = project.getProperty(property);
assertEquals("property " + property,value,result);
}

/**
* assert that a property equals "true".
*
* @param property property name
*/
public void assertPropertySet(String property) {
assertPropertyEquals(property, "true");
}

/**
* assert that a property is null.
*
* @param property property name
*/
public void assertPropertyUnset(String property) {
assertPropertyEquals(property, null);
}

/**
* call a target, verify named property is "true".
*
* @param target build file target
* @param property property name
*/
public void expectPropertySet(String target, String property) {
expectPropertySet(target, property, "true");
}

/**
* Call a target, verify property is null.
*
* @param target build file target
* @param property property name
*/
public void expectPropertyUnset(String target, String property) {
expectPropertySet(target, property, null);
}

/**
* Retrieve a resource from the caller classloader to avoid
* assuming a vm working directory. The resource path must be
* relative to the package name or absolute from the root path.
*
* @param resource the resource to retrieve its url.
* @throws junit.framework.AssertionFailedError if the resource is not found.
*/
public URL getResource(String resource){
URL url = getClass().getResource(resource);
assertNotNull("Could not find resource :" + resource, url);
return url;
}

/**
* an output stream which saves stuff to our buffer.
*/
private static class AntOutputStream extends java.io.OutputStream {
private StringBuffer buffer;

public AntOutputStream( StringBuffer buffer ) {
this.buffer = buffer;
}

public void write(int b) {
buffer.append((char)b);
}
}

/**
* Our own personal build listener.
*/
private class AntTestListener implements BuildListener {
private int logLevel;

/**
* Constructs a test listener which will ignore log events
* above the given level.
*/
public AntTestListener(int logLevel) {
this.logLevel = logLevel;
}

/**
* Fired before any targets are started.
*/
public void buildStarted(BuildEvent event) {
}

/**
* Fired after the last target has finished. This event
* will still be thrown if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
public void buildFinished(BuildEvent event) {
}

/**
* Fired when a target is started.
*
* @see BuildEvent#getTarget()
*/
public void targetStarted(BuildEvent event) {
//System.out.println("targetStarted " + event.getTarget().getName());
}

/**
* Fired when a target has finished. This event will
* still be thrown if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
public void targetFinished(BuildEvent event) {
//System.out.println("targetFinished " + event.getTarget().getName());
}

/**
* Fired when a task is started.
*
* @see BuildEvent#getTask()
*/
public void taskStarted(BuildEvent event) {
//System.out.println("taskStarted " + event.getTask().getTaskName());
}

/**
* Fired when a task has finished. This event will still
* be throw if an error occurred during the build.
*
* @see BuildEvent#getException()
*/
public void taskFinished(BuildEvent event) {
//System.out.println("taskFinished " + event.getTask().getTaskName());
}

/**
* Fired whenever a message is logged.
*
* @see BuildEvent#getMessage()
* @see BuildEvent#getPriority()
*/
public void messageLogged(BuildEvent event) {
if (event.getPriority() > logLevel) {
// ignore event
return;
}

if (event.getPriority() == Project.MSG_INFO ||
event.getPriority() == Project.MSG_WARN ||
event.getPriority() == Project.MSG_ERR) {
logBuffer.append(event.getMessage());
}
fullLogBuffer.append(event.getMessage());
}
}

}

+ 54
- 0
src/tests/junit/org/apache/tools/ant/CaseTest.java View File

@@ -0,0 +1,54 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

/**
* Simple tests of build file processing
*/
public class CaseTest extends BuildFileTest {

public CaseTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/core/case.xml");
}

/**
* Test whether the build file treats nested elements without
* regard to case. This should not cause an exception.
*/
public void testCaseSensitivity() {
executeTarget("case-sensitivity");
}

/**
* Test whether the build file uses case when determining
* task names.
*/
public void testTaskCase() {
expectBuildExceptionContaining("taskcase",
"Task names are case sensitive",
"Problem: failed to create task or type ecHO");
}
}


+ 534
- 0
src/tests/junit/org/apache/tools/ant/DirectoryScannerTest.java View File

@@ -0,0 +1,534 @@
/*
* 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;

import org.apache.tools.ant.taskdefs.condition.Os;
import org.apache.tools.ant.util.FileUtils;


import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;

/**
* JUnit 3 testcases for org.apache.tools.ant.DirectoryScanner
*
*/
public class DirectoryScannerTest extends BuildFileTest {

public DirectoryScannerTest(String name) {super(name);}

// keep track of what operating systems are supported here.
private boolean supportsSymlinks = Os.isFamily("unix");

public void setUp() {
configureProject("src/etc/testcases/core/directoryscanner.xml");
getProject().executeTarget("setup");
}

public void tearDown() {
getProject().executeTarget("cleanup");
}

public void test1() {
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha"});
ds.scan();
compareFiles(ds, new String[] {} ,new String[] {"alpha"});
}

public void test2() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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 testAllowSymlinks() {
if (!supportsSymlinks) {
return;
}

getProject().executeTarget("symlink-setup");
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/beta/gamma/"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
new String[] {"alpha/beta/gamma"});
}

public void testProhibitSymlinks() {
if (!supportsSymlinks) {
return;
}

getProject().executeTarget("symlink-setup");
DirectoryScanner ds = new DirectoryScanner();
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[] {});
}

// father and child pattern test
public void testOrderOfIncludePatternsIrrelevant() {
String [] expectedFiles = {"alpha/beta/beta.xml",
"alpha/beta/gamma/gamma.xml"};
String [] expectedDirectories = {"alpha/beta", "alpha/beta/gamma" };
DirectoryScanner ds = new DirectoryScanner();
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 = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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"});
}

/**
* Test case for setFollowLinks() and associated functionality.
* Only supports test on Linux at the moment because Java has
* no real notion of symlinks built in, so an os-specfic call
* to Runtime.exec() must be made to create a link to test against.
*/
public void testSetFollowLinks() throws IOException {
if (supportsSymlinks) {
File linkFile = new File(System.getProperty("root"), "src/main/org/apache/tools/ThisIsALink");
System.err.println("link exists pre-test? " + linkFile.exists());
try {
// add conditions and more commands as soon as the need arises
String[] command = new String[] {
"ln", "-s", "ant", linkFile.getAbsolutePath()
};
try {
Runtime.getRuntime().exec(command);
// give ourselves some time for the system call
// to execute... tweak if you have a really over
// loaded system.
Thread.sleep(1000);
} catch (IOException ioe) {
fail("IOException making link "+ioe);
} catch (InterruptedException ie) {
}

File dir = new File(System.getProperty("root"), "src/main/org/apache/tools");
System.err.println("link exists after exec? " + linkFile.exists());
System.err.println("Ant knows it is a link? " + FileUtils.getFileUtils().isSymbolicLink(dir, "ThisIsALink"));

DirectoryScanner ds = new DirectoryScanner();

// followLinks should be true by default, but if this ever
// changes we will need this line.
ds.setFollowSymlinks(true);

ds.setBasedir(dir);
ds.setExcludes(new String[] {"ant/**"});
ds.scan();

boolean haveZipPackage = false;
boolean haveTaskdefsPackage = false;

String[] included = ds.getIncludedDirectories();
for (int i=0; i<included.length; i++) {
if (included[i].equals("zip")) {
haveZipPackage = true;
} else if (included[i].equals("ThisIsALink"
+ File.separator
+ "taskdefs")) {
haveTaskdefsPackage = true;
}
}

// if we followed the symlink we just made we should
// bypass the excludes.

assertTrue("(1) zip package included", haveZipPackage);
assertTrue("(1) taskdefs package included",
haveTaskdefsPackage);


ds = new DirectoryScanner();
ds.setFollowSymlinks(false);

ds.setBasedir(dir);
ds.setExcludes(new String[] {"ant/**"});
ds.scan();

haveZipPackage = false;
haveTaskdefsPackage = false;
included = ds.getIncludedDirectories();
for (int i=0; i<included.length; i++) {
if (included[i].equals("zip")) {
haveZipPackage = true;
} else if (included[i].equals("ThisIsALink"
+ File.separator
+ "taskdefs")) {
haveTaskdefsPackage = true;
}
}
assertTrue("(2) zip package included", haveZipPackage);
assertTrue("(2) taskdefs package not included",
!haveTaskdefsPackage);

} finally {
System.err.println("link exists pre-delete? " + linkFile.exists());
if (!linkFile.delete()) {
throw new RuntimeException("Failed to delete " + linkFile);
}
System.err.println("link exists post-delete? " + linkFile.exists());
}
}
}

public void testExcludeOneFile() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
DirectoryScanner ds = new DirectoryScanner();
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() {
getProject().executeTarget("children-of-excluded-dir-setup");
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
ds.setExcludes(new String[] {"alpha/**"});
ds.setFollowSymlinks(false);
ds.scan();
compareFiles(ds, new String[] {"delta/delta.xml"},
new String[] {"", "delta"});

ds = new DirectoryScanner();
ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
ds.setExcludes(new String[] {"alpha"});
ds.setFollowSymlinks(false);
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"});

}

public void testIsExcludedDirectoryScanned() {
String shareclassloader = getProject().getProperty("tests.and.ant.share.classloader");
// when the test is started by the build.xml of ant
// if the property tests.and.ant.share.classloader is not set in the build.xml
// a sysproperty with name tests.and.ant.share.classloader and value
// ${tests.and.ant.share.classloader} will be set
// we are trying to catch this here.
if (shareclassloader == null
|| (shareclassloader != null && shareclassloader.indexOf("${") == 0)) {
System.out.println("cannot execute testIsExcludedDirectoryScanned when tests are forked, " +
"package private method called");
return;
}
getProject().executeTarget("children-of-excluded-dir-setup");
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
ds.setExcludes(new String[] {"**/gamma/**"});
ds.setFollowSymlinks(false);
ds.scan();
Set set = ds.getScannedDirs();
assertFalse("empty set", set.isEmpty());
String s = "alpha/beta/gamma/".replace('/', File.separatorChar);
assertFalse("scanned " + s, set.contains(s));
}

public void testAbsolute1() {
getProject().executeTarget("extended-setup");
DirectoryScanner ds = new DirectoryScanner();
String tmpdir = getProject().getBaseDir().getAbsolutePath().replace(
File.separatorChar, '/') + "/tmp";
ds.setIncludes(new String[] {tmpdir + "/**/*"});
ds.scan();
compareFiles(ds, new String[] {tmpdir + "/alpha/beta/beta.xml",
tmpdir + "/alpha/beta/gamma/gamma.xml",
tmpdir + "/delta/delta.xml"},
new String[] {tmpdir + "/alpha",
tmpdir + "/alpha/beta",
tmpdir + "/alpha/beta/gamma",
tmpdir + "/delta"});
}

public void testAbsolute2() {
getProject().executeTarget("setup");
DirectoryScanner ds = new DirectoryScanner();
ds.setIncludes(new String[] {"alpha/**", "alpha/beta/gamma/**"});
ds.scan();
String[] mt = new String[0];
compareFiles(ds, mt, mt);
}

public void testAbsolute3() {
getProject().executeTarget("extended-setup");
DirectoryScanner ds = new DirectoryScanner();
String tmpdir = getProject().getBaseDir().getAbsolutePath().replace(
File.separatorChar, '/') + "/tmp";
ds.setIncludes(new String[] {tmpdir + "/**/*"});
ds.setExcludes(new String[] {"**/alpha",
"**/delta/*"});
ds.scan();
compareFiles(ds, new String[] {tmpdir + "/alpha/beta/beta.xml",
tmpdir + "/alpha/beta/gamma/gamma.xml"},
new String[] {tmpdir + "/alpha/beta",
tmpdir + "/alpha/beta/gamma",
tmpdir + "/delta"});
}

public void testAbsolute4() {
getProject().executeTarget("extended-setup");
DirectoryScanner ds = new DirectoryScanner();
String tmpdir = getProject().getBaseDir().getAbsolutePath().replace(
File.separatorChar, '/') + "/tmp";
ds.setIncludes(new String[] {tmpdir + "/alpha/beta/**/*",
tmpdir + "/delta/*"});
ds.setExcludes(new String[] {"**/beta.xml"});
ds.scan();
compareFiles(ds, new String[] {tmpdir + "/alpha/beta/gamma/gamma.xml",
tmpdir + "/delta/delta.xml"},
new String[] {tmpdir + "/alpha/beta/gamma"});
}

public void testAbsolute5() {
//testing drive letter search from root:
if (!(Os.isFamily("dos") || Os.isFamily("netware"))) {
return;
}
DirectoryScanner ds = new DirectoryScanner();
String pattern = new File(File.separator).getAbsolutePath().toUpperCase() + "*";
ds.setIncludes(new String[] {pattern});
ds.scan();
//if this is our context we assume there must be something here:
assertTrue("should have at least one resident file",
ds.getIncludedFilesCount() + ds.getIncludedDirsCount() > 0);
}

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);

TreeSet files = new TreeSet();
for (int counter=0; counter < includedFiles.length; counter++) {
files.add(includedFiles[counter].replace(File.separatorChar, '/'));
}
TreeSet directories = new TreeSet();
for (int counter=0; counter < includedDirectories.length; counter++) {
directories.add(includedDirectories[counter]
.replace(File.separatorChar, '/'));
}

String currentfile;
Iterator i = files.iterator();
int counter = 0;
while (i.hasNext()) {
currentfile = (String) i.next();
assertEquals(expectedFiles[counter], currentfile);
counter++;
}
String currentdirectory;
Iterator dirit = directories.iterator();
counter = 0;
while (dirit.hasNext()) {
currentdirectory = (String) dirit.next();
assertEquals(expectedDirectories[counter], currentdirectory);
counter++;
}
}

}

+ 36
- 0
src/tests/junit/org/apache/tools/ant/DispatchTaskTest.java View File

@@ -0,0 +1,36 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

public class DispatchTaskTest extends BuildFileTest {

public DispatchTaskTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/core/dispatch/dispatch.xml");
}

public void testDisp() {
expectBuildException("disp", "list");
}
}

+ 32
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskAbstract.java View File

@@ -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;

import org.apache.tools.ant.Task;

public abstract class DummyTaskAbstract extends Task {

public DummyTaskAbstract() {
}

public void execute() {
}

public abstract void abstractDummy();
}

+ 25
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskInterface.java View File

@@ -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.apache.tools.ant;

public interface DummyTaskInterface {

void execute();

}

+ 31
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskOk.java View File

@@ -0,0 +1,31 @@
/*
* 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;

import org.apache.tools.ant.Task;

public class DummyTaskOk extends Task {

public DummyTaskOk() {
}

public void execute() {
}

}

+ 29
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskOkNonTask.java View File

@@ -0,0 +1,29 @@
/*
* 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;

public class DummyTaskOkNonTask {

public DummyTaskOkNonTask() {
}

public void execute() {
}

}

+ 29
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskWithNonPublicExecute.java View File

@@ -0,0 +1,29 @@
/*
* 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;

public class DummyTaskWithNonPublicExecute {

public DummyTaskWithNonPublicExecute() {
}

void execute() {
}

}

+ 30
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskWithNonVoidExecute.java View File

@@ -0,0 +1,30 @@
/*
* 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;

public class DummyTaskWithNonVoidExecute {

public DummyTaskWithNonVoidExecute() {
}

public int execute() {
return 0;
}

}

+ 31
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskWithoutDefaultConstructor.java View File

@@ -0,0 +1,31 @@
/*
* 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;

import org.apache.tools.ant.Task;

public class DummyTaskWithoutDefaultConstructor extends Task {

public DummyTaskWithoutDefaultConstructor(int dummy) {
}

public void execute() {
}

}

+ 29
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskWithoutExecute.java View File

@@ -0,0 +1,29 @@
/*
* 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;

public class DummyTaskWithoutExecute {

public DummyTaskWithoutExecute() {
}

public void execute(String dummy) {
}

}

+ 31
- 0
src/tests/junit/org/apache/tools/ant/DummyTaskWithoutPublicConstructor.java View File

@@ -0,0 +1,31 @@
/*
* 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;

import org.apache.tools.ant.Task;

public class DummyTaskWithoutPublicConstructor extends Task {

DummyTaskWithoutPublicConstructor() {
}

public void execute() {
}

}

+ 129
- 0
src/tests/junit/org/apache/tools/ant/ExecutorTest.java View File

@@ -0,0 +1,129 @@
/*
* 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;

import java.util.Vector;


/**
* Executor tests
*/
public class ExecutorTest extends BuildFileTest implements BuildListener {
private static final String SINGLE_CHECK
= "org.apache.tools.ant.helper.SingleCheckExecutor";
private static final Vector targetNames;
static {
targetNames = new Vector();
targetNames.add("a");
targetNames.add("b");
}

private int targetCount;

/* BuildListener stuff */
public void targetStarted(BuildEvent event) {
targetCount++;
}
public void buildStarted(BuildEvent event) {}
public void buildFinished(BuildEvent event) {}
public void targetFinished(BuildEvent event) {}
public void taskStarted(BuildEvent event) {}
public void taskFinished(BuildEvent event) {}
public void messageLogged(BuildEvent event) {}

public ExecutorTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/core/executor.xml");
targetCount = 0;
getProject().addBuildListener(this);
}

private Project getProject(String e) {
return getProject(e, false);
}

private Project getProject(String e, boolean f) {
return getProject(e, f, false);
}

private Project getProject(String e, boolean f, boolean k) {
Project p = getProject();
p.setNewProperty("ant.executor.class", e);
p.setKeepGoingMode(k);
if (f) {
p.setNewProperty("failfoo", "foo");
}
return p;
}

public void testDefaultExecutor() {
getProject().executeTargets(targetNames);
assertEquals(targetCount, 4);
}

public void testSingleCheckExecutor() {
getProject(SINGLE_CHECK).executeTargets(targetNames);
assertEquals(targetCount, 3);
}

public void testDefaultFailure() {
try {
getProject(null, true).executeTargets(targetNames);
fail("should fail");
} catch (BuildException e) {
assertTrue(e.getMessage().equals("failfoo"));
assertEquals(targetCount, 1);
}
}

public void testSingleCheckFailure() {
try {
getProject(SINGLE_CHECK, true).executeTargets(targetNames);
fail("should fail");
} catch (BuildException e) {
assertTrue(e.getMessage().equals("failfoo"));
assertEquals(targetCount, 1);
}
}

public void testKeepGoingDefault() {
try {
getProject(null, true, true).executeTargets(targetNames);
fail("should fail");
} catch (BuildException e) {
assertTrue(e.getMessage().equals("failfoo"));
assertEquals(targetCount, 2);
}
}

public void testKeepGoingSingleCheck() {
try {
getProject(SINGLE_CHECK, true, true).executeTargets(targetNames);
fail("should fail");
} catch (BuildException e) {
assertTrue(e.getMessage().equals("failfoo"));
assertEquals(targetCount, 1);
}
}

}


+ 65
- 0
src/tests/junit/org/apache/tools/ant/ExtendedTaskdefTest.java View File

@@ -0,0 +1,65 @@
/*
* 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;

/**
* created 16-Mar-2006 12:25:12
*/

public class ExtendedTaskdefTest extends BuildFileTest {

/**
* Constructor for the BuildFileTest object.
*
* @param name string to pass up to TestCase constructor
*/
public ExtendedTaskdefTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/core/extended-taskdef.xml");
}

/**
* Automatically calls the target called "tearDown"
* from the build file tested if it exits.
* <p/>
* This allows to use Ant tasks directly in the build file
* to clean up after each test. Note that no "setUp" target
* is automatically called, since it's trivial to have a
* test target depend on it.
*/
protected void tearDown() throws Exception {
super.tearDown();
executeTarget("teardown");
}

public void testRun() throws Exception {
expectBuildExceptionContaining("testRun",
"exception thrown by the subclass",
"executing the Foo task");
}

public void testRun2() throws Exception {
expectBuildExceptionContaining("testRun2",
"exception thrown by the subclass",
"executing the Foo task");
}

}

+ 78
- 0
src/tests/junit/org/apache/tools/ant/ImmutableTest.java View File

@@ -0,0 +1,78 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class ImmutableTest extends BuildFileTest {

public ImmutableTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/core/immutable.xml");
}

// override allowed on <available>
public void test1() {
executeTarget("test1");
assertEquals("override", project.getProperty("test"));
}

// ensure <tstamp>'s new prefix attribute is working
public void test2() {
executeTarget("test2");
assertNotNull(project.getProperty("DSTAMP"));
assertNotNull(project.getProperty("start.DSTAMP"));
}

// ensure <tstamp> follows the immutability rule
public void test3() {
executeTarget("test3");
assertEquals("original", project.getProperty("DSTAMP"));
}

// ensure <condition> follows the immutability rule
public void test4() {
executeTarget("test4");
assertEquals("original", project.getProperty("test"));
}
// ensure <checksum> follows the immutability rule
public void test5() {
executeTarget("test5");
assertEquals("original", project.getProperty("test"));
}

// ensure <exec> follows the immutability rule
public void test6() {
executeTarget("test6");
assertEquals("original", project.getProperty("test1"));
assertEquals("original", project.getProperty("test2"));
}

// ensure <pathconvert> follows the immutability rule
public void test7() {
executeTarget("test7");
assertEquals("original", project.getProperty("test"));
}
}


+ 133
- 0
src/tests/junit/org/apache/tools/ant/IncludeTest.java View File

@@ -0,0 +1,133 @@
/*
* 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;

import junit.framework.AssertionFailedError;

import org.apache.tools.ant.BuildFileTest;

/**
* Test the build file inclusion using XML entities.
*
*/
public class IncludeTest extends BuildFileTest {

public IncludeTest(String name) {
super(name);
}

public void test1() {
configureProject("src/etc/testcases/core/include/basic/include.xml");
expectLog("test1", "from included entity");
}

public void test2() {
configureProject("src/etc/testcases/core/include/frag#ment/include.xml");
expectLog("test1", "from included entity");
}

public void test3() {
configureProject("src/etc/testcases/core/include/frag#ment/simple.xml");
expectLog("test1", "from simple buildfile");
}

public void test4() {
configureProject("src/etc/testcases/core/include/basic/relative.xml");
expectLog("test1", "from included entity");
}

public void test5() {
configureProject("src/etc/testcases/core/include/frag#ment/relative.xml");
expectLog("test1", "from included entity");
}

public void testParseErrorInIncluding() {
try {
configureProject("src/etc/testcases/core/include/including_file_parse_error/build.xml");
fail("should have caused a parser exception");
} catch (BuildException e) {
assertTrue(e.getLocation().toString()
+ " should refer to build.xml",
e.getLocation().toString().indexOf("build.xml:") > -1);
}
}

public void testTaskErrorInIncluding() {
configureProject("src/etc/testcases/core/include/including_file_task_error/build.xml");
try {
executeTarget("test");
fail("should have cause a build failure");
} catch (BuildException e) {
assertTrue(e.getMessage()
+ " should start with \'Warning: Could not find",
e.getMessage().startsWith("Warning: Could not find file "));
assertTrue(e.getLocation().toString()
+ " should end with build.xml:14: ",
e.getLocation().toString().endsWith("build.xml:14: "));
}
}

public void testParseErrorInIncluded() {
try {
configureProject("src/etc/testcases/core/include/included_file_parse_error/build.xml");
fail("should have caused a parser exception");
} catch (BuildException e) {
assertTrue(e.getLocation().toString()
+ " should refer to included_file.xml",
e.getLocation().toString()
.indexOf("included_file.xml:") > -1);
}
}

public void testTaskErrorInIncluded() {
configureProject("src/etc/testcases/core/include/included_file_task_error/build.xml");
try {
executeTarget("test");
fail("should have cause a build failure");
} catch (BuildException e) {
assertTrue(e.getMessage()
+ " should start with \'Warning: Could not find",
e.getMessage().startsWith("Warning: Could not find file "));
assertTrue(e.getLocation().toString()
+ " should end with included_file.xml:2: ",
e.getLocation().toString().endsWith("included_file.xml:2: "));
}
}

public void testWithSpaceInclude() {
configureProject("src/etc/testcases/core/include/with space/include.xml");
try {
expectLog("test1", "from included entity in 'with space'");
} catch (Throwable t) {
throw new AssertionFailedError(
t.toString() + "; log=\n" + getFullLog());
}
}

public void testWithSpaceSimple() {
configureProject("src/etc/testcases/core/include/with space/simple.xml");
expectLog("test1", "from simple buildfile in 'with space'");
}

public void testWithSpaceRelative() {
configureProject("src/etc/testcases/core/include/with space/relative.xml");
expectLog("test1", "from included entity in 'with space'");
}

}

+ 683
- 0
src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java View File

@@ -0,0 +1,683 @@
/*
* 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;

import junit.framework.TestCase;
import junit.framework.AssertionFailedError;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.tools.ant.taskdefs.condition.Os;

/**
* JUnit 3 testcases for org.apache.tools.ant.IntrospectionHelper.
*
*/

public class IntrospectionHelperTest extends TestCase {

private Project p;
private IntrospectionHelper ih;
private static final String projectBasedir = File.separator;

public IntrospectionHelperTest(String name) {
super(name);
}

public void setUp() {
p = new Project();
p.setBasedir(projectBasedir);
ih = IntrospectionHelper.getHelper(getClass());
}

public void testIsDynamic() {
assertTrue("Not dynamic", false == ih.isDynamic());
}

public void testIsContainer() {
assertTrue("Not a container", false == ih.isContainer());
}

public void testAddText() throws BuildException {
ih.addText(p, this, "test");
try {
ih.addText(p, this, "test2");
fail("test2 shouldn\'t be equal to test");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}

ih = IntrospectionHelper.getHelper(String.class);
try {
ih.addText(p, "", "test");
fail("String doesn\'t support addText");
} catch (BuildException be) {
}
}

public void testGetAddTextMethod() {
Method m = ih.getAddTextMethod();
assertMethod(m, "addText", String.class, "test", "bing!");

ih = IntrospectionHelper.getHelper(String.class);
try {
m = ih.getAddTextMethod();
} catch (BuildException e) {}
}

public void testSupportsCharacters() {
assertTrue("IntrospectionHelperTest supports addText",
ih.supportsCharacters());

ih = IntrospectionHelper.getHelper(String.class);
assertTrue("String doesn\'t support addText", !ih.supportsCharacters());
}

public void addText(String text) {
assertEquals("test", text);
}

public void testElementCreators() throws BuildException {
try {
ih.getElementType("one");
fail("don't have element type one");
} catch (BuildException be) {
}
try {
ih.getElementType("two");
fail("createTwo takes arguments");
} catch (BuildException be) {
}
try {
ih.getElementType("three");
fail("createThree returns void");
} catch (BuildException be) {
}
try {
ih.getElementType("four");
fail("createFour returns array");
} catch (BuildException be) {
}
try {
ih.getElementType("five");
fail("createFive returns primitive type");
} catch (BuildException be) {
}
assertEquals(String.class, ih.getElementType("six"));
assertEquals("test", ih.createElement(p, this, "six"));

try {
ih.getElementType("seven");
fail("addSeven takes two arguments");
} catch (BuildException be) {
}
try {
ih.getElementType("eight");
fail("addEight takes no arguments");
} catch (BuildException be) {
}
try {
ih.getElementType("nine");
fail("nine return non void");
} catch (BuildException be) {
}
try {
ih.getElementType("ten");
fail("addTen takes array argument");
} catch (BuildException be) {
}
try {
ih.getElementType("eleven");
fail("addEleven takes primitive argument");
} catch (BuildException be) {
}
try {
ih.getElementType("twelve");
fail("no primitive constructor for java.lang.Class");
} catch (BuildException be) {
}
assertEquals(StringBuffer.class, ih.getElementType("thirteen"));
assertEquals("test", ih.createElement(p, this, "thirteen").toString());

try {
ih.createElement(p, this, "fourteen");
fail("fourteen throws NullPointerException");
} catch (BuildException be) {
assertTrue(be.getException() instanceof NullPointerException);
}

try {
ih.createElement(p, this, "fourteen");
fail("fifteen throws NullPointerException");
} catch (BuildException be) {
assertTrue(be.getException() instanceof NullPointerException);
}
}

private Map getExpectedNestedElements() {
Map elemMap = new Hashtable();
elemMap.put("six", String.class);
elemMap.put("thirteen", StringBuffer.class);
elemMap.put("fourteen", StringBuffer.class);
elemMap.put("fifteen", StringBuffer.class);
return elemMap;
}

public void testGetNestedElements() {
Map elemMap = getExpectedNestedElements();
Enumeration e = ih.getNestedElements();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Class expect = (Class) elemMap.get(name);
assertNotNull("Support for "+name+" in IntrospectioNHelperTest?",
expect);
assertEquals("Return type of "+name, expect, ih.getElementType(name));
elemMap.remove(name);
}
assertTrue("Found all", elemMap.isEmpty());
}

public void testGetNestedElementMap() {
Map elemMap = getExpectedNestedElements();
Map actualMap = ih.getNestedElementMap();
for (Iterator i = actualMap.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
String elemName = (String) entry.getKey();
Class elemClass = (Class) elemMap.get(elemName);
assertNotNull("Support for " + elemName +
" in IntrospectionHelperTest?", elemClass);
assertEquals("Type of " + elemName, elemClass, entry.getValue());
elemMap.remove(elemName);
}
assertTrue("Found all", elemMap.isEmpty());

// Check it's a read-only map.
try {
actualMap.clear();
} catch (UnsupportedOperationException e) {}
}

public void testGetElementMethod() {
assertElemMethod("six", "createSix", String.class, null);
assertElemMethod("thirteen", "addThirteen", null, StringBuffer.class);
assertElemMethod("fourteen", "addFourteen", null, StringBuffer.class);
assertElemMethod("fifteen", "createFifteen", StringBuffer.class, null);
}

private void assertElemMethod(String elemName, String methodName,
Class returnType, Class methodArg) {
Method m = ih.getElementMethod(elemName);
assertEquals("Method name", methodName, m.getName());
Class expectedReturnType = (returnType == null)? Void.TYPE: returnType;
assertEquals("Return type", expectedReturnType, m.getReturnType());
Class[] args = m.getParameterTypes();
if (methodArg != null) {
assertEquals("Arg Count", 1, args.length);
assertEquals("Arg Type", methodArg, args[0]);
} else {
assertEquals("Arg Count", 0, args.length);
}
}

public Object createTwo(String s) {
return null;
}

public void createThree() {}

public Object[] createFour() {
return null;
}

public int createFive() {
return 0;
}

public String createSix() {
return "test";
}

public StringBuffer createFifteen() {
throw new NullPointerException();
}

public void addSeven(String s, String s2) {}

public void addEight() {}

public String addNine(String s) {
return null;
}

public void addTen(String[] s) {}

public void addEleven(int i) {}

public void addTwelve(Class c) {}

public void addThirteen(StringBuffer sb) {
sb.append("test");
}

public void addFourteen(StringBuffer s) {
throw new NullPointerException();
}

public void testAttributeSetters() throws BuildException {
try {
ih.setAttribute(p, this, "one", "test");
fail("setOne doesn't exist");
} catch (BuildException be) {
}
try {
ih.setAttribute(p, this, "two", "test");
fail("setTwo returns non void");
} catch (BuildException be) {
}
try {
ih.setAttribute(p, this, "three", "test");
fail("setThree takes no args");
} catch (BuildException be) {
}
try {
ih.setAttribute(p, this, "four", "test");
fail("setFour takes two args");
} catch (BuildException be) {
}
try {
ih.setAttribute(p, this, "five", "test");
fail("setFive takes array arg");
} catch (BuildException be) {
}
try {
ih.setAttribute(p, this, "six", "test");
fail("Project doesn't have a String constructor");
} catch (BuildException be) {
}
ih.setAttribute(p, this, "seven", "2");
try {
ih.setAttribute(p, this, "seven", "3");
fail("2 shouldn't be equals to three");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "eight", "2");
try {
ih.setAttribute(p, this, "eight", "3");
fail("2 shouldn't be equals to three - as int");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "nine", "2");
try {
ih.setAttribute(p, this, "nine", "3");
fail("2 shouldn't be equals to three - as Integer");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "ten", "2");
try {
ih.setAttribute(p, this, "ten", "3");
fail(projectBasedir+"2 shouldn't be equals to "+projectBasedir+"3");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "eleven", "2");
try {
ih.setAttribute(p, this, "eleven", "on");
fail("on shouldn't be false");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "twelve", "2");
try {
ih.setAttribute(p, this, "twelve", "on");
fail("on shouldn't be false");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "thirteen", "org.apache.tools.ant.Project");
try {
ih.setAttribute(p, this, "thirteen", "org.apache.tools.ant.ProjectHelper");
fail("org.apache.tools.ant.Project shouldn't be equal to org.apache.tools.ant.ProjectHelper");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
try {
ih.setAttribute(p, this, "thirteen", "org.apache.tools.ant.Project2");
fail("org.apache.tools.ant.Project2 doesn't exist");
} catch (BuildException be) {
assertTrue(be.getException() instanceof ClassNotFoundException);
}
ih.setAttribute(p, this, "fourteen", "2");
try {
ih.setAttribute(p, this, "fourteen", "on");
fail("2 shouldn't be equals to three - as StringBuffer");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "fifteen", "abcd");
try {
ih.setAttribute(p, this, "fifteen", "on");
fail("o shouldn't be equal to a");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "sixteen", "abcd");
try {
ih.setAttribute(p, this, "sixteen", "on");
fail("o shouldn't be equal to a");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "seventeen", "17");
try {
ih.setAttribute(p, this, "seventeen", "3");
fail("17 shouldn't be equals to three");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "eightteen", "18");
try {
ih.setAttribute(p, this, "eightteen", "3");
fail("18 shouldn't be equals to three");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
ih.setAttribute(p, this, "nineteen", "19");
try {
ih.setAttribute(p, this, "nineteen", "3");
fail("19 shouldn't be equals to three");
} catch (BuildException be) {
assertTrue(be.getException() instanceof AssertionFailedError);
}
}

private Map getExpectedAttributes() {
Map attrMap = new Hashtable();
attrMap.put("seven", String.class);
attrMap.put("eight", Integer.TYPE);
attrMap.put("nine", Integer.class);
attrMap.put("ten", File.class);
attrMap.put("eleven", Boolean.TYPE);
attrMap.put("twelve", Boolean.class);
attrMap.put("thirteen", Class.class);
attrMap.put("fourteen", StringBuffer.class);
attrMap.put("fifteen", Character.TYPE);
attrMap.put("sixteen", Character.class);
attrMap.put("seventeen", Byte.TYPE);
attrMap.put("eightteen", Short.TYPE);
attrMap.put("nineteen", Double.TYPE);

/*
* JUnit 3.7 adds a getName method to TestCase - so we now
* have a name attribute in IntrospectionHelperTest if we run
* under JUnit 3.7 but not in earlier versions.
*
* Simply add it here and remove it after the tests.
*/
attrMap.put("name", String.class);

return attrMap;
}

public void testGetAttributes() {
Map attrMap = getExpectedAttributes();
Enumeration e = ih.getAttributes();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Class expect = (Class) attrMap.get(name);
assertNotNull("Support for "+name+" in IntrospectionHelperTest?",
expect);
assertEquals("Type of "+name, expect, ih.getAttributeType(name));
attrMap.remove(name);
}
attrMap.remove("name");
assertTrue("Found all", attrMap.isEmpty());
}

public void testGetAttributeMap() {
Map attrMap = getExpectedAttributes();
Map actualMap = ih.getAttributeMap();
for (Iterator i = actualMap.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
String attrName = (String) entry.getKey();
Class attrClass = (Class) attrMap.get(attrName);
assertNotNull("Support for " + attrName +
" in IntrospectionHelperTest?", attrClass);
assertEquals("Type of " + attrName, attrClass, entry.getValue());
attrMap.remove(attrName);
}
attrMap.remove("name");
assertTrue("Found all", attrMap.isEmpty());

// Check it's a read-only map.
try {
actualMap.clear();
} catch (UnsupportedOperationException e) {}
}

public void testGetAttributeMethod() {
assertAttrMethod("seven", "setSeven", String.class,
"2", "3");
assertAttrMethod("eight", "setEight", Integer.TYPE,
new Integer(2), new Integer(3));
assertAttrMethod("nine", "setNine", Integer.class,
new Integer(2), new Integer(3));
assertAttrMethod("ten", "setTen", File.class,
new File(projectBasedir + 2), new File("toto"));
assertAttrMethod("eleven", "setEleven", Boolean.TYPE,
Boolean.FALSE, Boolean.TRUE);
assertAttrMethod("twelve", "setTwelve", Boolean.class,
Boolean.FALSE, Boolean.TRUE);
assertAttrMethod("thirteen", "setThirteen", Class.class,
Project.class, Map.class);
assertAttrMethod("fourteen", "setFourteen", StringBuffer.class,
new StringBuffer("2"), new StringBuffer("3"));
assertAttrMethod("fifteen", "setFifteen", Character.TYPE,
new Character('a'), new Character('b'));
assertAttrMethod("sixteen", "setSixteen", Character.class,
new Character('a'), new Character('b'));
assertAttrMethod("seventeen", "setSeventeen", Byte.TYPE,
new Byte((byte)17), new Byte((byte)10));
assertAttrMethod("eightteen", "setEightteen", Short.TYPE,
new Short((short)18), new Short((short)10));
assertAttrMethod("nineteen", "setNineteen", Double.TYPE,
new Double(19), new Double((short)10));

try {
assertAttrMethod("onehundred", null, null, null, null);
fail("Should have raised a BuildException!");
} catch (BuildException e) {}
}

private void assertAttrMethod(String attrName, String methodName,
Class methodArg, Object arg, Object badArg) {
Method m = ih.getAttributeMethod(attrName);
assertMethod(m, methodName, methodArg, arg, badArg);
}

public int setTwo(String s) {
return 0;
}

public void setThree() {}

public void setFour(String s1, String s2) {}

public void setFive(String[] s) {}

public void setSix(Project p) {}

public void setSeven(String s) {
assertEquals("2", s);
}

public void setEight(int i) {
assertEquals(2, i);
}

public void setNine(Integer i) {
assertEquals(2, i.intValue());
}

public void setTen(File f) {
String path = f.getAbsolutePath();
if (Os.isFamily("unix") || Os.isFamily("openvms")) {
assertEquals(projectBasedir+"2", path);
} else if (Os.isFamily("netware")) {
assertEquals(projectBasedir+"2", path.toLowerCase(Locale.US));
} else {
assertEquals(":"+projectBasedir+"2",
path.toLowerCase(Locale.US).substring(1));
}
}

public void setEleven(boolean b) {
assertTrue(!b);
}

public void setTwelve(Boolean b) {
assertTrue(!b.booleanValue());
}

public void setThirteen(Class c) {
assertEquals(Project.class, c);
}

public void setFourteen(StringBuffer sb) {
assertEquals("2", sb.toString());
}

public void setFifteen(char c) {
assertEquals(c, 'a');
}

public void setSixteen(Character c) {
assertEquals(c.charValue(), 'a');
}

public void setSeventeen(byte b) {
assertEquals(17, b);
}

public void setEightteen(short s) {
assertEquals(18, s);
}

public void setNineteen(double d) {
assertEquals(19, d, 1e-6);
}

public void testGetExtensionPoints() {
List extensions = ih.getExtensionPoints();
final int adders = 2;
assertEquals("extension count", adders, extensions.size());

// this original test assumed something about the order of
// add(Number) and addConfigured(Map) returned by reflection.
// Unfortunately the assumption doesn't hold for all VMs
// (failed on MacOS X using JDK 1.4.2_05) and the possible
// combinatorics are too hard to check. We really only want
// to ensure that the more derived Hashtable can be found
// before Map.
// assertExtMethod(extensions.get(0), "add", Number.class,
// new Integer(2), new Integer(3));

// addConfigured(Hashtable) should come before addConfigured(Map)
assertExtMethod(extensions.get(adders - 2),
"addConfigured", Hashtable.class,
makeTable("key", "value"), makeTable("1", "2"));

assertExtMethod(extensions.get(adders - 1), "addConfigured", Map.class,
new HashMap(), makeTable("1", "2"));
}

private void assertExtMethod(Object mo, String methodName, Class methodArg,
Object arg, Object badArg) {
assertMethod((Method) mo, methodName, methodArg, arg, badArg);
}

private void assertMethod(Method m, String methodName, Class methodArg,
Object arg, Object badArg) {
assertEquals("Method name", methodName, m.getName());
assertEquals("Return type", Void.TYPE, m.getReturnType());
Class[] args = m.getParameterTypes();
assertEquals("Arg Count", 1, args.length);
assertEquals("Arg Type", methodArg, args[0]);

try {
m.invoke(this, new Object[] { arg });
} catch (IllegalAccessException e) {
throw new BuildException(e);
} catch (InvocationTargetException e) {
throw new BuildException(e);
}

try {
m.invoke(this, new Object[] { badArg });
fail("Should have raised an assertion exception");
} catch (IllegalAccessException e) {
throw new BuildException(e);
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
assertTrue(t instanceof junit.framework.AssertionFailedError);
}
}

public List add(List l) {
// INVALID extension point
return null;
}

// see comments in testGetExtensionPoints
// public void add(Number n) {
// // Valid extension point
// assertEquals(2, n.intValue());
// }

public void add(List l, int i) {
// INVALID extension point
}

public void addConfigured(Map m) {
// Valid extension point
assertTrue(m.size() == 0);
}

public void addConfigured(Hashtable h) {
// Valid extension point, more derived than Map above, but *after* it!
assertEquals(makeTable("key", "value"), h);
}

private Hashtable makeTable(Object key, Object value) {
Hashtable table = new Hashtable();
table.put(key, value);
return table;
}

} // IntrospectionHelperTest


+ 45
- 0
src/tests/junit/org/apache/tools/ant/LoaderRefTest.java View File

@@ -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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class LoaderRefTest extends BuildFileTest {

public LoaderRefTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/core/loaderref/loaderref.xml");
}

public void tearDown() {
executeTarget("clean");
}

// override allowed on <available>
public void testBadRef() {
expectBuildExceptionContaining("testbadref", "Should fail due to ref "
+ "not being a class loader", "does not reference a class loader");
}
}


+ 77
- 0
src/tests/junit/org/apache/tools/ant/LocationTest.java View File

@@ -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;

import org.apache.tools.ant.taskdefs.ConditionTask;
import org.apache.tools.ant.taskdefs.Echo;
import org.apache.tools.ant.types.FileSet;

public class LocationTest extends BuildFileTest {

public void setUp() {
configureProject("src/etc/testcases/core/location.xml");
}

public void testPlainTask() {
executeTarget("testPlainTask");
Echo e = (Echo) getProject().getReference("echo");
assertFalse(e.getLocation() == Location.UNKNOWN_LOCATION);
assertFalse(e.getLocation().getLineNumber() == 0);
}

public void testStandaloneType() {
executeTarget("testStandaloneType");
Echo e = (Echo) getProject().getReference("echo2");
FileSet f = (FileSet) getProject().getReference("fs");
assertFalse(f.getLocation() == Location.UNKNOWN_LOCATION);
assertEquals(e.getLocation().getLineNumber() + 1,
f.getLocation().getLineNumber());
}

public void testConditionTask() {
executeTarget("testConditionTask");
TaskAdapter ta = (TaskAdapter) getProject().getReference("cond");
ConditionTask c = (ConditionTask) ta.getProxy();
assertFalse(c.getLocation() == Location.UNKNOWN_LOCATION);
assertFalse(c.getLocation().getLineNumber() == 0);
}

public void testMacrodefWrappedTask() {
executeTarget("testMacrodefWrappedTask");
Echo e = (Echo) getProject().getReference("echo3");
assertTrue(getLog().indexOf("Line: "
+ (e.getLocation().getLineNumber() + 1))
> -1);
}

public void testPresetdefWrappedTask() {
executeTarget("testPresetdefWrappedTask");
Echo e = (Echo) getProject().getReference("echo4");
assertTrue(getLog().indexOf("Line: "
+ (e.getLocation().getLineNumber() + 1))
> -1);
}

public static class EchoLocation extends Task {
public void execute() {
log("Line: " + getLocation().getLineNumber(), Project.MSG_INFO);
}
}
}


+ 63
- 0
src/tests/junit/org/apache/tools/ant/MockBuildListener.java View File

@@ -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;

import java.util.Vector;

import junit.framework.Assert;

public class MockBuildListener extends Assert implements BuildListener {

private final Vector buffer = new Vector();
private final Project project;

public MockBuildListener(final Project project) {
this.project = project;
}

public void buildStarted(BuildEvent event) {}
public void buildFinished(BuildEvent event) {}
public void targetStarted(BuildEvent event) {}
public void targetFinished(BuildEvent event) {}
public void taskStarted(BuildEvent event) {}
public void taskFinished(BuildEvent event) {}

public void messageLogged(final BuildEvent actual) {
if(actual.getPriority()==Project.MSG_DEBUG)
return;
assertTrue("unexpected messageLogged: "+actual.getMessage(), !buffer.isEmpty());
assertEquals("unexpected project ", project, actual.getProject());

BuildEvent expected = (BuildEvent) buffer.elementAt(0);
buffer.removeElementAt(0);
assertEquals("unexpected messageLogged ", expected.getMessage(), actual.getMessage());
assertEquals("unexpected priority ", expected.getPriority(), actual.getPriority());
}

public void assertEmpty() {
assertTrue("MockBuildListener is not empty", buffer.isEmpty());
}

public void addBuildEvent(final String message, final int priority) {
final BuildEvent be = new BuildEvent(project);
be.setMessage(message, priority);
buffer.addElement(be);
}

}

+ 31
- 0
src/tests/junit/org/apache/tools/ant/PickOneTask.java View File

@@ -0,0 +1,31 @@
/*
* 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;

import org.apache.tools.ant.dispatch.DispatchTask;

public class PickOneTask extends DispatchTask {
public void list() {
throw new BuildException("list");
}

public void show() {
throw new BuildException("show");
}
}

+ 296
- 0
src/tests/junit/org/apache/tools/ant/ProjectTest.java View File

@@ -0,0 +1,296 @@
/*
* 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;

import org.apache.tools.ant.input.DefaultInputHandler;
import org.apache.tools.ant.input.InputHandler;
import org.apache.tools.ant.input.PropertyFileInputHandler;
import org.apache.tools.ant.taskdefs.condition.Os;
import org.apache.tools.ant.types.*;

import java.io.File;
import junit.framework.TestCase;


/**
* Very limited test class for Project. Waiting to be extended.
*
*/
public class ProjectTest extends TestCase {

private Project p;
private String root;
private MockBuildListener mbl;

public ProjectTest(String name) {
super(name);
}

public void setUp() {
p = new Project();
p.init();
root = new File(File.separator).getAbsolutePath().toUpperCase();
mbl = new MockBuildListener(p);
}

public void testDataTypes() throws BuildException {
assertNull("dummy is not a known data type",
p.createDataType("dummy"));
Object o = p.createDataType("fileset");
assertNotNull("fileset is a known type", o);
assertTrue("fileset creates FileSet", o instanceof FileSet);
assertTrue("PatternSet",
p.createDataType("patternset") instanceof PatternSet);
assertTrue("Path", p.createDataType("path") instanceof Path);
}

/**
* This test has been a starting point for moving the code to FileUtils.
*/
public void testResolveFile() {
if (Os.isFamily("netware") || Os.isFamily("dos")) {
assertEqualsIgnoreDriveCase(localize(File.separator),
p.resolveFile("/", null).getPath());
assertEqualsIgnoreDriveCase(localize(File.separator),
p.resolveFile("\\", null).getPath());
/*
* throw in drive letters
*/
String driveSpec = "C:";
assertEquals(driveSpec + "\\",
p.resolveFile(driveSpec + "/", null).getPath());
assertEquals(driveSpec + "\\",
p.resolveFile(driveSpec + "\\", null).getPath());
String driveSpecLower = "c:";
assertEquals(driveSpec + "\\",
p.resolveFile(driveSpecLower + "/", null).getPath());
assertEquals(driveSpec + "\\",
p.resolveFile(driveSpecLower + "\\", null).getPath());
/*
* promised to eliminate consecutive slashes after drive letter.
*/
assertEquals(driveSpec + "\\",
p.resolveFile(driveSpec + "/////", null).getPath());
assertEquals(driveSpec + "\\",
p.resolveFile(driveSpec + "\\\\\\\\\\\\", null).getPath());
} else {
/*
* Start with simple absolute file names.
*/
assertEquals(File.separator,
p.resolveFile("/", null).getPath());
assertEquals(File.separator,
p.resolveFile("\\", null).getPath());
/*
* drive letters are not used, just to be considered as normal
* part of a name
*/
String driveSpec = "C:";
String udir = System.getProperty("user.dir") + File.separatorChar;
assertEquals(udir + driveSpec,
p.resolveFile(driveSpec + "/", null).getPath());
assertEquals(udir + driveSpec,
p.resolveFile(driveSpec + "\\", null).getPath());
String driveSpecLower = "c:";
assertEquals(udir + driveSpecLower,
p.resolveFile(driveSpecLower + "/", null).getPath());
assertEquals(udir + driveSpecLower,
p.resolveFile(driveSpecLower + "\\", null).getPath());
}
/*
* Now test some relative file name magic.
*/
assertEquals(localize("/1/2/3/4"),
p.resolveFile("4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"),
p.resolveFile("./4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"),
p.resolveFile(".\\4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"),
p.resolveFile("./.\\4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"),
p.resolveFile("../3/4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"),
p.resolveFile("..\\3\\4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"),
p.resolveFile("../../5/.././2/./3/6/../4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"),
p.resolveFile("..\\../5/..\\./2/./3/6\\../4", new File(localize("/1/2/3"))).getPath());

}

/**
* 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
* the drive letter is in lower case under cygwin
* calling this method allows tests where FileUtils.normalize
* is called via resolveFile to pass under cygwin
*/
private void assertEqualsIgnoreDriveCase(String s1, String s2) {
if ((Os.isFamily("dos") || Os.isFamily("netware"))
&& s1.length() >= 1 && s2.length() >= 1) {
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);
}
}

private void assertTaskDefFails(final Class taskClass,
final String message) {
final String dummyName = "testTaskDefinitionDummy";
try {
mbl.addBuildEvent(message, Project.MSG_ERR);
p.addTaskDefinition(dummyName, taskClass);
fail("expected BuildException(\""+message+"\", Project.MSG_ERR) when adding task " + taskClass);
}
catch(BuildException e) {
assertEquals(message, e.getMessage());
mbl.assertEmpty();
assertTrue(!p.getTaskDefinitions().containsKey(dummyName));
}
}

public void testAddTaskDefinition() {
p.addBuildListener(mbl);

p.addTaskDefinition("Ok", DummyTaskOk.class);
assertEquals(DummyTaskOk.class, p.getTaskDefinitions().get("Ok"));
p.addTaskDefinition("OkNonTask", DummyTaskOkNonTask.class);
assertEquals(DummyTaskOkNonTask.class, p.getTaskDefinitions().get("OkNonTask"));
mbl.assertEmpty();

assertTaskDefFails(DummyTaskPrivate.class, DummyTaskPrivate.class + " is not public");

assertTaskDefFails(DummyTaskProtected.class,
DummyTaskProtected.class + " is not public");

assertTaskDefFails(DummyTaskPackage.class, DummyTaskPackage.class + " is not public");

assertTaskDefFails(DummyTaskAbstract.class, DummyTaskAbstract.class + " is abstract");
assertTaskDefFails(DummyTaskInterface.class, DummyTaskInterface.class + " is abstract");

assertTaskDefFails(DummyTaskWithoutDefaultConstructor.class, "No public no-arg constructor in " + DummyTaskWithoutDefaultConstructor.class);
assertTaskDefFails(DummyTaskWithoutPublicConstructor.class, "No public no-arg constructor in " + DummyTaskWithoutPublicConstructor.class);

assertTaskDefFails(DummyTaskWithoutExecute.class, "No public execute() in " + DummyTaskWithoutExecute.class);
assertTaskDefFails(DummyTaskWithNonPublicExecute.class, "No public execute() in " + DummyTaskWithNonPublicExecute.class);

mbl.addBuildEvent("return type of execute() should be void but was \"int\" in " + DummyTaskWithNonVoidExecute.class, Project.MSG_WARN);
p.addTaskDefinition("NonVoidExecute", DummyTaskWithNonVoidExecute.class);
mbl.assertEmpty();
assertEquals(DummyTaskWithNonVoidExecute.class, p.getTaskDefinitions().get("NonVoidExecute"));
}

public void testInputHandler() {
InputHandler ih = p.getInputHandler();
assertNotNull(ih);
assertTrue(ih instanceof DefaultInputHandler);
InputHandler pfih = new PropertyFileInputHandler();
p.setInputHandler(pfih);
assertSame(pfih, p.getInputHandler());
}

public void testTaskDefinitionContainsKey() {
assertTrue(p.getTaskDefinitions().containsKey("echo"));
}

public void testTaskDefinitionContains() {
assertTrue(p.getTaskDefinitions().contains(org.apache.tools.ant.taskdefs.Echo.class));
}

public void testDuplicateTargets() {
// fail, because buildfile contains two targets with the same name
try {
BFT bft = new BFT("", "core/duplicate-target.xml");
} catch (BuildException ex) {
assertEquals("specific message",
"Duplicate target 'twice'",
ex.getMessage());
return;
}
fail("Should throw BuildException about duplicate target");
}

public void testDuplicateTargetsImport() {
// overriding target from imported buildfile is allowed
BFT bft = new BFT("", "core/duplicate-target2.xml");
bft.expectLog("once", "once from buildfile");
}


private class DummyTaskPrivate extends Task {
public DummyTaskPrivate() {}
public void execute() {}
}

protected class DummyTaskProtected extends Task {
public DummyTaskProtected() {}
public void execute() {}
}

private class BFT extends org.apache.tools.ant.BuildFileTest {
BFT(String name, String buildfile) {
super(name);
this.buildfile = buildfile;
setUp();
}

// avoid multiple configurations
boolean isConfigured = false;

// the buildfile to use
String buildfile = "";

public void setUp() {
if (!isConfigured) {
configureProject("src/etc/testcases/"+buildfile);
isConfigured = true;
}
}

public void tearDown() { }

// call a target
public void doTarget(String target) {
if (!isConfigured) setUp();
executeTarget(target);
}

public org.apache.tools.ant.Project getProject() {
return super.getProject();
}
}//class-BFT

}

class DummyTaskPackage extends Task {
public DummyTaskPackage() {}
public void execute() {}
}

+ 90
- 0
src/tests/junit/org/apache/tools/ant/PropertyExpansionTest.java View File

@@ -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;

/**
* class to look at how we expand properties
*/
public class PropertyExpansionTest extends BuildFileTest {


public PropertyExpansionTest(String name) {
super(name);
}

/**
* we bind to an existing test file because we are too lazy to write our
* own, and we don't really care what it is
*/
public void setUp() {
configureProject("src/etc/testcases/core/immutable.xml");
}

/**
* run through the test cases of expansion
*/
public void testPropertyExpansion() {
assertExpandsTo("","");
assertExpandsTo("$","$");
assertExpandsTo("$$-","$-");
assertExpandsTo("$$","$");
project.setProperty("expanded","EXPANDED");
assertExpandsTo("a${expanded}b","aEXPANDEDb");
assertExpandsTo("${expanded}${expanded}","EXPANDEDEXPANDED");
assertExpandsTo("$$$","$$");
assertExpandsTo("$$$$-","$$-");
assertExpandsTo("","");
assertExpandsTo("Class$$subclass","Class$subclass");
}

/**
* new things we want
*/
public void testDollarPassthru() {
assertExpandsTo("$-","$-");
assertExpandsTo("Class$subclass","Class$subclass");
assertExpandsTo("$$$-","$$-");
assertExpandsTo("$$$$$","$$$");
assertExpandsTo("${unassigned.property}","${unassigned.property}");
assertExpandsTo("a$b","a$b");
assertExpandsTo("$}}","$}}");
}


/**
* old things we dont want; not a test no more
*/
public void oldtestQuirkyLegacyBehavior() {
assertExpandsTo("Class$subclass","Classsubclass");
assertExpandsTo("$$$-","$-");
assertExpandsTo("a$b","ab");
assertExpandsTo("$}}","}}");
}

/**
* little helper method to validate stuff
*/
private void assertExpandsTo(String source,String expected) {
String actual=project.replaceProperties(source);
assertEquals(source,expected,actual);
}

//end class
}

+ 61
- 0
src/tests/junit/org/apache/tools/ant/TaskContainerTest.java View File

@@ -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;

public class TaskContainerTest extends BuildFileTest {

public TaskContainerTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/core/taskcontainer.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testPropertyExpansion() {
executeTarget("testPropertyExpansion");
assertTrue("attribute worked",
getLog().indexOf("As attribute: it worked") > -1);
assertTrue("nested text worked",
getLog().indexOf("As nested text: it worked") > -1);
}

public void testTaskdef() {
executeTarget("testTaskdef");
assertTrue("attribute worked",
getLog().indexOf("As attribute: it worked") > -1);
assertTrue("nested text worked",
getLog().indexOf("As nested text: it worked") > -1);
assertTrue("nested text worked",
getLog().indexOf("As nested task: it worked") > -1);
}

public void testCaseInsensitive() {
executeTarget("testCaseInsensitive");
assertTrue("works outside of container",
getLog().indexOf("hello ") > -1);
assertTrue("works inside of container",
getLog().indexOf("world") > -1);
}

}

+ 49
- 0
src/tests/junit/org/apache/tools/ant/TopLevelTaskTest.java View File

@@ -0,0 +1,49 @@
/*
* 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;

// This test will fail with embed, or if top-level is moved out of
// dependency - as 'echo' happens as part of configureProject stage.

/**
* Tests for builds with tasks at the top level
*
* @since Ant 1.6
*/
public class TopLevelTaskTest extends BuildFileTest {

public TopLevelTaskTest(String name) {
super(name);
}

public void testNoTarget() {
configureProject("src/etc/testcases/core/topleveltasks/notarget.xml");
expectLog("", "Called");
}

public void testCalledFromTopLevelAnt() {
configureProject("src/etc/testcases/core/topleveltasks/toplevelant.xml");
expectLog("", "Called");
}

public void testCalledFromTargetLevelAnt() {
configureProject("src/etc/testcases/core/topleveltasks/targetlevelant.xml");
expectLog("foo", "Called");
}
}

+ 154
- 0
src/tests/junit/org/apache/tools/ant/filters/ConcatFilterTest.java View File

@@ -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.filters;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.StringUtils;

/**
* JUnit Testcases for ConcatReader
*/
public class ConcatFilterTest extends BuildFileTest {

private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
private static final String lSep = StringUtils.LINE_SEP;

private static final String FILE_PREPEND_WITH =
"this-should-be-the-first-line" + lSep
+ "Line 1" + lSep
+ "Line 2" + lSep
+ "Line 3" + lSep
+ "Line 4" + lSep
;

private static final String FILE_PREPEND =
"Line 1" + lSep
+ "Line 2" + lSep
+ "Line 3" + lSep
+ "Line 4" + lSep
+ "Line 5" + lSep
;

private static final String FILE_APPEND_WITH =
"Line 57" + lSep
+ "Line 58" + lSep
+ "Line 59" + lSep
+ "Line 60" + lSep
+ "this-should-be-the-last-line" + lSep
;

private static final String FILE_APPEND =
"Line 56" + lSep
+ "Line 57" + lSep
+ "Line 58" + lSep
+ "Line 59" + lSep
+ "Line 60" + lSep
;


public ConcatFilterTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/concat.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testFilterReaderNoArgs() throws IOException {
executeTarget("testFilterReaderNoArgs");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"input/concatfilter.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(), "result/concat.FilterReaderNoArgs.test");
assertTrue("testFilterReaderNoArgs: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testFilterReaderBefore() {
doTest("testFilterReaderPrepend", FILE_PREPEND_WITH, FILE_APPEND);
}

public void testFilterReaderAfter() {
doTest("testFilterReaderAppend", FILE_PREPEND, FILE_APPEND_WITH);
}

public void testFilterReaderBeforeAfter() {
doTest("testFilterReaderPrependAppend", FILE_PREPEND_WITH, FILE_APPEND_WITH);
}

public void testConcatFilter() {
doTest("testConcatFilter", FILE_PREPEND, FILE_APPEND);
}

public void testConcatFilterBefore() {
doTest("testConcatFilterPrepend", FILE_PREPEND_WITH, FILE_APPEND);
}

public void testConcatFilterAfter() {
doTest("testConcatFilterAppend", FILE_PREPEND, FILE_APPEND_WITH);
}

public void testConcatFilterBeforeAfter() {
doTest("testConcatFilterPrependAppend", FILE_PREPEND_WITH, FILE_APPEND_WITH);
}


/**
* Executes a target and checks the beginning and the ending of a file.
* The filename depends on the target name: target name <i>testHelloWorld</i>
* will search for a file <i>result/concat.HelloWorld.test</i>.
* @param target The target to invoke
* @param expectedStart The string which should be at the beginning of the file
* @param expectedEnd The string which should be at the end of the file
*/
protected void doTest(String target, String expectedStart, String expectedEnd) {
executeTarget(target);
String resultContent = read("result/concat." + target.substring(4) + ".test");
assertTrue("First 5 lines differs.", resultContent.startsWith(expectedStart));
assertTrue("Last 5 lines differs.", resultContent.endsWith(expectedEnd));
}


/**
* Wrapper for FileUtils.readFully().
* Additionally it resolves the filename according the the projects basedir
* and closes the used reader.
* @param filename The name of the file to read
* @return the content of the file or <i>null</i> if something goes wrong
*/
protected String read(String filename) {
String content = null;
try {
File file = FILE_UTILS.resolveFile(getProject().getBaseDir(), filename);
java.io.FileReader rdr = new java.io.FileReader(file);
content = FileUtils.readFully(rdr);
rdr.close();
rdr = null;
} catch (Exception e) {
e.printStackTrace();
}
return content;
}

}

+ 112
- 0
src/tests/junit/org/apache/tools/ant/filters/DynamicFilterTest.java View File

@@ -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.filters;

import java.io.Reader;
import java.io.FileReader;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class DynamicFilterTest extends BuildFileTest {

private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
public DynamicFilterTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/dynamicfilter.xml");
executeTarget("init");
}

public void tearDown() {
executeTarget("cleanup");
}
public void testCustomFilter() throws IOException {
expectFileContains("dynamicfilter", "result/dynamicfilter",
"hellO wOrld");
}

// ------------------------------------------------------
// Helper methods
// -----------------------------------------------------

private String getFileString(String filename)
throws IOException
{
Reader r = null;
try {
r = new FileReader(FILE_UTILS.resolveFile(getProject().getBaseDir(), filename));
return FileUtils.readFully(r);
}
finally {
FileUtils.close(r);
}

}

private void expectFileContains(String name, String contains)
throws IOException
{
String content = getFileString(name);
assertTrue(
"expecting file " + name + " to contain " + contains +
" but got " + content, content.indexOf(contains) > -1);
}

private void expectFileContains(
String target, String name, String contains)
throws IOException
{
executeTarget(target);
expectFileContains(name, contains);
}

public static class CustomFilter implements ChainableReader {
char replace = 'x';
char with = 'y';

public void setReplace(char replace) {
this.replace = replace;
}

public void setWith(char with) {
this.with = with;
}

public Reader chain(final Reader rdr) {
return new BaseFilterReader(rdr) {
public int read()
throws IOException
{
int c = in.read();
if (c == replace)
return with;
else
return c;
}
};
}
}
}

+ 52
- 0
src/tests/junit/org/apache/tools/ant/filters/EscapeUnicodeTest.java View File

@@ -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.filters;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class EscapeUnicodeTest extends BuildFileTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public EscapeUnicodeTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/build.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testEscapeUnicode() throws IOException {
executeTarget("testEscapeUnicode");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(), "expected/escapeunicode.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(), "result/escapeunicode.test");
assertTrue(FILE_UTILS.contentEquals(expected, result));
}

}

+ 131
- 0
src/tests/junit/org/apache/tools/ant/filters/HeadTailTest.java View File

@@ -0,0 +1,131 @@
/*
* 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.filters;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/** JUnit Testcases for TailFilter and HeadFilter
*/
/* I wrote the testcases in one java file because I want also to test the
* combined behaviour (see end of the class).
*/
public class HeadTailTest extends BuildFileTest {

private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
public HeadTailTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/head-tail.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testHead() throws IOException {
executeTarget("testHead");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(), "expected/head-tail.head.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(), "result/head-tail.head.test");
assertTrue("testHead: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testHeadLines() throws IOException {
executeTarget("testHeadLines");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(), "expected/head-tail.headLines.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(), "result/head-tail.headLines.test");
assertTrue("testHeadLines: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testHeadSkip() throws IOException {
executeTarget("testHeadSkip");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.headSkip.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/head-tail.headSkip.test");
assertTrue("testHeadSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testHeadLinesSkip() throws IOException {
executeTarget("testHeadLinesSkip");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.headLinesSkip.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/head-tail.headLinesSkip.test");
assertTrue("testHeadLinesSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testFilterReaderHeadLinesSkip() throws IOException {
executeTarget("testFilterReaderHeadLinesSkip");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),
"expected/head-tail.headLinesSkip.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),
"result/head-tail.filterReaderHeadLinesSkip.test");
assertTrue("testFilterReaderHeadLinesSkip: Result not like expected",
FILE_UTILS.contentEquals(expected, result));
}

public void testTail() throws IOException {
executeTarget("testTail");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tail.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/head-tail.tail.test");
assertTrue("testTail: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testTailLines() throws IOException {
executeTarget("testTailLines");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tailLines.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/head-tail.tailLines.test");
assertTrue("testTailLines: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testTailSkip() throws IOException {
executeTarget("testTailSkip");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tailSkip.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/head-tail.tailSkip.test");
assertTrue("testTailSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testTailLinesSkip() throws IOException {
executeTarget("testTailLinesSkip");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tailLinesSkip.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/head-tail.tailLinesSkip.test");
assertTrue("testTailLinesSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

public void testFilterReaderTailLinesSkip() throws IOException {
executeTarget("testFilterReaderTailLinesSkip");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),
"expected/head-tail.tailLinesSkip.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),
"result/head-tail.filterReaderTailLinesSkip.test");
assertTrue("testFilterReaderTailLinesSkip: Result not like expected",
FILE_UTILS.contentEquals(expected, result));
}

public void testHeadTail() throws IOException {
executeTarget("testHeadTail");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.headtail.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/head-tail.headtail.test");
assertTrue("testHeadTail: Result not like expected", FILE_UTILS.contentEquals(expected, result));
}

}

+ 56
- 0
src/tests/junit/org/apache/tools/ant/filters/LineContainsTest.java View File

@@ -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.filters;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class LineContainsTest extends BuildFileTest {

private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
public LineContainsTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/build.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testLineContains() throws IOException {
executeTarget("testLineContains");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/linecontains.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/linecontains.test");
assertTrue(FILE_UTILS.contentEquals(expected, result));
}

public void testNegateLineContains() throws IOException {
executeTarget("testNegateLineContains");
}

}

+ 49
- 0
src/tests/junit/org/apache/tools/ant/filters/NoNewLineTest.java View File

@@ -0,0 +1,49 @@
/*
* 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.filters;

import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;

/** JUnit Testcases for No new line when filterchain used
*/


public class NoNewLineTest extends BuildFileTest {

public NoNewLineTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/build.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testNoAddNewLine() throws IOException {
executeTarget("testNoAddNewLine");
}


}


+ 59
- 0
src/tests/junit/org/apache/tools/ant/filters/ReplaceTokensTest.java View File

@@ -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.filters;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class ReplaceTokensTest extends BuildFileTest {

private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public ReplaceTokensTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/build.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testReplaceTokens() throws IOException {
executeTarget("testReplaceTokens");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/replacetokens.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/replacetokens.test");
assertTrue(FILE_UTILS.contentEquals(expected, result));
}

public void testReplaceTokensPropertyFile() throws IOException {
executeTarget("testReplaceTokensPropertyFile");
File expected = FILE_UTILS.resolveFile(getProjectDir(), "expected/replacetokens.test");
File result = FILE_UTILS.resolveFile(getProjectDir(), "result/replacetokensPropertyFile.test");
assertTrue(FILE_UTILS.contentEquals(expected, result));
}

}

+ 52
- 0
src/tests/junit/org/apache/tools/ant/filters/StripJavaCommentsTest.java View File

@@ -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.filters;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class StripJavaCommentsTest extends BuildFileTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public StripJavaCommentsTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/build.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testStripJavaComments() throws IOException {
executeTarget("testStripJavaComments");
File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/stripjavacomments.test");
File result = FILE_UTILS.resolveFile(getProject().getBaseDir(),"result/stripjavacomments.test");
assertTrue(FILE_UTILS.contentEquals(expected, result));
}

}

+ 296
- 0
src/tests/junit/org/apache/tools/ant/filters/TokenFilterTest.java View File

@@ -0,0 +1,296 @@
/*
* 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.filters;

import java.io.Reader;
import java.io.FileReader;
import java.io.IOException;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class TokenFilterTest extends BuildFileTest {

private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
public TokenFilterTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/filters/tokenfilter.xml");
executeTarget("init");
}

public void tearDown() {
executeTarget("cleanup");
}

/** make sure tokenfilter exists */
public void testTokenfilter() throws IOException {
executeTarget("tokenfilter");
}

public void testTrimignore() throws IOException {
expectLogContaining("trimignore", "Hello-World");
}

public void testStringTokenizer() throws IOException {
expectLogContaining(
"stringtokenizer", "#This#is#a#number#of#words#");
}

public void testUnixLineOutput() throws IOException {
expectFileContains(
"unixlineoutput", "result/unixlineoutput",
"\nThis\nis\na\nnumber\nof\nwords\n");
}

public void testDosLineOutput() throws IOException {
expectFileContains(
"doslineoutput", "result/doslineoutput",
"\r\nThis\r\nis\r\na\r\nnumber\r\nof\r\nwords\r\n");
}

public void testFileTokenizer() throws IOException {
String contents = getFileString(
"filetokenizer", "result/filetokenizer");
assertStringContains(contents, " of words");
assertStringNotContains(contents, " This is");
}

public void testReplaceString() throws IOException {
expectFileContains(
"replacestring", "result/replacestring",
"this is the moon");
}

public void testReplaceStrings() throws IOException {
expectLogContaining("replacestrings", "bar bar bar");
}

public void testContainsString() throws IOException {
String contents = getFileString(
"containsstring", "result/containsstring");
assertStringContains(contents, "this is a line contains foo");
assertStringNotContains(contents, "this line does not");
}

public void testReplaceRegex() throws IOException {
if (! hasRegex("testReplaceRegex"))
return;
String contents = getFileString(
"replaceregex", "result/replaceregex");
assertStringContains(contents, "world world world world");
assertStringContains(contents, "dog Cat dog");
assertStringContains(contents, "moon Sun Sun");
assertStringContains(contents, "found WhiteSpace");
assertStringContains(contents, "Found digits [1234]");
assertStringNotContains(contents, "This is a line with digits");
}

public void testFilterReplaceRegex() throws IOException {
if (! hasRegex("testFilterReplaceRegex"))
return;
String contents = getFileString(
"filterreplaceregex", "result/filterreplaceregex");
assertStringContains(contents, "world world world world");
}

public void testHandleDollerMatch() throws IOException {
if (! hasRegex("testFilterReplaceRegex"))
return;
executeTarget("dollermatch");
}

public void testTrimFile() throws IOException {
String contents = getFileString(
"trimfile", "result/trimfile");
assertTrue("no ws at start", contents.startsWith("This is th"));
assertTrue("no ws at end", contents.endsWith("second line."));
assertStringContains(contents, " This is the second");
}

public void testTrimFileByLine() throws IOException {
String contents = getFileString(
"trimfilebyline", "result/trimfilebyline");
assertFalse("no ws at start", contents.startsWith("This is th"));
assertFalse("no ws at end", contents.endsWith("second line."));
assertStringNotContains(contents, " This is the second");
assertStringContains(contents, "file.\nThis is the second");
}

public void testFilterReplaceString() throws IOException {
String contents = getFileString(
"filterreplacestring", "result/filterreplacestring");
assertStringContains(contents, "This is the moon");
}

public void testFilterReplaceStrings() throws IOException {
expectLogContaining("filterreplacestrings", "bar bar bar");
}

public void testContainsRegex() throws IOException {
if (! hasRegex("testContainsRegex"))
return;
String contents = getFileString(
"containsregex", "result/containsregex");
assertStringContains(contents, "hello world");
assertStringNotContains(contents, "this is the moon");
assertStringContains(contents, "World here");
}

public void testFilterContainsRegex() throws IOException {
if (! hasRegex("testFilterContainsRegex"))
return;
String contents = getFileString(
"filtercontainsregex", "result/filtercontainsregex");
assertStringContains(contents, "hello world");
assertStringNotContains(contents, "this is the moon");
assertStringContains(contents, "World here");
}

public void testContainsRegex2() throws IOException {
if (! hasRegex("testContainsRegex2"))
return;
String contents = getFileString(
"containsregex2", "result/containsregex2");
assertStringContains(contents, "void register_bits();");
}

public void testDeleteCharacters() throws IOException {
String contents = getFileString(
"deletecharacters", "result/deletechars");
assertStringNotContains(contents, "#");
assertStringNotContains(contents, "*");
assertStringContains(contents, "This is some ");
}

public void testScriptFilter() throws IOException {
if (! hasScript("testScriptFilter"))
return;

expectFileContains("scriptfilter", "result/scriptfilter",
"HELLO WORLD");
}


public void testScriptFilter2() throws IOException {
if (! hasScript("testScriptFilter"))
return;

expectFileContains("scriptfilter2", "result/scriptfilter2",
"HELLO MOON");
}

public void testCustomTokenFilter() throws IOException {
expectFileContains("customtokenfilter", "result/custom",
"Hello World");
}

// ------------------------------------------------------
// Helper methods
// -----------------------------------------------------
private boolean hasScript(String test) {
try {
executeTarget("hasscript");
}
catch (Throwable ex) {
System.out.println(
test + ": skipped - script not present ");
return false;
}
return true;
}

private boolean hasRegex(String test) {
try {
executeTarget("hasregex");
expectFileContains("result/replaceregexp", "bye world");
}
catch (Throwable ex) {
System.out.println(test + ": skipped - regex not present "
+ ex);
return false;
}
return true;
}

private void assertStringContains(String string, String contains) {
assertTrue("[" + string + "] does not contain [" + contains +"]",
string.indexOf(contains) > -1);
}

private void assertStringNotContains(String string, String contains) {
assertTrue("[" + string + "] does contain [" + contains +"]",
string.indexOf(contains) == -1);
}

private String getFileString(String filename)
throws IOException
{
Reader r = null;
try {
r = new FileReader(FILE_UTILS.resolveFile(getProject().getBaseDir(),filename));
return FileUtils.readFully(r);
}
finally {
FileUtils.close(r);
}

}

private String getFileString(String target, String filename)
throws IOException
{
executeTarget(target);
return getFileString(filename);
}

private void expectFileContains(String name, String contains)
throws IOException
{
String content = getFileString(name);
assertTrue(
"expecting file " + name + " to contain " + contains +
" but got " + content, content.indexOf(contains) > -1);
}

private void expectFileContains(
String target, String name, String contains)
throws IOException
{
executeTarget(target);
expectFileContains(name, contains);
}

public static class Capitalize
implements TokenFilter.Filter
{
public String filter(String token) {
if (token.length() == 0)
return token;
return token.substring(0, 1).toUpperCase() +
token.substring(1);
}
}

}

+ 61
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/AbstractCvsTaskTest.java View File

@@ -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.taskdefs;

import java.io.File;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class AbstractCvsTaskTest extends BuildFileTest {

public AbstractCvsTaskTest() {
this( "AbstractCvsTaskTest" );
}

public AbstractCvsTaskTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/abstractcvstask.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testAbstractCvsTask() {
executeTarget( "all" );
}

public void testPackageAttribute() {
File f = getProject().resolveFile("tmpdir/ant/build.xml");
assertTrue("starting empty", !f.exists());
expectLogContaining("package-attribute", "U ant/build.xml");
assertTrue("now it is there", f.exists());
}

public void testTagAttribute() {
File f = getProject().resolveFile("tmpdir/ant/build.xml");
assertTrue("starting empty", !f.exists());
expectLogContaining("tag-attribute", "ANT_141 (revision: 1.175.2.13)");
assertTrue("now it is there", f.exists());
}
}

+ 62
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/AntLikeTasksAtTopLevelTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;

/**
* @since Ant 1.6
*/
public class AntLikeTasksAtTopLevelTest extends BuildFileTest {
public AntLikeTasksAtTopLevelTest(String name) {
super(name);
}

public void testAnt() {
try {
configureProject("src/etc/testcases/taskdefs/toplevelant.xml");
fail("no exception thrown");
} catch (BuildException e) {
assertEquals("ant task at the top level must not invoke its own"
+ " build file.", e.getMessage());
}
}

public void testSubant() {
try {
configureProject("src/etc/testcases/taskdefs/toplevelsubant.xml");
fail("no exception thrown");
} catch (BuildException e) {
assertEquals("subant task at the top level must not invoke its own"
+ " build file.", e.getMessage());
}
}

public void testAntcall() {
try {
configureProject("src/etc/testcases/taskdefs/toplevelantcall.xml");
fail("no exception thrown");
} catch (BuildException e) {
assertEquals("antcall must not be used at the top level.",
e.getMessage());
}
}

}// AntLikeTasksAtTopLevelTest

+ 97
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/AntStructureTest.java View File

@@ -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;

import java.io.PrintWriter;
import java.util.Hashtable;
import junit.framework.Assert;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Project;

/**
*/
public class AntStructureTest extends BuildFileTest {

public AntStructureTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/antstructure.xml");
}

public void tearDown() {
executeTarget("tearDown");
}

public void test1() {
expectBuildException("test1", "required argument not specified");
}

public void testCustomPrinter() {
executeTarget("testCustomPrinter");
// can't access the booleans in MyPrinter here (even if they
// were static) since the MyPrinter instance that was used in
// the test has likely been loaded via a different classloader
// than this class. Therefore we make the printer assert its
// state and only check for the tail invocation.
assertLogContaining(MyPrinter.TAIL_CALLED);
}

public static class MyPrinter implements AntStructure.StructurePrinter {
private static final String TAIL_CALLED = "tail has been called";
private boolean headCalled = false;
private boolean targetCalled = false;
private boolean tailCalled = false;
private int elementCalled = 0;
private Project p;

public void printHead(PrintWriter out, Project p, Hashtable tasks,
Hashtable types) {
Assert.assertTrue(!headCalled);
Assert.assertTrue(!targetCalled);
Assert.assertTrue(!tailCalled);
Assert.assertEquals(0, elementCalled);
headCalled = true;
}
public void printTargetDecl(PrintWriter out) {
Assert.assertTrue(headCalled);
Assert.assertTrue(!targetCalled);
Assert.assertTrue(!tailCalled);
Assert.assertEquals(0, elementCalled);
targetCalled = true;
}
public void printElementDecl(PrintWriter out, Project p, String name,
Class element) {
Assert.assertTrue(headCalled);
Assert.assertTrue(targetCalled);
Assert.assertTrue(!tailCalled);
elementCalled++;
this.p = p;
}
public void printTail(PrintWriter out) {
Assert.assertTrue(headCalled);
Assert.assertTrue(targetCalled);
Assert.assertTrue(!tailCalled);
Assert.assertTrue(elementCalled > 0);
tailCalled = true;
p.log(TAIL_CALLED);
}
}
}

+ 512
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java View File

@@ -0,0 +1,512 @@
/*
* 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;

import java.io.File;

import junit.framework.AssertionFailedError;

import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.input.InputHandler;
import org.apache.tools.ant.input.PropertyFileInputHandler;
import org.apache.tools.ant.types.Path;

/**
*/
public class AntTest extends BuildFileTest {

public AntTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/ant.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "recursive call");
}

// target must be specified
public void test2() {
expectBuildException("test2", "required argument not specified");
}

// Should fail since a recursion will occur...
public void test3() {
expectBuildException("test1", "recursive call");
}

public void test4() {
expectBuildException("test4", "target attribute must not be empty");
}

public void test4b() {
expectBuildException("test4b", "target doesn't exist");
}

public void test5() {
executeTarget("test5");
}

public void test6() {
executeTarget("test6");
}

public void testExplicitBasedir1() {
File dir1 = getProjectDir();
File dir2 = project.resolveFile("..");
testBaseDirs("explicitBasedir1",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath()
});
}

public void testExplicitBasedir2() {
File dir1 = getProjectDir();
File dir2 = project.resolveFile("..");
testBaseDirs("explicitBasedir2",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath()
});
}

public void testInheritBasedir() {
String basedir = getProjectDir().getAbsolutePath();
testBaseDirs("inheritBasedir", new String[] {basedir, basedir});
}

public void testDoNotInheritBasedir() {
File dir1 = getProjectDir();
File dir2 = project.resolveFile("ant");
String basedir = getProjectDir().getAbsolutePath();
testBaseDirs("doNotInheritBasedir",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath()
});
}

public void testBasedirTripleCall() {
File dir1 = getProjectDir();
File dir2 = project.resolveFile("ant");
testBaseDirs("tripleCall",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath(),
dir1.getAbsolutePath()
});
}

protected void testBaseDirs(String target, String[] dirs) {
BasedirChecker bc = new BasedirChecker(dirs);
project.addBuildListener(bc);
executeTarget(target);
AssertionFailedError ae = bc.getError();
if (ae != null) {
throw ae;
}
project.removeBuildListener(bc);
}

public void testReferenceInheritance() {
Path p = Path.systemClasspath;
p.setProject(project);
project.addReference("path", p);
project.addReference("no-override", p);
testReference("testInherit", new String[] {"path", "path"},
new boolean[] {true, true}, p);
testReference("testInherit",
new String[] {"no-override", "no-override"},
new boolean[] {true, false}, p);
testReference("testInherit",
new String[] {"no-override", "no-override"},
new boolean[] {false, false}, null);
}

public void testReferenceNoInheritance() {
Path p = Path.systemClasspath;
p.setProject(project);
project.addReference("path", p);
project.addReference("no-override", p);
testReference("testNoInherit", new String[] {"path", "path"},
new boolean[] {true, false}, p);
testReference("testNoInherit", new String[] {"path", "path"},
new boolean[] {false, true}, null);
testReference("testInherit",
new String[] {"no-override", "no-override"},
new boolean[] {true, false}, p);
testReference("testInherit",
new String[] {"no-override", "no-override"},
new boolean[] {false, false}, null);
}

public void testReferenceRename() {
Path p = Path.systemClasspath;
p.setProject(project);
project.addReference("path", p);
testReference("testRename", new String[] {"path", "path"},
new boolean[] {true, false}, p);
testReference("testRename", new String[] {"path", "path"},
new boolean[] {false, true}, null);
testReference("testRename", new String[] {"newpath", "newpath"},
new boolean[] {false, true}, p);
}

public void testInheritPath() {
executeTarget("testInheritPath");
}

protected void testReference(String target, String[] keys,
boolean[] expect, Object value) {
ReferenceChecker rc = new ReferenceChecker(keys, expect, value);
project.addBuildListener(rc);
executeTarget(target);
AssertionFailedError ae = rc.getError();
if (ae != null) {
throw ae;
}
project.removeBuildListener(rc);
}

public void testLogfilePlacement() {
File[] logFiles = new File[] {
getProject().resolveFile("test1.log"),
getProject().resolveFile("test2.log"),
getProject().resolveFile("ant/test3.log"),
getProject().resolveFile("ant/test4.log")
};
for (int i=0; i<logFiles.length; i++) {
assertTrue(logFiles[i].getName()+" doesn\'t exist",
!logFiles[i].exists());
}

executeTarget("testLogfilePlacement");

for (int i=0; i<logFiles.length; i++) {
assertTrue(logFiles[i].getName()+" exists",
logFiles[i].exists());
}
}

public void testInputHandlerInheritance() {
InputHandler ih = new PropertyFileInputHandler();
getProject().setInputHandler(ih);
InputHandlerChecker ic = new InputHandlerChecker(ih);
getProject().addBuildListener(ic);
executeTarget("tripleCall");
AssertionFailedError ae = ic.getError();
if (ae != null) {
throw ae;
}
getProject().removeBuildListener(ic);
}

public void testRefId() {
Path testPath = new Path(project);
testPath.createPath().setPath(System.getProperty("java.class.path"));
PropertyChecker pc =
new PropertyChecker("testprop",
new String[] {null,
testPath.toString()});
project.addBuildListener(pc);
executeTarget("testRefid");
AssertionFailedError ae = pc.getError();
if (ae != null) {
throw ae;
}
project.removeBuildListener(pc);
}

public void testUserPropertyWinsInheritAll() {
getProject().setUserProperty("test", "7");
expectLogContaining("test-property-override-inheritall-start",
"The value of test is 7");
}

public void testUserPropertyWinsNoInheritAll() {
getProject().setUserProperty("test", "7");
expectLogContaining("test-property-override-no-inheritall-start",
"The value of test is 7");
}

public void testOverrideWinsInheritAll() {
expectLogContaining("test-property-override-inheritall-start",
"The value of test is 4");
}

public void testOverrideWinsNoInheritAll() {
expectLogContaining("test-property-override-no-inheritall-start",
"The value of test is 4");
}

public void testPropertySet() {
executeTarget("test-propertyset");
assertTrue(getLog().indexOf("test1 is ${test1}") > -1);
assertTrue(getLog().indexOf("test2 is ${test2}") > -1);
assertTrue(getLog().indexOf("test1.x is 1") > -1);
}

public void testInfiniteLoopViaDepends() {
expectBuildException("infinite-loop-via-depends", "recursive call");
}

public void testMultiSameProperty() {
expectLog("multi-same-property", "prop is two");
}

public void testTopLevelTarget() {
expectLog("topleveltarget", "Hello world");
}

public void testMultiplePropertyFileChildren() {
PropertyChecker pcBar = new PropertyChecker("bar",
new String[] {null, "Bar"});
PropertyChecker pcFoo = new PropertyChecker("foo",
new String[] {null, "Foo"});
project.addBuildListener(pcBar);
project.addBuildListener(pcFoo);
executeTarget("multiple-property-file-children");
AssertionFailedError aeBar = pcBar.getError();
if (aeBar != null) {
throw aeBar;
}
AssertionFailedError aeFoo = pcFoo.getError();
if (aeFoo != null) {
throw aeFoo;
}
project.removeBuildListener(pcBar);
project.removeBuildListener(pcFoo);
}

public void testBlankTarget() {
expectBuildException("blank-target", "target name must not be empty");
}

public void testMultipleTargets() {
expectLog("multiple-targets", "tadadctbdbtc");
}

public void testMultipleTargets2() {
expectLog("multiple-targets-2", "dadctb");
}

private class BasedirChecker implements BuildListener {
private String[] expectedBasedirs;
private int calls = 0;
private AssertionFailedError error;

BasedirChecker(String[] dirs) {
expectedBasedirs = dirs;
}

public void buildStarted(BuildEvent event) {}
public void buildFinished(BuildEvent event) {}
public void targetFinished(BuildEvent event){}
public void taskStarted(BuildEvent event) {}
public void taskFinished(BuildEvent event) {}
public void messageLogged(BuildEvent event) {}

public void targetStarted(BuildEvent event) {
if (event.getTarget().getName().equals("")) {
return;
}
if (error == null) {
try {
assertEquals(expectedBasedirs[calls++],
event.getProject().getBaseDir().getAbsolutePath());
} catch (AssertionFailedError e) {
error = e;
}
}
}

AssertionFailedError getError() {
return error;
}

}

private class ReferenceChecker implements BuildListener {
private String[] keys;
private boolean[] expectSame;
private Object value;
private int calls = 0;
private AssertionFailedError error;

ReferenceChecker(String[] keys, boolean[] expectSame, Object value) {
this.keys = keys;
this.expectSame = expectSame;
this.value = value;
}

public void buildStarted(BuildEvent event) {}
public void buildFinished(BuildEvent event) {}
public void targetFinished(BuildEvent event){}
public void taskStarted(BuildEvent event) {}
public void taskFinished(BuildEvent event) {}
public void messageLogged(BuildEvent event) {}

public void targetStarted(BuildEvent event) {
if (event.getTarget().getName().equals("")) {
return;
}
if (error == null) {
try {
String msg =
"Call " + calls + " refid=\'" + keys[calls] + "\'";
if (value == null) {
Object o = event.getProject().getReference(keys[calls]);
if (expectSame[calls++]) {
assertNull(msg, o);
} else {
assertNotNull(msg, o);
}
} else {
// a rather convoluted equals() test
Path expect = (Path) value;
Path received = (Path) event.getProject().getReference(keys[calls]);
boolean shouldBeEqual = expectSame[calls++];
if (received == null) {
assertTrue(msg, !shouldBeEqual);
} else {
String[] l1 = expect.list();
String[] l2 = received.list();
if (l1.length == l2.length) {
for (int i=0; i<l1.length; i++) {
if (!l1[i].equals(l2[i])) {
assertTrue(msg, !shouldBeEqual);
}
}
assertTrue(msg, shouldBeEqual);
} else {
assertTrue(msg, !shouldBeEqual);
}
}
}
} catch (AssertionFailedError e) {
error = e;
}
}
}

AssertionFailedError getError() {
return error;
}

}

private class InputHandlerChecker implements BuildListener {
private InputHandler ih;
private AssertionFailedError error;

InputHandlerChecker(InputHandler value) {
ih = value;
}

public void buildStarted(BuildEvent event) {
check(event);
}
public void buildFinished(BuildEvent event) {
check(event);
}
public void targetFinished(BuildEvent event) {
check(event);
}
public void taskStarted(BuildEvent event) {
check(event);
}
public void taskFinished(BuildEvent event) {
check(event);
}
public void messageLogged(BuildEvent event) {
check(event);
}

public void targetStarted(BuildEvent event) {
check(event);
}

private void check(BuildEvent event) {
if (error == null) {
try {
assertNotNull(event.getProject().getInputHandler());
assertSame(ih, event.getProject().getInputHandler());
} catch (AssertionFailedError e) {
error = e;
}
}
}

AssertionFailedError getError() {
return error;
}

}

private class PropertyChecker implements BuildListener {
private String[] expectedValues;
private String key;
private int calls = 0;
private AssertionFailedError error;

PropertyChecker(String key, String[] values) {
this.key = key;
this.expectedValues = values;
}

public void buildStarted(BuildEvent event) {}
public void buildFinished(BuildEvent event) {}
public void targetFinished(BuildEvent event){}
public void taskStarted(BuildEvent event) {}
public void taskFinished(BuildEvent event) {}
public void messageLogged(BuildEvent event) {}

public void targetStarted(BuildEvent event) {
if (event.getTarget().getName().equals("")) {
return;
}
if (calls >= expectedValues.length) {
error = new AssertionFailedError("Unexpected invocation of"
+ " target "
+ event.getTarget().getName());
}

if (error == null) {
try {
assertEquals(expectedValues[calls++],
event.getProject().getProperty(key));
} catch (AssertionFailedError e) {
error = e;
}
}
}

AssertionFailedError getError() {
return error;
}

}


}

+ 94
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/AntlibTest.java View File

@@ -0,0 +1,94 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;

/**
*/
public class AntlibTest extends BuildFileTest {
public AntlibTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/antlib.xml");
}

/**
* only do the antlib tests if we are in the same JVM as ant.
* @return
*/
private boolean isSharedJVM() {
String property = System.getProperty("tests.and.ant.share.classloader");
return property!=null && Project.toBoolean(property);
}

public void testAntlibFile() {
expectLog("antlib.file", "MyTask called");
}

/**
* Confirms that all matching resources will be used, so that you
* can collect several antlibs in one Definer call.
* @see "http://issues.apache.org/bugzilla/show_bug.cgi?id=24024"
*/
public void testAntlibResource() {
expectLog("antlib.resource", "MyTask called-and-then-MyTask2 called");
}

public void testNsCurrent() {
expectLog("ns.current", "Echo2 inside a macroHello from x:p");
}


public void testAntlib_uri() {
if (isSharedJVM()) {
executeTarget("antlib_uri");
}
}

public void testAntlib_uri_auto() {
if (isSharedJVM()) {
executeTarget("antlib_uri_auto");
}
}

public void testAntlib_uri_auto2() {
if (isSharedJVM()) {
executeTarget("antlib_uri_auto2");
}
}
public static class MyTask extends Task {
public void execute() {
log("MyTask called");
}
}

public static class MyTask2 extends Task {
public void execute() {
log("MyTask2 called");
}
}

}


+ 77
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/AptTest.java View File

@@ -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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class AptTest extends BuildFileTest {
public AptTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/apt.xml");
}

/**
* Tears down the fixture, for example, close a network connection. This
* method is called after a test is executed.
*/
protected void tearDown() throws Exception {
executeTarget("clean");
}

public void testApt() {
executeTarget("testApt");
}

public void testAptFork() {
executeTarget("testAptFork");
}
public void testAptForkFalse() {
executeTarget("testAptForkFalse");
assertLogContaining(Apt.WARNING_IGNORING_FORK);
}

public void testListAnnotationTypes() {
executeTarget("testListAnnotationTypes");
assertLogContaining("Set of annotations found:");
assertLogContaining("Distributed");
}

public void testAptNewFactory() {
executeTarget("testAptNewFactory");
assertProcessed();
}

public void testAptNewFactoryFork() {
executeTarget("testAptNewFactoryFork");
assertProcessed();
}
private void assertProcessed() {
assertLogContaining("DistributedAnnotationProcessor-is-go");
assertLogContaining("[-Abuild.dir=");
assertLogContaining("visiting DistributedAnnotationFactory");
}
}


+ 213
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/AvailableTest.java View File

@@ -0,0 +1,213 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

/**
* JUnit test for the Available task/condition.
*/
public class AvailableTest extends BuildFileTest {

public AvailableTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/available.xml");
}

// Nothing specified -> Fail
public void test1() {
expectBuildException("test1", "required argument not specified");
}

// Only property specified -> Fail
public void test2() {
expectBuildException("test2", "required argument not specified");
}

// Only file specified -> Fail
public void test3() {
expectBuildException("test3", "required argument not specified");
}

// file doesn't exist -> property 'test' == null
public void test4() {
executeTarget("test4");
assertTrue(project.getProperty("test") == null);
}

// file does exist -> property 'test' == 'true'
public void test5() {
executeTarget("test5");
assertEquals("true", project.getProperty("test"));
}

// resource doesn't exist -> property 'test' == null
public void test6() {
executeTarget("test6");
assertTrue(project.getProperty("test") == null);
}

// resource does exist -> property 'test' == 'true'
public void test7() {
executeTarget("test7");
assertEquals("true", project.getProperty("test"));
}

// class doesn't exist -> property 'test' == null
public void test8() {
executeTarget("test8");
assertTrue(project.getProperty("test") == null);
}

// class does exist -> property 'test' == 'true'
public void test9() {
executeTarget("test9");
assertEquals("true", project.getProperty("test"));
}

// All three specified and all three exist -> true
public void test10() {
executeTarget("test10");
assertEquals("true", project.getProperty("test"));
}

// All three specified but class missing -> null
public void test11() {
executeTarget("test11");
assertNull(project.getProperty("test"));
}

// Specified property-name is "" -> true
public void test12() {
executeTarget("test12");
assertNull(project.getProperty("test"));
assertEquals("true", project.getProperty(""));
}

// Specified file is "" -> invalid files do not exist
public void test13() {
executeTarget("test13");
assertNull(project.getProperty("test"));
}

// Specified file is "" actually a directory, so it should pass
public void test13b() {
executeTarget("test13b");
assertEquals("true", project.getProperty("test"));
}

// Specified resource is "" -> can such a thing exist?
/*
* returns non null IBM JDK 1.3 Linux
*/
// public void test14() {
// executeTarget("test14");
// assertEquals(project.getProperty("test"), null);
// }

// Specified class is "" -> can not exist
public void test15() {
executeTarget("test15");
assertNull(project.getProperty("test"));
}

// Specified dir is "" -> this is the current directory and should
// always exist
public void test16() {
executeTarget("test16");
assertEquals("true", project.getProperty("test"));
}

// Specified dir is "../taskdefs" -> should exist since it's the
// location of the buildfile used...
public void test17() {
executeTarget("test17");
assertEquals("true", project.getProperty("test"));
}

// Specified dir is "../this_dir_should_never_exist" -> null
public void test18() {
executeTarget("test18");
assertNull(project.getProperty("test"));
}

// Invalid type specified
public void test19() {
expectBuildException("test19", "Invalid value for type attribute.");
}

// Core class that exists in system classpath is ignored
public void test20() {
executeTarget("test20");
assertNull(project.getProperty("test"));
}

// Core class that exists in system classpath is ignored, but found in specified classpath
public void test21() {
executeTarget("test21");
assertEquals("true", project.getProperty("test"));
}

// Core class that exists in system classpath is not ignored with ignoresystemclass="false"
public void test22() {
executeTarget("test22");
assertEquals("true", project.getProperty("test"));
}

// Core class that exists in system classpath is not ignored with default ignoresystemclasses value
public void test23() {
executeTarget("test23");
assertEquals("true", project.getProperty("test"));
}

// Class is found in specified classpath
public void test24() {
executeTarget("test24");
assertEquals("true", project.getProperty("test"));
}

// File is not found in specified filepath
public void testSearchInPathNotThere() {
executeTarget("searchInPathNotThere");
assertNull(project.getProperty("test"));
}

// File is not found in specified filepath
public void testSearchInPathIsThere() {
executeTarget("searchInPathIsThere");
assertEquals("true", project.getProperty("test"));
}

// test when file begins with basedir twice
public void testDoubleBasedir() {
executeTarget("testDoubleBasedir");
}

// test for searching parents
public void testSearchParents() {
executeTarget("search-parents");
}
// test for not searching parents
public void testSearchParentsNot() {
executeTarget("search-parents-not");
}
}

+ 63
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/BUnzip2Test.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;


/**
*/
public class BUnzip2Test extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public BUnzip2Test(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/bunzip2.xml");
executeTarget("prepare");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testRealTest() throws java.io.IOException {
testRealTest("realTest");
}

public void testRealTestWithResource() throws java.io.IOException {
testRealTest("realTestWithResource");
}

private void testRealTest(String target) throws java.io.IOException {
executeTarget(target);
assertTrue("File content mismatch after bunzip2",
FILE_UTILS.contentEquals(project.resolveFile("expected/asf-logo-huge.tar"),
project.resolveFile("asf-logo-huge.tar")));
}

public void testDocumentationClaimsOnCopy() throws java.io.IOException {
testRealTest("testDocumentationClaimsOnCopy");
}
}

+ 111
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/BZip2Test.java View File

@@ -0,0 +1,111 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.bzip2.CBZip2InputStream;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;

/**
*/
public class BZip2Test extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public BZip2Test(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/bzip2.xml");
executeTarget("prepare");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testRealTest() throws IOException {
executeTarget("realTest");

// doesn't work: Depending on the compression engine used,
// compressed bytes may differ. False errors would be
// reported.
// assertTrue("File content mismatch",
// FILE_UTILS.contentEquals(project.resolveFile("expected/asf-logo-huge.tar.bz2"),
// project.resolveFile("asf-logo-huge.tar.bz2")));

// We have to compare the decompressed content instead:

File originalFile =
project.resolveFile("expected/asf-logo-huge.tar.bz2");
File actualFile = project.resolveFile("asf-logo-huge.tar.bz2");

InputStream originalIn =
new BufferedInputStream(new FileInputStream(originalFile));
assertEquals((byte) 'B', originalIn.read());
assertEquals((byte) 'Z', originalIn.read());

InputStream actualIn =
new BufferedInputStream(new FileInputStream(actualFile));
assertEquals((byte) 'B', actualIn.read());
assertEquals((byte) 'Z', actualIn.read());

originalIn = new CBZip2InputStream(originalIn);
actualIn = new CBZip2InputStream(actualIn);

while (true) {
int expected = originalIn.read();
int actual = actualIn.read();
if (expected >= 0) {
if (expected != actual) {
fail("File content mismatch");
}
} else {
if (actual >= 0) {
fail("File content mismatch");
}
break;
}
}

originalIn.close();
actualIn.close();
}

public void testResource(){
executeTarget("realTestWithResource");
}

public void testDateCheck(){
executeTarget("testDateCheck");
String log = getLog();
assertTrue(
"Expecting message ending with 'asf-logo.gif.bz2 is up to date.' but got '" + log + "'",
log.endsWith("asf-logo.gif.bz2 is up to date."));
}

}

+ 83
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/BasenameTest.java View File

@@ -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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class BasenameTest extends BuildFileTest {

public BasenameTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/basename.xml");
}

public void test1() {
expectBuildException("test1", "required attribute missing");
}

public void test2() {
expectBuildException("test2", "required attribute missing");
}

public void test3() {
expectBuildException("test3", "required attribute missing");
}

public void test4() {
executeTarget("test4");
String checkprop = project.getProperty("file.w.suf");
assertEquals("foo.txt", checkprop);
}

public void test5() {
executeTarget("test5");
String checkprop = project.getProperty("file.wo.suf");
assertEquals("foo", checkprop);
}

public void testMultipleDots() {
executeTarget("testMultipleDots");
String checkprop = project.getProperty("file.wo.suf");
assertEquals("foo.bar", checkprop);
}

public void testNoDots() {
executeTarget("testNoDots");
String checkprop = project.getProperty("file.wo.suf");
assertEquals("foo.bar", checkprop);
}

public void testValueEqualsSuffixWithDot() {
executeTarget("testValueEqualsSuffixWithDot");
String checkprop = project.getProperty("file.wo.suf");
assertEquals("", checkprop);
}

public void testValueEqualsSuffixWithoutDot() {
executeTarget("testValueEqualsSuffixWithoutDot");
String checkprop = project.getProperty("file.wo.suf");
assertEquals("", checkprop);
}

}

+ 122
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/CVSPassTest.java View File

@@ -0,0 +1,122 @@
/*
* 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;

import java.io.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.BuildFileTest;

/**
* Tests CVSLogin task.
*
*/
public class CVSPassTest extends BuildFileTest {
private final String EOL = System.getProperty("line.separator");
private static final String JAKARTA_URL =
":pserver:anoncvs@jakarta.apache.org:/home/cvspublic Ay=0=h<Z";
private static final String XML_URL =
":pserver:anoncvs@xml.apache.org:/home/cvspublic Ay=0=h<Z";
private static final String TIGRIS_URL =
":pserver:guest@cvs.tigris.org:/cvs AIbdZ,";


public CVSPassTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/cvspass.xml");
}

public void testNoCVSRoot() {
try{
executeTarget("test1");
fail("BuildException not thrown");
}catch(BuildException e){
assertEquals("cvsroot is required", e.getMessage());
}
}

public void testNoPassword() {
try{
executeTarget("test2");
fail("BuildException not thrown");
}catch(BuildException e){
assertEquals("password is required", e.getMessage());
}
}

public void tearDown() {
executeTarget("cleanup");
}

public void testPassFile() throws Exception {
executeTarget("test3");
File f = new File(getProjectDir(), "testpassfile.tmp");

assertTrue( "Passfile "+f+" not created", f.exists());

assertEquals(JAKARTA_URL+EOL, readFile(f));

}

public void testPassFileDuplicateEntry() throws Exception {
executeTarget("test4");
File f = new File(getProjectDir(), "testpassfile.tmp");

assertTrue( "Passfile "+f+" not created", f.exists());

assertEquals(
JAKARTA_URL+ EOL+
TIGRIS_URL+ EOL,
readFile(f));
}

public void testPassFileMultipleEntry() throws Exception {
executeTarget("test5");
File f = new File(getProjectDir(), "testpassfile.tmp");

assertTrue( "Passfile "+f+" not created", f.exists());

assertEquals(
JAKARTA_URL+ EOL+
XML_URL+ EOL+
TIGRIS_URL+ EOL,
readFile(f));
}

private String readFile(File f) throws Exception {
BufferedReader reader = null;

try {
reader = new BufferedReader(new FileReader(f));

StringBuffer buf = new StringBuffer();
String line=null;
while((line=reader.readLine())!=null){
buf.append(line + EOL);
}
return buf.toString();
} finally {
if (reader != null) {
reader.close();
}
}
}
}

+ 72
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/CallTargetTest.java View File

@@ -0,0 +1,72 @@
/*
* 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;

import java.util.Vector;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class CallTargetTest extends BuildFileTest {

public CallTargetTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/calltarget.xml");
}

// see bugrep 21724 (references not passing through with antcall)
public void testInheritRefFileSet() {
expectLogContaining("testinheritreffileset", "calltarget.xml");
}

// see bugrep 21724 (references not passing through with antcall)
public void testInheritFilterset() {
project.executeTarget("testinheritreffilterset");
}

// see bugrep 11418 (In repeated calls to the same target,
// params will not be passed in)
public void testMultiCall() {
Vector v = new Vector();
v.add("call-multi");
v.add("call-multi");
project.executeTargets(v);
assertLogContaining("multi is SETmulti is SET");
}

public void testBlankTarget() {
expectBuildException("blank-target", "target name must not be empty");
}

public void testMultipleTargets() {
expectLog("multiple-targets", "tadadctbdbtc");
}

public void testMultipleTargets2() {
expectLog("multiple-targets-2", "dadctb");
}

public void tearDown() {
project.executeTarget("cleanup");
}
}

+ 93
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ChecksumTest.java View File

@@ -0,0 +1,93 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

import java.io.IOException;

/**
*/
public class ChecksumTest extends BuildFileTest {

public ChecksumTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/checksum.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testCreateMd5() throws IOException {
executeTarget("createMd5");
}

public void testCreateMD5SUMformat() throws IOException {
executeTarget("createMD5SUMformat");
}
public void testCreateSVFformat() throws IOException {
executeTarget("createSVFformat");
}
public void testCreatePattern() throws IOException {
executeTarget("createPattern");
}

public void testSetProperty() {
executeTarget("setProperty");
}

public void testVerifyTotal() {
executeTarget("verifyTotal");
}

public void testVerifyTotalRC() {
executeTarget("verifyTotalRC");
}

public void testVerifyChecksumdir() {
executeTarget("verifyChecksumdir");
}

public void testVerifyAsTask() {
executeTarget("verifyAsTask");
}

public void testVerifyMD5SUMAsTask() {
executeTarget("verifyMD5SUMAsTask");
}

public void testVerifyAsCondition() {
executeTarget("verifyAsCondition");
}

public void testVerifyFromProperty() {
executeTarget("verifyFromProperty");
}

public void testVerifyChecksumdirNoTotal() {
executeTarget("verifyChecksumdirNoTotal");
}

}

+ 284
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java View File

@@ -0,0 +1,284 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

/**
* A test class for the 'concat' task, used to concatenate a series of
* files into a single stream.
*
*/
public class ConcatTest
extends BuildFileTest {

/**
* The name of the temporary file.
*/
private static final String tempFile = "concat.tmp";

/**
* The name of the temporary file.
*/
private static final String tempFile2 = "concat.tmp.2";

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

/**
* Required constructor.
*/
public ConcatTest(String name) {
super(name);
}

/**
* Test set up, called by the unit test framework prior to each
* test.
*/
public void setUp() {
configureProject("src/etc/testcases/taskdefs/concat.xml");
}

/**
* Test tear down, called by the unit test framework prior to each
* test.
*/
public void tearDown() {
executeTarget("cleanup");
}

/**
* Expect an exception when insufficient information is provided.
*/
public void test1() {
expectBuildException("test1", "Insufficient information.");
}

/**
* Expect an exception when the destination file is invalid.
*/
public void test2() {
expectBuildException("test2", "Invalid destination file.");
}

/**
* Cats the string 'Hello, World!' to a temporary file.
*/
public void test3() {

File file = new File(getProjectDir(), tempFile);
if (file.exists()) {
file.delete();
}

executeTarget("test3");

assertTrue(file.exists());
}

/**
* Cats the file created in test3 three times.
*/
public void test4() {
test3();

File file = new File(getProjectDir(), tempFile);
final long origSize = file.length();

executeTarget("test4");

File file2 = new File(getProjectDir(), tempFile2);
final long newSize = file2.length();

assertEquals(origSize * 3, newSize);
}

/**
* Cats the string 'Hello, World!' to the console.
*/
public void test5() {
expectLog("test5", "Hello, World!");
}

public void test6() {
String filename = "src/etc/testcases/taskdefs/thisfiledoesnotexist"
.replace('/', File.separatorChar);
expectLogContaining("test6", filename +" does not exist.");
}

public void testConcatNoNewline() {
expectLog("testConcatNoNewline", "ab");
}

public void testConcatNoNewlineEncoding() {
expectLog("testConcatNoNewlineEncoding", "ab");
}

public void testPath() {
test3();

File file = new File(getProjectDir(), tempFile);
final long origSize = file.length();

executeTarget("testPath");

File file2 = new File(getProjectDir(), tempFile2);
final long newSize = file2.length();

assertEquals(origSize, newSize);

}
public void testAppend() {
test3();

File file = new File(getProjectDir(), tempFile);
final long origSize = file.length();

executeTarget("testAppend");

File file2 = new File(getProjectDir(), tempFile2);
final long newSize = file2.length();

assertEquals(origSize*2, newSize);

}

public void testFilter() {
executeTarget("testfilter");
assertTrue(getLog().indexOf("REPLACED") > -1);
}

public void testNoOverwrite() {
executeTarget("testnooverwrite");
File file2 = new File(getProjectDir(), tempFile2);
long size = file2.length();
assertEquals(size, 0);
}

public void testheaderfooter() {
test3();
expectLog("testheaderfooter", "headerHello, World!footer");
}

public void testfileheader() {
test3();
expectLog("testfileheader", "Hello, World!Hello, World!");
}

/**
* Expect an exception when attempting to cat an file to itself
*/
public void testsame() {
expectBuildException("samefile", "output file same as input");
}

/**
* Check if filter inline works
*/
public void testfilterinline() {
executeTarget("testfilterinline");
assertTrue(getLog().indexOf("REPLACED") > -1);
}

/**
* Check if multireader works
*/
public void testmultireader() {
executeTarget("testmultireader");
assertTrue(getLog().indexOf("Bye") > -1);
assertTrue(getLog().indexOf("Hello") == -1);
}
/**
* Check if fixlastline works
*/
public void testfixlastline()
throws IOException
{
expectFileContains(
"testfixlastline", "concat.line4",
"end of line" + System.getProperty("line.separator")
+ "This has");
}

/**
* Check if fixlastline works with eol
*/
public void testfixlastlineeol()
throws IOException
{
expectFileContains(
"testfixlastlineeol", "concat.linecr",
"end of line\rThis has");
}

// ------------------------------------------------------
// Helper methods - should be in BuildFileTest
// -----------------------------------------------------

private String getFileString(String filename)
throws IOException
{
Reader r = null;
try {
r = new FileReader(getProject().resolveFile(filename));
return FileUtils.readFully(r);
}
finally {
FileUtils.close(r);
}

}

private String getFileString(String target, String filename)
throws IOException
{
executeTarget(target);
return getFileString(filename);
}

private void expectFileContains(
String target, String filename, String contains)
throws IOException
{
String content = getFileString(target, filename);
assertTrue(
"expecting file " + filename + " to contain " +
contains +
" but got " + content, content.indexOf(contains) > -1);
}

public void testTranscoding() throws IOException {
executeTarget("testTranscoding");
File f1 = getProject().resolveFile("copy/expected/utf-8");
File f2 = getProject().resolveFile("concat.utf8");
assertTrue(FILE_UTILS.contentEquals(f1, f2));
}

public void testResources() {
executeTarget("testResources");
}

}

+ 275
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ConditionTest.java View File

@@ -0,0 +1,275 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

/**
* @created 13 January 2002
*/
public class ConditionTest extends BuildFileTest {

/**
* Constructor for the ConditionTest object
*
* @param name we dont know
*/
public ConditionTest(String name) {
super(name);
}


/**
* The JUnit setup method
*/
public void setUp() {
configureProject("src/etc/testcases/taskdefs/condition.xml");
}


/**
* The teardown method for JUnit
*/
public void tearDown() {
executeTarget("cleanup");
}

public void testBasic() {
expectPropertySet("basic","basic");
}

public void testConditionIncomplete() {
expectSpecificBuildException("condition-incomplete",
"property attribute has been omitted",
"The property attribute is required.");
}

public void testConditionEmpty() {
expectSpecificBuildException("condition-empty",
"no conditions",
"You must nest a condition into <condition>");
}

public void testShortcut() {
expectPropertySet("shortcut","shortcut","set");
}

public void testUnset() {
expectPropertyUnset("dontset","dontset");
}

public void testSetValue() {
expectPropertySet("setvalue","setvalue","woowoo");
}

public void testNegation() {
expectPropertySet("negation","negation");
}

public void testNegationFalse() {
expectPropertyUnset("negationfalse","negationfalse");
}

public void testNegationIncomplete() {
expectSpecificBuildException("negationincomplete",
"no conditions in <not>",
"You must nest a condition into <not>");
}

public void testAnd() {
expectPropertySet("and","and");
}

public void testAndFails() {
expectPropertyUnset("andfails","andfails");
}

public void testAndIncomplete() {
expectPropertyUnset("andincomplete","andincomplete");
}

public void testAndempty() {
expectPropertySet("andempty","andempty");
}

public void testOr() {
expectPropertySet("or","or");
}

public void testOrincomplete() {
expectPropertySet("or","or");
}

public void testOrFails() {
expectPropertyUnset("orfails","orfails");
}

public void testOrboth() {
expectPropertySet("orboth","orboth");
}

public void testFilesmatchIdentical() {
expectPropertySet("filesmatch-identical","filesmatch-identical");
}


public void testFilesmatchIncomplete() {
expectSpecificBuildException("filesmatch-incomplete",
"Missing file2 attribute",
"both file1 and file2 are required in filesmatch");
}

public void testFilesmatchOddsizes() {
expectPropertyUnset("filesmatch-oddsizes","filesmatch-oddsizes");
}

public void testFilesmatchExistence() {
expectPropertyUnset("filesmatch-existence", "filesmatch-existence");
}

public void testFilesmatchDifferent() {
expectPropertyUnset("filesmatch-different","filesmatch-different");
}

public void testFilesmatchMatch() {
expectPropertySet("filesmatch-match","filesmatch-match");
}

public void testFilesmatchDifferentSizes() {
expectPropertyUnset("filesmatch-different-sizes",
"filesmatch-different-sizes");
}

public void testFilesmatchDifferentOnemissing() {
expectPropertyUnset("filesmatch-different-onemissing",
"filesmatch-different-onemissing");
}

public void testFilesmatchDifferentEol() {
executeTarget("filesmatch-different-eol");
}

public void testFilesmatchSameEol() {
executeTarget("filesmatch-same-eol");
}

public void testFilesmatchNeitherExist() {
executeTarget("filesmatch-neitherexist");
}

public void testContains() {
expectPropertySet("contains","contains");
}


public void testContainsDoesnt() {
expectPropertyUnset("contains-doesnt","contains-doesnt");
}

public void testContainsAnycase() {
expectPropertySet("contains-anycase","contains-anycase");
}


public void testContainsIncomplete1() {
expectSpecificBuildException("contains-incomplete1",
"Missing contains attribute",
"both string and substring are required in contains");
}

public void testContainsIncomplete2() {
expectSpecificBuildException("contains-incomplete2",
"Missing contains attribute",
"both string and substring are required in contains");
}

public void testIstrue() {
expectPropertySet("istrue","istrue");
}

public void testIstrueNot() {
expectPropertyUnset("istrue-not","istrue-not");
}

public void testIstrueFalse() {
expectPropertyUnset("istrue-false","istrue-false");
}


public void testIstrueIncomplete1() {
expectSpecificBuildException("istrue-incomplete",
"Missing attribute",
"Nothing to test for truth");
}

public void testIsfalseTrue() {
expectPropertyUnset("isfalse-true","isfalse-true");
}

public void testIsfalseNot() {
expectPropertySet("isfalse-not","isfalse-not");
}

public void testIsfalseFalse() {
expectPropertySet("isfalse-false","isfalse-false");
}


public void testIsfalseIncomplete1() {
expectSpecificBuildException("isfalse-incomplete",
"Missing attribute",
"Nothing to test for falsehood");
}

public void testElse() {
executeTarget("testElse");
}

public void testResourcesmatchError() {
expectBuildException("resourcesmatch-error",
"should fail because no resources specified");
}

public void testResourcesmatchEmpty() {
executeTarget("resourcesmatch-match-empty");
}

public void testResourcesmatchOne() {
executeTarget("resourcesmatch-match-one");
}

public void testResourcesmatchBinary() {
executeTarget("resourcesmatch-match-binary");
}

public void testResourcesmatchMultipleBinary() {
executeTarget("resourcesmatch-match-multiple-binary");
}

public void testResourcesmatchDiffer() {
executeTarget("resourcesmatch-differ");
}

public void testResourcesmatchText() {
executeTarget("resourcesmatch-match-text");
}

public void testResourcesmatchNoneExist() {
executeTarget("resourcesmatch-noneexist");
}
}

+ 231
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java View File

@@ -0,0 +1,231 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
* Tests FileSet using the Copy task.
*
*/
public class CopyTest extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public CopyTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/copy.xml");
}

public void test1() {
executeTarget("test1");
File f = new File(getProjectDir(), "copytest1.tmp");
if ( !f.exists()) {
fail("Copy failed");
}
}

public void tearDown() {
executeTarget("cleanup");
}

public void test2() {
executeTarget("test2");
File f = new File(getProjectDir(), "copytest1dir/copy.xml");
if ( !f.exists()) {
fail("Copy failed");
}
}

public void test3() {
executeTarget("test3");
File file3 = new File(getProjectDir(), "copytest3.tmp");
assertTrue(file3.exists());
File file3a = new File(getProjectDir(), "copytest3a.tmp");
assertTrue(file3a.exists());
File file3b = new File(getProjectDir(), "copytest3b.tmp");
assertTrue(file3b.exists());
File file3c = new File(getProjectDir(), "copytest3c.tmp");
assertTrue(file3c.exists());

//file length checks rely on touch generating a zero byte file
if(file3.length()==0) {
fail("could not overwrite an existing, older file");
}
if(file3c.length()!=0) {
fail("could not force overwrite an existing, newer file");
}
if(file3b.length()==0) {
fail("unexpectedly overwrote an existing, newer file");
}

//file time checks for java1.2+
assertTrue(file3a.lastModified()==file3.lastModified());
assertTrue(file3c.lastModified()<file3a.lastModified());

}

public void testFilterTest() {
executeTarget("filtertest");
assertTrue(getOutput().indexOf("loop in tokens") == -1);
}

public void testInfiniteFilter() {
executeTarget("infinitetest");
assertTrue(getOutput().indexOf("loop in tokens") != -1);
}

public void testFilterSet() throws IOException {
executeTarget("testFilterSet");
File tmp = new File(getProjectDir(), "copy.filterset.tmp");
File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
assertTrue(FILE_UTILS.contentEquals(tmp, check));
}

public void testFilterChain() throws IOException {
executeTarget("testFilterChain");
File tmp = new File(getProjectDir(), "copy.filterchain.tmp");
File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
assertTrue(FILE_UTILS.contentEquals(tmp, check));
}

public void testSingleFileFileset() {
executeTarget("test_single_file_fileset");
File file = new File(getProjectDir(),
"copytest_single_file_fileset.tmp");
assertTrue(file.exists());
}

public void testSingleFilePath() {
executeTarget("test_single_file_path");
File file = new File(getProjectDir(),
"copytest_single_file_path.tmp");
assertTrue(file.exists());
}

public void testTranscoding() throws IOException {
executeTarget("testTranscoding");
File f1 = getProject().resolveFile("copy/expected/utf-8");
File f2 = getProject().resolveFile("copytest1.tmp");
assertTrue(FILE_UTILS.contentEquals(f1, f2));
}

public void testMissingFileIgnore() {
expectLogContaining("testMissingFileIgnore",
"Warning: Could not find file ");
}

public void testMissingFileBail() {
expectBuildException("testMissingFileBail", "not-there doesn't exist");
assertTrue(getBuildException().getMessage()
.startsWith("Warning: Could not find file "));
}

public void testMissingDirIgnore() {
expectLogContaining("testMissingDirIgnore", "Warning: ");
}

public void testMissingDirBail() {
expectBuildException("testMissingDirBail", "not-there doesn't exist");
assertTrue(getBuildException().getMessage().endsWith(" not found."));
}
public void testFileResourcePlain() {
executeTarget("testFileResourcePlain");
File file1 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file1.txt");
File file2 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file2.txt");
File file3 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file3.txt");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}
public void _testFileResourceWithMapper() {
executeTarget("testFileResourceWithMapper");
File file1 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file1.txt.bak");
File file2 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file2.txt.bak");
File file3 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file3.txt.bak");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}
public void testFileResourceWithFilter() {
executeTarget("testFileResourceWithFilter");
File file1 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/fileNR.txt");
assertTrue(file1.exists());
try {
String file1Content = FILE_UTILS.readFully(new FileReader(file1));
assertEquals("This is file 42", file1Content);
} catch (IOException e) {
// no-op: not a real business error
}
}
public void testPathAsResource() {
executeTarget("testPathAsResource");
File file1 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file1.txt");
File file2 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file2.txt");
File file3 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file3.txt");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}
public void testZipfileset() {
executeTarget("testZipfileset");
File file1 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file1.txt");
File file2 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file2.txt");
File file3 = new File(getProjectDir(), getProject().getProperty("to.dir")+"/file3.txt");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}

public void testDirset() {
executeTarget("testDirset");
}
public void _testResourcePlain() {
executeTarget("testResourcePlain");
}
public void _testResourcePlainWithMapper() {
executeTarget("testResourcePlainWithMapper");
}
public void _testResourcePlainWithFilter() {
executeTarget("testResourcePlainWithFilter");
}
public void _testOnlineResources() {
executeTarget("testOnlineResources");
}
}

+ 68
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/CopydirTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class CopydirTest extends BuildFileTest {

public CopydirTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/copydir.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "required argument not specified");
}

public void test2() {
expectBuildException("test2", "required argument not specified");
}

public void test3() {
expectBuildException("test3", "required argument not specified");
}

public void test4() {
expectLog("test4", "DEPRECATED - The copydir task is deprecated. Use copy instead.Warning: src == dest");
}

public void test5() {
executeTarget("test5");
java.io.File f = new java.io.File(getProjectDir(), "../taskdefs.tmp");
if (!f.exists() || !f.isDirectory()) {
fail("Copy failed");
}
// We keep this, so we have something to delete in later tests :-)
}

public void test6() {
expectBuildException("test6", "target is file");
}

}

+ 68
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/CopyfileTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class CopyfileTest extends BuildFileTest {

public void test6() {
expectBuildException("test6", "target is directory");
}

public CopyfileTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/copyfile.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "required argument not specified");
}

public void test2() {
expectBuildException("test2", "required argument not specified");
}

public void test3() {
expectBuildException("test3", "required argument not specified");
}

public void test4() {
expectLog("test4", "DEPRECATED - The copyfile task is deprecated. Use copy instead.Warning: src == dest");
}

public void test5() {
executeTarget("test5");
java.io.File f = new java.io.File(getProjectDir(), "copyfile.tmp");
if (f.exists()) {
f.delete();
} else {
fail("Copy failed");
}
}
}

+ 111
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DefaultExcludesTest.java View File

@@ -0,0 +1,111 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.DirectoryScanner;

/**
*/
public class DefaultExcludesTest extends BuildFileTest {

public DefaultExcludesTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/defaultexcludes.xml");
}

public void tearDown() {
project.executeTarget("cleanup");
}

// Output the default excludes
public void test1() {
String[] expected = {
"**/*~",
"**/#*#",
"**/.#*",
"**/%*%",
"**/._*",
"**/CVS",
"**/CVS/**",
"**/.cvsignore",
"**/SCCS",
"**/SCCS/**",
"**/vssver.scc",
"**/.svn",
"**/.svn/**",
"**/.DS_Store"};
project.executeTarget("test1");
assertEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
}

// adding something to the excludes'
public void test2() {
String[] expected = {
"**/*~",
"**/#*#",
"**/.#*",
"**/%*%",
"**/._*",
"**/CVS",
"**/CVS/**",
"**/.cvsignore",
"**/SCCS",
"**/SCCS/**",
"**/vssver.scc",
"**/.svn",
"**/.svn/**",
"**/.DS_Store",
"foo"};
project.executeTarget("test2");
assertEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
}

// removing something from the defaults
public void test3() {
String[] expected = {
"**/*~",
"**/#*#",
"**/.#*",
"**/%*%",
"**/._*",
//CVS missing
"**/CVS/**",
"**/.cvsignore",
"**/SCCS",
"**/SCCS/**",
"**/vssver.scc",
"**/.svn",
"**/.svn/**",
"**/.DS_Store"};
project.executeTarget("test3");
assertEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
}
private void assertEquals(String message, String[] expected, String[] actual) {
// check that both arrays have the same size
assertEquals(message + " : string array length match", expected.length, actual.length);
for (int counter=0; counter <expected.length; counter++) {
assertEquals(message + " : " + counter + "th element in array match", expected[counter], actual[counter]);
}

}
}

+ 83
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DeleteTest.java View File

@@ -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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class DeleteTest extends BuildFileTest {

public DeleteTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/delete.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "required argument not specified");
}

public void test2() {
executeTarget("test2");
}
//where oh where has my test case 3 gone?
public void test4() {
executeTarget("test4");
}
public void test5() {
executeTarget("test5");
}
public void test6() {
executeTarget("test6");
}
public void test7() {
executeTarget("test7");
}
public void test8() {
executeTarget("test8");
}
public void test9() {
executeTarget("test9");
}
public void test10() {
executeTarget("test10");
}
public void test11() {
executeTarget("test11");
}
public void test12() {
executeTarget("test12");
}
public void test13() {
executeTarget("test13");
}
public void test14() {
executeTarget("test14");
}
public void test15() {
executeTarget("test15");
}
}

+ 44
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DeltreeTest.java View File

@@ -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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class DeltreeTest extends BuildFileTest {

public DeltreeTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/deltree.xml");
}

public void test1() {
expectBuildException("test1", "required argument not specified");
}

public void test2() {
// We try to delete the directory created in CopydirTest
executeTarget("test2");
}

}

+ 75
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DemuxOutputTask.java View File

@@ -0,0 +1,75 @@
/*
* 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;

import java.util.Random;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

/**
* A simple task that prints to System.out and System.err and then catches
* the output which it then checks. If the output does not match, an
* exception is thrown
*
* @since 1.5
* @created 21 February 2002
*/
public class DemuxOutputTask extends Task {
private String randomOutValue;
private String randomErrValue;
private boolean outputReceived = false;
private boolean errorReceived = false;

public void execute() {
Random generator = new Random();
randomOutValue = "Output Value is " + generator.nextInt();
randomErrValue = "Error Value is " + generator.nextInt();

System.out.println(randomOutValue);
System.err.println(randomErrValue);
if (!outputReceived) {
throw new BuildException("Did not receive output");
}

if (!errorReceived) {
throw new BuildException("Did not receive error");
}
}

protected void handleOutput(String line) {
line = line.trim();
if (line.length() != 0 && !line.equals(randomOutValue)) {
String message = "Received = [" + line + "], expected = ["
+ randomOutValue + "]";
throw new BuildException(message);
}
outputReceived = true;
}

protected void handleErrorOutput(String line) {
line = line.trim();
if (line.length() != 0 && !line.equals(randomErrValue)) {
String message = "Received = [" + line + "], expected = ["
+ randomErrValue + "]";
throw new BuildException(message);
}
errorReceived = true;
}
}


+ 70
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DependSetTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;

/**
* Tests DependSet.
*
*/
public class DependSetTest extends BuildFileTest {

public DependSetTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/dependset.xml");
}

public void test1() {
expectBuildException("test1","At least one <srcfileset> or <srcfilelist> element must be set");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test2() {
expectBuildException("test2","At least one <targetfileset> or <targetfilelist> element must be set");
}

public void test3() {
expectBuildException("test1","At least one <srcfileset> or <srcfilelist> element must be set");
}

public void test4() {
executeTarget("test4");
}

public void test5() {
executeTarget("test5");
}

public void test6() {
executeTarget("test6");
}
public void test7() {
executeTarget("test7");
}
public void test8() {
executeTarget("test8");
}
}

+ 70
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DirnameTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.taskdefs.condition.Os;

/**
*/
public class DirnameTest extends BuildFileTest {

public DirnameTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/dirname.xml");
}

public void test1() {
expectBuildException("test1", "required attribute missing");
}

public void test2() {
expectBuildException("test2", "required attribute missing");
}

public void test3() {
expectBuildException("test3", "required attribute missing");
}

public void test4() {
if (Os.isFamily("netware") || Os.isFamily("dos")) {
return;
}
executeTarget("test4");
String filesep = System.getProperty("file.separator");
String expected = filesep + "usr" + filesep + "local";
String checkprop = project.getProperty("local.dir");
if (!checkprop.equals(expected)) {
fail("dirname failed");
}
}

public void test5() {
executeTarget("test5");
String expected = project.getProperty("basedir");
String checkprop = project.getProperty("base.dir");
if (!checkprop.equals(expected)) {
fail("dirname failed");
}
}

}

+ 46
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTask.java View File

@@ -0,0 +1,46 @@
/*
* 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;

import org.apache.tools.ant.DynamicConfigurator;
import org.apache.tools.ant.Task;

public class DynamicTask extends Task implements DynamicConfigurator {

public void execute() {
}

public void setDynamicAttribute(String name, String value) {
getProject().setNewProperty(name, value);
}

public Object createDynamicElement(String name) {
return new Sub();
}

public class Sub implements DynamicConfigurator {
public void setDynamicAttribute(String name, String value) {
getProject().setNewProperty(name, value);
}

public Object createDynamicElement(String name) {
return null;
}
}
}

+ 40
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;

public class DynamicTest extends BuildFileTest {

public DynamicTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/dynamictask.xml");
}

public void testSimple() {
executeTarget("simple");
assertEquals("1", project.getProperty("prop1"));
assertEquals("2", project.getProperty("prop2"));
assertEquals("3", project.getProperty("prop3"));
assertEquals("4", project.getProperty("prop4"));
}
}

+ 77
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/EchoTest.java View File

@@ -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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class EchoTest extends BuildFileTest {

public EchoTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/echo.xml");
}

public void tearDown() {
executeTarget("clean");
}

// Output an empty String
public void test1() {
expectLog("test1", "");
}

// Output 'OUTPUT OF ECHO'
public void test2() {
expectLog("test2", "OUTPUT OF ECHO");
}

public void test3() {
expectLog("test3", "\n"+
" This \n"+
" is\n"+
" a \n"+
" multiline\n"+
" message\n"+
" ");
}

public void testFile() throws Exception {
executeTarget("testFile");
}

public void testAppend() throws Exception {
executeTarget("testAppend");
}

public void testEmptyEncoding() throws Exception {
executeTarget("testEmptyEncoding");
}

public void testUTF16Encoding() throws Exception {
executeTarget("testUTF16Encoding");
}
public void testUTF8Encoding() throws Exception {
executeTarget("testUTF8Encoding");
}
}

+ 49
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/EchoXMLTest.java View File

@@ -0,0 +1,49 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

public class EchoXMLTest extends BuildFileTest {

public EchoXMLTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/echoxml.xml");
}

public void tearDown() {
executeTarget("tearDown");
}

public void testPass() {
executeTarget("testPass");
}

public void testFail() {
expectBuildExceptionContaining("testFail", "must fail", "${foo}=bar");
}

public void testEmpty() {
expectBuildExceptionContaining("testEmpty", "must fail", "No nested XML specified");
}

}

+ 491
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ExecTaskTest.java View File

@@ -0,0 +1,491 @@
/*
* 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;

import org.apache.tools.ant.*;
import org.apache.tools.ant.util.FileUtils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.GregorianCalendar;

import junit.framework.ComparisonFailure;

/**
* Unit test for the &lt;exec&gt; task.
*/
public class ExecTaskTest extends BuildFileTest {
private static final String BUILD_PATH = "src/etc/testcases/taskdefs/exec/";
private static final String BUILD_FILE = BUILD_PATH + "exec.xml";
private static final int TIME_TO_WAIT = 1;
/** maximum time allowed for the build in milliseconds */
private static final int MAX_BUILD_TIME = 4000;
private static final int SECURITY_MARGIN = 2000; // wait 2 second extras
// the test failed with 100 ms of margin on cvs.apache.org on August 1st, 2003

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

private File logFile;
private MonitoredBuild myBuild = null;
volatile private boolean buildFinished = false;
public ExecTaskTest(String name) {
super(name);
}

public void setUp() {
configureProject(BUILD_FILE);
}

public void tearDown() {
if (logFile != null && logFile.exists()) {
getProject().setProperty("logFile", logFile.getAbsolutePath());
}
executeTarget("cleanup");
}

public void testNoRedirect() {
executeTarget("no-redirect");
if (getProject().getProperty("test.can.run") == null) {
return;
}
assertEquals("unexpected log content",
getProject().getProperty("ant.file") + " out"
+ getProject().getProperty("ant.file") + " err", getLog());
}

public void testRedirect1() throws IOException {
executeTarget("redirect1");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String expectedOut = getProject().getProperty("ant.file") + " out\n"
+ getProject().getProperty("ant.file") + " err\n";

assertEquals("unexpected output",
expectedOut, getFileString("redirect.out"));
}

public void testRedirect2() throws IOException {
executeTarget("redirect2");
if (getProject().getProperty("test.can.run") == null) {
return;
}

assertEquals("unexpected output",
getProject().getProperty("ant.file") + " out\n",
getFileString("redirect.out"));
assertEquals("unexpected error output",
getProject().getProperty("ant.file") + " err\n",
getFileString("redirect.err"));
}

public void testRedirect3() throws IOException {
executeTarget("redirect3");
if (getProject().getProperty("test.can.run") == null) {
return;
}
assertEquals("unexpected log content",
getProject().getProperty("ant.file") + " err", getLog());
String expectedOut = getProject().getProperty("ant.file") + " out\n";

assertEquals("unexpected output",
expectedOut, getFileString("redirect.out"));
assertPropertyEquals("redirect.out", expectedOut.trim());
}

public void testRedirect4() throws IOException {
executeTarget("redirect4");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String expectedOut = getProject().getProperty("ant.file") + " out\n";
String expectedErr = getProject().getProperty("ant.file") + " err\n";

assertEquals("unexpected output",
expectedOut, getFileString("redirect.out"));
assertPropertyEquals("redirect.out", expectedOut.trim());
assertEquals("unexpected error output",
expectedErr, getFileString("redirect.err"));
assertPropertyEquals("redirect.err", expectedErr.trim());
}

public void testRedirect5() throws IOException {
testRedirect5or6("redirect5");
}

public void testRedirect6() throws IOException {
testRedirect5or6("redirect6");
}

public void testRedirect5or6(String target) throws IOException {
executeTarget(target);
if (getProject().getProperty("wc.can.run") == null) {
return;
}

assertEquals("unexpected output", "3", getFileString("redirect.out").trim());
assertEquals("property redirect.out", "3",
getProject().getProperty("redirect.out").trim());
assertNull("unexpected error output", getFileString("redirect.err"));
assertPropertyEquals("redirect.err", "");
}

public void testRedirect7() throws IOException {
executeTarget("redirect7");
if (getProject().getProperty("wc.can.run") == null) {
return;
}

assertEquals("unexpected output", "3", getFileString("redirect.out").trim());
assertEquals("property redirect.out", "3",
getProject().getProperty("redirect.out").trim());
assertNull("unexpected error output", getFileString("redirect.err"));
}

public void testRedirector1() {
executeTarget("init");
if (getProject().getProperty("test.can.run") == null) {
return;
}
expectBuildException("redirector1", "cannot have > 1 nested <redirector>s");
}

public void testRedirector2() throws IOException {
executeTarget("redirector2");
if (getProject().getProperty("test.can.run") == null) {
return;
}

assertEquals("unexpected output",
getProject().getProperty("ant.file") + " out\n"
+ getProject().getProperty("ant.file") + " err\n",
getFileString("redirector.out"));
}

public void testRedirector3() throws IOException {
executeTarget("redirector3");
if (getProject().getProperty("test.can.run") == null) {
return;
}

assertEquals("unexpected output",
getProject().getProperty("ant.file") + " out\n",
getFileString("redirector.out"));
assertEquals("unexpected error output",
getProject().getProperty("ant.file") + " err\n",
getFileString("redirector.err"));
}

public void testRedirector4() throws IOException {
executeTarget("redirector4");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String expectedOut = getProject().getProperty("ant.file") + " out\n";

assertEquals("unexpected log content",
getProject().getProperty("ant.file") + " err", getLog());
assertEquals("unexpected output", expectedOut,
getFileString("redirector.out"));
assertPropertyEquals("redirector.out", expectedOut.trim());
}

public void testRedirector5() throws IOException {
testRedirector5or6("redirector5");
}

public void testRedirector6() throws IOException {
testRedirector5or6("redirector6");
}

private void testRedirector5or6(String target) throws IOException {
executeTarget(target);
if (getProject().getProperty("test.can.run") == null) {
return;
}
String expectedOut = getProject().getProperty("ant.file") + " out\n";
String expectedErr = getProject().getProperty("ant.file") + " err\n";

assertEquals("unexpected output", expectedOut,
getFileString("redirector.out"));
assertPropertyEquals("redirector.out", expectedOut.trim());
assertEquals("unexpected error output", expectedErr,
getFileString("redirector.err"));
assertPropertyEquals("redirector.err", expectedErr.trim());
}

public void testRedirector7() throws IOException {
executeTarget("redirector7");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String expectedOut = getProject().getProperty("ant.file") + " out\n";
String expectedErr = getProject().getProperty("ant.file") + " ERROR!!!\n";

assertEquals("unexpected output", expectedOut,
getFileString("redirector.out"));
assertPropertyEquals("redirector.out", expectedOut.trim());
assertEquals("unexpected error output", expectedErr,
getFileString("redirector.err"));
assertPropertyEquals("redirector.err", expectedErr.trim());
}

public void testRedirector8() throws IOException {
executeTarget("redirector8");
if (getProject().getProperty("wc.can.run") == null) {
return;
}

assertEquals("unexpected output", "3", getFileString("redirector.out").trim());
assertEquals("property redirector.out", "3",
getProject().getProperty("redirector.out").trim());
assertNull("unexpected error output", getFileString("redirector.err"));
assertPropertyEquals("redirector.err", "");
}

public void testRedirector9() throws IOException {
testRedirector9Thru12("redirector9");
}

public void testRedirector10() throws IOException {
testRedirector9Thru12("redirector10");
}

public void testRedirector11() throws IOException {
testRedirector9Thru12("redirector11");
}

public void testRedirector12() throws IOException {
testRedirector9Thru12("redirector12");
}

private void testRedirector9Thru12(String target) throws IOException {
executeTarget(target);
if (getProject().getProperty("cat.can.run") == null) {
return;
}
String expectedOut = "blah after blah";

assertEquals("unexpected output",
expectedOut, getFileString("redirector.out").trim());
assertPropertyEquals("redirector.out", expectedOut.trim());
assertNull("unexpected error output", getFileString("redirector.err"));
assertPropertyEquals("redirector.err", "");
}

public void testRedirector13() {
executeTarget("redirector13");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String antfile = getProject().getProperty("ant.file");
try {
//no point in setting a message
assertEquals(antfile + " OUTPUT???" + antfile + " ERROR!!!", getLog());
} catch (ComparisonFailure cf) {
assertEquals("unexpected log content",
antfile + " ERROR!!!" + antfile + " OUTPUT???", getLog());
}
}

public void testRedirector14() {
executeTarget("redirector14");
if (getProject().getProperty("cat.can.run") == null) {
return;
}
assertEquals("unexpected log output", "blah after blah", getLog());
}

public void testRedirector15() throws IOException {
executeTarget("redirector15");
if (getProject().getProperty("cat.can.run") == null) {
return;
}
assertTrue("error with transcoding",
FILE_UTILS.contentEquals(
getProject().resolveFile("expected/utf-8"),
getProject().resolveFile("redirector.out")));
}

public void testRedirector16() {
executeTarget("redirector16");
}

public void testRedirector17() {
executeTarget("redirector17");
}

public void testRedirector18() {
if (getProject().getProperty("test.can.run") == null) {
return;
}
expectLog("redirector18", getProject().getProperty("ant.file")
+ " out" + getProject().getProperty("ant.file") + " err");
}

public void testspawn() {
project.executeTarget("init");
if (project.getProperty("test.can.run") == null) {
return;
}
myBuild = new MonitoredBuild(new File(System.getProperty("root"), BUILD_FILE), "spawn");
logFile = FILE_UTILS.createTempFile("spawn","log", project.getBaseDir());
// this is guaranteed by FileUtils#createTempFile
assertTrue("log file not existing", !logFile.exists());
// make the spawned process run 4 seconds
myBuild.setTimeToWait(TIME_TO_WAIT);
myBuild.setLogFile(logFile.getAbsolutePath());
myBuild.addBuildListener(new MonitoredBuildListener());
myBuild.start();
GregorianCalendar startwait = new GregorianCalendar();
// this loop runs parallel to the build
while (!buildFinished) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println("my sleep was interrupted");
}
GregorianCalendar now = new GregorianCalendar();
// security
if (now.getTime().getTime() - startwait.getTime().getTime() > MAX_BUILD_TIME) {
System.out.println("aborting wait, too long " + (now.getTime().getTime() - startwait.getTime().getTime()) + "milliseconds");
break;
}
}
// now wait until the spawned process is finished
try {
Thread.sleep((TIME_TO_WAIT) * 1000 + SECURITY_MARGIN);
} catch (InterruptedException e) {
System.out.println("my sleep was interrupted");
}
// time of the build in milli seconds
long elapsed = myBuild.getTimeElapsed();
assertTrue("we waited more than the process lasted", TIME_TO_WAIT * 1000
+ SECURITY_MARGIN > elapsed);
logFile = new File(logFile.getAbsolutePath());
assertTrue("log file found after spawn", logFile.exists());
}

public void testExecUnknownOS() {
executeTarget("testExecUnknownOS");
}

public void testExecOSFamily() {
executeTarget("testExecOSFamily");
}

public void testExecInconsistentSettings() {
executeTarget("testExecInconsistentSettings");
}
private static class MonitoredBuild implements Runnable {
private Thread worker;
private File myBuildFile = null;
private String target = null;
private Project project = null;
private int timeToWait = 0;
private String logFile = null;
private GregorianCalendar timeStarted = null;
private GregorianCalendar timeFinished = null;

public void setLogFile(String logFile) {
this.logFile = logFile;
project.setProperty("logFile", logFile);
}

public void setTimeToWait(int timeToWait) {
this.timeToWait = timeToWait;
project.setProperty("timeToWait", Long.toString(timeToWait));
}

public void addBuildListener(BuildListener bl) {
project.addBuildListener(bl);
}
public MonitoredBuild(File buildFile, String target) {
myBuildFile = buildFile;
this.target = target;
project=new Project();
project = new Project();
project.init();
project.setUserProperty( "ant.file" , myBuildFile.getAbsolutePath() );
ProjectHelper.configureProject(project, myBuildFile);
}
/**
*
* @return time in millis of the build
*/
public long getTimeElapsed() {
return timeFinished.getTime().getTime() - timeStarted.getTime().getTime();
}
public void start() {
worker = new Thread(this, myBuildFile.toString() + "/" + target);
worker.start();
}
public void run() {
startProject();
}
private void startProject() {
timeStarted = new GregorianCalendar();
project.executeTarget(target);
timeFinished = new GregorianCalendar();
}
}
private class MonitoredBuildListener implements BuildListener {
public void buildStarted(BuildEvent event) {
}

public void buildFinished(BuildEvent event) {
}

public void targetStarted(BuildEvent event) {
}

public void targetFinished(BuildEvent event) {
if (event.getTarget().getName().equals("spawn")) {
buildFinished = true;
}
}

public void taskStarted(BuildEvent event) {
}

public void taskFinished(BuildEvent event) {
}

public void messageLogged(BuildEvent event) {
}
}

//borrowed from TokenFilterTest
private String getFileString(String filename) throws IOException {
String result = null;
FileReader reader = null;
try {
reader = new FileReader(getProject().resolveFile(filename));
result = FileUtils.readFully(reader);
} catch (IOException eyeOhEx) {
} finally {
FileUtils.close(reader);
}
return result;
}

}

+ 136
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteJavaTest.java View File

@@ -0,0 +1,136 @@
/*
* 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;

import org.apache.tools.ant.MagicNames;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.taskdefs.condition.Os;
import org.apache.tools.ant.util.JavaEnvUtils;

import junit.framework.TestCase;

/**
* Simple testcase for the ExecuteJava class - mostly stolen from
* ExecuteWatchdogTest.
*
*/
public class ExecuteJavaTest extends TestCase {

private final static int TIME_OUT = 5000;

private final static int CLOCK_ERROR=200;
private final static int TIME_OUT_TEST=TIME_OUT-CLOCK_ERROR;

private ExecuteJava ej;
private Project project;
private Path cp;

public ExecuteJavaTest(String name) {
super(name);
}

protected void setUp(){
ej = new ExecuteJava();
ej.setTimeout(new Long(TIME_OUT));
project = new Project();
project.setBasedir(".");
project.setProperty(MagicNames.ANT_HOME, System.getProperty(MagicNames.ANT_HOME));
cp = new Path(project, getTestClassPath());
ej.setClasspath(cp);
}

private Commandline getCommandline(int timetorun) throws Exception {
Commandline cmd = new Commandline();
cmd.setExecutable(TimeProcess.class.getName());
cmd.createArgument().setValue(String.valueOf(timetorun));
return cmd;
}

public void testNoTimeOut() throws Exception {
Commandline cmd = getCommandline(TIME_OUT/2);
ej.setJavaCommand(cmd);
ej.execute(project);
assertTrue("process should not have been killed", !ej.killedProcess());
}

// test that the watchdog ends the process
public void testTimeOut() throws Exception {
Commandline cmd = getCommandline(TIME_OUT*2);
ej.setJavaCommand(cmd);
long now = System.currentTimeMillis();
ej.execute(project);
long elapsed = System.currentTimeMillis() - now;
assertTrue("process should have been killed", ej.killedProcess());

assertTrue("elapse time of "+elapsed
+" ms is less than timeout value of "+TIME_OUT_TEST+" ms",
elapsed >= TIME_OUT_TEST);
assertTrue("elapse time of "+elapsed
+" ms is greater than run value of "+(TIME_OUT*2)+" ms",
elapsed < TIME_OUT*2);
}


public void testNoTimeOutForked() throws Exception {
Commandline cmd = getCommandline(TIME_OUT/2);
ej.setJavaCommand(cmd);
ej.fork(cp);
assertTrue("process should not have been killed", !ej.killedProcess());
}

// test that the watchdog ends the process
public void testTimeOutForked() throws Exception {
//process doesn't die properly under this combination,
//thus test fails. No workaround?
if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_2)
&& Os.isFamily("dos")) {
return;
}
Commandline cmd = getCommandline(TIME_OUT*2);
ej.setJavaCommand(cmd);
long now = System.currentTimeMillis();
ej.fork(cp);
long elapsed = System.currentTimeMillis() - now;
assertTrue("process should have been killed", ej.killedProcess());

assertTrue("elapse time of "+elapsed
+" ms is less than timeout value of "+TIME_OUT_TEST+" ms",
elapsed >= TIME_OUT_TEST);
assertTrue("elapse time of "+elapsed
+" ms is greater than run value of "+(TIME_OUT*2)+" ms",
elapsed < TIME_OUT*2);
}

/**
* Dangerous method to obtain the classpath for the test. This is
* severely tighted to the build.xml properties.
*/
private static String getTestClassPath(){
String classpath = System.getProperty("build.tests");
if (classpath == null) {
System.err.println("WARNING: 'build.tests' property is not available !");
classpath = System.getProperty("java.class.path");
}

return classpath;
}

}

+ 599
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteOnTest.java View File

@@ -0,0 +1,599 @@
/*
* 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;

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;

/**
* Unit test for the &lt;apply&gt; task.
*/
public class ExecuteOnTest extends BuildFileTest {
private static final String BUILD_PATH = "src/etc/testcases/taskdefs/exec/";
private static final String BUILD_FILE = BUILD_PATH + "apply.xml";
private static final String LINE_SEP = System.getProperty("line.separator");
public ExecuteOnTest(String name) {
super(name);
}

public void setUp() {
configureProject(BUILD_FILE);
}

public void tearDown() {
executeTarget("cleanup");
}

public void testNoRedirect() {
executeTarget("no-redirect");
if (getProject().getProperty("test.can.run") == null) {
return;
}

String log = getLog();
File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = log.indexOf(x + " out");
int yout = log.indexOf(y + " out");
int zout = log.indexOf(z + " out");
int xerr = log.indexOf(x + " err");
int yerr = log.indexOf(y + " err");
int zerr = log.indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);
}

public void testRedirect1() throws IOException {
executeTarget("redirect1");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String actualOut = getFileString("redirect.out");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = actualOut.indexOf(x + " err");
int yerr = actualOut.indexOf(y + " err");
int zerr = actualOut.indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);
}

public void testRedirect2() throws IOException {
executeTarget("redirect2");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String actualOut = getFileString("redirect.out");
String actualErr = getFileString("redirect.err");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = actualErr.indexOf(x + " err");
int yerr = actualErr.indexOf(y + " err");
int zerr = actualErr.indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);
}

public void testRedirect3() throws IOException {
executeTarget("redirect3");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String actualOut = getFileString("redirect.out");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = getLog().indexOf(x + " err");
int yerr = getLog().indexOf(y + " err");
int zerr = getLog().indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);

String outProperty = getProject().getProperty("redirect.out");
int pxout = outProperty.indexOf(x + " out");
int pyout = outProperty.indexOf(y + " out");
int pzout = outProperty.indexOf(z + " out");
assertFalse("pxout=" + pxout, pxout < 0);
assertFalse("pyout=" + pyout, pyout < 0);
assertFalse("pzout=" + pzout, pzout < 0);
assertFalse("pyout < pxout", pyout < pxout);
assertFalse("pzout < pyout", pzout < pyout);
}

public void testRedirect4() throws IOException {
executeTarget("redirect4");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String actualOut = getFileString("redirect.out");
String actualErr = getFileString("redirect.err");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = actualErr.indexOf(x + " err");
int yerr = actualErr.indexOf(y + " err");
int zerr = actualErr.indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);

String outProperty = getProject().getProperty("redirect.out");
int pxout = outProperty.indexOf(x + " out");
int pyout = outProperty.indexOf(y + " out");
int pzout = outProperty.indexOf(z + " out");
assertFalse("pxout=" + pxout, pxout < 0);
assertFalse("pyout=" + pyout, pyout < 0);
assertFalse("pzout=" + pzout, pzout < 0);
assertFalse("pyout < pxout", pyout < pxout);
assertFalse("pzout < pyout", pzout < pyout);

String errorProperty = getProject().getProperty("redirect.err");
int pxerr = errorProperty.indexOf(x + " err");
int pyerr = errorProperty.indexOf(y + " err");
int pzerr = errorProperty.indexOf(z + " err");
assertFalse("pxerr=" + pxerr, pxerr < 0);
assertFalse("pyerr=" + pyerr, pyerr < 0);
assertFalse("pzerr=" + pzerr, pzerr < 0);
assertFalse("pyerr < pxerr", pyerr < pxerr);
assertFalse("pzerr < pyerr", pzerr < pyerr);
}

public void testRedirect5() throws IOException {
testRedirect5or6("redirect5");
}

public void testRedirect6() throws IOException {
testRedirect5or6("redirect6");
}

private void testRedirect5or6(String target) throws IOException {
executeTarget(target);
if (getProject().getProperty("sed.can.run") == null) {
return;
}

assertPropertyEquals("redirect.out", getProject().replaceProperties(
"blah y z${line.separator}x blah z${line.separator}x y blah"));
assertPropertyEquals("redirect.err", "");
assertEquals("unexpected output",
"blah y z\nx blah z\nx y blah\n", getFileString("redirect.out"));
assertNull("unexpected error output", getFileString("redirect.err"));
}

public void testRedirect7() throws IOException {
executeTarget("redirect7");
if (getProject().getProperty("sed.can.run") == null) {
return;
}

assertPropertyEquals("redirect.out", "blah y z");
assertPropertyUnset("redirect.err");
assertEquals("unexpected output",
"x y blah\n", getFileString("redirect.out"));
assertNull("unexpected error output", getFileString("redirect.err"));
}

public void testRedirector1() {
executeTarget("init");
if (getProject().getProperty("test.can.run") == null) {
return;
}
expectBuildException("redirector1", "cannot have > 1 nested <redirector>s");
}

public void testRedirector2() throws IOException {
executeTarget("redirector2");
if (getProject().getProperty("test.can.run") == null) {
return;
}

String actualOut = getFileString("redirector.out");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = actualOut.indexOf(x + " err");
int yerr = actualOut.indexOf(y + " err");
int zerr = actualOut.indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);
}

public void testRedirector3() throws IOException {
executeTarget("redirector3");
if (getProject().getProperty("test.can.run") == null) {
return;
}

String actualOut = getFileString("redirector.out");
String actualErr = getFileString("redirector.err");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = actualErr.indexOf(x + " err");
int yerr = actualErr.indexOf(y + " err");
int zerr = actualErr.indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);
}

public void testRedirector4() throws IOException {
executeTarget("redirector4");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String actualOut = getFileString("redirector.out");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = getLog().indexOf(x + " err");
int yerr = getLog().indexOf(y + " err");
int zerr = getLog().indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);

String outProperty = getProject().getProperty("redirector.out");
int pxout = outProperty.indexOf(x + " out");
int pyout = outProperty.indexOf(y + " out");
int pzout = outProperty.indexOf(z + " out");
assertFalse("pxout=" + pxout, pxout < 0);
assertFalse("pyout=" + pyout, pyout < 0);
assertFalse("pzout=" + pzout, pzout < 0);
assertFalse("pyout < pxout", pyout < pxout);
assertFalse("pzout < pyout", pzout < pyout);
}

public void testRedirector5() throws IOException {
testRedirector5or6("redirector5");
}

public void testRedirector6() throws IOException {
testRedirector5or6("redirector6");
}

private void testRedirector5or6(String target) throws IOException {
executeTarget(target);
if (getProject().getProperty("test.can.run") == null) {
return;
}
String actualOut = getFileString("redirector.out");
String actualErr = getFileString("redirector.err");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = actualErr.indexOf(x + " err");
int yerr = actualErr.indexOf(y + " err");
int zerr = actualErr.indexOf(z + " err");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);

String outProperty = getProject().getProperty("redirector.out");
int pxout = outProperty.indexOf(x + " out");
int pyout = outProperty.indexOf(y + " out");
int pzout = outProperty.indexOf(z + " out");
assertFalse("pxout=" + pxout, pxout < 0);
assertFalse("pyout=" + pyout, pyout < 0);
assertFalse("pzout=" + pzout, pzout < 0);
assertFalse("pyout < pxout", pyout < pxout);
assertFalse("pzout < pyout", pzout < pyout);

String errorProperty = getProject().getProperty("redirector.err");
int pxerr = errorProperty.indexOf(x + " err");
int pyerr = errorProperty.indexOf(y + " err");
int pzerr = errorProperty.indexOf(z + " err");
assertFalse("pxerr=" + pxerr, pxerr < 0);
assertFalse("pyerr=" + pyerr, pyerr < 0);
assertFalse("pzerr=" + pzerr, pzerr < 0);
assertFalse("pyerr < pxerr", pyerr < pxerr);
assertFalse("pzerr < pyerr", pzerr < pyerr);
}

public void testRedirector7() throws IOException {
executeTarget("redirector7");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String actualOut = getFileString("redirector.out");
String actualErr = getFileString("redirector.err");

File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = actualOut.indexOf(x + " out");
int yout = actualOut.indexOf(y + " out");
int zout = actualOut.indexOf(z + " out");
int xerr = actualErr.indexOf(x + " ERROR!!!");
int yerr = actualErr.indexOf(y + " ERROR!!!");
int zerr = actualErr.indexOf(z + " ERROR!!!");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);

String outProperty = getProject().getProperty("redirector.out");
int pxout = outProperty.indexOf(x + " out");
int pyout = outProperty.indexOf(y + " out");
int pzout = outProperty.indexOf(z + " out");
assertFalse("pxout=" + pxout, pxout < 0);
assertFalse("pyout=" + pyout, pyout < 0);
assertFalse("pzout=" + pzout, pzout < 0);
assertFalse("pyout < pxout", pyout < pxout);
assertFalse("pzout < pyout", pzout < pyout);

String errorProperty = getProject().getProperty("redirector.err");
int pxerr = errorProperty.indexOf(x + " ERROR!!!");
int pyerr = errorProperty.indexOf(y + " ERROR!!!");
int pzerr = errorProperty.indexOf(z + " ERROR!!!");
assertFalse("pxerr=" + pxerr, pxerr < 0);
assertFalse("pyerr=" + pyerr, pyerr < 0);
assertFalse("pzerr=" + pzerr, pzerr < 0);
assertFalse("pyerr < pxerr", pyerr < pxerr);
assertFalse("pzerr < pyerr", pzerr < pyerr);
}

public void testRedirector8() throws IOException {
executeTarget("redirector8");
if (getProject().getProperty("sed.can.run") == null) {
return;
}

assertPropertyEquals("redirector.out", getProject().replaceProperties(
"blah y z${line.separator}x blah z${line.separator}x y blah"));
assertPropertyEquals("redirector.err", "");
assertEquals("unexpected output",
"blah y z\nx blah z\nx y blah\n", getFileString("redirector.out"));
assertNull("unexpected error output", getFileString("redirector.err"));
}

public void testRedirector9() throws IOException {
testRedirector9Thru12("redirector9");
}

public void testRedirector10() throws IOException {
testRedirector9Thru12("redirector10");
}

public void testRedirector11() throws IOException {
testRedirector9Thru12("redirector11");
}

public void testRedirector12() throws IOException {
testRedirector9Thru12("redirector12");
}

private void testRedirector9Thru12(String target) throws IOException {
executeTarget(target);
if (getProject().getProperty("sed.can.run") == null) {
return;
}

assertNull("unexpected error output", getFileString("redirector.err"));
assertPropertyEquals("redirector.out", getProject().replaceProperties(
"blah after y after z${line.separator}x after blah after z"
+ "${line.separator}x after y after blah"));
assertPropertyEquals("redirector.err", "");
assertEquals("unexpected output",
"blah after y after z\nx after blah after z"
+ "\nx after y after blah\n", getFileString("redirector.out"));
}

public void testRedirector13() {
executeTarget("redirector13");
if (getProject().getProperty("test.can.run") == null) {
return;
}
String log = getLog();
File x = getProject().resolveFile("x");
File y = getProject().resolveFile("y");
File z = getProject().resolveFile("z");
int xout = log.indexOf(x + " OUTPUT???");
int yout = log.indexOf(y + " OUTPUT???");
int zout = log.indexOf(z + " OUTPUT???");
int xerr = log.indexOf(x + " ERROR!!!");
int yerr = log.indexOf(y + " ERROR!!!");
int zerr = log.indexOf(z + " ERROR!!!");
assertFalse("xout=" + xout, xout < 0);
assertFalse("yout=" + yout, yout < 0);
assertFalse("zout=" + zout, zout < 0);
assertFalse("xerr=" + xerr, xerr < 0);
assertFalse("yerr=" + yerr, yerr < 0);
assertFalse("zerr=" + zerr, zerr < 0);
assertFalse("yout < xout", yout < xout);
assertFalse("zout < yout", zout < yout);
assertFalse("yerr < xerr", yerr < xerr);
assertFalse("zerr < yerr", zerr < yerr);
}

public void testRedirector14() throws IOException {
executeTarget("redirector14");
if (getProject().getProperty("sed.can.run") == null) {
return;
}

assertEquals("unexpected log content",
"z after y after blahx after y after blah", getLog());

assertEquals("unexpected redirector.out content",
"x after blah after z\n", getFileString("redirector.out"));

assertNull("unexpected redirector.err content", getFileString("redirector.err"));
}

public void testIgnoreMissing() {
executeTarget("ignoremissing");
}

public void testForce() {
executeTarget("force");
}

public void testNoDest() {
executeTarget("testNoDest");
}

public void testLsPath() {
testLsPath("lsPath");
}

public void testLsPathParallel() {
testLsPath("lsPathParallel");
}

private void testLsPath(String target) {
executeTarget(target);
if (getProject().getProperty("ls.can.run") == null) {
return;
}
String foo = getProject().getProperty("foo");
assertNotNull(foo);
int indNoExt = foo.indexOf("ls" + LINE_SEP);
int indExe = foo.indexOf("ls.exe" + LINE_SEP);
assertTrue(indNoExt >= 0 || indExe >= 0);
}

//borrowed from TokenFilterTest
private String getFileString(String filename) throws IOException {
String result = null;
FileReader reader = null;
try {
reader = new FileReader(getProject().resolveFile(filename));
result = FileUtils.readFully(reader);
} finally {
FileUtils.close(reader);
}
return result;
}

}

+ 153
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteWatchdogTest.java View File

@@ -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;

import org.apache.tools.ant.util.JavaEnvUtils;
import junit.framework.*;
import java.io.*;

/**
* Simple testcase for the ExecuteWatchdog class.
*
*/
public class ExecuteWatchdogTest extends TestCase {

private final static long TIME_OUT = 5000;

private final static String TEST_CLASSPATH = getTestClassPath();

private final static int CLOCK_ERROR=200;
private final static long TIME_OUT_TEST=TIME_OUT-CLOCK_ERROR;

private ExecuteWatchdog watchdog;

public ExecuteWatchdogTest(String name) {
super(name);
}

protected void setUp(){
watchdog = new ExecuteWatchdog(TIME_OUT);
}

/**
* Dangerous method to obtain the classpath for the test. This is
* severely tighted to the build.xml properties.
*/
private static String getTestClassPath(){
String classpath = System.getProperty("build.tests");
if (classpath == null) {
System.err.println("WARNING: 'build.tests' property is not available !");
classpath = System.getProperty("java.class.path");
}

return classpath;
}

private Process getProcess(long timetorun) throws Exception {
String[] cmdArray = {
JavaEnvUtils.getJreExecutable("java"), "-classpath", TEST_CLASSPATH,
TimeProcess.class.getName(), String.valueOf(timetorun)
};
//System.out.println("Testing with classpath: " + System.getProperty("java.class.path"));
return Runtime.getRuntime().exec(cmdArray);
}

private String getErrorOutput(Process p) throws Exception {
BufferedReader err = new BufferedReader( new InputStreamReader(p.getErrorStream()) );
StringBuffer buf = new StringBuffer();
String line;
while ( (line = err.readLine()) != null){
buf.append(line);
}
return buf.toString();
}

private int waitForEnd(Process p) throws Exception {
int retcode = p.waitFor();
if (retcode != 0){
String err = getErrorOutput(p);
if (err.length() > 0){
System.err.println("ERROR:");
System.err.println(err);
}
}
return retcode;
}

public void testNoTimeOut() throws Exception {
Process process = getProcess(TIME_OUT/2);
watchdog.start(process);
int retCode = waitForEnd(process);
assertTrue("process should not have been killed", !watchdog.killedProcess());
assertFalse(Execute.isFailure(retCode));
}

// test that the watchdog ends the process
public void testTimeOut() throws Exception {
Process process = getProcess(TIME_OUT*2);
long now = System.currentTimeMillis();
watchdog.start(process);
int retCode = process.waitFor();
long elapsed = System.currentTimeMillis() - now;
assertTrue("process should have been killed", watchdog.killedProcess());
// assertTrue("return code is invalid: " + retCode, retCode!=0);
assertTrue("elapse time of "+elapsed+" ms is less than timeout value of "+TIME_OUT_TEST+" ms", elapsed >= TIME_OUT_TEST);
assertTrue("elapse time of "+elapsed+" ms is greater than run value of "+(TIME_OUT*2)+" ms", elapsed < TIME_OUT*2);
}

// test a process that runs and failed
public void testFailed() throws Exception {
Process process = getProcess(-1); // process should abort
watchdog.start(process);
int retCode = process.waitFor();
assertTrue("process should not have been killed", !watchdog.killedProcess());
assertTrue("return code is invalid: " + retCode, retCode!=0);
}

public void testManualStop() throws Exception {
final Process process = getProcess(TIME_OUT*2);
watchdog.start(process);

// I assume that starting this takes less than TIME_OUT/2 ms...
Thread thread = new Thread(){
public void run(){
try {
process.waitFor();
} catch(InterruptedException e){
// not very nice but will do the job
fail("process interrupted in thread");
}
}
};
thread.start();

// wait for TIME_OUT/2, there should be about TIME_OUT/2 ms remaining before timeout
thread.join(TIME_OUT/2);

// now stop the watchdog.
watchdog.stop();

// wait for the thread to die, should be the end of the process
thread.join();

// process should be dead and well finished
assertEquals(0, process.exitValue());
assertTrue("process should not have been killed", !watchdog.killedProcess());
}
}

+ 164
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/FailTest.java View File

@@ -0,0 +1,164 @@
/*
* 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;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;

/**
*/
public class FailTest extends BuildFileTest {

public FailTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/fail.xml");
}

public void test1() {
expectBuildExceptionContaining("test1",
"it is required to fail :-)",
"No message");
}

public void test2() {
expectSpecificBuildException("test2",
"it is required to fail :-)",
"test2");
}

public void testText() {
expectSpecificBuildException("testText",
"it is required to fail :-)",
"testText");
}

public void testIf() {
try {
executeTarget("testIf");
} catch (BuildException be) {
fail("foo has not been defined, testIf must not fail");
}
project.setProperty("foo", "");
expectBuildException("testIf", "testIf must fail if foo has been set");
}

public void testUnless() {
expectBuildException("testUnless",
"testUnless must fail unless foo has been set");
project.setProperty("foo", "");
try {
executeTarget("testUnless");
} catch (BuildException be) {
fail("foo has been defined, testUnless must not fail");
}
}

/**
* see that the different combinations work, and
* that the autogenerated text contains information
* about which condition was not met
*/
public void testIfAndUnless() {
//neither
executeTarget("testIfAndUnless");
project.setProperty("if", "");
expectBuildExceptionContaining("testIfAndUnless",
"expect fail on defined(if)",
"if=if and unless=unless");
project.setProperty("unless", "");
//this call should succeed as unless overrides if
executeTarget("testIfAndUnless");
}
/**
* see that the different combinations work, and
* that the autogenerated text contains information
* about which condition was not met
*/
public void testIfAndUnless2() {
project.setProperty("unless", "");
try {
executeTarget("testIfAndUnless");
} catch (BuildException be) {
fail("defined(if) && !defined(unless); testIfAndUnless must not fail");
}
}

public void testNested1() {
expectSpecificBuildException("testNested1",
"it is required to fail :-)",
"condition satisfied");
}

public void testNested2() {
try {
executeTarget("testNested2");
} catch (BuildException be) {
fail("condition not satisfied; testNested2 must not fail");
}
}

public void testNested3() {
expectSpecificBuildException("testNested3",
"it is required to fail :-)",
"testNested3");
}

public void testNested4() {
String specificMessage = "Nested conditions "
+ "not permitted in conjunction with if/unless attributes";

char[] c = {'a', 'b', 'c'};
StringBuffer target = new StringBuffer("testNested4x");

for (int i = 0; i < c.length; i++) {
target.setCharAt(target.length() - 1, c[i]);
expectSpecificBuildException(target.toString(),
"it is required to fail :-)", specificMessage);
}
}

public void testNested5() {
expectSpecificBuildException("testNested5",
"it is required to fail :-)",
"Only one nested condition is allowed.");
}

public void testNested6() {
expectSpecificBuildException("testNested6",
"it is required to fail :-)",
"testNested6\ntestNested6\ntestNested6");
}

public void testNested7() {
String specificMessage = "A single nested condition is required.";

char[] c = {'a', 'b'};
StringBuffer target = new StringBuffer("testNested7x");

for (int i = 0; i < c.length; i++) {
target.setCharAt(target.length() - 1, c[i]);
expectSpecificBuildException(target.toString(),
"it is required to fail :-)", specificMessage);
}
}

}

+ 114
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/FilterTest.java View File

@@ -0,0 +1,114 @@
/*
* 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;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.tools.ant.BuildFileTest;

/**
*/
public class FilterTest extends BuildFileTest {

public FilterTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/filter.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "required argument missing");
}

public void test2() {
expectBuildException("test2", "required argument missing");
}

public void test3() {
expectBuildException("test3", "required argument missing");
}

public void test4() {
executeTarget("test4");
}

public void test5() {
executeTarget("test5");
assertEquals("2000",
getFilteredFile("5", "filtered.tmp"));
}


public void test6() {
executeTarget("test6");
assertEquals("2000",
getFilteredFile("6", "taskdefs.tmp/filter1.txt"));
}

public void test7() {
executeTarget("test7");
assertEquals("<%@ include file=\"root/some/include.jsp\"%>",
getFilteredFile("7", "filtered.tmp"));
}

public void test8() {
executeTarget("test8");
assertEquals("<%@ include file=\"root/some/include.jsp\"%>",
getFilteredFile("8", "taskdefs.tmp/filter2.txt"));
}

public void test9() {
executeTarget("test9");
assertEquals("included",
getFilteredFile("9", "taskdefs.tmp/filter3.txt"));
}

private String getFilteredFile(String testNumber, String filteredFile) {

String line = null;
File f = new File(getProjectDir(), filteredFile);
if (!f.exists()) {
fail("filter test"+testNumber+" failed");
} else {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException fnfe) {
fail("filter test"+testNumber+" failed, filtered file: " + f.toString() + " not found");
}
try {
line = in.readLine();
in.close();
} catch (IOException ioe) {
fail("filter test"+testNumber+" failed. IOException while reading filtered file: " + ioe);
}
}
f.delete();
return line;
}
}

+ 219
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/FixCrLfTest.java View File

@@ -0,0 +1,219 @@
/*
* 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;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import junit.framework.AssertionFailedError;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class FixCrLfTest extends BuildFileTest {

public FixCrLfTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/fixcrlf/build.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() throws IOException {
executeTarget("test1");
}

public void test2() throws IOException {
executeTarget("test2");
}

public void test3() throws IOException {
executeTarget("test3");
}

public void test4() throws IOException {
executeTarget("test4");
}

public void test5() throws IOException {
executeTarget("test5");
}

public void test6() throws IOException {
executeTarget("test6");
}

public void test7() throws IOException {
executeTarget("test7");
}

public void test8() throws IOException {
executeTarget("test8");
}

public void test9() throws IOException {
executeTarget("test9");
}

public void testMacLines() throws IOException {
executeTarget("testMacLines");
}

public void testNoOverwrite() throws IOException {
executeTarget("testNoOverwrite");
}

public void testEncoding() throws IOException {
executeTarget("testEncoding");
}

public void testOutputEncoding() throws IOException {
executeTarget("testOutputEncoding");
}

public void testLongLines() throws IOException {
executeTarget("testLongLines");
}

public void testCrCrLfSequenceUnix() throws IOException {
executeTarget("testCrCrLfSequence-unix");
}

public void testCrCrLfSequenceDos() throws IOException {
executeTarget("testCrCrLfSequence-dos");
}

public void testCrCrLfSequenceMac() throws IOException {
executeTarget("testCrCrLfSequence-mac");
}

public void testFixlastDos() throws IOException {
executeTarget("testFixlastDos");
}

public void testFixlastFalseMac() throws IOException {
executeTarget("testFixlastFalseMac");
}

public void testFixFile() throws Exception {
executeTarget("testFixFile");
}

public void testFixFileExclusive() throws Exception {
expectBuildExceptionContaining("testFixFileExclusive",
FixCRLF.ERROR_FILE_AND_SRCDIR, FixCRLF.ERROR_FILE_AND_SRCDIR);
}

/**
* Bugzilla Report 20840
*
* Will fail with an exception if the parent directories do not
* get created.
*/
public void testCreateParentDirs() {
executeTarget("createParentDirs");
}

public void testPreserveLastModified() {
executeTarget("testPreserveLastModified");
}

public void testFilter1() {
executeTarget("testFilter1");
}

public void testFilter2() {
executeTarget("testFilter2");
}

public void testFilter3() {
executeTarget("testFilter3");
}

public void testFilter4() {
executeTarget("testFilter4");
}

public void testFilter5() {
executeTarget("testFilter5");
}

public void testFilter6() {
executeTarget("testFilter6");
}

public void testFilter7() {
executeTarget("testFilter7");
}

public void testFilter8() {
executeTarget("testFilter8");
}

public void testFilter9() {
executeTarget("testFilter9");
}

public void testCannotDoubleEof() {
executeTarget("testCannotDoubleEof");
}

public void testTabInLiteralInComment() {
executeTarget("testTabInLiteralInComment");
}

// not used, but public so theoretically must remain for BC?
public void assertEqualContent(File expect, File result)
throws AssertionFailedError, IOException {
if (!result.exists()) {
fail("Expected file "+result+" doesn\'t exist");
}

InputStream inExpect = null;
InputStream inResult = null;
try {
inExpect = new BufferedInputStream(new FileInputStream(expect));
inResult = new BufferedInputStream(new FileInputStream(result));

int expectedByte = inExpect.read();
while (expectedByte != -1) {
assertEquals(expectedByte, inResult.read());
expectedByte = inExpect.read();
}
assertEquals("End of file", -1, inResult.read());
} finally {
if (inResult != null) {
inResult.close();
}
if (inExpect != null) {
inExpect.close();
}
}
}

}

+ 71
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/GUnzipTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class GUnzipTest extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public GUnzipTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/gunzip.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "required argument missing");
}

public void test2() {
expectBuildException("test2", "attribute src invalid");
}

public void testRealTest() throws java.io.IOException {
testRealTest("realTest");
}

public void testRealTestWithResource() throws java.io.IOException {
testRealTest("realTestWithResource");
}

private void testRealTest(String target) throws java.io.IOException {
executeTarget(target);
assertTrue(FILE_UTILS.contentEquals(project.resolveFile("../asf-logo.gif"),
project.resolveFile("asf-logo.gif")));
}

public void testTestGzipTask() throws java.io.IOException {
testRealTest("testGzipTask");
}

public void testDocumentationClaimsOnCopy() throws java.io.IOException {
testRealTest("testDocumentationClaimsOnCopy");
}
}

+ 71
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/GetTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class GetTest extends BuildFileTest {

public GetTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/get.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "required argument missing");
}

public void test2() {
expectBuildException("test2", "required argument missing");
}

public void test3() {
expectBuildException("test3", "required argument missing");
}

public void test4() {
expectBuildException("test4", "src invalid");
}

public void test5() {
expectBuildException("test5", "dest invalid (or no http-server on local machine)");
}

public void test6() {
executeTarget("test6");
}

public void testUseTimestamp() {
executeTarget("testUseTimestamp");
}

public void testUseTomorrow() {
executeTarget("testUseTomorrow");
}

}

+ 76
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/GzipTest.java View File

@@ -0,0 +1,76 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class GzipTest extends BuildFileTest {

public GzipTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/gzip.xml");
}

public void test1() {
expectBuildException("test1", "required argument missing");
}

public void test2() {
expectBuildException("test2", "required argument missing");
}

public void test3() {
expectBuildException("test3", "required argument missing");
}

public void test4() {
expectBuildException("test4", "zipfile must not point to a directory");
}

public void testGZip(){
executeTarget("realTest");
String log = getLog();
assertTrue("Expecting message starting with 'Building:' but got '"
+ log + "'", log.startsWith("Building:"));
assertTrue("Expecting message ending with 'asf-logo.gif.gz' but got '"
+ log + "'", log.endsWith("asf-logo.gif.gz"));
}

public void testResource(){
executeTarget("realTestWithResource");
}

public void testDateCheck(){
executeTarget("testDateCheck");
String log = getLog();
assertTrue(
"Expecting message ending with 'asf-logo.gif.gz is up to date.' but got '" + log + "'",
log.endsWith("asf-logo.gif.gz is up to date."));
}

public void tearDown(){
executeTarget("cleanup");
}

}

+ 172
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ImportTest.java View File

@@ -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.taskdefs;

import java.io.File;
import java.io.IOException;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;

/**
*/
public class ImportTest extends BuildFileTest {

public ImportTest(String name) {
super(name);
}

public void setUp() {
}

public void tearDown() {
}

public void testSimpleImport() {
configureProject("src/etc/testcases/taskdefs/import/import.xml");
assertLogContaining("Before importIn imported topAfter import");
}

public void testUnnamedNesting() {
configureProject("src/etc/testcases/taskdefs/import/unnamedImport.xml",
Project.MSG_WARN);
String log = getLog();
assertTrue("Warnings logged when not expected: " + log,
log.length() == 0);
}

public void testSerial() {
configureProject("src/etc/testcases/taskdefs/import/subdir/serial.xml");
assertLogContaining("Unnamed2.xmlUnnamed1.xml");
String fullLog = getFullLog();
String substring = "Skipped already imported file";
assertTrue("expecting full log to contain \"" + substring
+ "\" full log was \"" + fullLog + "\"",
fullLog.indexOf(substring) >= 0);
}

// allow this as imported in targets are only tested when a target is run
public void testImportInTargetNoEffect() {
configureProject("src/etc/testcases/taskdefs/import/subdir/importintarget.xml");
expectPropertyUnset("no-import", "foo");
assertTrue(null == getProject().getReference("baz"));
}

// deactivate this test as imports within targets are not allowed
public void notTestImportInTargetWithEffect() {
configureProject("src/etc/testcases/taskdefs/import/subdir/importintarget.xml");
expectPropertySet("do-import", "foo", "bar");
assertNotNull(getProject().getReference("baz"));
}

public void testImportInTargetNotAllowed() {
configureProject(
"src/etc/testcases/taskdefs/import/subdir/importintarget.xml");
expectBuildExceptionContaining(
"do-import", "not a top level task",
"import only allowed as a top-level task");
}

public void testImportInSequential() {
configureProject(
"src/etc/testcases/taskdefs/import/subdir/importinsequential.xml");
expectPropertySet("within-imported", "foo", "bar");
assertNotNull(getProject().getReference("baz"));
}

public void testImportSameTargets() {
try {
configureProject(
"src/etc/testcases/taskdefs/import/same_target.xml");
} catch (BuildException ex) {
String message = ex.getMessage();
if (message.indexOf("Duplicate target") == -1) {
assertTrue("Did not see 'Duplicate target' in '" + message +"'", false);
}
return;
}
assertTrue(
"Did not see build exception",
false);
}

public void testImportError() {
try {
configureProject(
"src/etc/testcases/taskdefs/import/import_bad_import.xml");
} catch (BuildException ex) {
Location lo = ex.getLocation();
assertTrue(
"expected location of build exception to be set",
(lo != null));
assertTrue(
"expected location to contain calling file",
lo.getFileName().indexOf("import_bad_import.xml") != -1);
assertTrue(
"expected message of ex to contain called file",
ex.getMessage().indexOf("bad.xml") != -1);
return;
}
assertTrue(
"Did not see build exception",
false);
}

public void testSymlinkedImports() throws Exception {
String ln = "/usr/bin/ln";
if (!new File(ln).exists()) {
ln = "/bin/ln";
}
if (!new File(ln).exists()) {
// Running on Windows or something, so skip it.
return;
}
String symlink = "src/etc/testcases/taskdefs/import/symlinks/d3b";
File symlinkFile = new File(System.getProperty("root"), symlink);
if (Runtime.getRuntime().exec(new String[] {ln, "-s", "d3a", symlinkFile.getAbsolutePath()}).waitFor() != 0) {
throw new IOException("'" + ln + " -s d3a " + symlink + "' failed");
}
try {
configureProject(
"src/etc/testcases/taskdefs/import/symlinks/d1/p1.xml");
assertPropertyEquals(
"ant.file.p2",
new File(System.getProperty("root"), "src/etc/testcases/taskdefs/import/symlinks/d2/p2.xml")
.getAbsolutePath());
assertPropertyEquals(
"ant.file.p3",
new File(System.getProperty("root"), "src/etc/testcases/taskdefs/import/symlinks/d3b/p3.xml")
.getAbsolutePath());
} finally {
symlinkFile.delete();
}
}

public void testTargetFirst() {
configureProject("src/etc/testcases/taskdefs/import/importtargetfirst.xml");
assertLogContaining("Importing targetfirstAfter target firstAfter importing");
}

public void testTargetName() {
configureProject("src/etc/testcases/taskdefs/import/c.xml");
}

}

+ 64
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/InitializeClassTest.java View File

@@ -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.taskdefs;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
* Test to see if static initializers are invoked the same way
* when <java> is invoked in forked and unforked modes.
*
*/
public class InitializeClassTest extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

private File f1 = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/forkedout");
private File f2 = new File(System.getProperty("root"), "src/etc/testcases/taskdefs/unforkedout");

public InitializeClassTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/initializeclass.xml");
}

public void testAll() throws IOException {
executeTarget("forked");
PrintStream ps = System.out;
PrintStream newps = new PrintStream(new FileOutputStream(f2));
System.setOut(newps);
project.executeTarget("unforked");
System.setOut(ps);
newps.close();
assertTrue("Forked - non-forked mismatch", FILE_UTILS.contentEquals(f1, f2));
}

public void tearDown() {
f1.delete();
f2.delete();
}
}

+ 106
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/InputTest.java View File

@@ -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.taskdefs;

import java.io.FileInputStream;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.input.PropertyFileInputHandler;


public class InputTest extends BuildFileTest {

public InputTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/input.xml");
System.getProperties()
.put(PropertyFileInputHandler.FILE_NAME_KEY,
getProject().resolveFile("input.properties")
.getAbsolutePath());
getProject().setInputHandler(new PropertyFileInputHandler());
}

public void test1() {
executeTarget("test1");
}

public void test2() {
executeTarget("test2");
}

public void test3() {
expectSpecificBuildException("test3", "invalid input",
"Found invalid input test for \'"
+ getKey("All data is"
+ " going to be deleted from DB"
+ " continue?")
+ "\'");
}

public void test5() {
executeTarget("test5");
}

public void test6() {
executeTarget("test6");
assertEquals("scott", project.getProperty("db.user"));
}

public void testPropertyFileInlineHandler() {
executeTarget("testPropertyFileInlineHandler");
}

public void testDefaultInlineHandler() {
stdin();
executeTarget("testDefaultInlineHandler");
}

public void testGreedyInlineHandler() {
stdin();
executeTarget("testGreedyInlineHandler");
}

public void testGreedyInlineHandlerClassname() {
stdin();
executeTarget("testGreedyInlineHandlerClassname");
}

public void testGreedyInlineHandlerRefid() {
stdin();
executeTarget("testGreedyInlineHandlerRefid");
}

private void stdin() {
try {
System.setIn(new FileInputStream(
getProject().resolveFile("input.stdin")));
} catch (Exception e) {
throw e instanceof RuntimeException
? (RuntimeException) e : new RuntimeException(e.getMessage());
}
}

private String getKey(String key) {
return key; // XXX what is this for?
}

}

+ 270
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java View File

@@ -0,0 +1,270 @@
/*
* 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;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class JarTest extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

private static String tempJar = "tmp.jar";
private static String tempDir = "jartmp/";
private Reader r1, r2;

public JarTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/jar.xml");
}

public void tearDown() {
if (r1 != null) {
try {
r1.close();
} catch (IOException e) {
}
}
if (r2 != null) {
try {
r2.close();
} catch (IOException e) {
}
}

executeTarget("cleanup");
}

public void test1() {
expectBuildException("test1", "required argument not specified");
}

public void test2() {
expectBuildException("test2", "manifest file does not exist");
}

public void test3() {
expectBuildException("test3", "Unrecognized whenempty attribute: format C: /y");
}

public void test4() {
executeTarget("test4");
File jarFile = new File(getProjectDir(), tempJar);
assertTrue(jarFile.exists());
}

public void testNoRecreateWithoutUpdate() {
testNoRecreate("test4");
}

public void testNoRecreateWithUpdate() {
testNoRecreate("testNoRecreateWithUpdate");
}

private void testNoRecreate(String secondTarget) {
executeTarget("test4");
File jarFile = new File(getProjectDir(), tempJar);
long jarModifiedDate = jarFile.lastModified();
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
} // end of try-catch
executeTarget(secondTarget);
assertEquals("jar has not been recreated in " + secondTarget,
jarModifiedDate, jarFile.lastModified());
}

public void testRecreateWithoutUpdateAdditionalFiles() {
testRecreate("test4", "testRecreateWithoutUpdateAdditionalFiles");
}

public void testRecreateWithUpdateAdditionalFiles() {
testRecreate("test4", "testRecreateWithUpdateAdditionalFiles");
}

public void testRecreateWithoutUpdateNewerFile() {
testRecreate("testRecreateNewerFileSetup",
"testRecreateWithoutUpdateNewerFile");
}

public void testRecreateWithUpdateNewerFile() {
testRecreate("testRecreateNewerFileSetup",
"testRecreateWithUpdateNewerFile");
}

private void testRecreate(String firstTarget, String secondTarget) {
executeTarget(firstTarget);
long sleeptime = 3000
+ FILE_UTILS.getFileTimestampGranularity();
try {
Thread.sleep(sleeptime);
} catch (InterruptedException e) {
} // end of try-catch
File jarFile = new File(getProjectDir(), tempJar);
long jarModifiedDate = jarFile.lastModified();
executeTarget(secondTarget);
jarFile = new File(getProjectDir(), tempJar);
assertTrue("jar has been recreated in " + secondTarget,
jarModifiedDate < jarFile.lastModified());
}

public void testManifestStaysIntact()
throws IOException, ManifestException {
executeTarget("testManifestStaysIntact");

r1 = new FileReader(getProject()
.resolveFile(tempDir + "manifest"));
r2 = new FileReader(getProject()
.resolveFile(tempDir + "META-INF/MANIFEST.MF"));
Manifest mf1 = new Manifest(r1);
Manifest mf2 = new Manifest(r2);
assertEquals(mf1, mf2);
}

public void testNoRecreateBasedirExcludesWithUpdate() {
testNoRecreate("testNoRecreateBasedirExcludesWithUpdate");
}

public void testNoRecreateBasedirExcludesWithoutUpdate() {
testNoRecreate("testNoRecreateBasedirExcludesWithoutUpdate");
}

public void testNoRecreateZipfilesetExcludesWithUpdate() {
testNoRecreate("testNoRecreateZipfilesetExcludesWithUpdate");
}

public void testNoRecreateZipfilesetExcludesWithoutUpdate() {
testNoRecreate("testNoRecreateZipfilesetExcludesWithoutUpdate");
}

public void testRecreateZipfilesetWithoutUpdateAdditionalFiles() {
testRecreate("test4",
"testRecreateZipfilesetWithoutUpdateAdditionalFiles");
}

public void testRecreateZipfilesetWithUpdateAdditionalFiles() {
testRecreate("test4",
"testRecreateZipfilesetWithUpdateAdditionalFiles");
}

public void testRecreateZipfilesetWithoutUpdateNewerFile() {
testRecreate("testRecreateNewerFileSetup",
"testRecreateZipfilesetWithoutUpdateNewerFile");
}

public void testRecreateZipfilesetWithUpdateNewerFile() {
testRecreate("testRecreateNewerFileSetup",
"testRecreateZipfilesetWithUpdateNewerFile");
}

public void testCreateWithEmptyFileset() {
executeTarget("testCreateWithEmptyFilesetSetUp");
executeTarget("testCreateWithEmptyFileset");
executeTarget("testCreateWithEmptyFileset");
}

public void testUpdateIfOnlyManifestHasChanged() {
executeTarget("testUpdateIfOnlyManifestHasChanged");
File jarXml = getProject().resolveFile(tempDir + "jar.xml");
assertTrue(jarXml.exists());
}

// bugzilla report 10262
public void testNoDuplicateIndex() throws IOException {
ZipFile archive = null;
try {
executeTarget("testIndexTests");
archive = new ZipFile(getProject().resolveFile(tempJar));
Enumeration e = archive.entries();
int numberOfIndexLists = 0;
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
if (ze.getName().equals("META-INF/INDEX.LIST")) {
numberOfIndexLists++;
}
}
assertEquals(1, numberOfIndexLists);
} finally {
if (archive != null) {
archive.close();
}
}
}

// bugzilla report 16972
public void testRootFilesInIndex() throws IOException {
ZipFile archive = null;
try {
executeTarget("testIndexTests");
archive = new ZipFile(getProject().resolveFile(tempJar));
ZipEntry ze = archive.getEntry("META-INF/INDEX.LIST");
InputStream is = archive.getInputStream(ze);
BufferedReader r = new BufferedReader(new InputStreamReader(is,
"UTF8"));
boolean foundSub = false;
boolean foundSubFoo = false;
boolean foundFoo = false;

String line = r.readLine();
while (line != null) {
if (line.equals("foo")) {
foundFoo = true;
} else if (line.equals("sub")) {
foundSub = true;
} else if (line.equals("sub/foo")) {
foundSubFoo = true;
}
line = r.readLine();
}

assertTrue(foundSub);
assertTrue(!foundSubFoo);
assertTrue(foundFoo);
} finally {
if (archive != null) {
archive.close();
}
}
}
public void testManifestOnlyJar() {
expectLogContaining("testManifestOnlyJar", "Building MANIFEST-only jar: ");
File manifestFile = getProject().resolveFile(tempDir + "META-INF" + File.separator + "MANIFEST.MF");
assertTrue(manifestFile.exists());
}

public void testIndexJarsPlusJarMarker() {
executeTarget("testIndexJarsPlusJarMarker");
}
}

+ 328
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/JavaTest.java View File

@@ -0,0 +1,328 @@
/*
* 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;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.TeeOutputStream;

/**
* stress out java task
* */
public class JavaTest extends BuildFileTest {

private static final int TIME_TO_WAIT = 1;
// wait 1 second extra to allow for java to start ...
// this time was OK on a Win NT machine and on nagoya
private static final int SECURITY_MARGIN = 2000;

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

private boolean runFatalTests=false;

public JavaTest(String name) {
super(name);
}

/**
* configure the project.
* if the property junit.run.fatal.tests is set we run
* the fatal tests
*/
public void setUp() {
configureProject("src/etc/testcases/taskdefs/java.xml");

//final String propname="tests-classpath.value";
//String testClasspath=System.getProperty(propname);
//System.out.println("Test cp="+testClasspath);
String propname="tests-classpath.value";
String runFatal=System.getProperty("junit.run.fatal.tests");
if(runFatal!=null)
runFatalTests=true;
}

public void tearDown() {
// remove log file from testSpawn
project.executeTarget("cleanup");
}

public void testNoJarNoClassname(){
expectBuildExceptionContaining("testNoJarNoClassname",
"parameter validation",
"Classname must not be null.");
}

public void testJarNoFork() {
expectBuildExceptionContaining("testJarNoFork",
"parameter validation",
"Cannot execute a jar in non-forked mode. "
+ "Please set fork='true'. ");
}

public void testJarAndClassName() {
expectBuildException("testJarAndClassName",
"Should not be able to set both classname AND jar");
}


public void testClassnameAndJar() {
expectBuildException("testClassnameAndJar",
"Should not be able to set both classname AND jar");
}

public void testRun() {
executeTarget("testRun");
}



/** this test fails but we ignore the return value;
* we verify that failure only matters when failonerror is set
*/
public void testRunFail() {
if(runFatalTests) {
executeTarget("testRunFail");
}
}

public void testRunFailFoe() {
if(runFatalTests) {
expectBuildExceptionContaining("testRunFailFoe",
"java failures being propagated",
"Java returned:");
}
}

public void testRunFailFoeFork() {
expectBuildExceptionContaining("testRunFailFoeFork",
"java failures being propagated",
"Java returned:");
}

public void testExcepting() {
expectLogContaining("testExcepting",
"Exception raised inside called program");
}

public void testExceptingFork() {
expectLogContaining("testExceptingFork",
"Java Result:");
}

public void testExceptingFoe() {
expectBuildExceptionContaining("testExceptingFoe",
"passes exception through",
"Exception raised inside called program");
}

public void testExceptingFoeFork() {
expectBuildExceptionContaining("testExceptingFoeFork",
"exceptions turned into error codes",
"Java returned:");
}

public void testResultPropertyZero() {
executeTarget("testResultPropertyZero");
assertEquals("0",project.getProperty("exitcode"));
}

public void testResultPropertyNonZero() {
executeTarget("testResultPropertyNonZero");
assertEquals("2",project.getProperty("exitcode"));
}

public void testResultPropertyZeroNoFork() {
executeTarget("testResultPropertyZeroNoFork");
assertEquals("0",project.getProperty("exitcode"));
}

public void testResultPropertyNonZeroNoFork() {
executeTarget("testResultPropertyNonZeroNoFork");
assertEquals("-1",project.getProperty("exitcode"));
}

public void testRunFailWithFailOnError() {
expectBuildExceptionContaining("testRunFailWithFailOnError",
"non zero return code",
"Java returned:");
}

public void testRunSuccessWithFailOnError() {
executeTarget("testRunSuccessWithFailOnError");
}

public void testSpawn() {
File logFile = FILE_UTILS.createTempFile("spawn","log", project.getBaseDir());
// this is guaranteed by FileUtils#createTempFile
assertTrue("log file not existing", !logFile.exists());
project.setProperty("logFile", logFile.getAbsolutePath());
project.setProperty("timeToWait", Long.toString(TIME_TO_WAIT));
project.executeTarget("testSpawn");
try {
Thread.sleep(TIME_TO_WAIT * 1000 + SECURITY_MARGIN);
} catch (Exception ex) {
System.out.println("my sleep was interrupted");
}
// let's be nice with the next generation of developers
if (!logFile.exists()) {
System.out.println("suggestion: increase the constant"
+ " SECURITY_MARGIN to give more time for java to start.");
}
assertTrue("log file exists", logFile.exists());
}

public void testRedirect1() {
executeTarget("redirect1");
}

public void testRedirect2() {
executeTarget("redirect2");
}

public void testRedirect3() {
executeTarget("redirect3");
}

public void testRedirector1() {
executeTarget("redirector1");
}

public void testRedirector2() {
executeTarget("redirector2");
}

/**
* entry point class with no dependencies other
* than normal JRE runtime
*/
public static class EntryPoint {

/**
* this entry point is used by the java.xml tests to
* generate failure strings to handle
* argv[0] = exit code (optional)
* argv[1] = string to print to System.out (optional)
* argv[1] = string to print to System.err (optional)
*/
public static void main(String[] argv) {
int exitCode=0;
if(argv.length>0) {
try {
exitCode=Integer.parseInt(argv[0]);
} catch(NumberFormatException nfe) {
exitCode=-1;
}
}
if(argv.length>1) {
System.out.println(argv[1]);
}
if(argv.length>2) {
System.err.println(argv[2]);
}
if(exitCode!=0) {
System.exit(exitCode);
}
}
}

/**
* entry point class with no dependencies other
* than normal JRE runtime
*/
public static class ExceptingEntryPoint {

/**
* throw a run time exception which does not need
* to be in the signature of the entry point
*/
public static void main(String[] argv) {
throw new NullPointerException("Exception raised inside called program");
}
}
/**
* test class for spawn
*/
public static class SpawnEntryPoint {
public static void main(String [] argv) {
int sleepTime = 10;
String logFile = "spawn.log";
if (argv.length >= 1) {
sleepTime = Integer.parseInt(argv[0]);
}
if (argv.length >= 2)
{
logFile = argv[1];
}
OutputStreamWriter out = null;
try {
Thread.sleep(sleepTime * 1000);
} catch (InterruptedException ex) {
System.out.println("my sleep was interrupted");
}

try {
File dest = new File(logFile);
FileOutputStream fos = new FileOutputStream(dest);
out = new OutputStreamWriter(fos);
out.write("bye bye\n");
} catch (Exception ex) {}
finally {
try {out.close();} catch (IOException ioe) {}}

}
}

/**
* entry point class to pipe System.in to the specified stream:
* "out", "err", or "both". If none specified, swallow the input.
*/
public static class PipeEntryPoint {

/**
* pipe input to specified output
*/
public static void main(String[] args) {
OutputStream os = null;
if (args.length > 0) {
if ("out".equalsIgnoreCase(args[0])) {
os = System.out;
} else if ("err".equalsIgnoreCase(args[0])) {
os = System.err;
} else if ("both".equalsIgnoreCase(args[0])) {
os = new TeeOutputStream(System.out, System.err);
}
}
if (os != null) {
Thread t = new Thread(new StreamPumper(System.in, os, true));
t.start();
try {
t.join();
} catch (InterruptedException eyeEx) {
}
}
}
}
}

+ 245
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/JavacTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.compilers.CompilerAdapter;
import org.apache.tools.ant.taskdefs.compilers.CompilerAdapterFactory;
import org.apache.tools.ant.taskdefs.compilers.Javac12;
import org.apache.tools.ant.taskdefs.compilers.Javac13;
import org.apache.tools.ant.taskdefs.compilers.JavacExternal;
import org.apache.tools.ant.util.JavaEnvUtils;

import junit.framework.TestCase;

/**
* Testcase for <javac>.
*
*/
public class JavacTest extends TestCase {

private Project project;
private Javac javac;

public JavacTest(String name) {
super(name);
}

public void setUp() {
project = new Project();
project.init();
javac = new Javac();
javac.setProject(project);
}

/**
* Test setting the name of the javac executable.
*/
public void testForkedExecutableName() {
assertNull("no fork means no executable", javac.getJavacExecutable());

project.setProperty("build.compiler", "modern");
assertNull("no fork means no executable", javac.getJavacExecutable());

javac.setFork(true);
assertNotNull("normal fork", javac.getJavacExecutable());
assertTrue("name should contain \"javac\"",
javac.getJavacExecutable().indexOf("javac") > -1);

project.setProperty("build.compiler", "extJavac");
javac.setFork(false);
assertNotNull("fork via property", javac.getJavacExecutable());
assertTrue("name should contain \"javac\"",
javac.getJavacExecutable().indexOf("javac") > -1);

project.setProperty("build.compiler", "whatever");
assertNull("no fork and not extJavac means no executable",
javac.getJavacExecutable());

String myJavac = "Slartibartfast";
javac.setFork(true);
javac.setExecutable(myJavac);
assertEquals(myJavac, javac.getJavacExecutable());
}

/**
* Test nested compiler args.
*/
public void testCompilerArg() {
String[] args = javac.getCurrentCompilerArgs();
assertNotNull(args);
assertEquals("no args", 0, args.length);

Javac.ImplementationSpecificArgument arg = javac.createCompilerArg();
String ford = "Ford";
String prefect = "Prefect";
String testArg = ford + " " + prefect;
arg.setValue(testArg);
args = javac.getCurrentCompilerArgs();
assertEquals("unconditional single arg", 1, args.length);
assertEquals(testArg, args[0]);

arg.setCompiler("jikes");
args = javac.getCurrentCompilerArgs();
assertNotNull(args);
assertEquals("implementation is jikes but build.compiler is null",
0, args.length);

project.setProperty("build.compiler", "jvc");
args = javac.getCurrentCompilerArgs();
assertNotNull(args);
assertEquals("implementation is jikes but build.compiler is jvc",
0, args.length);

project.setProperty("build.compiler", "jikes");
args = javac.getCurrentCompilerArgs();
assertEquals("both are jikes", 1, args.length);
assertEquals(testArg, args[0]);

arg.setLine(testArg);
args = javac.getCurrentCompilerArgs();
assertEquals("split at space", 2, args.length);
assertEquals(ford, args[0]);
assertEquals(prefect, args[1]);
}

/**
* Test nested compiler args in the fork="true" and
* implementation="extJavac" case.
*/
public void testCompilerArgForForkAndExtJavac() {
Javac.ImplementationSpecificArgument arg = javac.createCompilerArg();
String ford = "Ford";
String prefect = "Prefect";
String testArg = ford + " " + prefect;
arg.setValue(testArg);
arg.setCompiler("extJavac");
javac.setFork(true);
String[] args = javac.getCurrentCompilerArgs();
assertEquals("both are forked javac", 1, args.length);
assertEquals(testArg, args[0]);
}

/**
* Test compiler attribute.
*/
public void testCompilerAttribute() {
// check defaults
String compiler = javac.getCompiler();
assertNotNull(compiler);
if (System.getProperty("build.compiler") != null) {
assertEquals(System.getProperty("build.compiler"),
compiler);
} else {
assertTrue("default value",
"javac1.1".equals(compiler)
|| "javac1.2".equals(compiler)
|| "javac1.3".equals(compiler)
|| "javac1.4".equals(compiler)
|| "javac1.5".equals(compiler)
|| "classic".equals(compiler));
}

javac.setFork(true);
assertNotNull(javac.getCompiler());
assertEquals("extJavac", javac.getCompiler());
assertEquals(compiler, javac.getCompilerVersion());

// check build.compiler provides defaults
javac = new Javac();
javac.setProject(project);
// setUserProperty to override system properties
project.setUserProperty("build.compiler", "jikes");
compiler = javac.getCompiler();
assertNotNull(compiler);
assertEquals("jikes", compiler);

javac.setFork(true);
compiler = javac.getCompiler();
assertNotNull(compiler);
assertEquals("jikes", compiler);

// check attribute overrides build.compiler
javac.setFork(false);
javac.setCompiler("jvc");
compiler = javac.getCompiler();
assertNotNull(compiler);
assertEquals("jvc", compiler);

javac.setFork(true);
compiler = javac.getCompiler();
assertNotNull(compiler);
assertEquals("jvc", compiler);
}

public void testCompilerAdapter() {
if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_2)
|| JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_3)) {
javac.setCompiler("javac1.1");
} else {
javac.setCompiler("javac1.4");
}

javac.setDepend(true);
CompilerAdapter adapter =
CompilerAdapterFactory.getCompiler(javac.getCompiler(), javac);

if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_2)
|| JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_3)) {
assertTrue(adapter instanceof Javac12);
} else {
assertTrue(adapter instanceof Javac13);
}

javac.setFork(true);
adapter =
CompilerAdapterFactory.getCompiler(javac.getCompiler(), javac);
assertTrue(adapter instanceof JavacExternal);
}

public void testSourceNoDefault() {
assertNull(javac.getSource());
}

public void testSourceWithDefault() {
project.setNewProperty("ant.build.javac.source", "1.4");
assertEquals("1.4", javac.getSource());
}

public void testSourceOverridesDefault() {
project.setNewProperty("ant.build.javac.source", "1.4");
javac.setSource("1.5");
assertEquals("1.5", javac.getSource());
}

public void testTargetNoDefault() {
assertNull(javac.getTarget());
}

public void testTargetWithDefault() {
project.setNewProperty("ant.build.javac.target", "1.4");
assertEquals("1.4", javac.getTarget());
}

public void testTargetOverridesDefault() {
project.setNewProperty("ant.build.javac.target", "1.4");
javac.setTarget("1.5");
assertEquals("1.5", javac.getTarget());
}
}

+ 134
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/JavadocTest.java View File

@@ -0,0 +1,134 @@
/*
* 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;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;

public class JavadocTest extends BuildFileTest {

public JavadocTest(String name) {
super(name);
}

private static final String BUILD_PATH = "src/etc/testcases/taskdefs/javadoc/";
private static final String BUILD_FILENAME = "javadoc.xml";
private static final String BUILD_FILE = BUILD_PATH + BUILD_FILENAME;

protected void setUp() throws Exception {
super.setUp();
configureProject(BUILD_FILE);
}

// PR 38370
public void testDirsetPath() throws Exception {
executeTarget("dirsetPath");
}

// PR 38370
public void testDirsetPathWithoutPackagenames() throws Exception {
try {
executeTarget("dirsetPathWithoutPackagenames");
} catch (BuildException e) {
fail("Contents of path should be picked up without specifying package names: " + e);
}
}

// PR 38370
public void testNestedDirsetPath() throws Exception {
executeTarget("nestedDirsetPath");
}

// PR 38370
public void testFilesetPath() throws Exception {
try {
executeTarget("filesetPath");
} catch (BuildException e) {
fail("A path can contain filesets: " + e);
}
}

// PR 38370
public void testNestedFilesetPath() throws Exception {
try {
executeTarget("nestedFilesetPath");
} catch (BuildException e) {
fail("A path can contain nested filesets: " + e);
}
}

// PR 38370
public void testFilelistPath() throws Exception {
try {
executeTarget("filelistPath");
} catch (BuildException e) {
fail("A path can contain filelists: " + e);
}
}

// PR 38370
public void testNestedFilelistPath() throws Exception {
try {
executeTarget("nestedFilelistPath");
} catch (BuildException e) {
fail("A path can contain nested filelists: " + e);
}
}

// PR 38370
public void testPathelementPath() throws Exception {
executeTarget("pathelementPath");
}

// PR 38370
public void testPathelementLocationPath() throws Exception {
try {
executeTarget("pathelementLocationPath");
} catch (BuildException e) {
fail("A path can contain pathelements pointing to a file: " + e);
}
}

// PR 38370
public void testNestedSource() throws Exception {
executeTarget("nestedSource");
}

// PR 38370
public void testNestedFilesetRef() throws Exception {
executeTarget("nestedFilesetRef");
}

// PR 38370
public void testNestedFilesetRefInPath() throws Exception {
executeTarget("nestedFilesetRefInPath");
}

public void testNestedFilesetNoPatterns() throws Exception {
executeTarget("nestedFilesetNoPatterns");
}

public void testDoublyNestedFileset() throws Exception {
executeTarget("doublyNestedFileset");
}

public void testDoublyNestedFilesetNoPatterns() throws Exception {
executeTarget("doublyNestedFilesetNoPatterns");
}
}

+ 123
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/LengthTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;

public class LengthTest extends BuildFileTest {

public LengthTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/length.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testEach() {
executeTarget("testEach");
}

public void testEachCondition() {
executeTarget("testEachCondition");
}

public void testAll() {
executeTarget("testAll");
}

public void testAllCondition() {
executeTarget("testAllCondition");
}

public void testFile() {
executeTarget("testFile");
}

public void testFileCondition() {
executeTarget("testFileCondition");
}

public void testBoth() {
executeTarget("testBoth");
}

public void testBothCondition() {
executeTarget("testBothCondition");
}

public void testDupes() {
executeTarget("testDupes");
}

public void testDupesCondition() {
executeTarget("testDupesCondition");
}

public void testString() {
executeTarget("testString");
}

public void testStringCondition() {
executeTarget("testStringCondition");
}

public void testTrimString() {
executeTarget("testTrimString");
}

public void testTrimStringCondition() {
executeTarget("testTrimStringCondition");
}

public void testNoTrimString() {
executeTarget("testNoTrimString");
}

public void testNoTrimStringCondition() {
executeTarget("testNoTrimStringCondition");
}

public void testStringFile() {
expectBuildExceptionContaining("testStringFile",
"should fail", "incompatible");
}

public void testTrimFile() {
expectBuildExceptionContaining("testTrimFile",
"should fail", "string length function only");
}

public void testImmutable() {
executeTarget("testImmutable");
}

public void testZipFileSet() {
executeTarget("testZipFileSet");
}

public void testZipFileSetCondition() {
executeTarget("testZipFileSetCondition");
}

}

+ 155
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java View File

@@ -0,0 +1,155 @@
/*
* 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;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;

/**
* Test the load file task
*
* @created 10 December 2001
*/
public class LoadFileTest extends BuildFileTest {

/**
* Constructor for the LoadFileTest object
*
* @param name Description of Parameter
*/
public LoadFileTest(String name) {
super(name);
}


/**
* The JUnit setup method
*/
public void setUp() {
configureProject("src/etc/testcases/taskdefs/loadfile.xml");
}


/**
* The teardown method for JUnit
*/
public void tearDown() {
executeTarget("cleanup");
}


/**
* A unit test for JUnit
*/
public void testNoSourcefileDefined() {
expectBuildException("testNoSourcefileDefined",
"source file not defined");
}


/**
* A unit test for JUnit
*/
public void testNoPropertyDefined() {
expectBuildException("testNoPropertyDefined",
"output property not defined");
}


/**
* A unit test for JUnit
*/
public void testNoSourcefilefound() {
expectBuildExceptionContaining("testNoSourcefilefound",
"File not found", " doesn't exist");
}

/**
* A unit test for JUnit
*/
public void testFailOnError()
throws BuildException {
expectPropertyUnset("testFailOnError","testFailOnError");
}


/**
* A unit test for JUnit
*/
public void testLoadAFile()
throws BuildException {
executeTarget("testLoadAFile");
if(project.getProperty("testLoadAFile").indexOf("eh?")<0) {
fail("property is not all in the file");
}
}


/**
* A unit test for JUnit
*/
public void testLoadAFileEnc()
throws BuildException {
executeTarget("testLoadAFileEnc");
if(project.getProperty("testLoadAFileEnc")==null) {
fail("file load failed");
}
}

/**
* A unit test for JUnit
*/
public void testEvalProps()
throws BuildException {
executeTarget("testEvalProps");
if(project.getProperty("testEvalProps").indexOf("rain")<0) {
fail("property eval broken");
}
}

/**
* Test FilterChain and FilterReaders
*/
public void testFilterChain()
throws BuildException {
executeTarget("testFilterChain");
if(project.getProperty("testFilterChain").indexOf("World!")<0) {
fail("Filter Chain broken");
}
}

/**
* Test StripJavaComments filterreader functionality.
*/
public final void testStripJavaComments()
throws BuildException {
executeTarget("testStripJavaComments");
final String expected = project.getProperty("expected");
final String generated = project.getProperty("testStripJavaComments");
assertEquals(expected, generated);
}

/**
* A unit test for JUnit
*/
public void testOneLine()
throws BuildException {
expectPropertySet("testOneLine","testOneLine","1,2,3,4");

}
}

+ 60
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/LoadPropertiesTest.java View File

@@ -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.ant.taskdefs;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class LoadPropertiesTest extends BuildFileTest {

public LoadPropertiesTest(String name) {
super(name);
}

/**
* The JUnit setup method
*/
public void setUp() {
configureProject("src/etc/testcases/taskdefs/loadproperties.xml");
}

/**
* The teardown method for JUnit
*/
public void tearDown() {
executeTarget("cleanup");
}

public void testPrefixedProperties() {
executeTarget("testPrefixedProperties");
String url = project.getProperty("server1.http.url");
assertEquals("http://localhost:80", url);
}

public void testPropertiesFromResource() {
executeTarget("testPropertiesFromResource");
executeTarget("loadPropertiesCheck");
}

public void testPropertiesFromFileSet() {
executeTarget("testPropertiesFromFileSet");
executeTarget("loadPropertiesCheck");
}
}

+ 158
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java View File

@@ -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;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;

/**
*/
public class MacroDefTest extends BuildFileTest {
public MacroDefTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/macrodef.xml");
}

public void testSimple() {
expectLog("simple", "Hello World");
}

public void testText() {
expectLog("text", "Inner Text");
}

public void testDuplicateAttribute() {
expectBuildException(
"duplicate.attribute",
"the attribute text has already been specified");
}

public void testDuplicateElement() {
expectBuildException(
"duplicate.element",
"the element text has already been specified");
}

public void testUri() {
expectLog("uri", "Hello World");
}

public void testNested() {
expectLog("nested", "A nested element");
}

public void testDouble() {
expectLog(
"double",
"@{prop} is 'property', value of ${property} is 'A property value'");
}

public void testIgnoreCase() {
expectLog(
"ignorecase",
"a is ab is b");
}

public void testIgnoreElementCase() {
expectLog(
"ignore-element-case",
"nested elementnested element");
}

public void testTextElement() {
expectLogContaining(
"textelement", "Hello world");
}

public void testTextTrim() {
expectLogContaining(
"text.trim", "[Hello world]");
}

public void testDuplicateTextName() {
expectBuildException(
"duplicatetextname",
"the name \"text\" is already used as an attribute");
}
public void testDuplicateTextName2() {
expectBuildException(
"duplicatetextname2",
"the attribute name \"text\" has already been used by the text element");
}
public void testEscape() {
expectLog(
"escape",
"a@b or a@b is avalue@bvalue");
}
public void testAttributeDescription() {
expectLog(
"attribute.description",
"description is hello world");
}
public void testOverrideDefault() {
expectLog(
"override.default",
"value is new");
}
public void testImplicit() {
expectLog(
"implicit", "Before implicitIn implicitAfter implicit");
}
public void testImplicitNotOptional() {
expectSpecificBuildException(
"implicit.notoptional",
"Missing nested elements for implicit element implicit",
"Missing nested elements for implicit element implicit");
}
public void testImplicitOptional() {
expectLog(
"implicit.optional", "Before implicitAfter implicit");
}
public void testImplicitExplicit() {
expectSpecificBuildException(
"implicit.explicit",
"Only one element allowed when using implicit elements",
"Only one element allowed when using implicit elements");
}

public void testBackTraceOff() {
try {
executeTarget("backtraceoff");
} catch (BuildException ex) {
if (ex.getMessage().indexOf("following error occurred") != -1) {
fail("error message contained backtrace - " + ex.getMessage());
}
}
}

public void testBackTrace() {
expectBuildExceptionContaining(
"backtraceon",
"Checking if a back trace is created",
"following error occurred");
}

public void testTopLevelText() {
expectLogContaining("top-level-text", "Hello World");
}
}


+ 137
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java View File

@@ -0,0 +1,137 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

import java.io.InputStream;
import java.io.IOException;
import java.net.URL;


public class MakeUrlTest extends BuildFileTest {

public MakeUrlTest(String s) {
super(s);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/makeurl.xml");
}

public void testEmpty() {
expectBuildExceptionContaining("testEmpty", "missing property", "property");
}

public void testNoProperty() {
expectBuildExceptionContaining("testNoProperty", "missing property", "property");
}

public void testNoFile() {
expectBuildExceptionContaining("testNoFile", "missing file", "file");
}

public void testValidation() {
expectBuildExceptionContaining("testValidation", MakeUrl.ERROR_MISSING_FILE, "file");
}

public void testWorks() {
executeTarget("testWorks");
assertPropertyContains("testWorks", "file:");
assertPropertyContains("testWorks", "/foo");
}

public void testIllegalChars() {
executeTarget("testIllegalChars");
assertPropertyContains("testIllegalChars", "file:");
assertPropertyContains("testIllegalChars", "fo%20o%25");
}

/**
* test that we can round trip by opening a url that exists
*
* @throws IOException
*/
public void testRoundTrip() throws IOException {
executeTarget("testRoundTrip");
assertPropertyContains("testRoundTrip", "file:");
String property = getProperty("testRoundTrip");
URL url = new URL(property);
InputStream instream = url.openStream();
instream.close();
}

public void testIllegalCombinations() {
executeTarget("testIllegalCombinations");
assertPropertyContains("testIllegalCombinations", "/foo");
assertPropertyContains("testIllegalCombinations", ".xml");
}

public void testFileset() {
executeTarget("testFileset");
assertPropertyContains("testFileset", ".xml ");
String result = getProperty("testFileset");
assertPropertyEndsWith("testFileset", ".xml");
}

public void testFilesetSeparator() {
executeTarget("testFilesetSeparator");
assertPropertyContains("testFilesetSeparator", ".xml\",\"");
assertPropertyEndsWith("testFilesetSeparator", ".xml");
}

public void testPath() {
executeTarget("testPath");
assertPropertyContains("testPath", "makeurl.xml");
}

/**
* assert that a property ends with
*
* @param property
* @param ending
*/
private void assertPropertyEndsWith(String property, String ending) {
String result = getProperty(property);
String substring = result.substring(result.length() - ending.length());
assertEquals(ending, substring);
}

/**
* assert that a property contains a string
*
* @param property name of property to look for
* @param contains what to search for in the string
*/
protected void assertPropertyContains(String property, String contains) {
String result = getProperty(property);

assertTrue("expected " + contains + " in " + result,
result != null && result.indexOf(contains) >= 0);
}

/**
* get a property from the project
*
* @param property
* @return
*/
protected String getProperty(String property) {
return project.getProperty(property);
}
}

+ 150
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ManifestClassPathTest.java View File

@@ -0,0 +1,150 @@
/*
* 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;
import org.apache.tools.ant.taskdefs.condition.Os;
import org.apache.tools.ant.BuildFileTest;
/**
* Tests &lt;bm:manifestclasspath&gt;.
*/
public class ManifestClassPathTest
extends BuildFileTest {
public void setUp() {
configureProject("src/etc/testcases/taskdefs/manifestclasspath.xml");
}
public void testBadDirectory() {
expectBuildExceptionContaining("test-bad-directory", "bad-jar-dir",
"Jar's directory not found:");
assertPropertyUnset("jar.classpath");
}
public void testBadNoProperty() {
expectBuildExceptionContaining("test-bad-no-property", "no-property",
"Missing 'property' attribute!");
assertPropertyUnset("jar.classpath");
}
public void testBadPropertyExists() {
expectBuildExceptionContaining("test-bad-property-exists",
"property-exits", "Property 'jar.classpath' already set!");
assertPropertyEquals("jar.classpath", "exists");
}
public void testBadNoJarfile() {
expectBuildExceptionContaining("test-bad-no-jarfile", "no-jarfile",
"Missing 'jarfile' attribute!");
assertPropertyUnset("jar.classpath");
}
public void testBadNoClassPath() {
expectBuildExceptionContaining("test-bad-no-classpath", "no-classpath",
"Missing nested <classpath>!");
assertPropertyUnset("jar.classpath");
}
public void testParentLevel1() {
executeTarget("test-parent-level1");
assertPropertyEquals("jar.classpath", "dsp-core/ " +
"dsp-pres/ " +
"dsp-void/ " +
"../generated/dsp-core/ " +
"../generated/dsp-pres/ " +
"../generated/dsp-void/ " +
"../resources/dsp-core/ " +
"../resources/dsp-pres/ " +
"../resources/dsp-void/");
}
public void testParentLevel2() {
executeTarget("test-parent-level2");
assertPropertyEquals("jar.classpath", "../dsp-core/ " +
"../dsp-pres/ " +
"../dsp-void/ " +
"../../generated/dsp-core/ " +
"../../generated/dsp-pres/ " +
"../../generated/dsp-void/ " +
"../../resources/dsp-core/ " +
"../../resources/dsp-pres/ " +
"../../resources/dsp-void/");
}
public void testParentLevel2TooDeep() {
expectBuildExceptionContaining("test-parent-level2-too-deep", "nopath",
"No suitable relative path from ");
assertPropertyUnset("jar.classpath");
}
public void testPseudoTahoeRefid() {
executeTarget("test-pseudo-tahoe-refid");
assertPropertyEquals("jar.classpath", "classes/dsp-core/ " +
"classes/dsp-pres/ " +
"classes/dsp-void/ " +
"generated/dsp-core/ " +
"resources/dsp-core/ " +
"resources/dsp-pres/");
}
public void testPseudoTahoeNested() {
executeTarget("test-pseudo-tahoe-nested");
assertPropertyEquals("jar.classpath", "classes/dsp-core/ " +
"classes/dsp-pres/ " +
"classes/dsp-void/ " +
"generated/dsp-core/ " +
"resources/dsp-core/ " +
"resources/dsp-pres/");
}
public void testParentLevel2WithJars() {
executeTarget("test-parent-level2-with-jars");
assertPropertyEquals("jar.classpath", "../../lib/acme-core.jar " +
"../../lib/acme-pres.jar " +
"../dsp-core/ " +
"../dsp-pres/ " +
"../dsp-void/ " +
"../../generated/dsp-core/ " +
"../../generated/dsp-pres/ " +
"../../generated/dsp-void/ " +
"../../resources/dsp-core/ " +
"../../resources/dsp-pres/ " +
"../../resources/dsp-void/");
}
public void testInternationalGerman() {
executeTarget("international-german");
expectLogContaining("run-two-jars", "beta alpha");
}
public void testInternationalHebrew() {
if (!Os.isFamily("windows")) {
executeTarget("international-hebrew");
expectLogContaining("run-two-jars", "beta alpha");
} else {
System.out.println("Test with hebrew path not attempted under Windows");
}
}
} // END class ManifestClassPathTest

+ 346
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java View File

@@ -0,0 +1,346 @@
/*
* 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;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Project;

/**
* Testcase for the Manifest class used in the jar task.
*
*/
public class ManifestTest extends BuildFileTest {

public static final String EXPANDED_MANIFEST
= "src/etc/testcases/taskdefs/manifests/META-INF/MANIFEST.MF";

public static final String LONG_LINE
= "AReallyLongLineToTestLineBreakingInManifests-ACapabilityWhich" +
"IsSureToLeadToHundredsOfQuestionsAboutWhyAntMungesManifests" +
"OfCourseTheAnswerIsThatIsWhatTheSpecRequiresAndIfAnythingHas" +
"AProblemWithThatItIsNotABugInAnt";

public static final String LONG_70_NAME
= "ThisNameIsJustSeventyCharactersWhichIsAllowedAccordingToTheSpecsFiller";
public static final String LONG_68_NAME
= "ThisNameIsJustSixtyEightCharactersWhichIsAllowedAccordingToTheSpecsX";
public static final String NOT_LONG_NAME
= "NameIsJustUnderSeventyCharactersWhichIsAllowedAccordingTheSpec";

public static final String VALUE = "NOT_LONG";

public ManifestTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/manifest.xml");
}

public void tearDown() {
executeTarget("clean");
}

/**
* Empty manifest - is OK
*/
public void test1() throws ManifestException, IOException {
executeTarget("test1");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
String version = manifest.getManifestVersion();
assertEquals("Manifest was not created with correct version - ", "1.0", version);
}

/**
* Simple Manifest with version 2.0
*/
public void test2() throws ManifestException, IOException {
executeTarget("test2");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
String version = manifest.getManifestVersion();
assertEquals("Manifest was not created with correct version - ", "2.0", version);
}

/**
* Malformed manifest - no : on the line
*/
public void test3() {
expectBuildExceptionContaining("test3", "Manifest is invalid - no colon on header line",
"Invalid Manifest");
}

/**
* Malformed manifest - starts with continuation line
*/
public void test4() {
expectBuildExceptionContaining("test4", "Manifest is invalid - section starts with continuation line",
"Invalid Manifest");
}

/**
* Malformed manifest - Name attribute in main section
*/
public void test5() {
executeTarget("test5");
String output = getLog();
boolean hasWarning = output.indexOf("Manifest warning: \"Name\" attributes should not occur in the main section") != -1;
assertEquals("Expected warning about Name in main section", true, hasWarning);
}

/**
* New Section not starting with Name attribute.
*/
public void test6() {
expectBuildExceptionContaining("test6", "Manifest is invalid - section starts with incorrect attribute",
"Invalid Manifest");
String output = getLog();
boolean hasWarning = output.indexOf("Manifest sections should start with a \"Name\" attribute") != -1;
assertEquals("Expected warning about section not starting with Name: attribute", true, hasWarning);
}

/**
* From attribute is illegal
*/
public void test7() {
executeTarget("test7");

boolean hasWarning = getLog().indexOf(Manifest.ERROR_FROM_FORBIDDEN) != -1;
assertEquals("Expected warning about From: attribute", true, hasWarning);
}

/**
* Inline manifest - OK
*/
public void test8() throws IOException, ManifestException {
executeTarget("test8");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
Manifest.Section mainSection = manifest.getMainSection();
String classpath = mainSection.getAttributeValue("class-path");
assertEquals("Class-Path attribute was not set correctly - ", "fubar", classpath);

Manifest.Section testSection = manifest.getSection("Test");
String testAttr = testSection.getAttributeValue("TestAttr");
assertEquals("TestAttr attribute was not set correctly - ", "Test", testAttr);
}

/**
* Inline manifest - Invalid since has a Name attribute in the section element
*/
public void test9() {
expectBuildExceptionContaining("test9", "Construction is invalid - Name attribute should not be used",
"Specify the section name using the \"name\" attribute of the <section> element");
}

/**
* Inline manifest - Invalid attribute without name
*/
public void test10() {
expectBuildExceptionContaining("test10", "Attribute has no name",
"Attributes must have name and value");
}

/**
* Inline manifest - Invalid attribute without value
*/
public void test11() {
expectBuildExceptionContaining("test11", "Attribute has no value",
"Attributes must have name and value");
}

/**
* Inline manifest - Invalid attribute without value
*/
public void test12() {
expectBuildExceptionContaining("test12", "Section with no name",
"Sections must have a name");
}

/**
* Inline manifest - Duplicate attribute
*/
public void test13() {
expectBuildExceptionContaining("test13", "Duplicate Attribute",
"The attribute \"Test\" may not occur more than once in the same section");
}

/**
* Inline manifest - OK since classpath entries can be duplicated.
*/
public void test14() throws IOException, ManifestException {
executeTarget("test14");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
Manifest.Section mainSection = manifest.getMainSection();
String classpath = mainSection.getAttributeValue("class-path");
assertEquals("Class-Path attribute was not set correctly - ",
"Test1 Test2 Test3 Test4", classpath);
}

/**
* Tets long line wrapping
*/
public void testLongLine() throws IOException, ManifestException {
Project p = getProject();
p.setUserProperty("test.longline", LONG_LINE);
p.setUserProperty("test.long68name" , LONG_68_NAME);
p.setUserProperty("test.long70name" , LONG_70_NAME);
p.setUserProperty("test.notlongname" , NOT_LONG_NAME);
p.setUserProperty("test.value", VALUE);
executeTarget("testLongLine");

Manifest manifest = getManifest(EXPANDED_MANIFEST);
Manifest.Section mainSection = manifest.getMainSection();
String classpath = mainSection.getAttributeValue("class-path");
assertEquals("Class-Path attribute was not set correctly - ",
LONG_LINE, classpath);
String value = mainSection.getAttributeValue(LONG_68_NAME);
assertEquals("LONG_68_NAME_VALUE_MISMATCH", VALUE, value);
value = mainSection.getAttributeValue(LONG_70_NAME);
assertEquals("LONG_70_NAME_VALUE_MISMATCH", VALUE, value);
value = mainSection.getAttributeValue(NOT_LONG_NAME);
assertEquals("NOT_LONG_NAME_VALUE_MISMATCH", VALUE, value);
BufferedReader in = new BufferedReader(new FileReader(EXPANDED_MANIFEST));
Set set = new HashSet();
String read = in.readLine();
while (read != null)
{
set.add(read);
read = in.readLine();
}
assertTrue("Manifest file should have contained string ", set
.remove(" NOT_LONG"));
assertTrue("Manifest file should have contained string ", set
.remove(" NG"));
assertTrue("Manifest file should have contained string ", set
.remove(LONG_70_NAME + ": "));
assertTrue("Manifest file should have contained string ", set
.remove(NOT_LONG_NAME + ": NOT_LO"));
}

/**
* Tests ordering of sections
*/
public void testOrder1() throws IOException, ManifestException {
executeTarget("testOrder1");

Manifest manifest = getManifest(EXPANDED_MANIFEST);
Enumeration e = manifest.getSectionNames();
String section1 = (String)e.nextElement();
String section2 = (String)e.nextElement();
assertEquals("First section name unexpected", "Test1", section1);
assertEquals("Second section name unexpected", "Test2", section2);

Manifest.Section section = manifest.getSection("Test1");
e = section.getAttributeKeys();
String attr1Key = (String)e.nextElement();
String attr2Key = (String)e.nextElement();
String attr1 = section.getAttribute(attr1Key).getName();
String attr2 = section.getAttribute(attr2Key).getName();
assertEquals("First attribute name unexpected", "TestAttr1", attr1);
assertEquals("Second attribute name unexpected", "TestAttr2", attr2);
}

/**
* Tests ordering of sections
*/
public void testOrder2() throws IOException, ManifestException {
executeTarget("testOrder2");

Manifest manifest = getManifest(EXPANDED_MANIFEST);
Enumeration e = manifest.getSectionNames();
String section1 = (String)e.nextElement();
String section2 = (String)e.nextElement();
assertEquals("First section name unexpected", "Test2", section1);
assertEquals("Second section name unexpected", "Test1", section2);

Manifest.Section section = manifest.getSection("Test1");
e = section.getAttributeKeys();
String attr1Key = (String)e.nextElement();
String attr2Key = (String)e.nextElement();
String attr1 = section.getAttribute(attr1Key).getName();
String attr2 = section.getAttribute(attr2Key).getName();
assertEquals("First attribute name unexpected", "TestAttr2", attr1);
assertEquals("Second attribute name unexpected", "TestAttr1", attr2);
}

/**
* file attribute for manifest task is required.
*/
public void testNoFile() {
expectBuildException("testNoFile", "file is required");
}

/**
* replace changes Manifest-Version from 2.0 to 1.0
*/
public void testReplace() throws IOException, ManifestException {
executeTarget("testReplace");
Manifest mf = getManifest("src/etc/testcases/taskdefs/mftest.mf");
assertNotNull(mf);
assertEquals(Manifest.getDefaultManifest(), mf);
}

/**
* update keeps the Manifest-Version and adds a new attribute Foo
*/
public void testUpdate() throws IOException, ManifestException {
executeTarget("testUpdate");
Manifest mf = getManifest("src/etc/testcases/taskdefs/mftest.mf");
assertNotNull(mf);
assertTrue(!Manifest.getDefaultManifest().equals(mf));
String mfAsString = mf.toString();
assertNotNull(mfAsString);
assertTrue(mfAsString.startsWith("Manifest-Version: 2.0"));
assertTrue(mfAsString.indexOf("Foo: Bar") > -1);

mf = getManifest("src/etc/testcases/taskdefs/mftest2.mf");
assertNotNull(mf);
mfAsString = mf.toString();
assertNotNull(mfAsString);
assertEquals(-1, mfAsString.indexOf("Foo: Bar"));
assertTrue(mfAsString.indexOf("Foo: Baz") > -1);
}

public void testFrom() {
expectLogContaining("testFrom", Manifest.ERROR_FROM_FORBIDDEN);
}
/**
* Reads mftest.mf.
*/
private Manifest getManifest(String filename) throws IOException, ManifestException {
FileReader r = new FileReader(new File(System.getProperty("root"), filename));
try {
return new Manifest(r);
} finally {
r.close();
}
}
}

+ 51
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/MkdirTest.java View File

@@ -0,0 +1,51 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;

/**
*/
public class MkdirTest extends BuildFileTest {

public MkdirTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/mkdir.xml");
}

public void test1() {
expectBuildException("test1", "required argument missing");
}

public void test2() {
expectBuildException("test2", "directory already exists as a file");
}

public void test3() {
executeTarget("test3");
java.io.File f = new java.io.File(getProjectDir(), "testdir.tmp");
if (!f.exists() || !f.isDirectory()) {
fail("mkdir failed");
} else {
f.delete();
}
}
}

+ 146
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/MoveTest.java View File

@@ -0,0 +1,146 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileUtils;
import java.io.File;
import java.io.IOException;

/**
* Tests the Move task.
*
*/
public class MoveTest extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public MoveTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/move.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testFilterSet() throws IOException {
executeTarget("testFilterSet");
File tmp = new File(getProjectDir(), "move.filterset.tmp");
File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
assertTrue(FILE_UTILS.contentEquals(tmp, check));
}

public void testFilterChain() throws IOException {
executeTarget("testFilterChain");
File tmp = new File(getProjectDir(), "move.filterchain.tmp");
File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
assertTrue(FILE_UTILS.contentEquals(tmp, check));
}

/** Bugzilla Report 11732 */
public void testDirectoryRemoval() throws IOException {
executeTarget("testDirectoryRemoval");
assertTrue(!getProject().resolveFile("E/B/1").exists());
assertTrue(getProject().resolveFile("E/C/2").exists());
assertTrue(getProject().resolveFile("E/D/3").exists());
assertTrue(getProject().resolveFile("A/B/1").exists());
assertTrue(!getProject().resolveFile("A/C/2").exists());
assertTrue(!getProject().resolveFile("A/D/3").exists());
assertTrue(!getProject().resolveFile("A/C").exists());
assertTrue(!getProject().resolveFile("A/D").exists());
}

/** Bugzilla Report 18886 */
public void testDirectoryRetaining() throws IOException {
executeTarget("testDirectoryRetaining");
assertTrue(getProject().resolveFile("E").exists());
assertTrue(getProject().resolveFile("E/1").exists());
assertTrue(!getProject().resolveFile("A/1").exists());
assertTrue(getProject().resolveFile("A").exists());
}

public void testCompleteDirectoryMove() throws IOException {
testCompleteDirectoryMove("testCompleteDirectoryMove");
}

public void testCompleteDirectoryMove2() throws IOException {
testCompleteDirectoryMove("testCompleteDirectoryMove2");
}

private void testCompleteDirectoryMove(String target) throws IOException {
executeTarget(target);
assertTrue(getProject().resolveFile("E").exists());
assertTrue(getProject().resolveFile("E/1").exists());
assertTrue(!getProject().resolveFile("A/1").exists());
// <path> swallows the basedir, it seems
//assertTrue(!getProject().resolveFile("A").exists());
}

public void testPathElementMove() throws IOException {
executeTarget("testPathElementMove");
assertTrue(getProject().resolveFile("E").exists());
assertTrue(getProject().resolveFile("E/1").exists());
assertTrue(!getProject().resolveFile("A/1").exists());
assertTrue(getProject().resolveFile("A").exists());
}

public void testMoveFileAndFileset() {
executeTarget("testMoveFileAndFileset");
}

public void testCompleteDirectoryMoveToExistingDir() {
executeTarget("testCompleteDirectoryMoveToExistingDir");
}

public void testCompleteDirectoryMoveFileToFile() {
executeTarget("testCompleteDirectoryMoveFileToFile");
}

public void testCompleteDirectoryMoveFileToDir() {
executeTarget("testCompleteDirectoryMoveFileToDir");
}

public void testCompleteDirectoryMoveFileAndFileset() {
executeTarget("testCompleteDirectoryMoveFileAndFileset");
}

public void testCompleteDirectoryMoveFileToExistingFile() {
executeTarget("testCompleteDirectoryMoveFileToExistingFile");
}

public void testCompleteDirectoryMoveFileToExistingDir() {
executeTarget("testCompleteDirectoryMoveFileToExistingDir");
}

public void testCompleteDirectoryMoveFileToDirWithExistingFile() {
executeTarget("testCompleteDirectoryMoveFileToDirWithExistingFile");
}

public void testCompleteDirectoryMoveFileToDirWithExistingDir() {
executeTarget("testCompleteDirectoryMoveFileToDirWithExistingDir");
}

}

+ 74
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/MultiMapTest.java View File

@@ -0,0 +1,74 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.util.FileNameMapper;


/**
*/
public class MultiMapTest extends BuildFileTest {

public MultiMapTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/multimap.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testMultiCopy() {
executeTarget("multicopy");
}

public void testMultiMove() {
executeTarget("multimove");
}

public void testSingleCopy() {
executeTarget("singlecopy");
}

public void testSingleMove() {
executeTarget("singlemove");
}

public void testCopyWithEmpty() {
executeTarget("copywithempty");
}

public void testMoveWithEmpty() {
executeTarget("movewithempty");
}

public static class TestMapper implements FileNameMapper {
public TestMapper() {}
public void setFrom(String from) {}
public void setTo(String to) {}
public String[] mapFileName(final String source_file_name) {
return new String[] {
source_file_name, source_file_name+".copy2" };
}
}
}

+ 62
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/NiceTest.java View File

@@ -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.taskdefs;

import org.apache.tools.ant.BuildFileTest;

/**
* test nice
*/
public class NiceTest extends BuildFileTest {

public NiceTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/nice.xml");
}

public void testNoop() {
executeTarget("noop");
}

public void testCurrent() {
executeTarget("current");
}

public void testFaster() {
executeTarget("faster");
}

public void testSlower() {
executeTarget("slower");
}

public void testTooSlow() {
expectBuildExceptionContaining(
"too_slow","out of range","out of the range 1-10");
}

public void testTooFast() {
expectBuildExceptionContaining(
"too_fast", "out of range", "out of the range 1-10");
}

}

+ 154
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java View File

@@ -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.taskdefs;
import java.io.PrintStream;

import junit.framework.AssertionFailedError;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.DemuxOutputStream;
import org.apache.tools.ant.Project;

/**
* Test of the parallel TaskContainer
*
* @created 21 February 2002
*/
public class ParallelTest extends BuildFileTest {
/** Standard property value for the basic test */
public final static String DIRECT_MESSAGE = "direct";
/** Standard property value for the basic and fail test */
public final static String DELAYED_MESSAGE = "delayed";
/** Standard property value for the fail test */
public final static String FAILURE_MESSAGE = "failure";

/** the build fiel associated with this test */
public final static String TEST_BUILD_FILE
= "src/etc/testcases/taskdefs/parallel.xml";

/**
* Constructor for the ParallelTest object
*
* @param name name of the test
*/
public ParallelTest(String name) {
super(name);
}

/** The JUnit setup method */
public void setUp() {
configureProject(TEST_BUILD_FILE);
}

/** tests basic operation of the parallel task */
public void testBasic() {
// should get no output at all
Project p = getProject();
p.setUserProperty("test.direct", DIRECT_MESSAGE);
p.setUserProperty("test.delayed", DELAYED_MESSAGE);
expectOutputAndError("testBasic", "", "");
String log = getLog();
assertEquals("parallel tasks didn't output correct data", log,
DIRECT_MESSAGE + DELAYED_MESSAGE);

}

/** tests basic operation of the parallel task */
public void testThreadCount() {
// should get no output at all
Project p = getProject();
p.setUserProperty("test.direct", DIRECT_MESSAGE);
p.setUserProperty("test.delayed", DELAYED_MESSAGE);
expectOutputAndError("testThreadCount", "", "");
String log = getLog();
int pos = 0;
while (pos > -1) {
pos = countThreads(log, pos);
}
}

/**
* the test result string should match the regex
* <code>^(\|\d+\/(+-)*)+\|$</code> for someting like
* <code>|3/++--+-|5/+++++-----|</code>
*
*@returns -1 no more tests
* # start pos of next test
*@throws AssertionFailedException when a constraint is invalid
*/
static int countThreads(String s, int start) {
int firstPipe = s.indexOf('|', start);
int beginSlash = s.indexOf('/', firstPipe);
int lastPipe = s.indexOf('|', beginSlash);
if ((firstPipe == -1) || (beginSlash == -1) || (lastPipe == -1)) {
return -1;
}

int max = Integer.parseInt(s.substring(firstPipe + 1, beginSlash));
int current = 0;
int pos = beginSlash + 1;
while (pos < lastPipe) {
switch (s.charAt(pos++)) {
case '+':
current++;
break;
case '-':
current--;
break;
default:
throw new AssertionFailedError("Only expect '+-' in result count, found "
+ s.charAt(--pos) + " at position " + pos);
}
if (current > max) {
throw new AssertionFailedError("Number of executing threads exceeded number allowed: "
+ current + " > " + max);
}
}
return lastPipe;
}


/** tests the failure of a task within a parallel construction */
public void testFail() {
// should get no output at all
Project p = getProject();
p.setUserProperty("test.failure", FAILURE_MESSAGE);
p.setUserProperty("test.delayed", DELAYED_MESSAGE);
expectBuildExceptionContaining("testFail",
"fail task in one parallel branch", FAILURE_MESSAGE);
}

/** tests the demuxing of output streams in a multithreaded situation */
public void testDemux() {
Project p = getProject();
p.addTaskDefinition("demuxtest", DemuxOutputTask.class);
PrintStream out = System.out;
PrintStream err = System.err;
System.setOut(new PrintStream(new DemuxOutputStream(p, false)));
System.setErr(new PrintStream(new DemuxOutputStream(p, true)));

try {
p.executeTarget("testDemux");
} finally {
System.setOut(out);
System.setErr(err);
}
}

}


+ 56
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/PathConvertTest.java View File

@@ -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;

import org.apache.tools.ant.BuildFileTest;

/**
* Unit test for the &lt;pathconvert&gt; task.
*/
public class PathConvertTest extends BuildFileTest {
private static final String BUILD_PATH = "src/etc/testcases/taskdefs/";
private static final String BUILD_FILENAME = "pathconvert.xml";
private static final String BUILD_FILE = BUILD_PATH + BUILD_FILENAME;
public PathConvertTest(String name) {
super(name);
}

public void setUp() {
configureProject(BUILD_FILE);
}

public void testMap() {
test("testmap");
}

public void testMapper() {
test("testmapper");
}

public void testNoTargetOs() {
executeTarget("testnotargetos");
}

private void test(String target) {
executeTarget(target);
assertPropertyEquals("result", "test#" + BUILD_FILENAME);
}

}

+ 117
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/PreSetDefTest.java View File

@@ -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;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;

/**
*/
public class PreSetDefTest extends BuildFileTest {
public PreSetDefTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/presetdef.xml");
}

public void testSimple() {
expectLog("simple", "Hello world");
}

public void testText() {
expectLog("text", "Inner Text");
}

public void testUri() {
expectLog("uri", "Hello world");
}

public void testDefaultTest() {
expectLog("defaulttest", "attribute is false");
}

public void testDoubleDefault() {
expectLog("doubledefault", "attribute is falseattribute is true");
}

public void testTextOptional() {
expectLog("text.optional", "MyTextoverride text");
}

public void testElementOrder() {
expectLog("element.order", "Line 1Line 2");
}

public void testElementOrder2() {
expectLog("element.order2", "Line 1Line 2Line 3");
}

public void testAntTypeTest() {
expectLog("antTypeTest", "");
}

public void testCorrectTaskNameBadAttr() {
expectBuildExceptionContaining(
"correct_taskname_badattr", "attribute message", "javac doesn't support the");
}

public void testCorrectTaskNameBadEl() {
expectBuildExceptionContaining(
"correct_taskname_badel", "element message", "javac doesn't support the");
}
public void testPresetdefWithNestedElementTwice() { // #38056
executeTarget("presetdef-with-nested-element-twice");
executeTarget("presetdef-with-nested-element-twice");
}
/**
* A test class to check default properties
*/
public static class DefaultTest extends Task {
boolean isSet = false;
boolean attribute = false;
public void setAttribute(boolean b) {
if (isSet) {
throw new BuildException("Attribute Already set");
}
attribute = b;
isSet = true;
}

public void execute() {
getProject().log("attribute is " + attribute);
}
}

/**
* A test class to check presetdef with add and addConfigured and ant-type
*/
public static class AntTypeTest extends Task {
public void addFileSet(FileSet fileset) {
}
public void addConfiguredConfigured(FileSet fileset) {
}
}
}


+ 84
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ProcessDestroyerTest.java View File

@@ -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.
*
*/

/*
* Created on Feb 19, 2003
*/
package org.apache.tools.ant.taskdefs;

import java.io.IOException;

import org.apache.tools.ant.util.JavaEnvUtils;

import junit.framework.TestCase;

/**
*/
public class ProcessDestroyerTest extends TestCase {

/**
* Constructor for ProcessDestroyerTest.
* @param arg0
*/
public ProcessDestroyerTest(String arg0) {
super(arg0);
}

public void testProcessDestroyer(){
if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_2)) {
return;
}

try {
ProcessDestroyer processDestroyer = new ProcessDestroyer();
Process process =
Runtime.getRuntime().exec(
"java -cp "
+ System.getProperty("java.class.path")
+ " "
+ getClass().getName());

assertFalse("Not registered as shutdown hook",
processDestroyer.isAddedAsShutdownHook());

processDestroyer.add(process);

assertTrue("Registered as shutdown hook",
processDestroyer.isAddedAsShutdownHook());
try {
process.destroy();
} finally {
processDestroyer.remove(process);
}

assertFalse("Not registered as shutdown hook",
processDestroyer.isAddedAsShutdownHook());
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args){
new ProcessDestroyerTest("testProcessDestroyer").testProcessDestroyer();
try{
Thread.sleep(60000);
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}

+ 111
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java View File

@@ -0,0 +1,111 @@
/*
* 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;

import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.util.FileUtils;

/**
*/
public class PropertyTest extends BuildFileTest {

/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();

public PropertyTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/property.xml");
}

public void test1() {
// should get no output at all
expectOutputAndError("test1", "", "");
}

public void test2() {
expectLog("test2", "testprop1=aa, testprop3=xxyy, testprop4=aazz");
}

public void test3() {
try {
executeTarget("test3");
}
catch (BuildException e) {
assertEquals("Circular definition not detected - ", true,
e.getMessage().indexOf("was circularly defined") != -1);
return;
}
fail("Did not throw exception on circular exception");
}

public void test4() {
expectLog("test4", "http.url is http://localhost:999");
}

public void test5() {
String baseDir = getProject().getProperty("basedir");
try {
String uri = FILE_UTILS.toURI(
baseDir + "/property3.properties");
getProject().setNewProperty(
"test5.url", uri);
} catch (Exception ex) {
throw new BuildException(ex);
}
expectLog("test5", "http.url is http://localhost:999");
}

public void testPrefixSuccess() {
executeTarget("prefix.success");
assertEquals("80", project.getProperty("server1.http.port"));
}

public void testPrefixFailure() {
try {
executeTarget("prefix.fail");
}
catch (BuildException e) {
assertEquals("Prefix allowed on non-resource/file load - ", true,
e.getMessage().indexOf("Prefix is only valid") != -1);
return;
}
fail("Did not throw exception on invalid use of prefix");
}

public void testCircularReference() {
try {
executeTarget("testCircularReference");
} catch (BuildException e) {
assertEquals("Circular definition not detected - ", true,
e.getMessage().indexOf("was circularly defined")
!= -1);
return;
}
fail("Did not throw exception on circular exception");
}

public void testThisIsNotACircularReference() {
expectLog("thisIsNotACircularReference", "b is A/A/A");
}

}

+ 95
- 0
src/tests/junit/org/apache/tools/ant/taskdefs/ProtectedJarMethodsTest.java View File

@@ -0,0 +1,95 @@
/*
* 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;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.tools.ant.BuildFileTest;

/**
*/
public class ProtectedJarMethodsTest extends BuildFileTest {

private static String tempJar = "tmp.jar";

public ProtectedJarMethodsTest(String name) {
super(name);
}

public void setUp() {
configureProject("src/etc/testcases/taskdefs/jar.xml");
}

public void tearDown() {
executeTarget("cleanup");
}

public void testGrabFilesAndDirs() throws IOException {
executeTarget("testIndexTests");
String archive = getProject().resolveFile(tempJar).getAbsolutePath();
ArrayList dirs = new ArrayList();
ArrayList files = new ArrayList();
String[] expectedDirs = new String[] {
"sub/",
};
String[] expectedFiles = new String[] {
"foo",
};
Jar.grabFilesAndDirs(archive, dirs, files);
assertEquals(expectedDirs.length, dirs.size());
for (int i = 0; i < expectedDirs.length; i++) {
assertTrue("Found " + expectedDirs[i],
dirs.contains(expectedDirs[i]));
}
assertEquals(expectedFiles.length, files.size());
for (int i = 0; i < expectedFiles.length; i++) {
assertTrue("Found " + expectedFiles[i],
files.contains(expectedFiles[i]));
}
}

public void testFindJarNameNoClasspath() {
assertEquals("foo", Jar.findJarName("foo", null));
assertEquals("foo", Jar.findJarName("lib" + File.separatorChar + "foo",
null));
}

public void testFindJarNameNoMatch() {
assertNull(Jar.findJarName("foo", new String[] {"bar"}));
}

public void testFindJarNameSimpleMatches() {
assertEquals("foo", Jar.findJarName("foo", new String[] {"foo"}));
assertEquals("lib/foo", Jar.findJarName("foo",
new String[] {"lib/foo"}));
assertEquals("foo", Jar.findJarName("bar" + File.separatorChar + "foo",
new String[] {"foo"}));
assertEquals("lib/foo",
Jar.findJarName("bar" + File.separatorChar + "foo",
new String[] {"lib/foo"}));
}

public void testFindJarNameLongestMatchWins() {
assertEquals("lib/foo",
Jar.findJarName("lib/foo",
new String[] {"foo", "lib/foo",
"lib/bar/foo"}));
}
}

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save