From b61c80746dd5df73899390826e197d2656784f91 Mon Sep 17 00:00:00 2001
From: mclarke
Date: Fri, 18 Apr 2014 21:00:38 +0000
Subject: [PATCH] Test improvements: convert to JUnit4, improved error testing
and remove sleeps
git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@1588563 13f79535-47bb-0310-9956-ffa450edef68
---
WHATSNEW | 10 +
manual/Types/selectors-program.html | 78 +--
.../tutorial-tasks-filesets-properties.html | 40 +-
manual/tutorial-writing-tasks.html | 83 +--
src/etc/testcases/taskdefs/copy.xml | 5 +-
src/etc/testcases/taskdefs/jar.xml | 2 -
.../taskdefs/optional/antlr/antlr.xml | 2 -
.../taskdefs/optional/depend/depend.xml | 26 +-
src/etc/testcases/taskdefs/optional/junit.xml | 9 +-
.../taskdefs/optional/replaceregexp.xml | 2 +-
.../taskdefs/optional/unix/symlink.xml | 2 +-
src/etc/testcases/taskdefs/uptodate.xml | 9 +-
src/etc/testcases/taskdefs/zip.xml | 1 -
src/etc/testcases/types/selectors.xml | 3 -
.../junit/org/apache/tools/ant/AntAssert.java | 72 +++
.../ant/AntClassLoaderDelegationTest.java | 19 +-
.../tools/ant/AntClassLoaderPerformance.java | 5 +-
.../apache/tools/ant/AntClassLoaderTest.java | 114 ++--
.../org/apache/tools/ant/BuildFileRule.java | 318 +++++++++++
.../org/apache/tools/ant/BuildFileTest.java | 3 +
.../junit/org/apache/tools/ant/CaseTest.java | 32 +-
.../apache/tools/ant/DefaultLoggerTest.java | 13 +-
.../tools/ant/DirectoryScannerTest.java | 192 ++++---
.../apache/tools/ant/DispatchTaskTest.java | 24 +-
.../org/apache/tools/ant/ExecutorTest.java | 56 +-
.../apache/tools/ant/ExtendedTaskdefTest.java | 61 +-
.../org/apache/tools/ant/FileUtilities.java | 88 +++
.../org/apache/tools/ant/ImmutableTest.java | 56 +-
.../org/apache/tools/ant/IncludeTest.java | 96 ++--
.../tools/ant/IntrospectionHelperTest.java | 94 +++-
.../org/apache/tools/ant/LoaderRefTest.java | 32 +-
.../org/apache/tools/ant/LocationTest.java | 46 +-
.../apache/tools/ant/MockBuildListener.java | 9 +-
.../tools/ant/ProjectComponentTest.java | 10 +-
.../ant/ProjectHelperRepositoryTest.java | 16 +-
.../org/apache/tools/ant/ProjectTest.java | 92 ++-
.../tools/ant/PropertyExpansionTest.java | 27 +-
.../apache/tools/ant/PropertyFileCLITest.java | 10 +-
.../apache/tools/ant/TaskContainerTest.java | 39 +-
.../apache/tools/ant/TopLevelTaskTest.java | 30 +-
.../apache/tools/ant/UnknownElementTest.java | 31 +-
.../tools/ant/filters/ConcatFilterTest.java | 82 ++-
.../tools/ant/filters/DynamicFilterTest.java | 67 +--
.../tools/ant/filters/EscapeUnicodeTest.java | 32 +-
.../tools/ant/filters/HeadTailTest.java | 126 +++--
.../tools/ant/filters/LineContainsTest.java | 37 +-
.../tools/ant/filters/NoNewLineTest.java | 19 +-
.../tools/ant/filters/ReplaceTokensTest.java | 40 +-
.../ant/filters/StripJavaCommentsTest.java | 33 +-
.../tools/ant/filters/TokenFilterTest.java | 297 +++++-----
.../apache/tools/ant/launch/LocatorTest.java | 53 +-
.../tools/ant/loader/AntClassLoader5Test.java | 14 +-
.../ant/taskdefs/AbstractCvsTaskTest.java | 43 +-
.../taskdefs/AntLikeTasksAtTopLevelTest.java | 24 +-
.../tools/ant/taskdefs/AntStructureTest.java | 41 +-
.../apache/tools/ant/taskdefs/AntTest.java | 247 +++++---
.../apache/tools/ant/taskdefs/AntlibTest.java | 50 +-
.../tools/ant/taskdefs/AvailableTest.java | 182 ++++--
.../tools/ant/taskdefs/BUnzip2Test.java | 38 +-
.../apache/tools/ant/taskdefs/BZip2Test.java | 42 +-
.../tools/ant/taskdefs/BasenameTest.java | 73 ++-
.../tools/ant/taskdefs/CVSPassTest.java | 75 ++-
.../tools/ant/taskdefs/CallTargetTest.java | 52 +-
.../tools/ant/taskdefs/ChecksumTest.java | 66 ++-
.../apache/tools/ant/taskdefs/ConcatTest.java | 197 ++++---
.../tools/ant/taskdefs/ConditionTest.java | 282 +++++++---
.../apache/tools/ant/taskdefs/CopyTest.java | 208 ++++---
.../tools/ant/taskdefs/CopydirTest.java | 67 ++-
.../tools/ant/taskdefs/CopyfileTest.java | 73 ++-
.../ant/taskdefs/DefaultExcludesTest.java | 42 +-
.../apache/tools/ant/taskdefs/DeleteTest.java | 71 ++-
.../tools/ant/taskdefs/DeltreeTest.java | 31 +-
.../tools/ant/taskdefs/DirnameTest.java | 70 ++-
.../tools/ant/taskdefs/DynamicTest.java | 28 +-
.../apache/tools/ant/taskdefs/EchoTest.java | 34 +-
.../tools/ant/taskdefs/EchoXMLTest.java | 42 +-
.../tools/ant/taskdefs/ExecTaskTest.java | 62 +-
.../tools/ant/taskdefs/ExecuteJavaTest.java | 21 +-
.../ant/taskdefs/ExecuteWatchdogTest.java | 31 +-
.../apache/tools/ant/taskdefs/FailTest.java | 166 ++++--
.../apache/tools/ant/taskdefs/FilterTest.java | 71 ++-
.../tools/ant/taskdefs/FixCrLfTest.java | 129 +++--
.../apache/tools/ant/taskdefs/GUnzipTest.java | 54 +-
.../apache/tools/ant/taskdefs/GetTest.java | 79 ++-
.../apache/tools/ant/taskdefs/GzipTest.java | 69 ++-
.../apache/tools/ant/taskdefs/ImportTest.java | 152 ++---
.../ant/taskdefs/InitializeClassTest.java | 47 +-
.../apache/tools/ant/taskdefs/InputTest.java | 100 ++--
.../apache/tools/ant/taskdefs/JarTest.java | 188 +++++--
.../apache/tools/ant/taskdefs/JavaTest.java | 232 +++++---
.../apache/tools/ant/taskdefs/JavacTest.java | 44 +-
.../tools/ant/taskdefs/JavadocTest.java | 123 ++--
.../tools/ant/taskdefs/LoadFileTest.java | 111 ++--
.../tools/ant/taskdefs/MacroDefTest.java | 172 ++++--
.../tools/ant/taskdefs/MakeUrlTest.java | 76 ++-
.../ant/taskdefs/ManifestClassPathTest.java | 222 +++++---
.../tools/ant/taskdefs/ManifestTest.java | 194 +++++--
.../apache/tools/ant/taskdefs/MkdirTest.java | 39 +-
.../apache/tools/ant/taskdefs/MoveTest.java | 129 +++--
.../tools/ant/taskdefs/MultiMapTest.java | 35 +-
.../apache/tools/ant/taskdefs/NiceTest.java | 49 +-
.../tools/ant/taskdefs/ParallelTest.java | 103 ++--
.../tools/ant/taskdefs/PathConvertTest.java | 29 +-
.../tools/ant/taskdefs/PreSetDefTest.java | 81 ++-
.../ant/taskdefs/ProcessDestroyerTest.java | 69 +--
.../tools/ant/taskdefs/PropertyTest.java | 102 ++--
.../ant/taskdefs/ProtectedJarMethodsTest.java | 31 +-
.../tools/ant/taskdefs/RecorderTest.java | 63 ++-
.../apache/tools/ant/taskdefs/RenameTest.java | 65 ++-
.../tools/ant/taskdefs/ReplaceTest.java | 121 +++-
.../tools/ant/taskdefs/RmicAdvancedTest.java | 196 ++++---
.../apache/tools/ant/taskdefs/RmicTest.java | 15 +-
.../tools/ant/taskdefs/SQLExecTest.java | 39 +-
.../tools/ant/taskdefs/SignJarTest.java | 65 ++-
.../apache/tools/ant/taskdefs/SleepTest.java | 55 +-
.../apache/tools/ant/taskdefs/StyleTest.java | 153 ++---
.../apache/tools/ant/taskdefs/SubAntTest.java | 71 ++-
.../apache/tools/ant/taskdefs/SyncTest.java | 108 ++--
.../apache/tools/ant/taskdefs/TStampTest.java | 21 +-
.../apache/tools/ant/taskdefs/TarTest.java | 116 ++--
.../tools/ant/taskdefs/TaskdefTest.java | 80 ++-
.../tools/ant/taskdefs/TaskdefsTest.java | 2 +-
.../tools/ant/taskdefs/TestProcess.java | 14 +-
.../apache/tools/ant/taskdefs/TouchTest.java | 66 ++-
.../tools/ant/taskdefs/TypeAdapterTest.java | 50 +-
.../tools/ant/taskdefs/TypedefTest.java | 87 ++-
.../apache/tools/ant/taskdefs/UntarTest.java | 68 ++-
.../apache/tools/ant/taskdefs/UnzipTest.java | 155 +++--
.../tools/ant/taskdefs/UpToDateTest.java | 47 +-
.../apache/tools/ant/taskdefs/WarTest.java | 22 +-
.../tools/ant/taskdefs/WhichResourceTest.java | 33 +-
.../tools/ant/taskdefs/XmlPropertyTest.java | 131 +++--
.../apache/tools/ant/taskdefs/XmlnsTest.java | 53 +-
.../tools/ant/taskdefs/ZipExtraFieldTest.java | 10 +-
.../apache/tools/ant/taskdefs/ZipTest.java | 176 ++++--
.../compilers/DefaultCompilerAdapterTest.java | 18 +-
.../taskdefs/condition/AntVersionTest.java | 29 +-
.../ant/taskdefs/condition/ContainsTest.java | 11 +-
.../ant/taskdefs/condition/EqualsTest.java | 12 +-
.../ant/taskdefs/condition/HttpTest.java | 51 +-
.../ant/taskdefs/condition/IsFailureTest.java | 21 +-
.../condition/IsFileSelectedTest.java | 47 +-
.../taskdefs/condition/IsReachableTest.java | 84 ++-
.../taskdefs/condition/IsReferenceTest.java | 52 +-
.../ant/taskdefs/condition/IsSignedTest.java | 31 +-
.../condition/ParserSupportsTest.java | 83 ++-
.../ant/taskdefs/condition/TypeFoundTest.java | 56 +-
.../tools/ant/taskdefs/condition/XorTest.java | 39 +-
.../taskdefs/cvslib/ChangeLogParserTest.java | 8 +-
.../taskdefs/cvslib/ChangeLogWriterTest.java | 6 +-
.../ant/taskdefs/email/EmailAddressTest.java | 30 +-
.../ant/taskdefs/email/EmailTaskTest.java | 34 +-
.../tools/ant/taskdefs/email/MessageTest.java | 14 +-
.../ant/taskdefs/optional/ANTLRTest.java | 132 +++--
.../optional/AbstractXSLTLiaisonTest.java | 18 +-
.../optional/BeanShellScriptTest.java | 24 +-
.../taskdefs/optional/EchoPropertiesTest.java | 184 +++---
.../ant/taskdefs/optional/JavahTest.java | 34 +-
.../tools/ant/taskdefs/optional/JspcTest.java | 99 ++--
.../taskdefs/optional/Native2AsciiTest.java | 31 +-
.../taskdefs/optional/PropertyFileTest.java | 113 ++--
.../tools/ant/taskdefs/optional/PvcsTest.java | 49 +-
.../taskdefs/optional/ReplaceRegExpTest.java | 83 +--
.../taskdefs/optional/RhinoReferenceTest.java | 23 +-
.../taskdefs/optional/RhinoScriptTest.java | 45 +-
.../tools/ant/taskdefs/optional/RpmTest.java | 13 +-
.../taskdefs/optional/SchemaValidateTest.java | 93 +--
.../taskdefs/optional/TraXLiaisonTest.java | 29 +-
.../optional/XmlValidateCatalogTest.java | 38 +-
.../taskdefs/optional/XmlValidateTest.java | 98 ++--
.../tools/ant/taskdefs/optional/XsltTest.java | 65 +--
.../taskdefs/optional/depend/DependTest.java | 107 +++-
.../taskdefs/optional/i18n/TranslateTest.java | 81 ++-
.../taskdefs/optional/image/ImageTest.java | 78 ++-
.../optional/jdepend/JDependTest.java | 58 +-
.../optional/junit/BatchTestTest.java | 109 ++--
.../taskdefs/optional/junit/DOMUtilTest.java | 10 +-
.../optional/junit/JUnitClassLoaderTest.java | 11 +-
.../optional/junit/JUnitReportTest.java | 146 ++---
.../optional/junit/JUnitTaskTest.java | 372 ++++++------
.../optional/junit/JUnitTestListenerTest.java | 103 ++--
.../optional/junit/JUnitTestRunnerTest.java | 48 +-
.../junit/JUnitVersionHelperTest.java | 28 +-
.../taskdefs/optional/junit/NoVmCrash.java | 9 +-
.../ant/taskdefs/optional/junit/Printer.java | 8 +-
.../ant/taskdefs/optional/junit/Sleeper.java | 17 +-
.../optional/junit/TearDownOnVmCrashTest.java | 29 +-
.../ant/taskdefs/optional/junit/VmCrash.java | 9 +-
.../XMLFormatterWithCDATAOnSystemOut.java | 30 +-
.../junit/XMLResultAggregatorTest.java | 15 +-
.../ant/taskdefs/optional/net/FTPTest.java | 528 +++++++++---------
.../optional/script/ScriptDefTest.java | 93 +--
.../ant/taskdefs/optional/sos/SOSTest.java | 71 ++-
.../optional/splash/SplashScreenTest.java | 12 +-
.../ant/taskdefs/optional/ssh/ScpTest.java | 36 +-
.../taskdefs/optional/unix/SymlinkTest.java | 401 ++++++-------
.../ant/taskdefs/optional/vss/MSVSSTest.java | 98 ++--
.../tools/ant/types/AbstractFileSetTest.java | 15 +-
.../apache/tools/ant/types/AddTypeTest.java | 91 ++-
.../tools/ant/types/AssertionsTest.java | 81 ++-
.../tools/ant/types/CommandlineJavaTest.java | 25 +-
.../tools/ant/types/CommandlineTest.java | 23 +-
.../tools/ant/types/DescriptionTest.java | 41 +-
.../apache/tools/ant/types/DirSetTest.java | 9 +-
.../ant/types/EnumeratedAttributeTest.java | 22 +-
.../apache/tools/ant/types/FileListTest.java | 88 +--
.../apache/tools/ant/types/FileSetTest.java | 3 -
.../apache/tools/ant/types/FilterSetTest.java | 130 +++--
.../tools/ant/types/FlexIntegerTest.java | 31 +-
.../apache/tools/ant/types/MapperTest.java | 62 +-
.../org/apache/tools/ant/types/PathTest.java | 32 +-
.../tools/ant/types/PatternSetTest.java | 21 +-
.../tools/ant/types/PermissionsTest.java | 28 +-
.../org/apache/tools/ant/types/PolyTest.java | 34 +-
.../ant/types/RedirectorElementTest.java | 56 +-
.../tools/ant/types/ResourceOutputTest.java | 54 +-
.../tools/ant/types/TarFileSetTest.java | 10 +-
.../ant/types/XMLCatalogBuildFileTest.java | 48 +-
.../tools/ant/types/XMLCatalogTest.java | 211 +++----
.../tools/ant/types/ZipFileSetTest.java | 11 +-
.../ant/types/mappers/GlobMapperTest.java | 22 +-
.../mappers/RegexpPatternMapperTest.java | 24 +-
.../ant/types/optional/ScriptMapperTest.java | 27 +-
.../types/optional/ScriptSelectorTest.java | 54 +-
.../optional/depend/ClassFileSetTest.java | 49 +-
.../ant/types/resources/FileResourceTest.java | 17 +-
.../ant/types/resources/JavaResourceTest.java | 28 +-
.../resources/LazyResourceCollectionTest.java | 14 +-
.../types/resources/MultiRootFileSetTest.java | 10 +-
.../ant/types/resources/ResourceListTest.java | 52 +-
.../ant/types/resources/TarResourceTest.java | 34 +-
.../ant/types/selectors/BaseSelectorRule.java | 125 +++++
.../ant/types/selectors/BaseSelectorTest.java | 4 +-
.../types/selectors/ContainsRegexpTest.java | 70 +--
.../types/selectors/ContainsSelectorTest.java | 107 ++--
.../ant/types/selectors/DateSelectorTest.java | 211 ++++---
.../types/selectors/DependSelectorTest.java | 234 ++++----
.../types/selectors/DepthSelectorTest.java | 102 ++--
.../types/selectors/FilenameSelectorTest.java | 57 +-
.../types/selectors/ModifiedSelectorTest.java | 446 ++++++++-------
.../types/selectors/PresentSelectorTest.java | 136 ++---
.../types/selectors/SignedSelectorTest.java | 27 +-
.../ant/types/selectors/SizeSelectorTest.java | 163 +++---
.../types/selectors/TokenizedPatternTest.java | 11 +-
.../ant/types/selectors/TypeSelectorTest.java | 55 +-
.../tools/ant/util/Base64ConverterTest.java | 13 +-
.../tools/ant/util/ClasspathUtilsTest.java | 16 +-
.../tools/ant/util/CollectionUtilsTest.java | 11 +-
.../tools/ant/util/DOMElementWriterTest.java | 32 +-
.../apache/tools/ant/util/DateUtilsTest.java | 17 +-
.../tools/ant/util/DeweyDecimalTest.java | 4 +-
.../apache/tools/ant/util/FileUtilsTest.java | 58 +-
.../tools/ant/util/GlobPatternMapperTest.java | 16 +-
.../apache/tools/ant/util/JAXPUtilsTest.java | 10 +-
.../tools/ant/util/JavaEnvUtilsTest.java | 161 +++---
.../util/LayoutPreservingPropertiesTest.java | 21 +-
.../ant/util/LazyFileOutputStreamTest.java | 18 +-
.../util/LineOrientedOutputStreamTest.java | 31 +-
.../tools/ant/util/LinkedHashtableTest.java | 23 +-
.../tools/ant/util/LoaderUtilsTest.java | 12 +-
.../tools/ant/util/PackageNameMapperTest.java | 9 +-
.../tools/ant/util/ReaderInputStreamTest.java | 27 +-
.../tools/ant/util/ResourceUtilsTest.java | 14 +-
.../tools/ant/util/StringUtilsTest.java | 32 +-
.../tools/ant/util/SymlinkUtilsTest.java | 13 +-
.../ant/util/UnPackageNameMapperTest.java | 8 +-
.../tools/ant/util/UnicodeUtilTest.java | 7 +-
.../apache/tools/ant/util/VectorSetTest.java | 44 +-
.../tools/ant/util/XMLFragmentTest.java | 25 +-
.../ant/util/facade/FacadeTaskHelperTest.java | 13 +-
.../ImplementationSpecificArgumentTest.java | 12 +-
.../apache/tools/bzip2/CBZip2StreamTest.java | 13 +-
.../apache/tools/mail/MailMessageTest.java | 139 ++---
.../org/apache/tools/tar/TarEntryTest.java | 9 +-
.../apache/tools/tar/TarOutputStreamTest.java | 7 +-
.../apache/tools/tar/TarRoundTripTest.java | 17 +-
.../apache/tools/zip/AsiExtraFieldTest.java | 18 +-
.../apache/tools/zip/ExtraFieldUtilsTest.java | 19 +-
.../apache/tools/zip/UTF8ZipFilesTest.java | 19 +-
.../org/apache/tools/zip/ZipEncodingTest.java | 19 +-
.../org/apache/tools/zip/ZipEntryTest.java | 18 +-
.../org/apache/tools/zip/ZipLongTest.java | 19 +-
.../apache/tools/zip/ZipOutputStreamTest.java | 26 +-
.../org/apache/tools/zip/ZipShortTest.java | 17 +-
.../junit/org/example/junit/Timeout.java | 7 +-
.../org/example/junit/XmlParserTest.java | 12 +-
286 files changed, 11159 insertions(+), 7183 deletions(-)
create mode 100644 src/tests/junit/org/apache/tools/ant/AntAssert.java
create mode 100644 src/tests/junit/org/apache/tools/ant/BuildFileRule.java
create mode 100644 src/tests/junit/org/apache/tools/ant/FileUtilities.java
create mode 100644 src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorRule.java
diff --git a/WHATSNEW b/WHATSNEW
index 25d2d6540..c1fafc065 100644
--- a/WHATSNEW
+++ b/WHATSNEW
@@ -26,6 +26,16 @@ Changes that could break older environments:
might lead to blocking or other undefined behavior.
Bugzilla Report 56149
+ * BuildFileTest and BaseSelectorTest have both been deprecated in
+ favour of BuildFileRule and BaseSelectorRule respectively, and the
+ tests that previously extended these base tests have been converted to
+ JUnit 4 tests using the new "rule"s. Any external test that sub-classed
+ a test in the Ant workspace, rather than BuildFileTest, will need
+ changed to either use JUnit4's annotations, or be modified to
+ extend BuildFileTest directly. This will not affect any tests that are
+ being executed by Ant's junit or batchtest tasks that are not specifically
+ testing Ant's code.
+
Fixed bugs:
-----------
diff --git a/manual/Types/selectors-program.html b/manual/Types/selectors-program.html
index 8e16b0338..074a54263 100644
--- a/manual/Types/selectors-program.html
+++ b/manual/Types/selectors-program.html
@@ -140,78 +140,58 @@
For a robust component (and selectors are (Project)Components) tests are
necessary. For testing Tasks we use JUnit TestCases - more specific
- org.apache.tools.ant.BuildFileTest extends junit.framework.TestCase .
+ org.apache.tools.ant.BuildFileRule extends org.junit.rules.ExternalResource .
Some of its features like configure the (test) project by reading its buildfile and
- execute targets we need for selector tests also. Therefore we use that BuildFileTest.
+ execute targets we need for selector tests also. Therefore we use that BuildFileRule.
But testing selectors requires some more work: having a set of files, instantiate
and configure the selector, check the selection work and more. Because we usually
extend BaseExtendSelector its features have to be tested also (e.g. setError()).
- That's why we have a base class for doing our selector tests:
- org.apache.tools.ant.types.selectors.BaseSelectorTest .
+ That's why we have a test rule for doing our selector tests:
+ org.apache.tools.ant.types.selectors.BaseSelectorRule .
- This class extends TestCase and therefore can included in the set of Ant's
- unit tests. It holds an instance of preconfigured BuildFileTest. Configuration
- is done by parsing the src/etc/testcases/types/selectors.xml. BaseSelectorTest
+
This class extends ExternalResource and therefore can included in the set of Ant's
+ unit tests. It holds an instance of preconfigured BuildFileRule. Configuration
+ is done by parsing the src/etc/testcases/types/selectors.xml. BaseSelectorRule
then gives us helper methods for handling multiple selections.
Because the term "testcase" or "testenvironment" are so often used, this
- special testenvironment got a new name: bed . Like you initialize the
- test environment by calling setUp() and cleaning by calling tearDown() (or like
- to make your bed before go sleeping ) you have to do that work with your
- bed by calling makeBed() respective cleanupBed() .
+ special testenvironment got a new name: bed . The setup and cleanup of
+ the bed is all handled by the BaseSelectorRule so any test only has to handle
+ the actual test scenarios
- A usual test scenario is
- make the bed
+ A usual test scenario is:
+
instantiate the selector
configure the selector
let the selector do some work
verify the work
- clean the bed
-
-
+
+
- For common way of instantiation you have to override the getInstance()
- simply by returning a new object of your selector. For easier "selection and verification work"
- BaseSelectorTest provides the method performTests() which
- iterates over all files (and directories) in the String array filenames
- and checks whether the given selector returns the expected result. If an error
- occurred (especially the selector does not return the expected result) the test
- fails and the failing filenames are logged.
An example test would be:
package org.apache.tools.ant.types.selectors;
-public class MySelectorTest extends BaseSelectorTest {
-
- public MySelectorTest(String name) {
- super(name);
- }
+public class MySelectorTest {
- public BaseSelector getInstance() {
- return new MySelector();
- }
+ @Rule
+ public final BaseSelectorRule selectorRule = new BaseSelectorRule();
+ @Test
public void testCase1() {
- try {
- // initialize test environment 'bed'
- makeBed();
-
- // Configure the selector
- MySelector s = (MySelector)getSelector();
- s.addParam("key1", "value1");
- s.addParam("key2", "value2");
- s.setXX(true);
- s.setYY("a value");
-
- // do the tests
- performTests(s, "FTTTTTTTTTTT"); // First is not selected - rest is
-
- } finally {
- // cleanup the environment
- cleanupBed();
- }
+
+
+ // Configure the selector
+ MySelector s = new MySelector();
+ s.addParam("key1", "value1");
+ s.addParam("key2", "value2");
+ s.setXX(true);
+ s.setYY("a value");
+
+ // do the tests
+ assertEquals("FTTTTTTTT", selectorRule.selectionString(s));
}
}
diff --git a/manual/tutorial-tasks-filesets-properties.html b/manual/tutorial-tasks-filesets-properties.html
index 5ba08f6ef..fdbe1be5b 100644
--- a/manual/tutorial-tasks-filesets-properties.html
+++ b/manual/tutorial-tasks-filesets-properties.html
@@ -135,20 +135,28 @@ to them, sorry :-)
we can call that from our testcase:
-import org.apache.tools.ant.BuildFileTest;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.Before;
+import org.junit.Assert;
+import org.apache.tools.ant.BuildFileRule;
-public class FindTest extends BuildFileTest {
- public FindTest(String name) {
- super(name);
- }
+public class FindTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
configureProject("build.xml");
}
+ @Test
public void testSimple() {
- expectLog("use.simple", "test-value");
+ buildRule.executeTarget("useSimgle");
+ Assert.assertEquals("test-value", buildRule.getLog());
}
}
@@ -211,10 +219,14 @@ Maybe you find some more testcases. But this is enough for now.
For each of these points we create a testXX method.
-public class FindTest extends BuildFileTest {
+public class FindTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
... // constructor, setUp as above
+ @Test
public void testMissingFile() {
Find find = new Find();
try {
@@ -227,6 +239,7 @@ public class FindTest extends BuildFileTest {
}
}
+ @Test
public void testMissingLocation() {
Find find = new Find();
find.setFile("ant.jar");
@@ -238,6 +251,7 @@ public class FindTest extends BuildFileTest {
}
}
+ @Test
public void testMissingFileset() {
Find find = new Find();
find.setFile("ant.jar");
@@ -250,15 +264,17 @@ public class FindTest extends BuildFileTest {
}
}
+ @Test
public void testFileNotPresent() {
- executeTarget("testFileNotPresent");
- String result = getProject().getProperty("location.ant-jar");
+ buildRule.executeTarget("testFileNotPresent");
+ String result = buildRule.getProject().getProperty("location.ant-jar");
assertNull("Property set to wrong value.", result);
}
+ @Test
public void testFilePresent() {
- executeTarget("testFilePresent");
- String result = getProject().getProperty("location.ant-jar");
+ buildRule.executeTarget("testFilePresent");
+ String result = buildRule.getProject().getProperty("location.ant-jar");
assertNotNull("Property not set.", result);
assertTrue("Wrong file found.", result.endsWith("ant.jar"));
}
@@ -906,7 +922,7 @@ entry. For both we need some information:
attachments
- all files needed to apply the path
+ all files needed to apply the path
Archive containing a patch with the new and modified resources
diff --git a/manual/tutorial-writing-tasks.html b/manual/tutorial-writing-tasks.html
index c4881e949..c3b8a6a82 100644
--- a/manual/tutorial-writing-tasks.html
+++ b/manual/tutorial-writing-tasks.html
@@ -17,8 +17,7 @@
Tutorial: Writing Tasks
-
-
+
Tutorial: Writing Tasks
@@ -596,12 +595,9 @@ Next step: test ...
Test the Task
We have written a test already: the use.* tasks in the buildfile. But its
difficult to test that automatically. Common (and in Ant) used is JUnit for
-that. For testing tasks Ant provides a baseclass org.apache.tools.ant.BuildFileTest .
-This class extends junit.framework.TestCase and can therefore be integrated
-into the unit tests. But this class provides some for testing tasks useful methods:
-initialize Ant, load a buildfile, execute targets,
-expecting BuildExceptions with a specified text, expect a special text
-in the output log ...
+that. For testing tasks Ant provides a JUnit Rule org.apache.tools.ant.BuildFileRule .
+This class provides some for testing tasks useful methods:
+initialize Ant, load a buildfile, execute targets, capturing debug and run logs ...
In Ant it is usual that the testcase has the same name as the task with a prepending
Test , therefore we will create a file HelloWorldTest.java . Because we
@@ -677,49 +673,68 @@ and <junitreport>
. So we add to the buildfile:
...
-Back to the src/HelloWorldTest.java . We create a class extending
-BuildFileTest with String-constructor (JUnit-standard), a setUp()
-method initializing Ant and for each testcase (targets use.*) a testXX()
-method invoking that target.
+Back to the src/HelloWorldTest.java . We create a class with a public
+BuildFileRule field annotated with JUnit's @Rule annotation. As per
+conventional JUnit4 tests, this class should have no constructors, or a default no-args
+constructor, setup methods should be annotated with @Before , tear down methods
+annotated with @After and any test method annotated with @Test .
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.Before;
+import org.junit.Rule;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
-public class HelloWorldTest extends BuildFileTest {
+public class HelloWorldTest {
- public HelloWorldTest(String s) {
- super(s);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
// initialize Ant
- configureProject("build.xml");
+ buildRule.configureProject("build.xml");
}
+ @Test
public void testWithout() {
- executeTarget("use.without");
- assertEquals("Message was logged but should not.", getLog(), "");
+ buildRule.executeTarget("use.without");
+ assertEquals("Message was logged but should not.", buildRule.getLog(), "");
}
public void testMessage() {
// execute target 'use.nestedText' and expect a message
// 'attribute-text' in the log
- expectLog("use.message", "attribute-text");
+ buildRule.executeTarget("use.message");
+ Assert.assertEquals("attribute-text", buildRule.getLog());
}
+ @Test
public void testFail() {
// execute target 'use.fail' and expect a BuildException
// with text 'Fail requested.'
- expectBuildException("use.fail", "Fail requested.");
+ try {
+ buildRule.executeTarget("use.fail");
+ fail("BuildException should have been thrown as task was set to fail");
+ } catch (BuildException ex) {
+ Assert.assertEquals("fail requested", ex.getMessage());
+ }
+
}
+ @Test
public void testNestedText() {
- expectLog("use.nestedText", "nested-text");
+ buildRule.executeTarget("use.nestedText");
+ Assert.assertEquals("nested-text", buildRule.getLog());
}
+ @Test
public void testNestedElement() {
- executeTarget("use.nestedElement");
- assertLogContaining("Nested Element 1");
- assertLogContaining("Nested Element 2");
+ buildRule.executeTarget("use.nestedElement");
+ AntAssert.assertContains("Nested Element 1", buildRule.getLog());
+ AntAssert.assertContains("Nested Element 2", buildRule.getLog());
}
}
@@ -790,14 +805,14 @@ The ZIP provided there contains
here [7] inside the manual.
-Used Links:
- [1] http://ant.apache.org/manual/properties.html#built-in-props
- [2] http://ant.apache.org/manual/Tasks/taskdef.html
- [3] http://ant.apache.org/manual/develop.html#set-magic
- [4] http://ant.apache.org/manual/develop.html#nested-elements
- [5] http://gump.covalent.net/jars/latest/ant/ant-testutil.jar
- [6] http://issues.apache.org/bugzilla/show_bug.cgi?id=22570
- [7] tutorial-writing-tasks-src.zip
+
Used Links:
+ [1] http://ant.apache.org/manual/properties.html#built-in-props
+ [2] http://ant.apache.org/manual/Tasks/taskdef.html
+ [3] http://ant.apache.org/manual/develop.html#set-magic
+ [4] http://ant.apache.org/manual/develop.html#nested-elements
+ [5] http://gump.covalent.net/jars/latest/ant/ant-testutil.jar
+ [6] http://issues.apache.org/bugzilla/show_bug.cgi?id=22570
+ [7] tutorial-writing-tasks-src.zip
diff --git a/src/etc/testcases/taskdefs/copy.xml b/src/etc/testcases/taskdefs/copy.xml
index dc3b4cae9..bf4441c17 100644
--- a/src/etc/testcases/taskdefs/copy.xml
+++ b/src/etc/testcases/taskdefs/copy.xml
@@ -63,13 +63,10 @@ a=b=
-
-
-
-
+
diff --git a/src/etc/testcases/taskdefs/jar.xml b/src/etc/testcases/taskdefs/jar.xml
index ab3a7d80c..78d1abc68 100644
--- a/src/etc/testcases/taskdefs/jar.xml
+++ b/src/etc/testcases/taskdefs/jar.xml
@@ -66,7 +66,6 @@
-
@@ -111,7 +110,6 @@
-
diff --git a/src/etc/testcases/taskdefs/optional/antlr/antlr.xml b/src/etc/testcases/taskdefs/optional/antlr/antlr.xml
index d015020d2..c136d0617 100644
--- a/src/etc/testcases/taskdefs/optional/antlr/antlr.xml
+++ b/src/etc/testcases/taskdefs/optional/antlr/antlr.xml
@@ -110,14 +110,12 @@
-
-
diff --git a/src/etc/testcases/taskdefs/optional/depend/depend.xml b/src/etc/testcases/taskdefs/optional/depend/depend.xml
index d11bf1632..8465bb026 100644
--- a/src/etc/testcases/taskdefs/optional/depend/depend.xml
+++ b/src/etc/testcases/taskdefs/optional/depend/depend.xml
@@ -19,11 +19,13 @@
-
-
+
+
+
+
@@ -71,16 +73,14 @@
-
-
+
-
-
+
@@ -138,16 +138,14 @@
-
-
+
-
-
+
@@ -173,10 +171,9 @@
+ classpathref="path.compile" fork="false" />
-
-
@@ -190,8 +187,7 @@
destdir="${classes.dir}" closure="yes"/>
-
-
+
diff --git a/src/etc/testcases/taskdefs/optional/junit.xml b/src/etc/testcases/taskdefs/optional/junit.xml
index 8a4943e8e..d976abf43 100644
--- a/src/etc/testcases/taskdefs/optional/junit.xml
+++ b/src/etc/testcases/taskdefs/optional/junit.xml
@@ -280,8 +280,7 @@
-
-
+
@@ -297,8 +296,7 @@
-
-
+
@@ -313,8 +311,7 @@
-
-
+
diff --git a/src/etc/testcases/taskdefs/optional/replaceregexp.xml b/src/etc/testcases/taskdefs/optional/replaceregexp.xml
index 3fa323a4a..58fdc59cd 100644
--- a/src/etc/testcases/taskdefs/optional/replaceregexp.xml
+++ b/src/etc/testcases/taskdefs/optional/replaceregexp.xml
@@ -43,7 +43,7 @@
-
+
diff --git a/src/etc/testcases/taskdefs/optional/unix/symlink.xml b/src/etc/testcases/taskdefs/optional/unix/symlink.xml
index bd0131748..f039a622f 100644
--- a/src/etc/testcases/taskdefs/optional/unix/symlink.xml
+++ b/src/etc/testcases/taskdefs/optional/unix/symlink.xml
@@ -44,7 +44,7 @@
before they have finnished (hopefully). Tweak if needed.
-->
-
+
diff --git a/src/etc/testcases/taskdefs/uptodate.xml b/src/etc/testcases/taskdefs/uptodate.xml
index 6e6ce86f6..04bb37077 100644
--- a/src/etc/testcases/taskdefs/uptodate.xml
+++ b/src/etc/testcases/taskdefs/uptodate.xml
@@ -19,7 +19,6 @@
-
@@ -28,19 +27,19 @@
-
+
-
+
-
+
@@ -48,7 +47,7 @@
-
+
diff --git a/src/etc/testcases/taskdefs/zip.xml b/src/etc/testcases/taskdefs/zip.xml
index ae6e3d0eb..4fa6de6c7 100644
--- a/src/etc/testcases/taskdefs/zip.xml
+++ b/src/etc/testcases/taskdefs/zip.xml
@@ -118,7 +118,6 @@
-
-
-
-
diff --git a/src/tests/junit/org/apache/tools/ant/AntAssert.java b/src/tests/junit/org/apache/tools/ant/AntAssert.java
new file mode 100644
index 000000000..7771924f5
--- /dev/null
+++ b/src/tests/junit/org/apache/tools/ant/AntAssert.java
@@ -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;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Provides common assert functions for use across multiple tests, similar to the Assert s
+ * within JUnit.
+ */
+public class AntAssert {
+
+ /**
+ * Assert that a string contains the given substring.
+ * @param message the message to fail with if the substring is not present in the target string.
+ * @param needle the string to search for.
+ * @param haystack the string to search in.
+ */
+ public static void assertContains(String message, String needle, String haystack) {
+ String formattedMessage = (message == null ? "" : message + " ");
+ assertTrue(formattedMessage + String.format("expected message containing: <%s> but got: <%s>", needle, haystack), haystack.contains(needle));
+ }
+
+ /**
+ * Assert that a string contains the given substring. A default failure message will be used if the target string
+ * is not found.
+ * @param needle the target string to search for.
+ * @param haystack the string to search in.
+ */
+ public static void assertContains(String needle, String haystack) {
+ assertContains("", needle, haystack);
+ }
+
+ /**
+ * Assert that a string does not contain the given substring.
+ * @param message the message to fail with if the substring is present in the target string.
+ * @param needle the string to search for.
+ * @param haystack the string to search in.
+ */
+ public static void assertNotContains(String message, String needle, String haystack) {
+ String formattedMessage = (message == null ? "" : message + " ");
+ assertFalse(formattedMessage + String.format("expected message not to contain: <%s> but got: <%s>", needle, haystack), haystack.contains(needle));
+ }
+
+ /**
+ * Assert that a string does not contain the given substring. A default failure message will be used if the target
+ * string is found.
+ * @param needle the target string to search for.
+ * @param haystack the string to search in.
+ */
+ public static void assertNotContains(String needle, String haystack) {
+ assertNotContains("", needle, haystack);
+ }
+
+
+}
diff --git a/src/tests/junit/org/apache/tools/ant/AntClassLoaderDelegationTest.java b/src/tests/junit/org/apache/tools/ant/AntClassLoaderDelegationTest.java
index 9839ed0d3..ae5ce6270 100644
--- a/src/tests/junit/org/apache/tools/ant/AntClassLoaderDelegationTest.java
+++ b/src/tests/junit/org/apache/tools/ant/AntClassLoaderDelegationTest.java
@@ -25,26 +25,27 @@ 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;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
/**
* Test case for ant class loader
*
*/
-public class AntClassLoaderDelegationTest extends TestCase {
+public class AntClassLoaderDelegationTest {
/** 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);
- }
-
+ @Before
public void setUp() {
p = new Project();
p.init();
@@ -53,7 +54,8 @@ public class AntClassLoaderDelegationTest extends TestCase {
/** Sample resource present in build/testcases/ */
private static final String TEST_RESOURCE
= "apache/tools/ant/IncludeTest.class";
-
+
+ @Test
public void testFindResources() throws Exception {
// This path should contain the class files for these testcases:
String buildTestcases = System.getProperty("build.tests");
@@ -79,6 +81,7 @@ public class AntClassLoaderDelegationTest extends TestCase {
enum2List(acl.getResources(TEST_RESOURCE)));
}
+ @Test
public void testFindIsolateResources() throws Exception {
String buildTestcases = System.getProperty("build.tests");
assertNotNull("defined ${build.tests}", buildTestcases);
diff --git a/src/tests/junit/org/apache/tools/ant/AntClassLoaderPerformance.java b/src/tests/junit/org/apache/tools/ant/AntClassLoaderPerformance.java
index 16251fcaf..2145cfa1e 100644
--- a/src/tests/junit/org/apache/tools/ant/AntClassLoaderPerformance.java
+++ b/src/tests/junit/org/apache/tools/ant/AntClassLoaderPerformance.java
@@ -19,15 +19,16 @@
package org.apache.tools.ant;
import java.io.File;
-import junit.framework.TestCase;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Test;
/**
* Used to verify the performance effect of classloader changes.
*/
-public class AntClassLoaderPerformance extends TestCase {
+public class AntClassLoaderPerformance {
+ @Test
public void testFindClass() throws Exception {
String testCaseURL = getClass()
.getClassLoader().getResource("junit/framework/TestCase.class")
diff --git a/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java b/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java
index 7877db3d2..8419037e1 100644
--- a/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java
+++ b/src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java
@@ -18,63 +18,75 @@
package org.apache.tools.ant;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
import java.io.File;
import java.io.PrintStream;
import java.net.URL;
+
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Test case for ant class loader
*
*/
-public class AntClassLoaderTest extends BuildFileTest {
+public class AntClassLoaderTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
private AntClassLoader loader;
- public AntClassLoaderTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- super.configureProject("src/etc/testcases/core/antclassloader.xml");
- getProject().executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/core/antclassloader.xml");
+ buildRule.executeTarget("setUp");
}
+ @After
public void tearDown() {
if (loader != null) {
loader.cleanup();
}
- try {
- super.tearDown();
- } catch ( Exception e) {
- System.err.println(e.getMessage());
- }
}
+
//test inspired by bug report 37085
+ @Test
public void testJarWithManifestInDirWithSpace() {
- String mainjarstring = getProject().getProperty("main.jar");
- String extjarstring = getProject().getProperty("ext.jar");
- Path myPath = new Path(getProject());
+ String mainjarstring = buildRule.getProject().getProperty("main.jar");
+ String extjarstring = buildRule.getProject().getProperty("ext.jar");
+ Path myPath = new Path(buildRule.getProject());
myPath.setLocation(new File(mainjarstring));
- getProject().setUserProperty("build.sysclasspath","ignore");
- loader = getProject().createClassLoader(myPath);
+ buildRule.getProject().setUserProperty("build.sysclasspath","ignore");
+ loader = buildRule.getProject().createClassLoader(myPath);
String path = loader.getClasspath();
assertEquals(mainjarstring + File.pathSeparator + extjarstring, path);
}
+
+ @Test
public void testJarWithManifestInNonAsciiDir() {
- String mainjarstring = getProject().getProperty("main.jar.nonascii");
- String extjarstring = getProject().getProperty("ext.jar.nonascii");
- Path myPath = new Path(getProject());
+ String mainjarstring = buildRule.getProject().getProperty("main.jar.nonascii");
+ String extjarstring = buildRule.getProject().getProperty("ext.jar.nonascii");
+ Path myPath = new Path(buildRule.getProject());
myPath.setLocation(new File(mainjarstring));
- getProject().setUserProperty("build.sysclasspath","ignore");
- loader = getProject().createClassLoader(myPath);
+ buildRule.getProject().setUserProperty("build.sysclasspath","ignore");
+ loader = buildRule.getProject().createClassLoader(myPath);
String path = loader.getClasspath();
assertEquals(mainjarstring + File.pathSeparator + extjarstring, path);
}
+
+ @Test
public void testCleanup() throws BuildException {
- Path path = new Path(project, ".");
- loader = project.createClassLoader(path);
+ Path path = new Path(buildRule.getProject(), ".");
+ loader = buildRule.getProject().createClassLoader(path);
try {
// we don't expect to find this
loader.findClass("fubar");
@@ -95,7 +107,7 @@ public class AntClassLoaderTest extends BuildFileTest {
}
// tell the build it is finished
- project.fireBuildFinished(null);
+ buildRule.getProject().fireBuildFinished(null);
try {
// we don't expect to find this
loader.findClass("fubar");
@@ -107,40 +119,43 @@ public class AntClassLoaderTest extends BuildFileTest {
}
}
+ @Test
public void testGetPackage() throws Exception {
- executeTarget("prepareGetPackageTest");
- Path myPath = new Path(getProject());
- myPath.setLocation(new File(getProject().getProperty("test.jar")));
- getProject().setUserProperty("build.sysclasspath","ignore");
- loader = getProject().createClassLoader(myPath);
+ buildRule.executeTarget("prepareGetPackageTest");
+ Path myPath = new Path(buildRule.getProject());
+ myPath.setLocation(new File(buildRule.getProject().getProperty("test.jar")));
+ buildRule.getProject().setUserProperty("build.sysclasspath","ignore");
+ loader = buildRule.getProject().createClassLoader(myPath);
assertNotNull("should find class", loader.findClass("org.example.Foo"));
assertNotNull("should find package",
new GetPackageWrapper(loader).getPackage("org.example"));
}
+ @Test
public void testCodeSource() throws Exception {
- executeTarget("prepareGetPackageTest");
- Path myPath = new Path(getProject());
- File testJar = new File(getProject().getProperty("test.jar"));
+ buildRule.executeTarget("prepareGetPackageTest");
+ Path myPath = new Path(buildRule.getProject());
+ File testJar = new File(buildRule.getProject().getProperty("test.jar"));
myPath.setLocation(testJar);
- getProject().setUserProperty("build.sysclasspath","ignore");
- loader = getProject().createClassLoader(myPath);
- Class foo = loader.findClass("org.example.Foo");
+ buildRule.getProject().setUserProperty("build.sysclasspath","ignore");
+ loader = buildRule.getProject().createClassLoader(myPath);
+ Class> foo = loader.findClass("org.example.Foo");
URL codeSourceLocation =
foo.getProtectionDomain().getCodeSource().getLocation();
assertEquals(codeSourceLocation + " should point to test.jar",
FileUtils.getFileUtils().getFileURL(testJar), codeSourceLocation);
}
+ @Test
public void testSignedJar() throws Exception {
- executeTarget("signTestJar");
- File jar = new File(getProject().getProperty("test.jar"));
+ buildRule.executeTarget("signTestJar");
+ File jar = new File(buildRule.getProject().getProperty("test.jar"));
- Path myPath = new Path(getProject());
+ Path myPath = new Path(buildRule.getProject());
myPath.setLocation(jar);
- getProject().setUserProperty("build.sysclasspath","ignore");
- loader = getProject().createClassLoader(myPath);
- Class foo = loader.findClass("org.example.Foo");
+ buildRule.getProject().setUserProperty("build.sysclasspath","ignore");
+ loader = buildRule.getProject().createClassLoader(myPath);
+ Class> foo = loader.findClass("org.example.Foo");
assertNotNull("should find class", foo);
assertNotNull("should have certificates",
@@ -154,23 +169,24 @@ public class AntClassLoaderTest extends BuildFileTest {
* bug 47593, request to log the name of corrupt zip files from which
* classes cannot be loaded
*/
+ @Test
public void testInvalidZipException() throws Exception {
- executeTarget("createNonJar");
- File jar = new File(getProject().getProperty("tmp.dir")
+ buildRule.executeTarget("createNonJar");
+ File jar = new File(buildRule.getProject().getProperty("tmp.dir")
+ "/foo.jar");
- Path myPath = new Path(getProject());
+ Path myPath = new Path(buildRule.getProject());
myPath.setLocation(jar);
- getProject().setUserProperty("build.sysclasspath","ignore");
- loader = getProject().createClassLoader(myPath);
+ buildRule.getProject().setUserProperty("build.sysclasspath","ignore");
+ loader = buildRule.getProject().createClassLoader(myPath);
PrintStream sysErr = System.err;
try {
StringBuffer errBuffer = new StringBuffer();
PrintStream err =
- new PrintStream(new BuildFileTest.AntOutputStream(errBuffer));
+ new PrintStream(new BuildFileRule.AntOutputStream(errBuffer));
System.setErr(err);
loader.getResource("foo.txt");
- String log = getLog();
+ String log = buildRule.getLog();
int startMessage = log.indexOf("CLASSPATH element ");
assertTrue(startMessage >= 0);
assertTrue(log.indexOf("foo.jar is not a JAR", startMessage) > 0);
diff --git a/src/tests/junit/org/apache/tools/ant/BuildFileRule.java b/src/tests/junit/org/apache/tools/ant/BuildFileRule.java
new file mode 100644
index 000000000..b4e00fdcf
--- /dev/null
+++ b/src/tests/junit/org/apache/tools/ant/BuildFileRule.java
@@ -0,0 +1,318 @@
+/*
+ * 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.OutputStream;
+import java.io.PrintStream;
+
+import org.apache.tools.ant.util.ProcessUtil;
+import org.junit.rules.ExternalResource;
+
+/**
+ * Provides access for JUnit tests to execute Ant targets and access execution details (i.e logs).
+ *
+ * Example usage:
+ *
+ * public class MyTest {
+ *
+ * \@Rule
+ * public BuildFileRule rule = new BuildFileRule();
+ *
+ * \@Before
+ * public void setUp() {
+ * rule.configureProject("my/and/file.xml");
+ * }
+ *
+ * \@Test
+ * public void testSuccess() {
+ * rule.executeTarget("passingTaget");
+ * assertEquals("Incorrect log message", "[taskName] Action Complete", rule.getLog());
+ * }
+ *
+ * \@Test
+ * public void testException() {
+ * try {
+ * rule.executeTarget("failingTarget");
+ * fail("Target should have thrown a BuildException");
+ * } catch (BuildException ex) {
+ * assertContains("Exception did not contain correct text", "Could not find compiler on classpath", ex.getMessage());
+ * }
+ * }
+ *
+ * }
+ *
+ */
+public class BuildFileRule extends ExternalResource {
+
+ private Project project;
+
+ private StringBuffer logBuffer;
+ private StringBuffer fullLogBuffer;
+ private StringBuffer outputBuffer;
+ private StringBuffer errorBuffer;
+
+
+
+ /**
+ * Tidies up following a test execution. If the currently configured
+ * project has a tearDown target then this will automatically
+ * be called, otherwise this method will not perform any actions.
+ */
+ @Override
+ protected void after() {
+ if (project == null) {
+ // configureProject has not been called - nothing we can clean-up
+ return;
+ }
+ final String tearDown = "tearDown";
+ if (project.getTargets().containsKey(tearDown)) {
+ project.executeTarget(tearDown);
+ }
+ }
+
+ /**
+ * Gets the INFO, WARNING and ERROR message from the current execution,
+ * unless the logging level is set above any of these level in which case
+ * the message is excluded.
+ * This is only valid if configureProject() has been called.
+ *
+ * @return The INFO, WARN and ERROR messages in the log.
+ */
+ public String getLog() {
+ return logBuffer.toString();
+ }
+
+ /**
+ * Gets any messages that have been logged during the current execution, unless
+ * the logging level has been set above the log level defined in the message.
+ *
+ * Only valid if configureProject() has been called.
+ * @return the content of the log.
+ */
+ public String getFullLog() {
+ return fullLogBuffer.toString();
+ }
+
+ /**
+ * Provides all output sent to the System.out stream during the current execution.
+ * @return all output messages in a single string, normalised to have platform independent line breaks.
+ */
+ public String getOutput() {
+ return cleanBuffer(outputBuffer);
+ }
+
+ /**
+ * Provides all output sent to the System.err stream during the current execution.
+ * @return all error messages in a single string, normalised to have platform independent line breaks.
+ */
+ public String getError() {
+ return cleanBuffer(errorBuffer);
+ }
+
+ private String cleanBuffer(StringBuffer buffer) {
+ StringBuilder cleanedBuffer = new StringBuilder();
+ for (int i = 0; i < buffer.length(); i++) {
+ char ch = buffer.charAt(i);
+ if (ch != '\r') {
+ 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.setProperty("ant.processid", ProcessUtil.getProcessId(""));
+ project.setProperty("ant.threadname", Thread.currentThread().getName());
+ project.setUserProperty("ant.file" , antFile.getAbsolutePath());
+ project.addBuildListener(new AntTestListener(logLevel));
+ ProjectHelper.configureProject(project, antFile);
+ }
+
+ /**
+ * Executes a target in the configured Ant build file. Requires #configureProject()
+ * to have been invoked before this call.
+ *
+ * @param targetName the target in the currently configured build file to run.
+ */
+ public void executeTarget(String targetName) {
+ outputBuffer = new StringBuffer();
+ PrintStream out = new PrintStream(new AntOutputStream(outputBuffer));
+ errorBuffer = new StringBuffer();
+ PrintStream err = new PrintStream(new AntOutputStream(errorBuffer));
+ logBuffer = new StringBuffer();
+ fullLogBuffer = new StringBuffer();
+
+ /* we synchronize to protect our custom output streams from being overridden
+ * by other tests executing targets concurrently. Ultimately this would only
+ * happen if we ran a multi-threaded test executing multiple targets at once, and
+ * this protection doesn't prevent a target from internally modifying the output
+ * stream during a test - but at least this scenario is fairly deterministic so
+ * easier to troubleshoot.
+ */
+ synchronized (System.out) {
+ PrintStream sysOut = System.out;
+ PrintStream sysErr = System.err;
+ sysOut.flush();
+ sysErr.flush();
+ try {
+ System.setOut(out);
+ System.setErr(err);
+ 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;
+ }
+
+
+ /**
+ * An output stream which saves contents to our buffer.
+ */
+ protected static class AntOutputStream extends 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) {
+ }
+
+ /**
+ * 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) {
+ }
+
+ /**
+ * Fired when a task is started.
+ *
+ * @see BuildEvent#getTask()
+ */
+ public void taskStarted(BuildEvent event) {
+ }
+
+ /**
+ * 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) {
+ }
+
+ /**
+ * 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());
+ }
+ }
+
+ public File getOutputDir() {
+ return new File(getProject().getProperty("output"));
+ }
+
+}
+
diff --git a/src/tests/junit/org/apache/tools/ant/BuildFileTest.java b/src/tests/junit/org/apache/tools/ant/BuildFileTest.java
index 841939cc9..e18d71b8b 100644
--- a/src/tests/junit/org/apache/tools/ant/BuildFileTest.java
+++ b/src/tests/junit/org/apache/tools/ant/BuildFileTest.java
@@ -32,7 +32,10 @@ import org.apache.tools.ant.util.ProcessUtil;
* This class provides a number of utility methods for particular build file
* tests which extend this class.
*
+ * @deprecated as of 1.9.4. Use BuildFileRule, Assert, AntAssert and JUnit4 annotations to drive tests instead
+ * @see org.apache.tools.ant.BuildFileRule
*/
+@Deprecated
public abstract class BuildFileTest extends TestCase {
protected Project project;
diff --git a/src/tests/junit/org/apache/tools/ant/CaseTest.java b/src/tests/junit/org/apache/tools/ant/CaseTest.java
index fcb56d752..81cf385f2 100644
--- a/src/tests/junit/org/apache/tools/ant/CaseTest.java
+++ b/src/tests/junit/org/apache/tools/ant/CaseTest.java
@@ -18,37 +18,47 @@
package org.apache.tools.ant;
-import org.apache.tools.ant.BuildFileTest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
/**
* Simple tests of build file processing
*/
-public class CaseTest extends BuildFileTest {
-
- public CaseTest(String name) {
- super(name);
- }
+public class CaseTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/case.xml");
+ buildRule.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.
*/
+ @Test
public void testCaseSensitivity() {
- executeTarget("case-sensitivity");
+ buildRule.executeTarget("case-sensitivity");
}
/**
* Test whether the build file uses case when determining
* task names.
*/
+ @Test
public void testTaskCase() {
- expectBuildExceptionContaining("taskcase",
- "Task names are case sensitive",
- "Problem: failed to create task or type ecHO");
+ try {
+ buildRule.executeTarget("taskcase");
+ fail("Build exception should have been thrown due to case sensitivity of name");
+ } catch(BuildException ex) {
+ assertContains("Task names should be case sensitive", "Problem: failed to create task or type ecHO", ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/DefaultLoggerTest.java b/src/tests/junit/org/apache/tools/ant/DefaultLoggerTest.java
index 0d004a093..00f4dfa19 100644
--- a/src/tests/junit/org/apache/tools/ant/DefaultLoggerTest.java
+++ b/src/tests/junit/org/apache/tools/ant/DefaultLoggerTest.java
@@ -18,15 +18,15 @@
package org.apache.tools.ant;
-import java.io.PrintWriter;
-import junit.framework.TestCase;
import org.apache.tools.ant.util.StringUtils;
+import org.junit.Test;
-public class DefaultLoggerTest extends TestCase {
+import java.io.PrintWriter;
+
+import static org.junit.Assert.assertEquals;
+
+public class DefaultLoggerTest {
- public DefaultLoggerTest(String n) {
- super(n);
- }
private static String msg(Throwable error, boolean verbose) {
StringBuffer m = new StringBuffer();
@@ -34,6 +34,7 @@ public class DefaultLoggerTest extends TestCase {
return m.toString();
}
+ @Test
public void testThrowableMessage() throws Exception { // #43398
BuildException be = new BuildException("oops", new Location("build.xml", 1, 0));
assertEquals(
diff --git a/src/tests/junit/org/apache/tools/ant/DirectoryScannerTest.java b/src/tests/junit/org/apache/tools/ant/DirectoryScannerTest.java
index 7aebfa0a2..c0c25fd7e 100644
--- a/src/tests/junit/org/apache/tools/ant/DirectoryScannerTest.java
+++ b/src/tests/junit/org/apache/tools/ant/DirectoryScannerTest.java
@@ -18,9 +18,11 @@
package org.apache.tools.ant;
-import org.apache.tools.ant.taskdefs.condition.Os;
-import org.apache.tools.ant.types.selectors.TokenizedPath;
-import org.apache.tools.ant.util.SymbolicLinkUtils;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+import static org.junit.Assume.assumeFalse;
import java.io.File;
import java.io.IOException;
@@ -30,34 +32,43 @@ import java.util.List;
import java.util.Set;
import java.util.TreeSet;
+import org.apache.tools.ant.taskdefs.condition.Os;
+import org.apache.tools.ant.types.selectors.TokenizedPath;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
/**
- * JUnit 3 testcases for org.apache.tools.ant.DirectoryScanner
+ * JUnit testcases for org.apache.tools.ant.DirectoryScanner
*
*/
-public class DirectoryScannerTest extends BuildFileTest {
-
- public DirectoryScannerTest(String name) {super(name);}
+public class DirectoryScannerTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
// keep track of what operating systems are supported here.
private boolean supportsSymlinks = Os.isFamily("unix");
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/directoryscanner.xml");
- getProject().executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/core/directoryscanner.xml");
+ buildRule.getProject().executeTarget("setUp");
}
-
+ @Test
public void test1() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha"});
ds.scan();
compareFiles(ds, new String[] {} ,new String[] {"alpha"});
}
+ @Test
public void test2() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/beta.xml",
@@ -65,9 +76,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void test3() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/beta.xml",
"alpha/beta/gamma/gamma.xml"},
@@ -75,27 +87,30 @@ public class DirectoryScannerTest extends BuildFileTest {
"alpha/beta/gamma"});
}
+ @Test
public void testFullPathMatchesCaseSensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
ds.scan();
compareFiles(ds, new String[] {}, new String[] {});
}
+ @Test
public void testFullPathMatchesCaseInsensitive() {
DirectoryScanner ds = new DirectoryScanner();
ds.setCaseSensitive(false);
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
new String[] {});
}
+ @Test
public void test2ButCaseInsensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"ALPHA/"});
ds.setCaseSensitive(false);
ds.scan();
@@ -104,28 +119,28 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testAllowSymlinks() {
- if (!supportsSymlinks) {
- return;
- }
+
+ assumeTrue("Current system does not support Symlinks", supportsSymlinks);
- getProject().executeTarget("symlink-setup");
+ buildRule.getProject().executeTarget("symlink-setup");
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/beta/gamma/"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
new String[] {"alpha/beta/gamma"});
}
+ @Test
public void testProhibitSymlinks() {
- if (!supportsSymlinks) {
- return;
- }
+ assumeTrue("Current system does not support Symlinks", supportsSymlinks);
+
- getProject().executeTarget("symlink-setup");
+ buildRule.getProject().executeTarget("symlink-setup");
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/beta/gamma/"});
ds.setFollowSymlinks(false);
ds.scan();
@@ -133,26 +148,28 @@ public class DirectoryScannerTest extends BuildFileTest {
}
// father and child pattern test
+ @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().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
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().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/beta/gamma/", "alpha/be?a/**"});
ds.scan();
compareFiles(ds, expectedFiles, expectedDirectories);
}
+ @Test
public void testPatternsDifferInCaseScanningSensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/beta.xml",
@@ -160,9 +177,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testPatternsDifferInCaseScanningInsensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
ds.setCaseSensitive(false);
ds.scan();
@@ -171,9 +189,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testFullpathDiffersInCaseScanningSensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {
"alpha/beta/gamma/gamma.xml",
"alpha/beta/gamma/GAMMA.XML"
@@ -183,9 +202,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {});
}
+ @Test
public void testFullpathDiffersInCaseScanningInsensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {
"alpha/beta/gamma/gamma.xml",
"alpha/beta/gamma/GAMMA.XML"
@@ -196,9 +216,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {});
}
+ @Test
public void testParentDiffersInCaseScanningSensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/beta.xml",
@@ -206,9 +227,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testParentDiffersInCaseScanningInsensitive() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
ds.setCaseSensitive(false);
ds.scan();
@@ -222,8 +244,10 @@ public class DirectoryScannerTest extends BuildFileTest {
* 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.
+ * @throws InterruptedException
*/
- public void testSetFollowLinks() throws IOException {
+ @Test
+ public void testSetFollowLinks() throws IOException, InterruptedException {
if (supportsSymlinks) {
File linkFile = new File(System.getProperty("root"), "src/main/org/apache/tools/ThisIsALink");
System.err.println("link exists pre-test? " + linkFile.exists());
@@ -233,20 +257,11 @@ public class DirectoryScannerTest extends BuildFileTest {
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) {
- }
+ Process process = Runtime.getRuntime().exec(command);
+ assertEquals("0 return code expected for external process", 0, process.waitFor());
+
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? " + SymbolicLinkUtils.getSymbolicLinkUtils().isSymbolicLink(dir, "ThisIsALink"));
DirectoryScanner ds = new DirectoryScanner();
@@ -304,18 +319,19 @@ public class DirectoryScannerTest extends BuildFileTest {
!haveTaskdefsPackage);
} finally {
- System.err.println("link exists pre-delete? " + linkFile.exists());
if (!linkFile.delete()) {
- throw new RuntimeException("Failed to delete " + linkFile);
+ //TODO log this?
+ //throw new RuntimeException("Failed to delete " + linkFile);
}
- System.err.println("link exists post-delete? " + linkFile.exists());
+
}
}
}
+ @Test
public void testExcludeOneFile() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {
"**/*.xml"
});
@@ -327,9 +343,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {});
}
+ @Test
public void testExcludeHasPrecedence() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {
"alpha/**"
});
@@ -342,9 +359,10 @@ public class DirectoryScannerTest extends BuildFileTest {
}
+ @Test
public void testAlternateIncludeExclude() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setIncludes(new String[] {
"alpha/**",
"alpha/beta/gamma/**"
@@ -358,9 +376,10 @@ public class DirectoryScannerTest extends BuildFileTest {
}
+ @Test
public void testAlternateExcludeInclude() {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setExcludes(new String[] {
"alpha/**",
"alpha/beta/gamma/**"
@@ -377,10 +396,11 @@ public class DirectoryScannerTest extends BuildFileTest {
/**
* Test inspired by Bug#1415.
*/
+ @Test
public void testChildrenOfExcludedDirectory() {
- getProject().executeTarget("children-of-excluded-dir-setup");
+ buildRule.getProject().executeTarget("children-of-excluded-dir-setup");
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setExcludes(new String[] {"alpha/**"});
ds.setFollowSymlinks(false);
ds.scan();
@@ -388,7 +408,7 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {"", "delta"});
ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setExcludes(new String[] {"alpha"});
ds.setFollowSymlinks(false);
ds.scan();
@@ -399,35 +419,35 @@ public class DirectoryScannerTest extends BuildFileTest {
}
+ @Test
public void testIsExcludedDirectoryScanned() {
- String shareclassloader = getProject().getProperty("tests.and.ant.share.classloader");
+ String shareclassloader = buildRule.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.startsWith("${"))) {
- System.out.println("cannot execute testIsExcludedDirectoryScanned when tests are forked, " +
- "package private method called");
- return;
- }
- getProject().executeTarget("children-of-excluded-dir-setup");
+ assumeFalse("cannot execute testIsExcludedDirectoryScanned when tests are forked, " +
+ "package private method called", shareclassloader == null
+ || (shareclassloader != null && shareclassloader.indexOf("${") == 0));
+ buildRule.getProject().executeTarget("children-of-excluded-dir-setup");
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
+
ds.setExcludes(new String[] {"**/gamma/**"});
ds.setFollowSymlinks(false);
ds.scan();
- Set set = ds.getScannedDirs();
+ Set set = ds.getScannedDirs();
assertFalse("empty set", set.isEmpty());
String s = "alpha/beta/gamma/".replace('/', File.separatorChar);
assertFalse("scanned " + s, set.contains(s));
}
+ @Test
public void testAbsolute1() {
- getProject().executeTarget("extended-setup");
+ buildRule.getProject().executeTarget("extended-setup");
DirectoryScanner ds = new DirectoryScanner();
- String tmpdir = getProject().getProperty("output").replace(
+ String tmpdir = buildRule.getProject().getProperty("output").replace(
File.separatorChar, '/');
ds.setIncludes(new String[] {tmpdir + "/**/*"});
ds.scan();
@@ -440,6 +460,7 @@ public class DirectoryScannerTest extends BuildFileTest {
tmpdir + "/delta"});
}
+ @Test
public void testAbsolute2() {
DirectoryScanner ds = new DirectoryScanner();
ds.setIncludes(new String[] {"alpha/**", "alpha/beta/gamma/**"});
@@ -448,10 +469,11 @@ public class DirectoryScannerTest extends BuildFileTest {
compareFiles(ds, mt, mt);
}
+ @Test
public void testAbsolute3() {
- getProject().executeTarget("extended-setup");
+ buildRule.getProject().executeTarget("extended-setup");
DirectoryScanner ds = new DirectoryScanner();
- String tmpdir = getProject().getProperty("output").replace(
+ String tmpdir = buildRule.getProject().getProperty("output").replace(
File.separatorChar, '/');
ds.setIncludes(new String[] {tmpdir + "/**/*"});
ds.setExcludes(new String[] {"**/alpha",
@@ -464,11 +486,12 @@ public class DirectoryScannerTest extends BuildFileTest {
tmpdir + "/delta"});
}
+ @Test
public void testAbsolute4() {
- getProject().executeTarget("extended-setup");
+ buildRule.getProject().executeTarget("extended-setup");
DirectoryScanner ds = new DirectoryScanner();
- String tmpdir = getProject().getProperty("output").replace(
- File.separatorChar, '/') ;
+ String tmpdir = buildRule.getProject().getProperty("output").replace(
+ File.separatorChar, '/') ;
ds.setIncludes(new String[] {tmpdir + "/alpha/beta/**/*",
tmpdir + "/delta/*"});
ds.setExcludes(new String[] {"**/beta.xml"});
@@ -478,11 +501,10 @@ public class DirectoryScannerTest extends BuildFileTest {
new String[] {tmpdir + "/alpha/beta/gamma"});
}
+ @Test
public void testAbsolute5() {
//testing drive letter search from root:
- if (!(Os.isFamily("dos") || Os.isFamily("netware"))) {
- return;
- }
+ assumeTrue("Can't use drive letters on non DOS or Netware systems", (Os.isFamily("dos") || Os.isFamily("netware")));
DirectoryScanner ds = new DirectoryScanner();
String pattern = new File(File.separator).getAbsolutePath().toUpperCase() + "*";
ds.setIncludes(new String[] {pattern});
@@ -501,18 +523,18 @@ public class DirectoryScannerTest extends BuildFileTest {
assertEquals("directories present: ", expectedDirectories.length,
includedDirectories.length);
- TreeSet files = new TreeSet();
+ TreeSet files = new TreeSet();
for (int counter = 0; counter < includedFiles.length; counter++) {
files.add(includedFiles[counter].replace(File.separatorChar, '/'));
}
- TreeSet directories = new TreeSet();
+ 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();
+ Iterator i = files.iterator();
int counter = 0;
while (i.hasNext()) {
currentfile = (String) i.next();
@@ -520,7 +542,7 @@ public class DirectoryScannerTest extends BuildFileTest {
counter++;
}
String currentdirectory;
- Iterator dirit = directories.iterator();
+ Iterator dirit = directories.iterator();
counter = 0;
while (dirit.hasNext()) {
currentdirectory = (String) dirit.next();
@@ -529,19 +551,20 @@ public class DirectoryScannerTest extends BuildFileTest {
}
}
+ @Test
public void testRecursiveExcludes() throws Exception {
DirectoryScanner ds = new DirectoryScanner();
- ds.setBasedir(new File(getProject().getProperty("output")));
+ ds.setBasedir(new File(buildRule.getProject().getProperty("output")));
ds.setExcludes(new String[] {"**/beta/**"});
ds.scan();
- List dirs = Arrays.asList(ds.getExcludedDirectories());
+ List dirs = Arrays.asList(ds.getExcludedDirectories());
assertEquals(2, dirs.size());
assertTrue("beta is excluded",
dirs.contains("alpha/beta".replace('/', File.separatorChar)));
assertTrue("gamma is excluded",
dirs.contains("alpha/beta/gamma".replace('/',
File.separatorChar)));
- List files = Arrays.asList(ds.getExcludedFiles());
+ List files = Arrays.asList(ds.getExcludedFiles());
assertEquals(2, files.size());
assertTrue("beta.xml is excluded",
files.contains("alpha/beta/beta.xml"
@@ -551,6 +574,7 @@ public class DirectoryScannerTest extends BuildFileTest {
.replace('/', File.separatorChar)));
}
+ @Test
public void testContentsExcluded() {
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(new File("."));
diff --git a/src/tests/junit/org/apache/tools/ant/DispatchTaskTest.java b/src/tests/junit/org/apache/tools/ant/DispatchTaskTest.java
index 2184a97dc..604a0a2ef 100644
--- a/src/tests/junit/org/apache/tools/ant/DispatchTaskTest.java
+++ b/src/tests/junit/org/apache/tools/ant/DispatchTaskTest.java
@@ -18,19 +18,29 @@
package org.apache.tools.ant;
-import org.apache.tools.ant.BuildFileTest;
+import static org.junit.Assert.fail;
-public class DispatchTaskTest extends BuildFileTest {
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
- public DispatchTaskTest(String name) {
- super(name);
- }
+public class DispatchTaskTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/dispatch/dispatch.xml");
+ buildRule.configureProject("src/etc/testcases/core/dispatch/dispatch.xml");
}
+ @Test
public void testDisp() {
- expectBuildException("disp", "list");
+ try {
+ buildRule.executeTarget("disp");
+ fail("BuildException should have been thrown");
+ } catch(BuildException ex) {
+ //FIXME the previous method used here ignored the build exception - what are we trying to test
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/ExecutorTest.java b/src/tests/junit/org/apache/tools/ant/ExecutorTest.java
index bf8c9bd91..6a370935d 100644
--- a/src/tests/junit/org/apache/tools/ant/ExecutorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/ExecutorTest.java
@@ -18,23 +18,35 @@
package org.apache.tools.ant;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
import java.util.Vector;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
/**
* Executor tests
*/
-public class ExecutorTest extends BuildFileTest implements BuildListener {
- private static final String SINGLE_CHECK
+public class ExecutorTest implements BuildListener {
+
+ private static final String SINGLE_CHECK
= "org.apache.tools.ant.helper.SingleCheckExecutor";
private static final String IGNORE_DEPS
= "org.apache.tools.ant.helper.IgnoreDependenciesExecutor";
- private static final Vector TARGET_NAMES;
+
+ private static final Vector TARGET_NAMES;
static {
- TARGET_NAMES = new Vector();
+ TARGET_NAMES = new Vector();
TARGET_NAMES.add("a");
TARGET_NAMES.add("b");
}
-
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
private int targetCount;
/* BuildListener stuff */
@@ -48,14 +60,11 @@ public class ExecutorTest extends BuildFileTest implements BuildListener {
public void taskFinished(BuildEvent event) {}
public void messageLogged(BuildEvent event) {}
- public ExecutorTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/executor.xml");
+ buildRule.configureProject("src/etc/testcases/core/executor.xml");
targetCount = 0;
- getProject().addBuildListener(this);
+ buildRule.getProject().addBuildListener(this);
}
private Project getProject(String e) {
@@ -67,7 +76,7 @@ public class ExecutorTest extends BuildFileTest implements BuildListener {
}
private Project getProject(String e, boolean f, boolean k) {
- Project p = getProject();
+ Project p = buildRule.getProject();
p.setNewProperty("ant.executor.class", e);
p.setKeepGoingMode(k);
if (f) {
@@ -76,75 +85,84 @@ public class ExecutorTest extends BuildFileTest implements BuildListener {
return p;
}
+ @Test
public void testDefaultExecutor() {
- getProject().executeTargets(TARGET_NAMES);
+ buildRule.getProject().executeTargets(TARGET_NAMES);
assertEquals(4, targetCount);
}
+ @Test
public void testSingleCheckExecutor() {
getProject(SINGLE_CHECK).executeTargets(TARGET_NAMES);
assertEquals(3, targetCount);
}
+ @Test
public void testIgnoreDependenciesExecutor() {
getProject(IGNORE_DEPS).executeTargets(TARGET_NAMES);
assertEquals(2, targetCount);
}
+ @Test
public void testDefaultFailure() {
try {
getProject(null, true).executeTargets(TARGET_NAMES);
fail("should fail");
} catch (BuildException e) {
- assertTrue(e.getMessage().equals("failfoo"));
+ assertEquals("failfoo", e.getMessage());
assertEquals(1, targetCount);
}
}
+ @Test
public void testSingleCheckFailure() {
try {
getProject(SINGLE_CHECK, true).executeTargets(TARGET_NAMES);
fail("should fail");
} catch (BuildException e) {
- assertTrue(e.getMessage().equals("failfoo"));
+ assertEquals("failfoo", e.getMessage());
assertEquals(1, targetCount);
}
}
+ @Test
public void testIgnoreDependenciesFailure() {
//no foo failure; foo is never executed as dependencies are ignored!
getProject(IGNORE_DEPS, true).executeTargets(TARGET_NAMES);
}
+ @Test
public void testKeepGoingDefault() {
try {
getProject(null, true, true).executeTargets(TARGET_NAMES);
fail("should fail");
} catch (BuildException e) {
- assertTrue(e.getMessage().equals("failfoo"));
+ assertEquals("failfoo", e.getMessage());
assertEquals(2, targetCount);
}
}
+ @Test
public void testKeepGoingSingleCheck() {
try {
getProject(SINGLE_CHECK, true, true).executeTargets(TARGET_NAMES);
fail("should fail");
} catch (BuildException e) {
- assertTrue(e.getMessage().equals("failfoo"));
+ assertEquals("failfoo", e.getMessage());
assertEquals(1, targetCount);
}
}
+ @Test
public void testKeepGoingIgnoreDependencies() {
try {
//explicitly add foo for failure
- Vector targetNames = new Vector(TARGET_NAMES);
+ Vector targetNames = new Vector(TARGET_NAMES);
targetNames.add(0, "foo");
getProject(IGNORE_DEPS, true, true).executeTargets(targetNames);
fail("should fail");
} catch (BuildException e) {
- assertTrue(e.getMessage().equals("failfoo"));
+ assertEquals("failfoo", e.getMessage());
assertEquals(3, targetCount);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/ExtendedTaskdefTest.java b/src/tests/junit/org/apache/tools/ant/ExtendedTaskdefTest.java
index 08a8029d9..a14124144 100644
--- a/src/tests/junit/org/apache/tools/ant/ExtendedTaskdefTest.java
+++ b/src/tests/junit/org/apache/tools/ant/ExtendedTaskdefTest.java
@@ -17,49 +17,52 @@
*/
package org.apache.tools.ant;
+import static org.junit.Assert.fail;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
/**
* 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 class ExtendedTaskdefTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/extended-taskdef.xml");
+ buildRule.configureProject("src/etc/testcases/core/extended-taskdef.xml");
}
- /**
- * 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 {
- super.tearDown();
- executeTarget("teardown");
+ @After
+ public void tearDown() throws Exception {
+ buildRule.executeTarget("teardown");
}
+ @Test
public void testRun() throws Exception {
- expectBuildExceptionContaining("testRun",
- "exception thrown by the subclass",
- "executing the Foo task");
+ try {
+ buildRule.executeTarget("testRun");
+ fail("BuildException should have been thrown");
+ } catch(BuildException ex) {
+ assertContains("exception thrown by the subclass", "executing the Foo task", ex.getMessage());
+ }
}
+ @Test
public void testRun2() throws Exception {
- expectBuildExceptionContaining("testRun2",
- "exception thrown by the subclass",
- "executing the Foo task");
+ try {
+ buildRule.executeTarget("testRun2");
+ fail("BuildException should have been thrown");
+ } catch(BuildException ex) {
+ assertContains("exception thrown by the subclass", "executing the Foo task", ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/FileUtilities.java b/src/tests/junit/org/apache/tools/ant/FileUtilities.java
new file mode 100644
index 000000000..a9de5cea4
--- /dev/null
+++ b/src/tests/junit/org/apache/tools/ant/FileUtilities.java
@@ -0,0 +1,88 @@
+/*
+ * 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.util.FileUtils;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+
+import static org.junit.Assume.assumeTrue;
+
+public class FileUtilities {
+
+ /**
+ * Reads the contents of a file into a String.
+ * @param project the project containing the base directory the file is in.
+ * @param fileName the path to the file from the base directory.
+ * @return the contents of the given file as a string.
+ * @throws IOException on error reading the file (not existing, not readable etc)
+ */
+ public static String getFileContents(Project project, String fileName) throws IOException {
+ return getFileContents(new File(project.getBaseDir(), fileName));
+ }
+
+ /**
+ * Reads the contents of a file into a String.
+ * @param file the file to read.
+ * @return the contents of the given file as a string.
+ * @throws IOException on error reading the file (not existing, not readable etc)
+ */
+ public static String getFileContents(File file) throws IOException {
+ FileReader rdr = null;
+ try {
+ rdr = new FileReader(file);
+ return FileUtils.readFully(rdr);
+ }
+ finally {
+ if (rdr != null) {
+ rdr.close();
+ }
+ }
+ }
+
+
+ /**
+ * Modified the timestamp on a file so it's seconds earlier than it was before. Where file
+ * is a directory, this function recurses into all child files (and directories) and reduces their modified
+ * timestamps by the same range, rather than set all timestamps to the same time.
+ * @param file the file to change, or the directory to change then recurse into
+ * @param seconds how many seconds to roll the timestamp back by
+ */
+ public static void rollbackTimetamps(File file, long seconds) {
+ if (null == file || !file.exists()) {
+ return;
+ }
+
+ assumeTrue(file.setLastModified(file.lastModified() - (seconds * 1000)));
+
+ if (file.isDirectory()) {
+ File[] children = file.listFiles();
+ // only possible if exception occurs, or abstract path was not valid
+ if (children == null) {
+ return;
+ }
+ for (File child : children) {
+ rollbackTimetamps(child, seconds);
+ }
+ }
+ }
+
+}
diff --git a/src/tests/junit/org/apache/tools/ant/ImmutableTest.java b/src/tests/junit/org/apache/tools/ant/ImmutableTest.java
index fef59cd7f..cd65a5a61 100644
--- a/src/tests/junit/org/apache/tools/ant/ImmutableTest.java
+++ b/src/tests/junit/org/apache/tools/ant/ImmutableTest.java
@@ -18,61 +18,73 @@
package org.apache.tools.ant;
-import org.apache.tools.ant.BuildFileTest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertEquals;
/**
*/
-public class ImmutableTest extends BuildFileTest {
+public class ImmutableTest {
- public ImmutableTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/immutable.xml");
+ buildRule.configureProject("src/etc/testcases/core/immutable.xml");
}
// override allowed on
+ @Test
public void test1() {
- executeTarget("test1");
- assertEquals("override", project.getProperty("test"));
+ buildRule.executeTarget("test1");
+ assertEquals("override",buildRule.getProject().getProperty("test"));
}
// ensure 's new prefix attribute is working
+ @Test
public void test2() {
- executeTarget("test2");
- assertNotNull(project.getProperty("DSTAMP"));
- assertNotNull(project.getProperty("start.DSTAMP"));
+ buildRule.executeTarget("test2");
+ assertNotNull(buildRule.getProject().getProperty("DSTAMP"));
+ assertNotNull(buildRule.getProject().getProperty("start.DSTAMP"));
}
// ensure follows the immutability rule
+ @Test
public void test3() {
- executeTarget("test3");
- assertEquals("original", project.getProperty("DSTAMP"));
+ buildRule.executeTarget("test3");
+ assertEquals("original", buildRule.getProject().getProperty("DSTAMP"));
}
// ensure follows the immutability rule
+ @Test
public void test4() {
- executeTarget("test4");
- assertEquals("original", project.getProperty("test"));
+ buildRule.executeTarget("test4");
+ assertEquals("original", buildRule.getProject().getProperty("test"));
}
// ensure follows the immutability rule
+ @Test
public void test5() {
- executeTarget("test5");
- assertEquals("original", project.getProperty("test"));
+ buildRule.executeTarget("test5");
+ assertEquals("original", buildRule.getProject().getProperty("test"));
}
// ensure follows the immutability rule
+ @Test
public void test6() {
- executeTarget("test6");
- assertEquals("original", project.getProperty("test1"));
- assertEquals("original", project.getProperty("test2"));
+ buildRule.executeTarget("test6");
+ assertEquals("original", buildRule.getProject().getProperty("test1"));
+ assertEquals("original", buildRule.getProject().getProperty("test2"));
}
// ensure follows the immutability rule
+ @Test
public void test7() {
- executeTarget("test7");
- assertEquals("original", project.getProperty("test"));
+ buildRule.executeTarget("test7");
+ assertEquals("original", buildRule.getProject().getProperty("test"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/IncludeTest.java b/src/tests/junit/org/apache/tools/ant/IncludeTest.java
index 56cb5d56e..54e61a41a 100644
--- a/src/tests/junit/org/apache/tools/ant/IncludeTest.java
+++ b/src/tests/junit/org/apache/tools/ant/IncludeTest.java
@@ -18,60 +18,75 @@
package org.apache.tools.ant;
-import junit.framework.AssertionFailedError;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
-import org.apache.tools.ant.BuildFileTest;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Test the build file inclusion using XML entities.
*
*/
-public class IncludeTest extends BuildFileTest {
-
- public IncludeTest(String name) {
- super(name);
- }
+public class IncludeTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Test
public void test1() {
- configureProject("src/etc/testcases/core/include/basic/include.xml");
- expectLog("test1", "from included entity");
+ buildRule.configureProject("src/etc/testcases/core/include/basic/include.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from included entity", buildRule.getLog());
}
+ @Test
public void test2() {
- configureProject("src/etc/testcases/core/include/frag#ment/include.xml");
- expectLog("test1", "from included entity");
+ buildRule.configureProject("src/etc/testcases/core/include/frag#ment/include.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from included entity", buildRule.getLog());
}
+ @Test
public void test3() {
- configureProject("src/etc/testcases/core/include/frag#ment/simple.xml");
- expectLog("test1", "from simple buildfile");
+ buildRule.configureProject("src/etc/testcases/core/include/frag#ment/simple.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from simple buildfile", buildRule.getLog());
}
+ @Test
public void test4() {
- configureProject("src/etc/testcases/core/include/basic/relative.xml");
- expectLog("test1", "from included entity");
+ buildRule.configureProject("src/etc/testcases/core/include/basic/relative.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from included entity", buildRule.getLog());
}
+ @Test
public void test5() {
- configureProject("src/etc/testcases/core/include/frag#ment/relative.xml");
- expectLog("test1", "from included entity");
+ buildRule.configureProject("src/etc/testcases/core/include/frag#ment/relative.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from included entity", buildRule.getLog());
}
+ @Test
public void testParseErrorInIncluding() {
try {
- configureProject("src/etc/testcases/core/include/including_file_parse_error/build.xml");
+ buildRule.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()
+ assertContains(e.getLocation().toString()
+ " should refer to build.xml",
- e.getLocation().toString().indexOf("build.xml:") > -1);
+ "build.xml:", e.getLocation().toString());
}
}
+ @Test
public void testTaskErrorInIncluding() {
- configureProject("src/etc/testcases/core/include/including_file_task_error/build.xml");
+ buildRule.configureProject("src/etc/testcases/core/include/including_file_task_error/build.xml");
try {
- executeTarget("test");
+ buildRule.executeTarget("test");
fail("should have cause a build failure");
} catch (BuildException e) {
assertTrue(e.getMessage()
@@ -83,22 +98,24 @@ public class IncludeTest extends BuildFileTest {
}
}
+ @Test
public void testParseErrorInIncluded() {
try {
- configureProject("src/etc/testcases/core/include/included_file_parse_error/build.xml");
+ buildRule.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()
+ assertContains(e.getLocation().toString()
+ " should refer to included_file.xml",
- e.getLocation().toString()
- .indexOf("included_file.xml:") > -1);
+ "included_file.xml:",
+ e.getLocation().toString());
}
}
+ @Test
public void testTaskErrorInIncluded() {
- configureProject("src/etc/testcases/core/include/included_file_task_error/build.xml");
+ buildRule.configureProject("src/etc/testcases/core/include/included_file_task_error/build.xml");
try {
- executeTarget("test");
+ buildRule.executeTarget("test");
fail("should have cause a build failure");
} catch (BuildException e) {
assertTrue(e.getMessage()
@@ -110,24 +127,25 @@ public class IncludeTest extends BuildFileTest {
}
}
+ @Test
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());
- }
+ buildRule.configureProject("src/etc/testcases/core/include/with space/include.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from included entity in 'with space'", buildRule.getLog());
}
+ @Test
public void testWithSpaceSimple() {
- configureProject("src/etc/testcases/core/include/with space/simple.xml");
- expectLog("test1", "from simple buildfile in 'with space'");
+ buildRule.configureProject("src/etc/testcases/core/include/with space/simple.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from simple buildfile in 'with space'", buildRule.getLog());
}
+ @Test
public void testWithSpaceRelative() {
- configureProject("src/etc/testcases/core/include/with space/relative.xml");
- expectLog("test1", "from included entity in 'with space'");
+ buildRule.configureProject("src/etc/testcases/core/include/with space/relative.xml");
+ buildRule.executeTarget("test1");
+ assertEquals("from included entity in 'with space'", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java
index d0003a931..ca4085d20 100644
--- a/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/IntrospectionHelperTest.java
@@ -18,8 +18,6 @@
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;
@@ -31,43 +29,53 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.tools.ant.taskdefs.condition.Os;
+import org.junit.Before;
+import org.junit.ComparisonFailure;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
- * JUnit 3 testcases for org.apache.tools.ant.IntrospectionHelper.
+ * JUnit testcases for org.apache.tools.ant.IntrospectionHelper.
*
*/
-public class IntrospectionHelperTest extends TestCase {
+public class IntrospectionHelperTest {
private Project p;
private IntrospectionHelper ih;
private static final String projectBasedir = File.separator;
- public IntrospectionHelperTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
p = new Project();
p.setBasedir(projectBasedir);
ih = IntrospectionHelper.getHelper(getClass());
}
+ @Test
public void testIsDynamic() {
- assertTrue("Not dynamic", false == ih.isDynamic());
+ assertFalse("Not dynamic", ih.isDynamic());
}
+ @Test
public void testIsContainer() {
- assertTrue("Not a container", false == ih.isContainer());
+ assertFalse("Not a container", ih.isContainer());
}
+ @Test
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof ComparisonFailure);
}
ih = IntrospectionHelper.getHelper(String.class);
@@ -75,9 +83,12 @@ public class IntrospectionHelperTest extends TestCase {
ih.addText(p, "", "test");
fail("String doesn\'t support addText");
} catch (BuildException be) {
+ //TODO the value should be asserted
}
}
+ @Test
+ @Ignore("This silently ignores a build exception")
public void testGetAddTextMethod() {
Method m = ih.getAddTextMethod();
assertMethod(m, "addText", String.class, "test", "bing!");
@@ -88,6 +99,7 @@ public class IntrospectionHelperTest extends TestCase {
} catch (BuildException e) {}
}
+ @Test
public void testSupportsCharacters() {
assertTrue("IntrospectionHelperTest supports addText",
ih.supportsCharacters());
@@ -100,31 +112,37 @@ public class IntrospectionHelperTest extends TestCase {
assertEquals("test", text);
}
+ @Test
public void testElementCreators() throws BuildException {
try {
ih.getElementType("one");
fail("don't have element type one");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("two");
fail("createTwo takes arguments");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("three");
fail("createThree returns void");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("four");
fail("createFour returns array");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("five");
fail("createFive returns primitive type");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
assertEquals(String.class, ih.getElementType("six"));
assertEquals("test", ih.createElement(p, this, "six"));
@@ -133,31 +151,37 @@ public class IntrospectionHelperTest extends TestCase {
ih.getElementType("seven");
fail("addSeven takes two arguments");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("eight");
fail("addEight takes no arguments");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("nine");
fail("nine return non void");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("ten");
fail("addTen takes array argument");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("eleven");
fail("addEleven takes primitive argument");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.getElementType("twelve");
fail("no primitive constructor for java.lang.Class");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
assertEquals(StringBuffer.class, ih.getElementType("thirteen"));
assertEquals("test", ih.createElement(p, this, "thirteen").toString());
@@ -186,6 +210,7 @@ public class IntrospectionHelperTest extends TestCase {
return elemMap;
}
+ @Test
public void testGetNestedElements() {
Map elemMap = getExpectedNestedElements();
Enumeration e = ih.getNestedElements();
@@ -200,6 +225,7 @@ public class IntrospectionHelperTest extends TestCase {
assertTrue("Found all", elemMap.isEmpty());
}
+ @Test
public void testGetNestedElementMap() {
Map elemMap = getExpectedNestedElements();
Map actualMap = ih.getNestedElementMap();
@@ -217,9 +243,11 @@ public class IntrospectionHelperTest extends TestCase {
// Check it's a read-only map.
try {
actualMap.clear();
+ //TODO we should be asserting a value somewhere in here
} catch (UnsupportedOperationException e) {}
}
+ @Test
public void testGetElementMethod() {
assertElemMethod("six", "createSix", String.class, null);
assertElemMethod("thirteen", "addThirteen", null, StringBuffer.class);
@@ -286,85 +314,92 @@ public class IntrospectionHelperTest extends TestCase {
throw new NullPointerException();
}
+ @Test
public void testAttributeSetters() throws BuildException {
try {
ih.setAttribute(p, this, "one", "test");
fail("setOne doesn't exist");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.setAttribute(p, this, "two", "test");
fail("setTwo returns non void");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.setAttribute(p, this, "three", "test");
fail("setThree takes no args");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.setAttribute(p, this, "four", "test");
fail("setFour takes two args");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.setAttribute(p, this, "five", "test");
fail("setFive takes array arg");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
try {
ih.setAttribute(p, this, "six", "test");
fail("Project doesn't have a String constructor");
} catch (BuildException be) {
+ //TODO we should be asserting a value in here
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof ComparisonFailure);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue("Cause of error: " + be.toString(), be.getCause() instanceof AssertionError);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
ih.setAttribute(p, this, "eleven", "2");
try {
ih.setAttribute(p, this, "eleven", "on");
fail("on shouldn't be false");
} catch (BuildException be) {
- assertTrue(be.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
ih.setAttribute(p, this, "twelve", "2");
try {
ih.setAttribute(p, this, "twelve", "on");
fail("on shouldn't be false");
} catch (BuildException be) {
- assertTrue(be.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
try {
ih.setAttribute(p, this, "thirteen", "org.apache.tools.ant.Project2");
@@ -377,42 +412,42 @@ public class IntrospectionHelperTest extends TestCase {
ih.setAttribute(p, this, "fourteen", "on");
fail("2 shouldn't be equals to three - as StringBuffer");
} catch (BuildException be) {
- assertTrue(be.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof ComparisonFailure);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
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.getCause() instanceof AssertionFailedError);
+ assertTrue(be.getCause() instanceof AssertionError);
}
}
@@ -444,6 +479,7 @@ public class IntrospectionHelperTest extends TestCase {
return attrMap;
}
+ @Test
public void testGetAttributes() {
Map attrMap = getExpectedAttributes();
Enumeration e = ih.getAttributes();
@@ -459,6 +495,7 @@ public class IntrospectionHelperTest extends TestCase {
assertTrue("Found all", attrMap.isEmpty());
}
+ @Test
public void testGetAttributeMap() {
Map attrMap = getExpectedAttributes();
Map actualMap = ih.getAttributeMap();
@@ -477,9 +514,11 @@ public class IntrospectionHelperTest extends TestCase {
// Check it's a read-only map.
try {
actualMap.clear();
+ //TODO we should be asserting a value somewhere in here
} catch (UnsupportedOperationException e) {}
}
+ @Test
public void testGetAttributeMethod() {
assertAttrMethod("seven", "setSeven", String.class,
"2", "3");
@@ -511,7 +550,9 @@ public class IntrospectionHelperTest extends TestCase {
try {
assertAttrMethod("onehundred", null, null, null, null);
fail("Should have raised a BuildException!");
- } catch (BuildException e) {}
+ } catch (BuildException e) {
+ //TODO we should be asserting a value in here
+ }
}
private void assertAttrMethod(String attrName, String methodName,
@@ -593,6 +634,7 @@ public class IntrospectionHelperTest extends TestCase {
assertTrue("Expected 19, received " + d, diff > -1e-6 && diff < 1e-6);
}
+ @Test
public void testGetExtensionPoints() {
List extensions = ih.getExtensionPoints();
final int adders = 2;
@@ -645,7 +687,7 @@ public class IntrospectionHelperTest extends TestCase {
throw new BuildException(e);
} catch (InvocationTargetException e) {
Throwable t = e.getTargetException();
- assertTrue(t instanceof junit.framework.AssertionFailedError);
+ assertTrue(t.toString(), t instanceof AssertionError);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/LoaderRefTest.java b/src/tests/junit/org/apache/tools/ant/LoaderRefTest.java
index 50cd3eaaa..2fb7439bc 100644
--- a/src/tests/junit/org/apache/tools/ant/LoaderRefTest.java
+++ b/src/tests/junit/org/apache/tools/ant/LoaderRefTest.java
@@ -18,25 +18,35 @@
package org.apache.tools.ant;
-import org.apache.tools.ant.BuildFileTest;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
*/
-public class LoaderRefTest extends BuildFileTest {
-
- public LoaderRefTest(String name) {
- super(name);
- }
+public class LoaderRefTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/loaderref/loaderref.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/core/loaderref/loaderref.xml");
+ buildRule.executeTarget("setUp");
}
// override allowed on
- public void testBadRef() {
- expectBuildExceptionContaining("testbadref", "Should fail due to ref "
- + "not being a class loader", "does not reference a class loader");
+ @Test
+ public void testBadRef() {
+ try {
+ buildRule.executeTarget("testbadref");
+ fail("BuildRule should have thrown an exception due to a bad classloader being specified");
+ } catch (BuildException ex) {
+ assertContains("Should fail due to ref not being a class loader", "does not reference a class loader", ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/LocationTest.java b/src/tests/junit/org/apache/tools/ant/LocationTest.java
index b8c9af03c..c8048a31a 100644
--- a/src/tests/junit/org/apache/tools/ant/LocationTest.java
+++ b/src/tests/junit/org/apache/tools/ant/LocationTest.java
@@ -21,49 +21,65 @@ 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;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class LocationTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+public class LocationTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/location.xml");
+ buildRule.configureProject("src/etc/testcases/core/location.xml");
}
+ @Test
public void testPlainTask() {
- executeTarget("testPlainTask");
- Echo e = (Echo) getProject().getReference("echo");
+ buildRule.executeTarget("testPlainTask");
+ Echo e = (Echo) buildRule.getProject().getReference("echo");
assertFalse(e.getLocation() == Location.UNKNOWN_LOCATION);
assertFalse(e.getLocation().getLineNumber() == 0);
}
+ @Test
public void testStandaloneType() {
- executeTarget("testStandaloneType");
- Echo e = (Echo) getProject().getReference("echo2");
- FileSet f = (FileSet) getProject().getReference("fs");
+ buildRule.executeTarget("testStandaloneType");
+ Echo e = (Echo) buildRule.getProject().getReference("echo2");
+ FileSet f = (FileSet) buildRule.getProject().getReference("fs");
assertFalse(f.getLocation() == Location.UNKNOWN_LOCATION);
assertEquals(e.getLocation().getLineNumber() + 1,
f.getLocation().getLineNumber());
}
+ @Test
public void testConditionTask() {
- executeTarget("testConditionTask");
- TaskAdapter ta = (TaskAdapter) getProject().getReference("cond");
+ buildRule.executeTarget("testConditionTask");
+ TaskAdapter ta = (TaskAdapter) buildRule.getProject().getReference("cond");
ConditionTask c = (ConditionTask) ta.getProxy();
assertFalse(c.getLocation() == Location.UNKNOWN_LOCATION);
assertFalse(c.getLocation().getLineNumber() == 0);
}
+ @Test
public void testMacrodefWrappedTask() {
- executeTarget("testMacrodefWrappedTask");
- Echo e = (Echo) getProject().getReference("echo3");
- assertTrue(getLog().indexOf("Line: "
+ buildRule.executeTarget("testMacrodefWrappedTask");
+ Echo e = (Echo) buildRule.getProject().getReference("echo3");
+ assertTrue(buildRule.getLog().indexOf("Line: "
+ (e.getLocation().getLineNumber() + 1))
> -1);
}
+ @Test
public void testPresetdefWrappedTask() {
- executeTarget("testPresetdefWrappedTask");
- Echo e = (Echo) getProject().getReference("echo4");
- assertTrue(getLog().indexOf("Line: "
+ buildRule.executeTarget("testPresetdefWrappedTask");
+ Echo e = (Echo) buildRule.getProject().getReference("echo4");
+ assertTrue(buildRule.getLog().indexOf("Line: "
+ (e.getLocation().getLineNumber() + 1))
> -1);
}
diff --git a/src/tests/junit/org/apache/tools/ant/MockBuildListener.java b/src/tests/junit/org/apache/tools/ant/MockBuildListener.java
index f68a828c6..e3a96a851 100644
--- a/src/tests/junit/org/apache/tools/ant/MockBuildListener.java
+++ b/src/tests/junit/org/apache/tools/ant/MockBuildListener.java
@@ -18,13 +18,14 @@
package org.apache.tools.ant;
-import java.util.Vector;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
-import junit.framework.Assert;
+import java.util.Vector;
-public class MockBuildListener extends Assert implements BuildListener {
+public class MockBuildListener implements BuildListener {
- private final Vector buffer = new Vector();
+ private final Vector buffer = new Vector();
private final Project project;
public MockBuildListener(final Project project) {
diff --git a/src/tests/junit/org/apache/tools/ant/ProjectComponentTest.java b/src/tests/junit/org/apache/tools/ant/ProjectComponentTest.java
index e195b4ec0..6e5120999 100644
--- a/src/tests/junit/org/apache/tools/ant/ProjectComponentTest.java
+++ b/src/tests/junit/org/apache/tools/ant/ProjectComponentTest.java
@@ -18,14 +18,14 @@
package org.apache.tools.ant;
-import junit.framework.TestCase;
+import org.junit.Test;
-public class ProjectComponentTest extends TestCase {
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
- public ProjectComponentTest(String name) {
- super(name);
- }
+public class ProjectComponentTest {
+ @Test
public void testClone() throws CloneNotSupportedException {
Project expectedProject = new Project();
Location expectedLocation = new Location("foo");
diff --git a/src/tests/junit/org/apache/tools/ant/ProjectHelperRepositoryTest.java b/src/tests/junit/org/apache/tools/ant/ProjectHelperRepositoryTest.java
index 9afecd8cb..550c342b7 100644
--- a/src/tests/junit/org/apache/tools/ant/ProjectHelperRepositoryTest.java
+++ b/src/tests/junit/org/apache/tools/ant/ProjectHelperRepositoryTest.java
@@ -19,17 +19,19 @@ package org.apache.tools.ant;
import java.io.File;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.helper.ProjectHelper2;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.types.resources.StringResource;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Testing around the management of the project helpers
*/
-public class ProjectHelperRepositoryTest extends TestCase {
+public class ProjectHelperRepositoryTest {
public static class SomeHelper extends ProjectHelper {
public boolean canParseBuildFile(Resource buildFile) {
@@ -42,6 +44,7 @@ public class ProjectHelperRepositoryTest extends TestCase {
}
}
+ @Test
public void testFind() throws Exception {
ProjectHelperRepository repo = ProjectHelperRepository.getInstance();
repo.registerProjectHelper(SomeHelper.class);
@@ -71,7 +74,9 @@ public class ProjectHelperRepositoryTest extends TestCase {
assertTrue(helper instanceof ProjectHelper2);
}
- public void testNoDefaultConstructor() throws Exception {
+ @Test
+ public void testNoDefaultContructor() throws Exception {
+
class IncrrectHelper extends ProjectHelper {
// the default constructor is not visible to ant here
}
@@ -82,9 +87,11 @@ public class ProjectHelperRepositoryTest extends TestCase {
fail("Registring an helper with no default constructor should fail");
} catch (BuildException e) {
// ok
+ //TODO we should be asserting a value in here
}
}
+ @Test
public void testUnkwnowHelper() throws Exception {
ProjectHelperRepository repo = ProjectHelperRepository.getInstance();
try {
@@ -92,6 +99,7 @@ public class ProjectHelperRepositoryTest extends TestCase {
fail("Registring an unknwon helper should fail");
} catch (BuildException e) {
// ok
+ //TODO we should be asserting a value in here
}
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/ProjectTest.java b/src/tests/junit/org/apache/tools/ant/ProjectTest.java
index fd4cff15d..89ed8c367 100644
--- a/src/tests/junit/org/apache/tools/ant/ProjectTest.java
+++ b/src/tests/junit/org/apache/tools/ant/ProjectTest.java
@@ -22,26 +22,39 @@ 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;
+
+import org.apache.tools.ant.types.FileSet;
+import org.apache.tools.ant.types.Path;
+import org.apache.tools.ant.types.PatternSet;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Very limited test class for Project. Waiting to be extended.
*
*/
-public class ProjectTest extends TestCase {
+public class ProjectTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
private Project p;
private String root;
private MockBuildListener mbl;
- public ProjectTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
p = new Project();
p.init();
@@ -49,6 +62,7 @@ public class ProjectTest extends TestCase {
mbl = new MockBuildListener(p);
}
+ @Test
public void testDataTypes() throws BuildException {
assertNull("dummy is not a known data type",
p.createDataType("dummy"));
@@ -63,6 +77,7 @@ public class ProjectTest extends TestCase {
/**
* This test has been a starting point for moving the code to FileUtils.
*/
+ @Test
public void testResolveFile() {
if (Os.isFamily("netware") || Os.isFamily("dos")) {
assertEqualsIgnoreDriveCase(localize(File.separator),
@@ -178,6 +193,7 @@ public class ProjectTest extends TestCase {
}
}
+ @Test
public void testAddTaskDefinition() {
p.addBuildListener(mbl);
@@ -209,6 +225,7 @@ public class ProjectTest extends TestCase {
assertEquals(DummyTaskWithNonVoidExecute.class, p.getTaskDefinitions().get("NonVoidExecute"));
}
+ @Test
public void testInputHandler() {
InputHandler ih = p.getInputHandler();
assertNotNull(ih);
@@ -218,33 +235,38 @@ public class ProjectTest extends TestCase {
assertSame(pfih, p.getInputHandler());
}
+ @Test
public void testTaskDefinitionContainsKey() {
assertTrue(p.getTaskDefinitions().containsKey("echo"));
}
+ @Test
public void testTaskDefinitionContains() {
assertTrue(p.getTaskDefinitions().contains(org.apache.tools.ant.taskdefs.Echo.class));
}
+ @Test
public void testDuplicateTargets() {
// fail, because buildfile contains two targets with the same name
try {
- BFT bft = new BFT("", "core/duplicate-target.xml");
+ buildRule.configureProject("src/etc/testcases/core/duplicate-target.xml");
+ fail("Should throw BuildException about duplicate target");
} catch (BuildException ex) {
assertEquals("specific message",
"Duplicate target 'twice'",
ex.getMessage());
- return;
}
- fail("Should throw BuildException about duplicate target");
}
+ @Test
public void testDuplicateTargetsImport() {
// overriding target from imported buildfile is allowed
- BFT bft = new BFT("", "core/duplicate-target2.xml");
- bft.expectLog("once", "once from buildfile");
+ buildRule.configureProject("src/etc/testcases/core/duplicate-target2.xml");
+ buildRule.executeTarget("once");
+ assertContains("once from buildfile", buildRule.getLog());
}
+ @Test
public void testOutputDuringMessageLoggedIsSwallowed()
throws InterruptedException {
final String FOO = "foo", BAR = "bar";
@@ -277,8 +299,10 @@ public class ProjectTest extends TestCase {
}
/**
- * @see https://issues.apache.org/bugzilla/show_bug.cgi?id=47623
+ * @see
+ * https://issues.apache.org/bugzilla/show_bug.cgi?id=47623
*/
+ @Test
public void testNullThrowableMessageLog() {
p.log(new Task() {}, null, new Throwable(), Project.MSG_ERR);
// be content if no exception has been thrown
@@ -294,42 +318,10 @@ public class ProjectTest extends TestCase {
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() {}
+ }
-class DummyTaskPackage extends Task {
- public DummyTaskPackage() {}
- public void execute() {}
-}
+}
\ No newline at end of file
diff --git a/src/tests/junit/org/apache/tools/ant/PropertyExpansionTest.java b/src/tests/junit/org/apache/tools/ant/PropertyExpansionTest.java
index 718d84340..4ac8c5f78 100644
--- a/src/tests/junit/org/apache/tools/ant/PropertyExpansionTest.java
+++ b/src/tests/junit/org/apache/tools/ant/PropertyExpansionTest.java
@@ -19,33 +19,39 @@
package org.apache.tools.ant;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
/**
* class to look at how we expand properties
*/
-public class PropertyExpansionTest extends BuildFileTest {
-
-
- public PropertyExpansionTest(String name) {
- super(name);
- }
+public class PropertyExpansionTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
/**
* 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
*/
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/immutable.xml");
+ buildRule.configureProject("src/etc/testcases/core/immutable.xml");
}
/**
* run through the test cases of expansion
*/
+ @Test
public void testPropertyExpansion() {
assertExpandsTo("","");
assertExpandsTo("$","$");
assertExpandsTo("$$-","$-");
assertExpandsTo("$$","$");
- project.setProperty("expanded","EXPANDED");
+ buildRule.getProject().setProperty("expanded","EXPANDED");
assertExpandsTo("a${expanded}b","aEXPANDEDb");
assertExpandsTo("${expanded}${expanded}","EXPANDEDEXPANDED");
assertExpandsTo("$$$","$$");
@@ -57,6 +63,7 @@ public class PropertyExpansionTest extends BuildFileTest {
/**
* new things we want
*/
+ @Test
public void testDollarPassthru() {
assertExpandsTo("$-","$-");
assertExpandsTo("Class$subclass","Class$subclass");
@@ -71,6 +78,8 @@ public class PropertyExpansionTest extends BuildFileTest {
/**
* old things we dont want; not a test no more
*/
+ @Test
+ @Ignore("Previously disabled through naming convention")
public void oldtestQuirkyLegacyBehavior() {
assertExpandsTo("Class$subclass","Classsubclass");
assertExpandsTo("$$$-","$-");
@@ -82,7 +91,7 @@ public class PropertyExpansionTest extends BuildFileTest {
* little helper method to validate stuff
*/
private void assertExpandsTo(String source,String expected) {
- String actual=project.replaceProperties(source);
+ String actual = buildRule.getProject().replaceProperties(source);
assertEquals(source,expected,actual);
}
diff --git a/src/tests/junit/org/apache/tools/ant/PropertyFileCLITest.java b/src/tests/junit/org/apache/tools/ant/PropertyFileCLITest.java
index 64e875324..371888298 100644
--- a/src/tests/junit/org/apache/tools/ant/PropertyFileCLITest.java
+++ b/src/tests/junit/org/apache/tools/ant/PropertyFileCLITest.java
@@ -21,11 +21,14 @@ package org.apache.tools.ant;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
-import junit.framework.TestCase;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Test;
-public class PropertyFileCLITest extends TestCase {
+import static org.apache.tools.ant.AntAssert.assertContains;
+public class PropertyFileCLITest {
+
+ @Test
public void testPropertyResolution() throws Exception {
FileUtils fu = FileUtils.getFileUtils();
File props = fu.createTempFile("propertyfilecli", ".properties",
@@ -51,8 +54,7 @@ public class PropertyFileCLITest extends TestCase {
"-l", log.getAbsolutePath()
}, null, null);
String l = FileUtils.safeReadFully(fr = new FileReader(log));
- assertTrue("expected log to contain 'Hello, world' but was " + l,
- l.indexOf("Hello, world") > -1);
+ assertContains("Hello, world", l);
} finally {
FileUtils.close(fw);
FileUtils.close(fr);
diff --git a/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java b/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java
index beff4c267..700b7c11d 100644
--- a/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java
+++ b/src/tests/junit/org/apache/tools/ant/TaskContainerTest.java
@@ -18,40 +18,49 @@
package org.apache.tools.ant;
-public class TaskContainerTest extends BuildFileTest {
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
- public TaskContainerTest(String name) {
- super(name);
- }
+import static org.junit.Assert.assertTrue;
+
+public class TaskContainerTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/taskcontainer.xml");
+ buildRule.configureProject("src/etc/testcases/core/taskcontainer.xml");
}
+ @Test
public void testPropertyExpansion() {
- executeTarget("testPropertyExpansion");
+ buildRule.executeTarget("testPropertyExpansion");
assertTrue("attribute worked",
- getLog().indexOf("As attribute: it worked") > -1);
+ buildRule.getLog().indexOf("As attribute: it worked") > -1);
assertTrue("nested text worked",
- getLog().indexOf("As nested text: it worked") > -1);
+ buildRule.getLog().indexOf("As nested text: it worked") > -1);
}
+ @Test
public void testTaskdef() {
- executeTarget("testTaskdef");
+ buildRule.executeTarget("testTaskdef");
assertTrue("attribute worked",
- getLog().indexOf("As attribute: it worked") > -1);
+ buildRule.getLog().indexOf("As attribute: it worked") > -1);
assertTrue("nested text worked",
- getLog().indexOf("As nested text: it worked") > -1);
+ buildRule.getLog().indexOf("As nested text: it worked") > -1);
assertTrue("nested text worked",
- getLog().indexOf("As nested task: it worked") > -1);
+ buildRule.getLog().indexOf("As nested task: it worked") > -1);
}
+ @Test
public void testCaseInsensitive() {
- executeTarget("testCaseInsensitive");
+ buildRule.executeTarget("testCaseInsensitive");
assertTrue("works outside of container",
- getLog().indexOf("hello ") > -1);
+ buildRule.getLog().indexOf("hello ") > -1);
assertTrue("works inside of container",
- getLog().indexOf("world") > -1);
+ buildRule.getLog().indexOf("world") > -1);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/TopLevelTaskTest.java b/src/tests/junit/org/apache/tools/ant/TopLevelTaskTest.java
index 1aceaa2e9..7d73dc0e3 100644
--- a/src/tests/junit/org/apache/tools/ant/TopLevelTaskTest.java
+++ b/src/tests/junit/org/apache/tools/ant/TopLevelTaskTest.java
@@ -21,29 +21,39 @@ 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.
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
/**
* Tests for builds with tasks at the top level
*
* @since Ant 1.6
*/
-public class TopLevelTaskTest extends BuildFileTest {
+public class TopLevelTaskTest {
- public TopLevelTaskTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Test
public void testNoTarget() {
- configureProject("src/etc/testcases/core/topleveltasks/notarget.xml");
- expectLog("", "Called");
+ buildRule.configureProject("src/etc/testcases/core/topleveltasks/notarget.xml");
+ buildRule.executeTarget("");
+ assertEquals("Called", buildRule.getLog());
}
+ @Test
public void testCalledFromTopLevelAnt() {
- configureProject("src/etc/testcases/core/topleveltasks/toplevelant.xml");
- expectLog("", "Called");
+ buildRule.configureProject("src/etc/testcases/core/topleveltasks/toplevelant.xml");
+ buildRule.executeTarget("");
+ assertEquals("Called", buildRule.getLog());
}
+ @Test
public void testCalledFromTargetLevelAnt() {
- configureProject("src/etc/testcases/core/topleveltasks/targetlevelant.xml");
- expectLog("foo", "Called");
+ buildRule.configureProject("src/etc/testcases/core/topleveltasks/targetlevelant.xml");
+ buildRule.executeTarget("foo");
+ assertEquals("Called", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java
index c70701454..be7e21b84 100644
--- a/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java
+++ b/src/tests/junit/org/apache/tools/ant/UnknownElementTest.java
@@ -18,26 +18,45 @@
package org.apache.tools.ant;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-public class UnknownElementTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNotNull;
+
+public class UnknownElementTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/core/unknownelement.xml");
+ buildRule.configureProject("src/etc/testcases/core/unknownelement.xml");
}
+
+ @Test
public void testMaybeConfigure() {
// make sure we do not get a NPE
- executeTarget("testMaybeConfigure");
+ buildRule.executeTarget("testMaybeConfigure");
}
/**
* Not really a UnknownElement test but rather one of "what
* information is available in taskFinished".
- * @see https://issues.apache.org/bugzilla/show_bug.cgi?id=26197
+ * @see
+ * https://issues.apache.org/bugzilla/show_bug.cgi?id=26197
*/
+ @Test
+ @Ignore("Previously disabled through naming convention")
public void XtestTaskFinishedEvent() {
- getProject().addBuildListener(new BuildListener() {
+ buildRule.getProject().addBuildListener(new BuildListener() {
public void buildStarted(BuildEvent event) {}
public void buildFinished(BuildEvent event) {}
public void targetStarted(BuildEvent event) {}
@@ -58,7 +77,7 @@ public class UnknownElementTest extends BuildFileTest {
t.getClass().getName());
}
});
- executeTarget("echo");
+ buildRule.executeTarget("echo");
}
public static class Child extends Task {
diff --git a/src/tests/junit/org/apache/tools/ant/filters/ConcatFilterTest.java b/src/tests/junit/org/apache/tools/ant/filters/ConcatFilterTest.java
index 8a0de7b73..38583540c 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/ConcatFilterTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/ConcatFilterTest.java
@@ -21,16 +21,21 @@ 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.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
import org.apache.tools.ant.util.StringUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
/**
* JUnit Testcases for ConcatReader
*/
-public class ConcatFilterTest extends BuildFileTest {
+public class ConcatFilterTest {
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
private static final String lSep = StringUtils.LINE_SEP;
private static final String FILE_PREPEND_WITH =
@@ -65,48 +70,55 @@ public class ConcatFilterTest extends BuildFileTest {
+ "Line 60" + lSep
;
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- public ConcatFilterTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/concat.xml");
+ buildRule.configureProject("src/etc/testcases/filters/concat.xml");
}
-
+ @Test
public void testFilterReaderNoArgs() throws IOException {
- executeTarget("testFilterReaderNoArgs");
- File expected = new File(getProject().getProperty("output"), "concatfilter.test");
- File result = new File(getProject().getProperty("output"), "concat.FilterReaderNoArgs.test");
- assertTrue("testFilterReaderNoArgs: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testFilterReaderNoArgs");
+ File expected = new File(buildRule.getProject().getProperty("output"), "concatfilter.test");
+ File result = new File(buildRule.getProject().getProperty("output"), "concat.FilterReaderNoArgs.test");
+ assertEquals("testFilterReaderNoArgs: Result not like expected", FileUtilities.getFileContents(expected),
+ FileUtilities.getFileContents(result));
}
- public void testFilterReaderBefore() {
+ @Test
+ public void testFilterReaderBefore() throws IOException {
doTest("testFilterReaderPrepend", FILE_PREPEND_WITH, FILE_APPEND);
}
- public void testFilterReaderAfter() {
+ @Test
+ public void testFilterReaderAfter() throws IOException {
doTest("testFilterReaderAppend", FILE_PREPEND, FILE_APPEND_WITH);
}
- public void testFilterReaderBeforeAfter() {
+ @Test
+ public void testFilterReaderBeforeAfter() throws IOException {
doTest("testFilterReaderPrependAppend", FILE_PREPEND_WITH, FILE_APPEND_WITH);
}
- public void testConcatFilter() {
+ @Test
+ public void testConcatFilter() throws IOException {
doTest("testConcatFilter", FILE_PREPEND, FILE_APPEND);
}
- public void testConcatFilterBefore() {
+ @Test
+ public void testConcatFilterBefore() throws IOException {
doTest("testConcatFilterPrepend", FILE_PREPEND_WITH, FILE_APPEND);
}
- public void testConcatFilterAfter() {
+ @Test
+ public void testConcatFilterAfter() throws IOException {
doTest("testConcatFilterAppend", FILE_PREPEND, FILE_APPEND_WITH);
}
- public void testConcatFilterBeforeAfter() {
+ @Test
+ public void testConcatFilterBeforeAfter() throws IOException {
doTest("testConcatFilterPrependAppend", FILE_PREPEND_WITH, FILE_APPEND_WITH);
}
@@ -119,33 +131,13 @@ public class ConcatFilterTest extends BuildFileTest {
* @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(getProject().getProperty("output") + "/concat." + target.substring(4) + ".test");
+ protected void doTest(String target, String expectedStart, String expectedEnd) throws IOException {
+ buildRule.executeTarget(target);
+ String resultContent = FileUtilities.getFileContents(
+ new File(buildRule.getProject().getProperty("output") + "/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 null 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;
- }
-
}
diff --git a/src/tests/junit/org/apache/tools/ant/filters/DynamicFilterTest.java b/src/tests/junit/org/apache/tools/ant/filters/DynamicFilterTest.java
index 74ff7f37b..5de7f6bc1 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/DynamicFilterTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/DynamicFilterTest.java
@@ -18,67 +18,38 @@
package org.apache.tools.ant.filters;
+import java.io.File;
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;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class DynamicFilterTest extends BuildFileTest {
+import static org.apache.tools.ant.AntAssert.assertContains;
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
-
- public DynamicFilterTest(String name) {
- super(name);
- }
+public class DynamicFilterTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/dynamicfilter.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/filters/dynamicfilter.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void testCustomFilter() throws IOException {
- expectFileContains("dynamicfilter", getProject().getProperty("output") + "/dynamicfilter",
- "hellO wOrld");
+ buildRule.executeTarget("dynamicfilter");
+ String content = FileUtilities.getFileContents(
+ new File(buildRule.getProject().getProperty("output") + "/dynamicfilter"));
+ assertContains("hellO wOrld", content);
}
- // ------------------------------------------------------
- // 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';
diff --git a/src/tests/junit/org/apache/tools/ant/filters/EscapeUnicodeTest.java b/src/tests/junit/org/apache/tools/ant/filters/EscapeUnicodeTest.java
index 4de10b4d1..7c5e30409 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/EscapeUnicodeTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/EscapeUnicodeTest.java
@@ -21,28 +21,30 @@ 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.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class EscapeUnicodeTest extends BuildFileTest {
-
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+import static org.junit.Assert.assertEquals;
- public EscapeUnicodeTest(String name) {
- super(name);
- }
+public class EscapeUnicodeTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/build.xml");
+ buildRule.configureProject("src/etc/testcases/filters/build.xml");
}
+ @Test
public void testEscapeUnicode() throws IOException {
- executeTarget("testEscapeUnicode");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(), "expected/escapeunicode.test");
- File result = new File(getProject().getProperty("output"), "escapeunicode.test");
- assertTrue(FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testEscapeUnicode");
+ File expected = buildRule.getProject().resolveFile("expected/escapeunicode.test");
+ File result = new File(buildRule.getProject().getProperty("output"), "escapeunicode.test");
+ assertEquals(FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/filters/HeadTailTest.java b/src/tests/junit/org/apache/tools/ant/filters/HeadTailTest.java
index 8f896ff42..7c910d12f 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/HeadTailTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/HeadTailTest.java
@@ -21,105 +21,117 @@ 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.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/** 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 {
+public class HeadTailTest {
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- public HeadTailTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/head-tail.xml");
+ buildRule.configureProject("src/etc/testcases/filters/head-tail.xml");
}
+ @Test
public void testHead() throws IOException {
- executeTarget("testHead");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(), "expected/head-tail.head.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.head.test");
- assertTrue("testHead: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testHead");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.head.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.head.test");
+ assertEquals("testHead: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testHeadLines() throws IOException {
- executeTarget("testHeadLines");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(), "expected/head-tail.headLines.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.headLines.test");
- assertTrue("testHeadLines: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testHeadLines");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.headLines.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.headLines.test");
+ assertEquals("testHeadLines: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testHeadSkip() throws IOException {
- executeTarget("testHeadSkip");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.headSkip.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.headSkip.test");
- assertTrue("testHeadSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testHeadSkip");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.headSkip.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.headSkip.test");
+ assertEquals("testHeadSkip: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testHeadLinesSkip() throws IOException {
- executeTarget("testHeadLinesSkip");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.headLinesSkip.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.headLinesSkip.test");
- assertTrue("testHeadLinesSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testHeadLinesSkip");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.headLinesSkip.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.headLinesSkip.test");
+ assertEquals("testHeadLinesSkip: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testFilterReaderHeadLinesSkip() throws IOException {
- executeTarget("testFilterReaderHeadLinesSkip");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),
- "expected/head-tail.headLinesSkip.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.filterReaderHeadLinesSkip.test");
- assertTrue("testFilterReaderHeadLinesSkip: Result not like expected",
- FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testFilterReaderHeadLinesSkip");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.headLinesSkip.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.filterReaderHeadLinesSkip.test");
+ assertEquals("testFilterReaderHeadLinesSkip: Result not like expected",
+ FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testTail() throws IOException {
- executeTarget("testTail");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tail.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.tail.test");
- assertTrue("testTail: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testTail");
+ File expected =buildRule.getProject().resolveFile("expected/head-tail.tail.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.tail.test");
+ assertEquals("testTail: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testTailLines() throws IOException {
- executeTarget("testTailLines");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tailLines.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.tailLines.test");
- assertTrue("testTailLines: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testTailLines");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.tailLines.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.tailLines.test");
+ assertEquals("testTailLines: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testTailSkip() throws IOException {
- executeTarget("testTailSkip");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tailSkip.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.tailSkip.test");
- assertTrue("testTailSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testTailSkip");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.tailSkip.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.tailSkip.test");
+ assertEquals("testTailSkip: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testTailLinesSkip() throws IOException {
- executeTarget("testTailLinesSkip");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.tailLinesSkip.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.tailLinesSkip.test");
- assertTrue("testTailLinesSkip: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testTailLinesSkip");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.tailLinesSkip.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.tailLinesSkip.test");
+ assertEquals("testTailLinesSkip: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testFilterReaderTailLinesSkip() throws IOException {
- executeTarget("testFilterReaderTailLinesSkip");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),
- "expected/head-tail.tailLinesSkip.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.filterReaderTailLinesSkip.test");
- assertTrue("testFilterReaderTailLinesSkip: Result not like expected",
- FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testFilterReaderTailLinesSkip");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.tailLinesSkip.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.filterReaderTailLinesSkip.test");
+ assertEquals("testFilterReaderTailLinesSkip: Result not like expected",
+ FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testHeadTail() throws IOException {
- executeTarget("testHeadTail");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/head-tail.headtail.test");
- File result = new File(getProject().getProperty("output") + "/head-tail.headtail.test");
- assertTrue("testHeadTail: Result not like expected", FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testHeadTail");
+ File expected = buildRule.getProject().resolveFile("expected/head-tail.headtail.test");
+ File result = new File(buildRule.getProject().getProperty("output") + "/head-tail.headtail.test");
+ assertEquals("testHeadTail: Result not like expected", FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/filters/LineContainsTest.java b/src/tests/junit/org/apache/tools/ant/filters/LineContainsTest.java
index e48a882b6..9dcb291be 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/LineContainsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/LineContainsTest.java
@@ -21,32 +21,37 @@ 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.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class LineContainsTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
-
- public LineContainsTest(String name) {
- super(name);
- }
+public class LineContainsTest {
+
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/build.xml");
+ buildRule.configureProject("src/etc/testcases/filters/build.xml");
}
+ @Test
public void testLineContains() throws IOException {
- executeTarget("testLineContains");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/linecontains.test");
- File result = new File(getProject().getProperty("output"),"linecontains.test");
- assertTrue(FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testLineContains");
+ File expected = buildRule.getProject().resolveFile("expected/linecontains.test");
+ File result = new File(buildRule.getProject().getProperty("output"),"linecontains.test");
+ assertEquals(FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testNegateLineContains() throws IOException {
- executeTarget("testNegateLineContains");
+ buildRule.executeTarget("testNegateLineContains");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/filters/NoNewLineTest.java b/src/tests/junit/org/apache/tools/ant/filters/NoNewLineTest.java
index 1b8779ca0..c12a1d3fd 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/NoNewLineTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/NoNewLineTest.java
@@ -20,24 +20,29 @@ package org.apache.tools.ant.filters;
import java.io.IOException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/** JUnit Testcases for No new line when filterchain used
*/
-public class NoNewLineTest extends BuildFileTest {
+public class NoNewLineTest {
- public NoNewLineTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/build.xml");
+ buildRule.configureProject("src/etc/testcases/filters/build.xml");
}
+
+ @Test
public void testNoAddNewLine() throws IOException {
- executeTarget("testNoAddNewLine");
+ buildRule.executeTarget("testNoAddNewLine");
}
diff --git a/src/tests/junit/org/apache/tools/ant/filters/ReplaceTokensTest.java b/src/tests/junit/org/apache/tools/ant/filters/ReplaceTokensTest.java
index 07ce0a4a5..c58dcc6d5 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/ReplaceTokensTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/ReplaceTokensTest.java
@@ -21,35 +21,39 @@ 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.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class ReplaceTokensTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+public class ReplaceTokensTest {
- public ReplaceTokensTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/build.xml");
+ buildRule.configureProject("src/etc/testcases/filters/build.xml");
}
+ @Test
public void testReplaceTokens() throws IOException {
- executeTarget("testReplaceTokens");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/replacetokens.test");
- File result = new File(getProject().getProperty("output"), "replacetokens.test");
- assertTrue(FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testReplaceTokens");
+ File expected = buildRule.getProject().resolveFile("expected/replacetokens.test");
+ File result = new File(buildRule.getProject().getProperty("output"), "replacetokens.test");
+ assertEquals(FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
+ @Test
public void testReplaceTokensPropertyFile() throws IOException {
- executeTarget("testReplaceTokensPropertyFile");
- File expected = FILE_UTILS.resolveFile(getProjectDir(), "expected/replacetokens.test");
- File result = new File(getProject().getProperty("output"), "replacetokensPropertyFile.test");
- assertTrue(FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testReplaceTokensPropertyFile");
+ File expected = buildRule.getProject().resolveFile("expected/replacetokens.test");
+ File result = new File(buildRule.getProject().getProperty("output"), "replacetokensPropertyFile.test");
+ assertEquals(FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/filters/StripJavaCommentsTest.java b/src/tests/junit/org/apache/tools/ant/filters/StripJavaCommentsTest.java
index 6356141ef..7114d497b 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/StripJavaCommentsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/StripJavaCommentsTest.java
@@ -21,28 +21,31 @@ 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.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class StripJavaCommentsTest extends BuildFileTest {
-
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+import static org.junit.Assert.assertEquals;
- public StripJavaCommentsTest(String name) {
- super(name);
- }
+public class StripJavaCommentsTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/build.xml");
+ buildRule.configureProject("src/etc/testcases/filters/build.xml");
}
+
+ @Test
public void testStripJavaComments() throws IOException {
- executeTarget("testStripJavaComments");
- File expected = FILE_UTILS.resolveFile(getProject().getBaseDir(),"expected/stripjavacomments.test");
- File result = new File(getProject().getProperty("output"), "stripjavacomments.test");
- assertTrue(FILE_UTILS.contentEquals(expected, result));
+ buildRule.executeTarget("testStripJavaComments");
+ File expected = buildRule.getProject().resolveFile("expected/stripjavacomments.test");
+ File result = new File(buildRule.getProject().getProperty("output"), "stripjavacomments.test");
+ assertEquals(FileUtilities.getFileContents(expected), FileUtilities.getFileContents(result));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/filters/TokenFilterTest.java b/src/tests/junit/org/apache/tools/ant/filters/TokenFilterTest.java
index 00aa66abb..f0db15a0c 100644
--- a/src/tests/junit/org/apache/tools/ant/filters/TokenFilterTest.java
+++ b/src/tests/junit/org/apache/tools/ant/filters/TokenFilterTest.java
@@ -18,265 +18,252 @@
package org.apache.tools.ant.filters;
-import java.io.Reader;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.apache.tools.ant.AntAssert.assertNotContains;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
import java.io.FileReader;
import java.io.IOException;
+import java.io.Reader;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
*/
-public class TokenFilterTest extends BuildFileTest {
+public class TokenFilterTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public TokenFilterTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/filters/tokenfilter.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/filters/tokenfilter.xml");
+ buildRule.executeTarget("setUp");
}
/** make sure tokenfilter exists */
+ @Test
public void testTokenfilter() throws IOException {
- executeTarget("tokenfilter");
+ buildRule.executeTarget("tokenfilter");
}
+ @Test
public void testTrimignore() throws IOException {
- expectLogContaining("trimignore", "Hello-World");
+ buildRule.executeTarget("trimignore");
+ assertContains("Hello-World", buildRule.getLog());
}
+ @Test
public void testStringTokenizer() throws IOException {
- expectLogContaining(
- "stringtokenizer", "#This#is#a#number#of#words#");
+ buildRule.executeTarget("stringtokenizer");
+ assertContains("#This#is#a#number#of#words#", buildRule.getLog());
}
+ @Test
public void testUnixLineOutput() throws IOException {
- expectFileContains(
- "unixlineoutput", getProject().getProperty("output") + "/unixlineoutput",
- "\nThis\nis\na\nnumber\nof\nwords\n");
+ buildRule.executeTarget("unixlineoutput");
+ assertContains("\nThis\nis\na\nnumber\nof\nwords\n",
+ getFileString(buildRule.getProject().getProperty("output") + "/unixlineoutput"));
}
+ @Test
public void testDosLineOutput() throws IOException {
- expectFileContains(
- "doslineoutput", getProject().getProperty("output") + "/doslineoutput",
- "\r\nThis\r\nis\r\na\r\nnumber\r\nof\r\nwords\r\n");
+
+ buildRule.executeTarget("doslineoutput");
+ assertContains("\r\nThis\r\nis\r\na\r\nnumber\r\nof\r\nwords\r\n",
+ getFileString(buildRule.getProject().getProperty("output") + "/doslineoutput"));
}
+ @Test
public void testFileTokenizer() throws IOException {
- String contents = getFileString(
- "filetokenizer", getProject().getProperty("output") + "/filetokenizer");
- assertStringContains(contents, " of words");
- assertStringNotContains(contents, " This is");
+ buildRule.executeTarget("filetokenizer");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/filetokenizer");
+ assertContains(" of words", contents);
+ assertNotContains(" This is", contents);
}
+ @Test
public void testReplaceString() throws IOException {
- expectFileContains(
- "replacestring", getProject().getProperty("output") + "/replacestring",
- "this is the moon");
+ buildRule.executeTarget("replacestring");
+ assertContains("this is the moon",
+ getFileString(buildRule.getProject().getProperty("output") + "/replacestring"));
}
+ @Test
public void testReplaceStrings() throws IOException {
- expectLogContaining("replacestrings", "bar bar bar");
+ buildRule.executeTarget("replacestrings");
+ assertContains("bar bar bar", buildRule.getLog());
}
+ @Test
public void testContainsString() throws IOException {
- String contents = getFileString(
- "containsstring", getProject().getProperty("output") + "/containsstring");
- assertStringContains(contents, "this is a line contains foo");
- assertStringNotContains(contents, "this line does not");
+ buildRule.executeTarget("containsstring");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/containsstring");
+ assertContains("this is a line contains foo", contents);
+ assertNotContains("this line does not", contents);
}
+ @Test
public void testReplaceRegex() throws IOException {
- if (! hasRegex("testReplaceRegex"))
- return;
- String contents = getFileString(
- "replaceregex", getProject().getProperty("output") + "/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");
+
+ buildRule.executeTarget("hasregex");
+ Assume.assumeTrue("Regex not present",
+ getFileString(buildRule.getProject().getProperty("output") + "/replaceregexp").contains("bye world"));
+
+ buildRule.executeTarget("replaceregex");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/replaceregex");
+ assertContains("world world world world", contents);
+ assertContains("dog Cat dog", contents);
+ assertContains("moon Sun Sun", contents);
+ assertContains("found WhiteSpace", contents);
+ assertContains("Found digits [1234]", contents);
+ assertNotContains("This is a line with digits", contents);
}
+ @Test
public void testFilterReplaceRegex() throws IOException {
- if (! hasRegex("testFilterReplaceRegex"))
- return;
- String contents = getFileString(
- "filterreplaceregex", getProject().getProperty("output") + "/filterreplaceregex");
- assertStringContains(contents, "world world world world");
+ buildRule.executeTarget("hasregex");
+ Assume.assumeTrue("Regex not present",
+ getFileString(buildRule.getProject().getProperty("output") + "/replaceregexp").contains("bye world"));
+
+ buildRule.executeTarget("filterreplaceregex");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/filterreplaceregex");
+ assertContains("world world world world", contents);
+
}
+ @Test
public void testHandleDollerMatch() throws IOException {
- if (! hasRegex("testFilterReplaceRegex"))
- return;
- executeTarget("dollermatch");
+ buildRule.executeTarget("hasregex");
+ Assume.assumeTrue("Regex not present", getFileString(buildRule.getProject().getProperty("output") + "/replaceregexp").contains("bye world"));
+
+ buildRule.executeTarget("dollermatch");
}
+ @Test
public void testTrimFile() throws IOException {
- String contents = getFileString(
- "trimfile", getProject().getProperty("output") + "/trimfile");
+ buildRule.executeTarget("trimfile");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/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");
+ assertContains(" This is the second", contents);
}
+ @Test
public void testTrimFileByLine() throws IOException {
- String contents = getFileString(
- "trimfilebyline", getProject().getProperty("output") + "/trimfilebyline");
+ buildRule.executeTarget("trimfilebyline");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/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");
+ assertNotContains(" This is the second", contents);
+ assertContains("file.\nThis is the second", contents);
}
+ @Test
public void testFilterReplaceString() throws IOException {
- String contents = getFileString(
- "filterreplacestring", getProject().getProperty("output") + "/filterreplacestring");
- assertStringContains(contents, "This is the moon");
+ buildRule.executeTarget("filterreplacestring");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/filterreplacestring");
+ assertContains("This is the moon", contents);
}
+ @Test
public void testFilterReplaceStrings() throws IOException {
- expectLogContaining("filterreplacestrings", "bar bar bar");
+ buildRule.executeTarget("filterreplacestrings");
+ assertContains("bar bar bar", buildRule.getLog());
}
+ @Test
public void testContainsRegex() throws IOException {
- if (! hasRegex("testContainsRegex"))
- return;
- String contents = getFileString(
- "containsregex", getProject().getProperty("output") + "/containsregex");
- assertStringContains(contents, "hello world");
- assertStringNotContains(contents, "this is the moon");
- assertStringContains(contents, "World here");
+ buildRule.executeTarget("hasregex");
+ Assume.assumeTrue("Regex not present", getFileString(buildRule.getProject().getProperty("output") + "/replaceregexp").contains("bye world"));
+
+ //expectFileContains(buildRule.getProject().getProperty("output") + "/replaceregexp", "bye world");
+
+ buildRule.executeTarget("containsregex");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/containsregex");
+ assertContains("hello world", contents);
+ assertNotContains("this is the moon", contents);
+ assertContains("World here", contents);
}
+ @Test
public void testFilterContainsRegex() throws IOException {
- if (! hasRegex("testFilterContainsRegex"))
- return;
- String contents = getFileString(
- "filtercontainsregex", getProject().getProperty("output") + "/filtercontainsregex");
- assertStringContains(contents, "hello world");
- assertStringNotContains(contents, "this is the moon");
- assertStringContains(contents, "World here");
+ buildRule.executeTarget("hasregex");
+ Assume.assumeTrue("Regex not present", getFileString(buildRule.getProject().getProperty("output") + "/replaceregexp").contains("bye world"));
+
+ buildRule.executeTarget("filtercontainsregex");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/filtercontainsregex");
+ assertContains("hello world", contents);
+ assertNotContains("this is the moon", contents);
+ assertContains("World here", contents);
}
+ @Test
public void testContainsRegex2() throws IOException {
- if (! hasRegex("testContainsRegex2"))
- return;
- String contents = getFileString(
- "containsregex2", getProject().getProperty("output") + "/containsregex2");
- assertStringContains(contents, "void register_bits();");
+ buildRule.executeTarget("hasregex");
+ Assume.assumeTrue("Regex not present", getFileString(buildRule.getProject().getProperty("output") + "/replaceregexp").contains("bye world"));
+
+ buildRule.executeTarget("containsregex2");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/containsregex2");
+ assertContains("void register_bits();", contents);
}
+ @Test
public void testDeleteCharacters() throws IOException {
- String contents = getFileString(
- "deletecharacters", getProject().getProperty("output") + "/deletechars");
- assertStringNotContains(contents, "#");
- assertStringNotContains(contents, "*");
- assertStringContains(contents, "This is some ");
+ buildRule.executeTarget("deletecharacters");
+ String contents = getFileString(buildRule.getProject().getProperty("output") + "/deletechars");
+ assertNotContains("#", contents);
+ assertNotContains("*", contents);
+ assertContains("This is some ", contents);
}
+ @Test
public void testScriptFilter() throws IOException {
- if (! hasScript("testScriptFilter"))
- return;
+ Assume.assumeTrue("Project does not have 'testScriptFilter' target",
+ buildRule.getProject().getTargets().contains("testScriptFilter"));
+ buildRule.executeTarget("scriptfilter");
+ assertContains("HELLO WORLD", getFileString(buildRule.getProject().getProperty("output") + "/scriptfilter"));
- expectFileContains("scriptfilter", getProject().getProperty("output") + "/scriptfilter",
- "HELLO WORLD");
}
-
+ @Test
public void testScriptFilter2() throws IOException {
- if (! hasScript("testScriptFilter"))
- return;
-
- expectFileContains("scriptfilter2", getProject().getProperty("output") + "/scriptfilter2",
- "HELLO MOON");
+ Assume.assumeTrue("Project does not have 'testScriptFilter' target", buildRule.getProject().getTargets().contains("testScriptFilter"));
+ buildRule.executeTarget("scriptfilter2");
+ assertContains("HELLO MOON", getFileString(buildRule.getProject().getProperty("output") + "/scriptfilter2"));
}
+ @Test
public void testCustomTokenFilter() throws IOException {
- expectFileContains("customtokenfilter", getProject().getProperty("output") + "/custom",
- "Hello World");
+ buildRule.executeTarget("customtokenfilter");
+ assertContains("Hello World", getFileString(buildRule.getProject().getProperty("output") + "/custom"));
}
// ------------------------------------------------------
// 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(getProject().getProperty("output") + "/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));
+ r = new FileReader(FILE_UTILS.resolveFile(buildRule.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
diff --git a/src/tests/junit/org/apache/tools/ant/launch/LocatorTest.java b/src/tests/junit/org/apache/tools/ant/launch/LocatorTest.java
index 51de06139..0c3c24fda 100644
--- a/src/tests/junit/org/apache/tools/ant/launch/LocatorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/launch/LocatorTest.java
@@ -17,39 +17,27 @@
*/
package org.apache.tools.ant.launch;
-import junit.framework.TestCase;
-
import java.io.File;
import org.apache.tools.ant.taskdefs.condition.Os;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import static junit.framework.Assert.assertEquals;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
/** Test the locator in the ant-launch JAR */
-public class LocatorTest extends TestCase {
+public class LocatorTest {
private boolean windows;
private boolean unix;
private static final String LAUNCHER_JAR = "//morzine/slo/Java/Apache/ant/lib/ant-launcher.jar";
private static final String SHARED_JAR_URI = "jar:file:"+ LAUNCHER_JAR +"!/org/apache/tools/ant/launch/Launcher.class";
- /**
- * No-arg constructor to enable serialization. This method is not intended to be used by mere mortals without calling
- * setName().
- */
- public LocatorTest() {
- }
- /** Constructs a test case with the given name.
- * @param name
- */
- public LocatorTest(String name) {
- super(name);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection.
- * This method is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
+ @Before
+ public void setUp() throws Exception {
windows = Os.isFamily(Os.FAMILY_DOS);
unix = Os.isFamily(Os.FAMILY_UNIX);
}
@@ -105,26 +93,27 @@ public class LocatorTest extends TestCase {
"\\\\PC03\\jclasses\\lib\\ant-1.7.0.jar");
}
- /**
- * This is not being tested as we don't appear to generate paths like this in the launcher
- * @throws Exception
- */
- public void NotestTripleForwardSlashNetworkURI() throws Exception {
+ @Ignore("We don't appear to generate paths like this in the launcher")
+ @Test
+ public void testTripleForwardSlashNetworkURI() throws Exception {
resolveTo("file:///PC03/jclasses/lib/ant-1.7.0.jar",
"///PC03/jclasses/lib/ant-1.7.0.jar",
"\\\\PC03\\jclasses\\lib\\ant-1.7.0.jar");
}
+ @Test
public void testUnixNetworkPath() throws Exception {
resolveTo("file://cluster/home/ant/lib",
"//cluster/home/ant/lib",
"\\\\cluster\\home\\ant\\lib");
}
+ @Test
public void testUnixPath() throws Exception {
resolveTo("file:/home/ant/lib", "/home/ant/lib", null);
}
+ @Test
public void testSpacedURI() throws Exception {
resolveTo("file:C:\\Program Files\\Ant\\lib",
"C:\\Program Files\\Ant\\lib",
@@ -135,6 +124,7 @@ public class LocatorTest extends TestCase {
* Bug 42275; Ant failing to run off a remote share
* @throws Throwable if desired
*/
+ @Test
public void testAntOnRemoteShare() throws Throwable {
String resolved=Locator.fromJarURI(SHARED_JAR_URI);
assertResolved(SHARED_JAR_URI, LAUNCHER_JAR, resolved, unix);
@@ -147,6 +137,7 @@ public class LocatorTest extends TestCase {
*
* @throws Throwable if desired
*/
+ @Test
public void testFileFromRemoteShare() throws Throwable {
String resolved = Locator.fromJarURI(SHARED_JAR_URI);
File f = new File(resolved);
@@ -156,17 +147,20 @@ public class LocatorTest extends TestCase {
}
}
+ @Test
public void testHttpURI() throws Exception {
String url = "http://ant.apache.org";
try {
Locator.fromURI(url);
+ fail("Exception should have been thrown");
} catch (IllegalArgumentException e) {
String message = e.getMessage();
- assertTrue(message, message.indexOf(Locator.ERROR_NOT_FILE_URI) >= 0);
- assertTrue(message, message.indexOf(url) >= 0);
+ assertContains(Locator.ERROR_NOT_FILE_URI, message);
+ assertContains(url, message);
}
}
+ @Test
public void testInternationalURI() throws Exception {
String result = assertResolves("L\u00f6wenbrau.aus.M\u00fcnchen");
char umlauted = result.charAt(1);
@@ -178,6 +172,7 @@ public class LocatorTest extends TestCase {
assertEquals("file:/tmp/hezky \u010Desky", Locator.decodeUri("file:/tmp/hezky%20\u010Desky")); // non-ISO-8859-1 variant
}
+ @Test
public void testOddLowAsciiURI() throws Exception {
assertResolves("hash# and percent%");
}
diff --git a/src/tests/junit/org/apache/tools/ant/loader/AntClassLoader5Test.java b/src/tests/junit/org/apache/tools/ant/loader/AntClassLoader5Test.java
index d06d26358..a01a940a8 100644
--- a/src/tests/junit/org/apache/tools/ant/loader/AntClassLoader5Test.java
+++ b/src/tests/junit/org/apache/tools/ant/loader/AntClassLoader5Test.java
@@ -21,19 +21,26 @@ package org.apache.tools.ant.loader;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
-import junit.framework.TestCase;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.CollectionUtils;
+import org.junit.Test;
-public class AntClassLoader5Test extends TestCase {
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public class AntClassLoader5Test {
/**
* Asserts that getResources won't return resources that cannot be
* seen by AntClassLoader but by ClassLoader.this.parent.
*
- * @see https://issues.apache.org/bugzilla/show_bug.cgi?id=46752
+ * @see
+ * https://issues.apache.org/bugzilla/show_bug.cgi?id=46752
*/
+ @Test
public void testGetResources() throws IOException {
AntClassLoader acl = new AntClassLoader5(new EmptyLoader(), null,
new Path(null), true);
@@ -46,6 +53,7 @@ public class AntClassLoader5Test extends TestCase {
assertTrue(acl.getResources("META-INF/MANIFEST.MF").hasMoreElements());
}
+ @Test
public void testGetResourcesUsingFactory() throws IOException {
AntClassLoader acl =
AntClassLoader.newAntClassLoader(new EmptyLoader(), null,
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AbstractCvsTaskTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AbstractCvsTaskTest.java
index e8473859f..227987fa8 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/AbstractCvsTaskTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AbstractCvsTaskTest.java
@@ -17,38 +17,55 @@
*/
package org.apache.tools.ant.taskdefs;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
import java.io.File;
-import org.apache.tools.ant.BuildFileTest;
+import static org.junit.Assert.assertTrue;
/**
*/
-public class AbstractCvsTaskTest extends BuildFileTest {
+public class AbstractCvsTaskTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- public AbstractCvsTaskTest() {
- this( "AbstractCvsTaskTest" );
+ @Before
+ public void setUp() {
+ buildRule.configureProject("src/etc/testcases/taskdefs/abstractcvstask.xml");
+ buildRule.executeTarget("setUp");
}
- public AbstractCvsTaskTest(String name) {
- super(name);
+ @After
+ public void tearDown() {
+ buildRule.executeTarget("cleanup");
}
- public void setUp() {
- configureProject("src/etc/testcases/taskdefs/abstractcvstask.xml");
- executeTarget("setUp");
+ @Test
+ public void testAbstractCvsTask() {
+ buildRule.executeTarget("all");
}
+ @Test
public void testPackageAttribute() {
- File f = new File(getProject().getProperty("output") + "/src/Makefile");
+ File f = new File(buildRule.getProject().getProperty("output") + "/src/Makefile");
assertTrue("starting empty", !f.exists());
- expectLogContaining("package-attribute", "U src/Makefile");
+ buildRule.executeTarget("package-attribute");
+ AntAssert.assertContains("U src/Makefile", buildRule.getLog());
assertTrue("now it is there", f.exists());
}
+ @Test
public void testTagAttribute() {
- File f = new File(getProject().getProperty("output") + "/src/Makefile");
+ File f = new File(buildRule.getProject().getProperty("output") + "/src/Makefile");
assertTrue("starting empty", !f.exists());
- expectLogContaining("tag-attribute", "OPENBSD_5_3");
+ buildRule.executeTarget("tag-attribute");
+ AntAssert.assertContains("OPENBSD_5_3", buildRule.getLog());
assertTrue("now it is there", f.exists());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AntLikeTasksAtTopLevelTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AntLikeTasksAtTopLevelTest.java
index e8c1349a9..298bf0987 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/AntLikeTasksAtTopLevelTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AntLikeTasksAtTopLevelTest.java
@@ -19,19 +19,25 @@
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* @since Ant 1.6
*/
-public class AntLikeTasksAtTopLevelTest extends BuildFileTest {
- public AntLikeTasksAtTopLevelTest(String name) {
- super(name);
- }
+public class AntLikeTasksAtTopLevelTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Test
public void testAnt() {
try {
- configureProject("src/etc/testcases/taskdefs/toplevelant.xml");
+ buildRule.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"
@@ -39,9 +45,10 @@ public class AntLikeTasksAtTopLevelTest extends BuildFileTest {
}
}
+ @Test
public void testSubant() {
try {
- configureProject("src/etc/testcases/taskdefs/toplevelsubant.xml");
+ buildRule.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"
@@ -49,9 +56,10 @@ public class AntLikeTasksAtTopLevelTest extends BuildFileTest {
}
}
+ @Test
public void testAntcall() {
try {
- configureProject("src/etc/testcases/taskdefs/toplevelantcall.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/toplevelantcall.xml");
fail("no exception thrown");
} catch (BuildException e) {
assertEquals("antcall must not be used at the top level.",
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AntStructureTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AntStructureTest.java
index af09c97f2..da51b5d97 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/AntStructureTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AntStructureTest.java
@@ -18,40 +18,57 @@
package org.apache.tools.ant.taskdefs;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.Project;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
import java.io.PrintWriter;
import java.util.Hashtable;
-import junit.framework.Assert;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.Project;
+
+import static org.junit.Assert.fail;
/**
*/
-public class AntStructureTest extends BuildFileTest {
+public class AntStructureTest {
- public AntStructureTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/antstructure.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/antstructure.xml");
}
+ @After
public void tearDown() {
- executeTarget("tearDown");
+ buildRule.executeTarget("tearDown");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void testCustomPrinter() {
- executeTarget("testCustomPrinter");
+ buildRule.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);
+ AntAssert.assertContains(MyPrinter.TAIL_CALLED, buildRule.getLog());
}
public static class MyPrinter implements AntStructure.StructurePrinter {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java
index 36581d768..0d6453c43 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java
@@ -22,94 +22,145 @@ import java.io.File;
import junit.framework.AssertionFailedError;
+import org.apache.tools.ant.AntAssert;
import org.apache.tools.ant.BuildEvent;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
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;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
*/
-public class AntTest extends BuildFileTest {
-
- public AntTest(String name) {
- super(name);
- }
+public class AntTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/ant.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/ant.xml");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void test1() {
- expectBuildException("test1", "recursive call");
+ try {
+ buildRule.executeTarget("test1");
+ fail("recursive call");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
// target must be specified
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("required argument not specified");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
// Should fail since a recursion will occur...
+ @Test
public void test3() {
- expectBuildException("test1", "recursive call");
+ try {
+ buildRule.executeTarget("test1");
+ fail("recursive call");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test4() {
- expectBuildException("test4", "target attribute must not be empty");
+ try {
+ buildRule.executeTarget("test4");
+ fail("target attribute must not be empty");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test4b() {
- expectBuildException("test4b", "target doesn't exist");
+ try {
+ buildRule.executeTarget("test4b");
+ fail("target doesn't exist");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
+ @Test
public void test6() {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
}
+ @Test
public void testExplicitBasedir1() {
- File dir1 = getProjectDir();
- File dir2 = project.resolveFile("..");
+ File dir1 = buildRule.getProject().getBaseDir();
+ File dir2 = buildRule.getProject().resolveFile("..");
testBaseDirs("explicitBasedir1",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath()
});
}
+ @Test
public void testExplicitBasedir2() {
- File dir1 = getProjectDir();
- File dir2 = project.resolveFile("..");
+ File dir1 = buildRule.getProject().getBaseDir();
+ File dir2 = buildRule.getProject().resolveFile("..");
testBaseDirs("explicitBasedir2",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath()
});
}
+ @Test
public void testInheritBasedir() {
- String basedir = getProjectDir().getAbsolutePath();
+ String basedir = buildRule.getProject().getBaseDir().getAbsolutePath();
testBaseDirs("inheritBasedir", new String[] {basedir, basedir});
}
+ @Test
public void testDoNotInheritBasedir() {
- File dir1 = getProjectDir();
- File dir2 = project.resolveFile("ant");
+ File dir1 = buildRule.getProject().getBaseDir();
+ File dir2 = buildRule.getProject().resolveFile("ant");
testBaseDirs("doNotInheritBasedir",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath()
});
}
+ @Test
public void testBasedirTripleCall() {
- File dir1 = getProjectDir();
- File dir2 = project.resolveFile("ant");
+ File dir1 = buildRule.getProject().getBaseDir();
+ File dir2 = buildRule.getProject().resolveFile("ant");
testBaseDirs("tripleCall",
new String[] {dir1.getAbsolutePath(),
dir2.getAbsolutePath(),
@@ -119,20 +170,21 @@ public class AntTest extends BuildFileTest {
protected void testBaseDirs(String target, String[] dirs) {
BasedirChecker bc = new BasedirChecker(dirs);
- project.addBuildListener(bc);
- executeTarget(target);
+ buildRule.getProject().addBuildListener(bc);
+ buildRule.executeTarget(target);
AssertionFailedError ae = bc.getError();
if (ae != null) {
throw ae;
}
- project.removeBuildListener(bc);
+ buildRule.getProject().removeBuildListener(bc);
}
+ @Test
public void testReferenceInheritance() {
Path p = Path.systemClasspath;
- p.setProject(project);
- project.addReference("path", p);
- project.addReference("no-override", p);
+ p.setProject(buildRule.getProject());
+ buildRule.getProject().addReference("path", p);
+ buildRule.getProject().addReference("no-override", p);
testReference("testInherit", new String[] {"path", "path"},
new boolean[] {true, true}, p);
testReference("testInherit",
@@ -143,11 +195,12 @@ public class AntTest extends BuildFileTest {
new boolean[] {false, false}, null);
}
+ @Test
public void testReferenceNoInheritance() {
Path p = Path.systemClasspath;
- p.setProject(project);
- project.addReference("path", p);
- project.addReference("no-override", p);
+ p.setProject(buildRule.getProject());
+ buildRule.getProject().addReference("path", p);
+ buildRule.getProject().addReference("no-override", p);
testReference("testNoInherit", new String[] {"path", "path"},
new boolean[] {true, false}, p);
testReference("testNoInherit", new String[] {"path", "path"},
@@ -160,10 +213,11 @@ public class AntTest extends BuildFileTest {
new boolean[] {false, false}, null);
}
+ @Test
public void testReferenceRename() {
Path p = Path.systemClasspath;
- p.setProject(project);
- project.addReference("path", p);
+ p.setProject(buildRule.getProject());
+ buildRule.getProject().addReference("path", p);
testReference("testRename", new String[] {"path", "path"},
new boolean[] {true, false}, p);
testReference("testRename", new String[] {"path", "path"},
@@ -172,35 +226,37 @@ public class AntTest extends BuildFileTest {
new boolean[] {false, true}, p);
}
+ @Test
public void testInheritPath() {
- executeTarget("testInheritPath");
+ buildRule.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);
+ buildRule.getProject().addBuildListener(rc);
+ buildRule.executeTarget(target);
AssertionFailedError ae = rc.getError();
if (ae != null) {
throw ae;
}
- project.removeBuildListener(rc);
+ buildRule.getProject().removeBuildListener(rc);
}
+ @Test
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")
+ buildRule.getProject().resolveFile("test1.log"),
+ buildRule.getProject().resolveFile("test2.log"),
+ buildRule.getProject().resolveFile("ant/test3.log"),
+ buildRule.getProject().resolveFile("ant/test4.log")
};
for (int i=0; i -1);
- assertTrue(getLog().indexOf("test2 is ${test2}") > -1);
- assertTrue(getLog().indexOf("test1.x is 1") > -1);
+ buildRule.executeTarget("test-propertyset");
+ assertTrue(buildRule.getLog().indexOf("test1 is ${test1}") > -1);
+ assertTrue(buildRule.getLog().indexOf("test2 is ${test2}") > -1);
+ assertTrue(buildRule.getLog().indexOf("test1.x is 1") > -1);
}
+ @Test
public void testInfiniteLoopViaDepends() {
- expectBuildException("infinite-loop-via-depends", "recursive call");
+ try {
+ buildRule.executeTarget("infinite-loop-via-depends");
+ fail("recursive call");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void testMultiSameProperty() {
- expectLog("multi-same-property", "prop is two");
+ buildRule.executeTarget("multi-same-property");
+ assertEquals("prop is two", buildRule.getLog());
}
+ @Test
public void testTopLevelTarget() {
- expectLog("topleveltarget", "Hello world");
+ buildRule.executeTarget("topleveltarget");
+
+ assertEquals("Hello world", buildRule.getLog());
}
+ @Test
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");
+ buildRule.getProject().addBuildListener(pcBar);
+ buildRule.getProject().addBuildListener(pcFoo);
+ buildRule.executeTarget("multiple-property-file-children");
AssertionFailedError aeBar = pcBar.getError();
if (aeBar != null) {
throw aeBar;
@@ -294,26 +372,37 @@ public class AntTest extends BuildFileTest {
if (aeFoo != null) {
throw aeFoo;
}
- project.removeBuildListener(pcBar);
- project.removeBuildListener(pcFoo);
+ buildRule.getProject().removeBuildListener(pcBar);
+ buildRule.getProject().removeBuildListener(pcFoo);
}
+ @Test
public void testBlankTarget() {
- expectBuildException("blank-target", "target name must not be empty");
+ try {
+ buildRule.executeTarget("blank-target");
+ fail("target name must not be empty");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void testMultipleTargets() {
- expectLog("multiple-targets", "tadadctbdbtc");
+ buildRule.executeTarget("multiple-targets");
+ assertEquals("tadadctbdbtc", buildRule.getLog());
}
+ @Test
public void testMultipleTargets2() {
- expectLog("multiple-targets-2", "dadctb");
+ buildRule.executeTarget("multiple-targets-2");
+ assertEquals("dadctb", buildRule.getLog());
}
+ @Test
public void testAntCoreLib() {
// Cf. #42263
- executeTarget("sub-show-ant.core.lib");
- String realLog = getLog();
+ buildRule.executeTarget("sub-show-ant.core.lib");
+ String realLog = buildRule.getLog();
assertTrue("found ant.core.lib in: " + realLog, realLog.matches(".*(ant[.]jar|build.classes).*"));
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AntlibTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AntlibTest.java
index ea9db5cb4..c5c78ab3b 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/AntlibTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AntlibTest.java
@@ -18,19 +18,26 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.Project;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
*/
-public class AntlibTest extends BuildFileTest {
- public AntlibTest(String name) {
- super(name);
- }
+public class AntlibTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/antlib.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/antlib.xml");
}
/**
@@ -42,8 +49,10 @@ public class AntlibTest extends BuildFileTest {
return property!=null && Project.toBoolean(property);
}
+ @Test
public void testAntlibFile() {
- expectLog("antlib.file", "MyTask called");
+ buildRule.executeTarget("antlib.file");
+ assertEquals("MyTask called", buildRule.getLog());
}
/**
@@ -51,31 +60,34 @@ public class AntlibTest extends BuildFileTest {
* can collect several antlibs in one Definer call.
* @see "http://issues.apache.org/bugzilla/show_bug.cgi?id=24024"
*/
+ @Test
public void testAntlibResource() {
- expectLog("antlib.resource", "MyTask called-and-then-MyTask2 called");
+ buildRule.executeTarget("antlib.resource");
+ assertEquals("MyTask called-and-then-MyTask2 called", buildRule.getLog());
}
+ @Test
public void testNsCurrent() {
- expectLog("ns.current", "Echo2 inside a macroHello from x:p");
+ buildRule.executeTarget("ns.current");
+ assertEquals("Echo2 inside a macroHello from x:p", buildRule.getLog());
}
-
+ @Test
public void testAntlib_uri() {
- if (isSharedJVM()) {
- executeTarget("antlib_uri");
- }
+ Assume.assumeTrue("Test requires shared JVM", isSharedJVM());
+ buildRule.executeTarget("antlib_uri");
}
+ @Test
public void testAntlib_uri_auto() {
- if (isSharedJVM()) {
- executeTarget("antlib_uri_auto");
- }
+ Assume.assumeTrue("Test requires shared JVM", isSharedJVM());
+ buildRule.executeTarget("antlib_uri_auto");
}
+ @Test
public void testAntlib_uri_auto2() {
- if (isSharedJVM()) {
- executeTarget("antlib_uri_auto2");
- }
+ Assume.assumeTrue("Test requires shared JVM", isSharedJVM());
+ buildRule.executeTarget("antlib_uri_auto2");
}
public static class MyTask extends Task {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/AvailableTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/AvailableTest.java
index 28145c473..ef97e3757 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/AvailableTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/AvailableTest.java
@@ -18,102 +18,140 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* JUnit test for the Available task/condition.
*/
-public class AvailableTest extends BuildFileTest {
-
- public AvailableTest(String name) {
- super(name);
- }
+public class AvailableTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/available.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/available.xml");
+ buildRule.executeTarget("setUp");
}
// Nothing specified -> Fail
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
// Only property specified -> Fail
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
// Only file specified -> Fail
+ @Test
public void test3() {
- expectBuildException("test3", "required argument not specified");
+ try {
+ buildRule.executeTarget("test3");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
// file doesn't exist -> property 'test' == null
+ @Test
public void test4() {
- executeTarget("test4");
- assertTrue(project.getProperty("test") == null);
+ buildRule.executeTarget("test4");
+ assertTrue(buildRule.getProject().getProperty("test") == null);
}
// file does exist -> property 'test' == 'true'
public void test5() {
- executeTarget("test5");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test5");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// resource doesn't exist -> property 'test' == null
+ @Test
public void test6() {
- executeTarget("test6");
- assertTrue(project.getProperty("test") == null);
+ buildRule.executeTarget("test6");
+ assertTrue(buildRule.getProject().getProperty("test") == null);
}
// resource does exist -> property 'test' == 'true'
+ @Test
public void test7() {
- executeTarget("test7");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test7");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// class doesn't exist -> property 'test' == null
+ @Test
public void test8() {
- executeTarget("test8");
- assertTrue(project.getProperty("test") == null);
+ buildRule.executeTarget("test8");
+ assertTrue(buildRule.getProject().getProperty("test") == null);
}
// class does exist -> property 'test' == 'true'
+ @Test
public void test9() {
- executeTarget("test9");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test9");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// All three specified and all three exist -> true
+ @Test
public void test10() {
- executeTarget("test10");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test10");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// All three specified but class missing -> null
+ @Test
public void test11() {
- executeTarget("test11");
- assertNull(project.getProperty("test"));
+ buildRule.executeTarget("test11");
+ assertNull(buildRule.getProject().getProperty("test"));
}
// Specified property-name is "" -> true
+ @Test
public void test12() {
- executeTarget("test12");
- assertNull(project.getProperty("test"));
- assertEquals("true", project.getProperty(""));
+ buildRule.executeTarget("test12");
+ assertNull(buildRule.getProject().getProperty("test"));
+ assertEquals("true", buildRule.getProject().getProperty(""));
}
// Specified file is "" -> invalid files do not exist
+ @Test
public void test13() {
- executeTarget("test13");
- assertNull(project.getProperty("test"));
+ buildRule.executeTarget("test13");
+ assertNull(buildRule.getProject().getProperty("test"));
}
// Specified file is "" actually a directory, so it should pass
+ @Test
public void test13b() {
- executeTarget("test13b");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test13b");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// Specified resource is "" -> can such a thing exist?
@@ -121,94 +159,114 @@ public class AvailableTest extends BuildFileTest {
* returns non null IBM JDK 1.3 Linux
*/
// public void test14() {
-// executeTarget("test14");
-// assertEquals(project.getProperty("test"), null);
+// buildRule.executeTarget("test14");
+// assertEquals(buildRule.getProject().getProperty("test"), null);
// }
// Specified class is "" -> can not exist
+ @Test
public void test15() {
- executeTarget("test15");
- assertNull(project.getProperty("test"));
+ buildRule.executeTarget("test15");
+ assertNull(buildRule.getProject().getProperty("test"));
}
// Specified dir is "" -> this is the current directory and should
// always exist
+ @Test
public void test16() {
- executeTarget("test16");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test16");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// Specified dir is "../taskdefs" -> should exist since it's the
// location of the buildfile used...
+ @Test
public void test17() {
- executeTarget("test17");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test17");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// Specified dir is "../this_dir_should_never_exist" -> null
+ @Test
public void test18() {
- executeTarget("test18");
- assertNull(project.getProperty("test"));
+ buildRule.executeTarget("test18");
+ assertNull(buildRule.getProject().getProperty("test"));
}
// Invalid type specified
+ @Test
public void test19() {
- expectBuildException("test19", "Invalid value for type attribute.");
+ try {
+ buildRule.executeTarget("test19");
+ fail("Invalid value for type attribute");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
// Core class that exists in system classpath is ignored
+ @Test
public void test20() {
- executeTarget("test20");
- assertNull(project.getProperty("test"));
+ buildRule.executeTarget("test20");
+ assertNull(buildRule.getProject().getProperty("test"));
}
// Core class that exists in system classpath is ignored, but found in specified classpath
+ @Test
public void test21() {
- executeTarget("test21");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test21");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// Core class that exists in system classpath is not ignored with ignoresystemclass="false"
+ @Test
public void test22() {
- executeTarget("test22");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test22");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// Core class that exists in system classpath is not ignored with default ignoresystemclasses value
+ @Test
public void test23() {
- executeTarget("test23");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test23");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// Class is found in specified classpath
+ @Test
public void test24() {
- executeTarget("test24");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("test24");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// File is not found in specified filepath
+ @Test
public void testSearchInPathNotThere() {
- executeTarget("searchInPathNotThere");
- assertNull(project.getProperty("test"));
+ buildRule.executeTarget("searchInPathNotThere");
+ assertNull(buildRule.getProject().getProperty("test"));
}
// File is not found in specified filepath
+ @Test
public void testSearchInPathIsThere() {
- executeTarget("searchInPathIsThere");
- assertEquals("true", project.getProperty("test"));
+ buildRule.executeTarget("searchInPathIsThere");
+ assertEquals("true", buildRule.getProject().getProperty("test"));
}
// test when file begins with basedir twice
+ @Test
public void testDoubleBasedir() {
- executeTarget("testDoubleBasedir");
+ buildRule.executeTarget("testDoubleBasedir");
}
// test for searching parents
+ @Test
public void testSearchParents() {
- executeTarget("search-parents");
+ buildRule.executeTarget("search-parents");
}
// test for not searching parents
+ @Test
public void testSearchParentsNot() {
- executeTarget("search-parents-not");
+ buildRule.executeTarget("search-parents-not");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/BUnzip2Test.java b/src/tests/junit/org/apache/tools/ant/taskdefs/BUnzip2Test.java
index b2bf71ca3..60ba5a6f6 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/BUnzip2Test.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/BUnzip2Test.java
@@ -18,45 +18,49 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
-/**
- */
-public class BUnzip2Test extends BuildFileTest {
- /** Utilities used for file operations */
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+public class BUnzip2Test {
- public BUnzip2Test(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/bunzip2.xml");
- executeTarget("prepare");
+ buildRule.configureProject("src/etc/testcases/taskdefs/bunzip2.xml");
+ buildRule.executeTarget("prepare");
}
+ @Test
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void testRealTest() throws java.io.IOException {
testRealTest("realTest");
}
+ @Test
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")));
+ buildRule.executeTarget(target);
+ assertEquals("File content mismatch after bunzip2",
+ FileUtilities.getFileContents(buildRule.getProject().resolveFile("expected/asf-logo-huge.tar")),
+ FileUtilities.getFileContents(buildRule.getProject().resolveFile("asf-logo-huge.tar")));
}
+ @Test
public void testDocumentationClaimsOnCopy() throws java.io.IOException {
testRealTest("testDocumentationClaimsOnCopy");
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/BZip2Test.java b/src/tests/junit/org/apache/tools/ant/taskdefs/BZip2Test.java
index 686e87886..774fb6e80 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/BZip2Test.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/BZip2Test.java
@@ -18,34 +18,44 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.bzip2.CBZip2InputStream;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
-import java.io.InputStream;
import java.io.IOException;
+import java.io.InputStream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
*/
-public class BZip2Test extends BuildFileTest {
+public class BZip2Test {
- public BZip2Test(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/bzip2.xml");
- executeTarget("prepare");
+ buildRule.configureProject("src/etc/testcases/taskdefs/bzip2.xml");
+ buildRule.executeTarget("prepare");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void testRealTest() throws IOException {
- executeTarget("realTest");
+ buildRule.executeTarget("realTest");
// doesn't work: Depending on the compression engine used,
// compressed bytes may differ. False errors would be
@@ -57,8 +67,8 @@ public class BZip2Test extends BuildFileTest {
// 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");
+ buildRule.getProject().resolveFile("expected/asf-logo-huge.tar.bz2");
+ File actualFile = buildRule.getProject().resolveFile("asf-logo-huge.tar.bz2");
InputStream originalIn =
new BufferedInputStream(new FileInputStream(originalFile));
@@ -92,13 +102,15 @@ public class BZip2Test extends BuildFileTest {
actualIn.close();
}
+ @Test
public void testResource(){
- executeTarget("realTestWithResource");
+ buildRule.executeTarget("realTestWithResource");
}
+ @Test
public void testDateCheck(){
- executeTarget("testDateCheck");
- String log = getLog();
+ buildRule.executeTarget("testDateCheck");
+ String log = buildRule.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."));
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/BasenameTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/BasenameTest.java
index 07d128150..3915d6b10 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/BasenameTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/BasenameTest.java
@@ -18,65 +18,96 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class BasenameTest extends BuildFileTest {
+public class BasenameTest {
- public BasenameTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/basename.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/basename.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required attribute missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("Required attribute missing");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required attribute missing");
+ try {
+ buildRule.executeTarget("test2");
+ fail("Required attribute missing");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required attribute missing");
+ try {
+ buildRule.executeTarget("test3");
+ fail("Required attribute missing");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test4() {
- executeTarget("test4");
- String checkprop = project.getProperty("file.w.suf");
+ buildRule.executeTarget("test4");
+ String checkprop = buildRule.getProject().getProperty("file.w.suf");
assertEquals("foo.txt", checkprop);
}
+ @Test
public void test5() {
- executeTarget("test5");
- String checkprop = project.getProperty("file.wo.suf");
+ buildRule.executeTarget("test5");
+ String checkprop = buildRule.getProject().getProperty("file.wo.suf");
assertEquals("foo", checkprop);
}
+ @Test
public void testMultipleDots() {
- executeTarget("testMultipleDots");
- String checkprop = project.getProperty("file.wo.suf");
+ buildRule.executeTarget("testMultipleDots");
+ String checkprop = buildRule.getProject().getProperty("file.wo.suf");
assertEquals("foo.bar", checkprop);
}
+ @Test
public void testNoDots() {
- executeTarget("testNoDots");
- String checkprop = project.getProperty("file.wo.suf");
+ buildRule.executeTarget("testNoDots");
+ String checkprop = buildRule.getProject().getProperty("file.wo.suf");
assertEquals("foo.bar", checkprop);
}
+ @Test
public void testValueEqualsSuffixWithDot() {
- executeTarget("testValueEqualsSuffixWithDot");
- String checkprop = project.getProperty("file.wo.suf");
+ buildRule.executeTarget("testValueEqualsSuffixWithDot");
+ String checkprop = buildRule.getProject().getProperty("file.wo.suf");
assertEquals("", checkprop);
}
+ @Test
public void testValueEqualsSuffixWithoutDot() {
- executeTarget("testValueEqualsSuffixWithoutDot");
- String checkprop = project.getProperty("file.wo.suf");
+ buildRule.executeTarget("testValueEqualsSuffixWithoutDot");
+ String checkprop = buildRule.getProject().getProperty("file.wo.suf");
assertEquals("", checkprop);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/CVSPassTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/CVSPassTest.java
index 57884f640..9fe42b150 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/CVSPassTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/CVSPassTest.java
@@ -19,14 +19,24 @@
package org.apache.tools.ant.taskdefs;
import java.io.*;
-import org.apache.tools.ant.*;
-import org.apache.tools.ant.BuildFileTest;
+
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Tests CVSLogin task.
*
*/
-public class CVSPassTest extends BuildFileTest {
+public class CVSPassTest {
private final String EOL = System.getProperty("line.separator");
private static final String JAKARTA_URL =
":pserver:anoncvs@jakarta.apache.org:/home/cvspublic Ay=0=h v = new Vector();
v.add("call-multi");
v.add("call-multi");
- project.executeTargets(v);
- assertLogContaining("multi is SETmulti is SET");
+ buildRule.getProject().executeTargets(v);
+ AntAssert.assertContains("multi is SETmulti is SET", buildRule.getLog());
}
+ @Test
public void testBlankTarget() {
- expectBuildException("blank-target", "target name must not be empty");
+ try {
+ buildRule.executeTarget("blank-target");
+ fail("target name must not be empty");
+ } catch (BuildException ex) {
+ //TODO assert exception contents
+ }
}
+ @Test
public void testMultipleTargets() {
- expectLog("multiple-targets", "tadadctbdbtc");
+ buildRule.executeTarget("multiple-targets");
+ assertEquals("tadadctbdbtc", buildRule.getLog());
}
+ @Test
public void testMultipleTargets2() {
- expectLog("multiple-targets-2", "dadctb");
+ buildRule.executeTarget("multiple-targets-2");
+ assertEquals("dadctb", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ChecksumTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ChecksumTest.java
index 346752ca7..bd4bdfcf0 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ChecksumTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ChecksumTest.java
@@ -18,76 +18,92 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.IOException;
-/**
- */
-public class ChecksumTest extends BuildFileTest {
-
- public ChecksumTest(String name) {
- super(name);
- }
+public class ChecksumTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/checksum.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/checksum.xml");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void testCreateMd5() throws IOException {
- executeTarget("createMd5");
+ buildRule.executeTarget("createMd5");
}
+ @Test
public void testCreateMD5SUMformat() throws IOException {
- executeTarget("createMD5SUMformat");
+ buildRule.executeTarget("createMD5SUMformat");
}
-
+
+ @Test
public void testCreateSVFformat() throws IOException {
- executeTarget("createSVFformat");
+ buildRule.executeTarget("createSVFformat");
}
-
+
+ @Test
public void testCreatePattern() throws IOException {
- executeTarget("createPattern");
+ buildRule.executeTarget("createPattern");
}
+ @Test
public void testSetProperty() {
- executeTarget("setProperty");
+ buildRule.executeTarget("setProperty");
}
+ @Test
public void testVerifyTotal() {
- executeTarget("verifyTotal");
+ buildRule.executeTarget("verifyTotal");
}
+ @Test
public void testVerifyTotalRC() {
- executeTarget("verifyTotalRC");
+ buildRule.executeTarget("verifyTotalRC");
}
+ @Test
public void testVerifyChecksumdir() {
- executeTarget("verifyChecksumdir");
+ buildRule.executeTarget("verifyChecksumdir");
}
+ @Test
public void testVerifyAsTask() {
- executeTarget("verifyAsTask");
+ buildRule.executeTarget("verifyAsTask");
}
+ @Test
public void testVerifyMD5SUMAsTask() {
- executeTarget("verifyMD5SUMAsTask");
+ buildRule.executeTarget("verifyMD5SUMAsTask");
}
+ @Test
public void testVerifyAsCondition() {
- executeTarget("verifyAsCondition");
+ buildRule.executeTarget("verifyAsCondition");
}
+ @Test
public void testVerifyFromProperty() {
- executeTarget("verifyFromProperty");
+ buildRule.executeTarget("verifyFromProperty");
}
+ @Test
public void testVerifyChecksumdirNoTotal() {
- executeTarget("verifyChecksumdirNoTotal");
+ buildRule.executeTarget("verifyChecksumdirNoTotal");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java
index cfb1296c8..b54418304 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ConcatTest.java
@@ -18,21 +18,28 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
-import java.io.FileReader;
import java.io.IOException;
-import java.io.Reader;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* A test class for the 'concat' task, used to concatenate a series of
* files into a single stream.
*
*/
-public class ConcatTest
- extends BuildFileTest {
+public class ConcatTest {
/**
* The name of the temporary file.
@@ -44,57 +51,68 @@ public class ConcatTest
*/
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);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
/**
* Test set up, called by the unit test framework prior to each
* test.
*/
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/concat.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/concat.xml");
}
/**
* Test tear down, called by the unit test framework prior to each
* test.
*/
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
/**
* Expect an exception when insufficient information is provided.
*/
+ @Test
public void test1() {
- expectBuildException("test1", "Insufficient information.");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException should have been thrown - Insufficient information");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
+
}
/**
* Expect an exception when the destination file is invalid.
*/
+ @Test
public void test2() {
- expectBuildException("test2", "Invalid destination file.");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException should have been thrown - Invalid destination file");
+ } catch(BuildException ex) {
+ //TODO assert value
+ }
}
/**
* Cats the string 'Hello, World!' to a temporary file.
*/
+ @Test
public void test3() {
- File file = new File(getProjectDir(), tempFile);
+ File file = new File(buildRule.getProject().getBaseDir(), tempFile);
if (file.exists()) {
file.delete();
}
- executeTarget("test3");
+ buildRule.executeTarget("test3");
assertTrue(file.exists());
}
@@ -102,15 +120,16 @@ public class ConcatTest
/**
* Cats the file created in test3 three times.
*/
+ @Test
public void test4() {
test3();
- File file = new File(getProjectDir(), tempFile);
+ File file = new File(buildRule.getProject().getBaseDir(), tempFile);
final long origSize = file.length();
- executeTarget("test4");
+ buildRule.executeTarget("test4");
- File file2 = new File(getProjectDir(), tempFile2);
+ File file2 = new File(buildRule.getProject().getBaseDir(), tempFile2);
final long newSize = file2.length();
assertEquals(origSize * 3, newSize);
@@ -119,170 +138,178 @@ public class ConcatTest
/**
* Cats the string 'Hello, World!' to the console.
*/
+ @Test
public void test5() {
- expectLog("test5", "Hello, World!");
+ buildRule.executeTarget("test5");
+ assertEquals("Hello, World!", buildRule.getLog());
}
+ @Test
public void test6() {
String filename = "src/etc/testcases/taskdefs/thisfiledoesnotexist"
.replace('/', File.separatorChar);
- expectLogContaining("test6", filename +" does not exist.");
+ buildRule.executeTarget("test6");
+ assertContains(filename + " does not exist", buildRule.getLog());
}
+ @Test
public void testConcatNoNewline() {
- expectLog("testConcatNoNewline", "ab");
+ buildRule.executeTarget("testConcatNoNewline");
+ assertEquals("ab", buildRule.getLog());
}
+ @Test
public void testConcatNoNewlineEncoding() {
- expectLog("testConcatNoNewlineEncoding", "ab");
+ buildRule.executeTarget("testConcatNoNewlineEncoding");
+ assertEquals("ab", buildRule.getLog());
}
+ @Test
public void testPath() {
test3();
- File file = new File(getProjectDir(), tempFile);
+ File file = new File(buildRule.getProject().getBaseDir(), tempFile);
final long origSize = file.length();
- executeTarget("testPath");
+ buildRule.executeTarget("testPath");
- File file2 = new File(getProjectDir(), tempFile2);
+ File file2 = new File(buildRule.getProject().getBaseDir(), tempFile2);
final long newSize = file2.length();
assertEquals(origSize, newSize);
}
+
+ @Test
public void testAppend() {
test3();
- File file = new File(getProjectDir(), tempFile);
+ File file = new File(buildRule.getProject().getBaseDir(), tempFile);
final long origSize = file.length();
- executeTarget("testAppend");
+ buildRule.executeTarget("testAppend");
- File file2 = new File(getProjectDir(), tempFile2);
+ File file2 = new File(buildRule.getProject().getBaseDir(), tempFile2);
final long newSize = file2.length();
assertEquals(origSize*2, newSize);
}
+ @Test
public void testFilter() {
- executeTarget("testfilter");
- assertTrue(getLog().indexOf("REPLACED") > -1);
+ buildRule.executeTarget("testfilter");
+ assertTrue(buildRule.getLog().indexOf("REPLACED") > -1);
}
+ @Test
public void testNoOverwrite() {
- executeTarget("testnooverwrite");
- File file2 = new File(getProjectDir(), tempFile2);
+ buildRule.executeTarget("testnooverwrite");
+ File file2 = new File(buildRule.getProject().getBaseDir(), tempFile2);
long size = file2.length();
assertEquals(size, 0);
}
+ @Test
public void testOverwrite() {
- executeTarget("testoverwrite");
- File file2 = new File(getProjectDir(), tempFile2);
+ buildRule.executeTarget("testoverwrite");
+ File file2 = new File(buildRule.getProject().getBaseDir(), tempFile2);
long size = file2.length();
assertTrue(size > 0);
}
+ @Test
public void testheaderfooter() {
test3();
- expectLog("testheaderfooter", "headerHello, World!footer");
+ buildRule.executeTarget("testheaderfooter");
+ assertEquals("headerHello, World!footer", buildRule.getLog());
}
+ @Test
public void testfileheader() {
test3();
- expectLog("testfileheader", "Hello, World!Hello, World!");
+ buildRule.executeTarget("testfileheader");
+ assertEquals("Hello, World!Hello, World!", buildRule.getLog());
}
/**
* Expect an exception when attempting to cat an file to itself
*/
+ @Test
public void testsame() {
- expectBuildException("samefile", "output file same as input");
+ try {
+ buildRule.executeTarget("samefile");
+ fail("Build exception should have been thrown - output file same as input");
+ } catch(BuildException ex) {
+ //TODO assert value
+ }
}
/**
* Check if filter inline works
*/
+ @Test
public void testfilterinline() {
- executeTarget("testfilterinline");
- assertTrue(getLog().indexOf("REPLACED") > -1);
+ buildRule.executeTarget("testfilterinline");
+ assertTrue(buildRule.getLog().indexOf("REPLACED") > -1);
}
/**
* Check if multireader works
*/
+ @Test
public void testmultireader() {
- executeTarget("testmultireader");
- assertTrue(getLog().indexOf("Bye") > -1);
- assertTrue(getLog().indexOf("Hello") == -1);
+ buildRule.executeTarget("testmultireader");
+ assertTrue(buildRule.getLog().indexOf("Bye") > -1);
+ assertTrue(buildRule.getLog().indexOf("Hello") == -1);
}
/**
* Check if fixlastline works
*/
+ @Test
public void testfixlastline()
throws IOException
{
- expectFileContains(
- "testfixlastline", "concat.line4",
- "end of line" + System.getProperty("line.separator")
- + "This has");
+ buildRule.executeTarget("testfixlastline");
+ assertContains("end of line" + System.getProperty("line.separator") + "This has",
+ FileUtilities.getFileContents(buildRule.getProject(), "concat.line4"));
}
/**
* Check if fixlastline works with eol
*/
+ @Test
public void testfixlastlineeol()
throws IOException
{
- expectFileContains(
- "testfixlastlineeol", "concat.linecr",
- "end of line\rThis has");
+ buildRule.executeTarget("testfixlastlineeol");
+ assertContains("end of line\rThis has", FileUtilities.getFileContents(buildRule.getProject(), "concat.linecr"));
}
- // ------------------------------------------------------
- // 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);
+ @Test
+ public void testTranscoding() throws IOException {
+ buildRule.executeTarget("testTranscoding");
+ File f1 = buildRule.getProject().resolveFile("copy/expected/utf-8");
+ File f2 = buildRule.getProject().resolveFile("concat.utf8");
+ assertEquals(f1.toString() + " differs from " + f2.toString(),
+ FileUtilities.getFileContents(f1), FileUtilities.getFileContents(f2));
}
- private void expectFileContains(
+ // ------------------------------------------------------
+ // Helper methods - should be in a utility class
+ // -----------------------------------------------------
+ private void expectFileContainsx(
String target, String filename, String contains)
throws IOException
{
- String content = getFileString(target, filename);
+ buildRule.executeTarget(target);
+ String content = FileUtilities.getFileContents(buildRule.getProject(), 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(f1.toString() + " differs from " + f2.toString(),
- FILE_UTILS.contentEquals(f1, f2));
- }
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ConditionTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ConditionTest.java
index 7cf71cc7b..1b6c1039b 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ConditionTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ConditionTest.java
@@ -17,259 +17,363 @@
*/
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- * @created 13 January 2002
- */
-public class ConditionTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
- /**
- * Constructor for the ConditionTest object
- *
- * @param name we dont know
- */
- public ConditionTest(String name) {
- super(name);
- }
+public class ConditionTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
/**
* The JUnit setup method
*/
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/condition.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/condition.xml");
}
/**
* The teardown method for JUnit
*/
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void testBasic() {
- expectPropertySet("basic","basic");
+ buildRule.executeTarget("basic");
+ assertEquals("true", buildRule.getProject().getProperty("basic"));
}
+ @Test
public void testConditionIncomplete() {
- expectSpecificBuildException("condition-incomplete",
- "property attribute has been omitted",
- "The property attribute is required.");
+ try {
+ buildRule.executeTarget("condition-incomplete");
+ fail("BuildException should have been thrown - property attribute has been omitted");
+ } catch (BuildException ex) {
+ assertEquals("The property attribute is required.", ex.getMessage());
+ }
}
+ @Test
public void testConditionEmpty() {
- expectSpecificBuildException("condition-empty",
- "no conditions",
- "You must nest a condition into ");
+ try {
+ buildRule.executeTarget("condition-empty");
+ fail("BuildException should have been thrown - no conditions");
+ } catch(BuildException ex) {
+ assertEquals("You must nest a condition into ", ex.getMessage());
+ }
}
+ @Test
public void testShortcut() {
- expectPropertySet("shortcut","shortcut","set");
+ buildRule.executeTarget("shortcut");
+ assertEquals("set", buildRule.getProject().getProperty("shortcut"));
}
+ @Test
public void testUnset() {
- expectPropertyUnset("dontset","dontset");
+ buildRule.executeTarget("dontset");
+ assertNull(buildRule.getProject().getProperty("dontset"));
}
+ @Test
public void testSetValue() {
- expectPropertySet("setvalue","setvalue","woowoo");
+ buildRule.executeTarget("setvalue");
+ assertEquals("woowoo", buildRule.getProject().getProperty("setvalue"));
}
+ @Test
public void testNegation() {
- expectPropertySet("negation","negation");
+ buildRule.executeTarget("negation");
+ assertEquals("true", buildRule.getProject().getProperty("negation"));
}
+ @Test
public void testNegationFalse() {
- expectPropertyUnset("negationfalse","negationfalse");
+ buildRule.executeTarget("negationfalse");
+ assertNull(buildRule.getProject().getProperty("negationfalse"));
}
+ @Test
public void testNegationIncomplete() {
- expectSpecificBuildException("negationincomplete",
- "no conditions in ",
- "You must nest a condition into ");
+ try {
+ buildRule.executeTarget("negationincomplete");
+ fail("BuildException should have been thrown - no conditions in ");
+ } catch (BuildException ex) {
+ assertEquals("You must nest a condition into ", ex.getMessage());
+ }
}
+ @Test
public void testAnd() {
- expectPropertySet("and","and");
+ buildRule.executeTarget("and");
+ assertEquals("true", buildRule.getProject().getProperty("and"));
}
+ @Test
public void testAndFails() {
- expectPropertyUnset("andfails","andfails");
+ buildRule.executeTarget("andfails");
+ assertNull(buildRule.getProject().getProperty("andfails"));
}
+ @Test
public void testAndIncomplete() {
- expectPropertyUnset("andincomplete","andincomplete");
+ buildRule.executeTarget("andincomplete");
+ assertNull(buildRule.getProject().getProperty("andincomplete"));
}
+ @Test
public void testAndempty() {
- expectPropertySet("andempty","andempty");
+ buildRule.executeTarget("andempty");
+ assertEquals("true", buildRule.getProject().getProperty("andempty"));
}
+ @Test
public void testOr() {
- expectPropertySet("or","or");
+ buildRule.executeTarget("or");
+ assertEquals("true", buildRule.getProject().getProperty("or"));
}
+ @Test
public void testOrincomplete() {
- expectPropertySet("or","or");
+ buildRule.executeTarget("or");
+ assertEquals("true", buildRule.getProject().getProperty("or"));
}
+ @Test
public void testOrFails() {
- expectPropertyUnset("orfails","orfails");
+ buildRule.executeTarget("orfails");
+ assertNull(buildRule.getProject().getProperty("orfails"));
}
+ @Test
public void testOrboth() {
- expectPropertySet("orboth","orboth");
+ buildRule.executeTarget("orboth");
+ assertEquals("true", buildRule.getProject().getProperty("orboth"));
}
+ @Test
public void testFilesmatchIdentical() {
- expectPropertySet("filesmatch-identical","filesmatch-identical");
+ buildRule.executeTarget("filesmatch-identical");
+ assertEquals("true", buildRule.getProject().getProperty("filesmatch-identical"));
}
-
+ @Test
public void testFilesmatchIncomplete() {
- expectSpecificBuildException("filesmatch-incomplete",
- "Missing file2 attribute",
- "both file1 and file2 are required in filesmatch");
+ try {
+ buildRule.executeTarget("filesmatch-incomplete");
+ fail("Build exception should have been thrown - Missing file2 attirbute");
+ } catch (BuildException ex) {
+ assertEquals("both file1 and file2 are required in filesmatch", ex.getMessage());
+ }
}
+ @Test
public void testFilesmatchOddsizes() {
- expectPropertyUnset("filesmatch-oddsizes","filesmatch-oddsizes");
+ buildRule.executeTarget("filesmatch-oddsizes");
+ assertNull(buildRule.getProject().getProperty("filesmatch-oddsizes"));
}
+ @Test
public void testFilesmatchExistence() {
- expectPropertyUnset("filesmatch-existence", "filesmatch-existence");
+ buildRule.executeTarget("filesmatch-existence");
+ assertNull(buildRule.getProject().getProperty("filesmatch-existence"));
}
+ @Test
public void testFilesmatchDifferent() {
- expectPropertyUnset("filesmatch-different","filesmatch-different");
+ buildRule.executeTarget("filesmatch-different");
+ assertNull(buildRule.getProject().getProperty("filesmatch-different"));
}
+ @Test
public void testFilesmatchMatch() {
- expectPropertySet("filesmatch-match","filesmatch-match");
+ buildRule.executeTarget("filesmatch-match");
+ assertEquals("true", buildRule.getProject().getProperty("filesmatch-match"));
}
+ @Test
public void testFilesmatchDifferentSizes() {
- expectPropertyUnset("filesmatch-different-sizes",
- "filesmatch-different-sizes");
+ buildRule.executeTarget("filesmatch-different-sizes");
+ assertNull(buildRule.getProject().getProperty("filesmatch-different-sizes"));
}
+ @Test
public void testFilesmatchDifferentOnemissing() {
- expectPropertyUnset("filesmatch-different-onemissing",
- "filesmatch-different-onemissing");
+ buildRule.executeTarget("filesmatch-different-onemissing");
+ assertNull(buildRule.getProject().getProperty("filesmatch-different-onemissing"));
}
+ @Test
public void testFilesmatchDifferentEol() {
- executeTarget("filesmatch-different-eol");
+ buildRule.executeTarget("filesmatch-different-eol");
}
+ @Test
public void testFilesmatchSameEol() {
- executeTarget("filesmatch-same-eol");
+ buildRule.executeTarget("filesmatch-same-eol");
}
+ @Test
public void testFilesmatchNeitherExist() {
- executeTarget("filesmatch-neitherexist");
+ buildRule.executeTarget("filesmatch-neitherexist");
}
+ @Test
public void testContains() {
- expectPropertySet("contains","contains");
+ buildRule.executeTarget("contains");
+ assertEquals("true", buildRule.getProject().getProperty("contains"));
}
-
+ @Test
public void testContainsDoesnt() {
- expectPropertyUnset("contains-doesnt","contains-doesnt");
+ buildRule.executeTarget("contains-doesnt");
+ assertNull(buildRule.getProject().getProperty("contains-doesnt"));
}
+ @Test
public void testContainsAnycase() {
- expectPropertySet("contains-anycase","contains-anycase");
+ buildRule.executeTarget("contains-anycase");
+ assertEquals("true", buildRule.getProject().getProperty("contains-anycase"));
}
-
+ @Test
public void testContainsIncomplete1() {
- expectSpecificBuildException("contains-incomplete1",
- "Missing contains attribute",
- "both string and substring are required in contains");
+ try {
+ buildRule.executeTarget("contains-incomplete1");
+ fail("BuildException should have been thrown - Missing contains attribute");
+ } catch(BuildException ex) {
+ assertEquals("both string and substring are required in contains", ex.getMessage());
+ }
}
+ @Test
public void testContainsIncomplete2() {
- expectSpecificBuildException("contains-incomplete2",
- "Missing contains attribute",
- "both string and substring are required in contains");
+ try {
+ buildRule.executeTarget("contains-incomplete2");
+ fail("BuildException should have been thrown - Missing contains attribute");
+ } catch(BuildException ex) {
+ assertEquals("both string and substring are required in contains", ex.getMessage());
+ }
}
+ @Test
public void testIstrue() {
- expectPropertySet("istrue","istrue");
+ buildRule.executeTarget("istrue");
+ assertEquals("true", buildRule.getProject().getProperty("istrue"));
}
+ @Test
public void testIstrueNot() {
- expectPropertyUnset("istrue-not","istrue-not");
+ buildRule.executeTarget("istrue-not");
+ assertNull(buildRule.getProject().getProperty("istrue-not"));
}
+ @Test
public void testIstrueFalse() {
- expectPropertyUnset("istrue-false","istrue-false");
+ buildRule.executeTarget("istrue-false");
+ assertNull(buildRule.getProject().getProperty("istrue-false"));
}
-
+ @Test
public void testIstrueIncomplete1() {
- expectSpecificBuildException("istrue-incomplete",
- "Missing attribute",
- "Nothing to test for truth");
+ try {
+ buildRule.executeTarget("istrue-incomplete");
+ fail("BuildException should have been thrown - Missing attribute");
+ } catch(BuildException ex) {
+ assertEquals("Nothing to test for truth", ex.getMessage());
+ }
}
+ @Test
public void testIsfalseTrue() {
- expectPropertyUnset("isfalse-true","isfalse-true");
+ buildRule.executeTarget("isfalse-true");
+ assertNull(buildRule.getProject().getProperty("isfalse-true"));
}
+ @Test
public void testIsfalseNot() {
- expectPropertySet("isfalse-not","isfalse-not");
+ buildRule.executeTarget("isfalse-not");
+ assertEquals("true", buildRule.getProject().getProperty("isfalse-not"));
}
+ @Test
public void testIsfalseFalse() {
- expectPropertySet("isfalse-false","isfalse-false");
- }
+ buildRule.executeTarget("isfalse-false");
+ assertEquals("true", buildRule.getProject().getProperty("isfalse-false"));
+ }
+ @Test
public void testIsfalseIncomplete1() {
- expectSpecificBuildException("isfalse-incomplete",
- "Missing attribute",
- "Nothing to test for falsehood");
+ try {
+ buildRule.executeTarget("isfalse-incomplete");
+ fail("BuildException should have been thrown - Missing attribute");
+ } catch(BuildException ex) {
+ assertEquals("Nothing to test for falsehood", ex.getMessage());
+ }
}
+ @Test
public void testElse() {
- executeTarget("testElse");
+ buildRule.executeTarget("testElse");
}
+ @Test
public void testResourcesmatchError() {
- expectBuildException("resourcesmatch-error",
- "should fail because no resources specified");
+ try {
+ buildRule.executeTarget("resourcematch-error");
+ fail("BuildException should have been thrown - no resources specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testResourcesmatchEmpty() {
- executeTarget("resourcesmatch-match-empty");
+ buildRule.executeTarget("resourcesmatch-match-empty");
}
+ @Test
public void testResourcesmatchOne() {
- executeTarget("resourcesmatch-match-one");
+ buildRule.executeTarget("resourcesmatch-match-one");
}
+ @Test
public void testResourcesmatchBinary() {
- executeTarget("resourcesmatch-match-binary");
+ buildRule.executeTarget("resourcesmatch-match-binary");
}
+ @Test
public void testResourcesmatchMultipleBinary() {
- executeTarget("resourcesmatch-match-multiple-binary");
+ buildRule.executeTarget("resourcesmatch-match-multiple-binary");
}
+ @Test
public void testResourcesmatchDiffer() {
- executeTarget("resourcesmatch-differ");
+ buildRule.executeTarget("resourcesmatch-differ");
}
+ @Test
public void testResourcesmatchText() {
- executeTarget("resourcesmatch-match-text");
+ buildRule.executeTarget("resourcesmatch-match-text");
}
+ @Test
public void testResourcesmatchNoneExist() {
- executeTarget("resourcesmatch-noneexist");
+ buildRule.executeTarget("resourcesmatch-noneexist");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java
index 3a7c62d6b..a7a32a9a5 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/CopyTest.java
@@ -18,55 +18,72 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
/**
* Tests FileSet using the Copy task.
*
*/
-public class CopyTest extends BuildFileTest {
+public class CopyTest {
- /** Utilities used for file operations */
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
- public CopyTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/copy.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/copy.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void test1() {
- executeTarget("test1");
- File f = new File(getOutputDir(), "copytest1.tmp");
+ buildRule.executeTarget("test1");
+ File f = new File(buildRule.getProject().getProperty("output"), "copytest1.tmp");
if ( !f.exists()) {
fail("Copy failed");
}
}
+ @Test
public void test2() {
- executeTarget("test2");
- File f = new File(getOutputDir(), "copytest1dir/copy.xml");
+ buildRule.executeTarget("test2");
+ File f = new File(buildRule.getProject().getProperty("output"), "copytest1dir/copy.xml");
if ( !f.exists()) {
fail("Copy failed");
}
}
+ @Test
public void test3() {
- executeTarget("test3");
- File file3 = new File(getOutputDir(), "copytest3.tmp");
+ buildRule.executeTarget("test3");
+ File file3 = new File(buildRule.getProject().getProperty("output"), "copytest3.tmp");
+ //rollback file timestamp instead of delaying test
+ FileUtilities.rollbackTimetamps(file3, 3);
+ buildRule.executeTarget("test3Part2");
assertTrue(file3.exists());
- File file3a = new File(getOutputDir(), "copytest3a.tmp");
+
+ File file3a = new File(buildRule.getProject().getProperty("output"), "copytest3a.tmp");
assertTrue(file3a.exists());
- File file3b = new File(getOutputDir(), "copytest3b.tmp");
+ File file3b = new File(buildRule.getProject().getProperty("output"), "copytest3b.tmp");
assertTrue(file3b.exists());
- File file3c = new File(getOutputDir(), "copytest3c.tmp");
+ File file3c = new File(buildRule.getProject().getProperty("output"), "copytest3c.tmp");
assertTrue(file3c.exists());
//file length checks rely on touch generating a zero byte file
@@ -86,96 +103,120 @@ public class CopyTest extends BuildFileTest {
}
+ @Test
public void testFilterTest() {
- executeTarget("filtertest");
- assertTrue(getOutput().indexOf("loop in tokens") == -1);
+ buildRule.executeTarget("filtertest");
+ assertTrue(buildRule.getLog().indexOf("loop in tokens") == -1);
}
+ @Test
public void testInfiniteFilter() {
- executeTarget("infinitetest");
- assertTrue(getOutput().indexOf("loop in tokens") != -1);
+ buildRule.executeTarget("infinitetest");
+ assertContains("loop in tokens", buildRule.getOutput());
}
+ @Test
public void testFilterSet() throws IOException {
- executeTarget("testFilterSet");
- File tmp = new File(getOutputDir(), "copy.filterset.tmp");
- File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
+ buildRule.executeTarget("testFilterSet");
+ File tmp = new File(buildRule.getProject().getProperty("output"), "copy.filterset.tmp");
+ File check = new File(buildRule.getProject().getBaseDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
- assertTrue(FILE_UTILS.contentEquals(tmp, check));
+ assertEquals(FileUtilities.getFileContents(tmp), FileUtilities.getFileContents(check));
}
+ @Test
public void testFilterChain() throws IOException {
- executeTarget("testFilterChain");
- File tmp = new File(getOutputDir(), "copy.filterchain.tmp");
- File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
+ buildRule.executeTarget("testFilterChain");
+ File tmp = new File(buildRule.getProject().getProperty("output"), "copy.filterchain.tmp");
+ File check = new File(buildRule.getProject().getBaseDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
- assertTrue(FILE_UTILS.contentEquals(tmp, check));
+ assertEquals(FileUtilities.getFileContents(tmp), FileUtilities.getFileContents(check));
}
+ @Test
public void testSingleFileFileset() {
- executeTarget("test_single_file_fileset");
- File file = new File(getOutputDir(),
+ buildRule.executeTarget("test_single_file_fileset");
+ File file = new File(buildRule.getProject().getProperty("output"),
"copytest_single_file_fileset.tmp");
assertTrue(file.exists());
}
+ @Test
public void testSingleFilePath() {
- executeTarget("test_single_file_path");
- File file = new File(getOutputDir(),
+ buildRule.executeTarget("test_single_file_path");
+ File file = new File(buildRule.getProject().getProperty("output"),
"copytest_single_file_path.tmp");
assertTrue(file.exists());
}
+ @Test
public void testTranscoding() throws IOException {
- executeTarget("testTranscoding");
- File f1 = getProject().resolveFile("copy/expected/utf-8");
- File f2 = new File(getOutputDir(), "copytest1.tmp");
- assertTrue(FILE_UTILS.contentEquals(f1, f2));
+ buildRule.executeTarget("testTranscoding");
+ File f1 = buildRule.getProject().resolveFile("copy/expected/utf-8");
+ File f2 = new File(buildRule.getProject().getProperty("output"), "copytest1.tmp");
+ assertEquals(FileUtilities.getFileContents(f1), FileUtilities.getFileContents(f2));
}
+ @Test
public void testMissingFileIgnore() {
- expectLogContaining("testMissingFileIgnore",
- "Warning: Could not find file ");
+ buildRule.executeTarget("testMissingFileIgnore");
+ assertContains("Warning: Could not find file", buildRule.getLog());
}
+ @Test
public void testMissingFileBail() {
- expectBuildException("testMissingFileBail", "not-there doesn't exist");
- assertTrue(getBuildException().getMessage()
- .startsWith("Warning: Could not find file "));
+ try {
+ buildRule.executeTarget("testMissingFileBail");
+ fail("not-there doesn't exist");
+ } catch (BuildException ex) {
+ assertTrue(ex.getMessage()
+ .startsWith("Warning: Could not find file "));
+ }
}
+ @Test
public void testMissingDirIgnore() {
- expectLogContaining("testMissingDirIgnore", "Warning: ");
+ buildRule.executeTarget("testMissingDirIgnore");
+ assertContains("Warning: ", buildRule.getLog());
}
+ @Test
public void testMissingDirBail() {
- expectBuildException("testMissingDirBail", "not-there doesn't exist");
- assertTrue(getBuildException().getMessage().endsWith(" does not exist."));
+ try {
+ buildRule.executeTarget("testMissingDirBail");
+ fail("not-there doesn't exist");
+ } catch (BuildException ex) {
+ assertTrue(ex.getMessage().endsWith(" does not exist."));
+ }
}
+ @Test
public void testFileResourcePlain() {
- executeTarget("testFileResourcePlain");
- File file1 = new File(getProject().getProperty("to.dir")+"/file1.txt");
- File file2 = new File(getProject().getProperty("to.dir")+"/file2.txt");
- File file3 = new File(getProject().getProperty("to.dir")+"/file3.txt");
+ buildRule.executeTarget("testFileResourcePlain");
+ File file1 = new File(buildRule.getProject().getProperty("to.dir")+"/file1.txt");
+ File file2 = new File(buildRule.getProject().getProperty("to.dir")+"/file2.txt");
+ File file3 = new File(buildRule.getProject().getProperty("to.dir")+"/file3.txt");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}
-
- public void _testFileResourceWithMapper() {
- executeTarget("testFileResourceWithMapper");
- File file1 = new File(getProject().getProperty("to.dir")+"/file1.txt.bak");
- File file2 = new File(getProject().getProperty("to.dir")+"/file2.txt.bak");
- File file3 = new File(getProject().getProperty("to.dir")+"/file3.txt.bak");
+
+ @Ignore("Previously ignored by naming convention")
+ @Test
+ public void testFileResourceWithMapper() {
+ buildRule.executeTarget("testFileResourceWithMapper");
+ File file1 = new File(buildRule.getProject().getProperty("to.dir")+"/file1.txt.bak");
+ File file2 = new File(buildRule.getProject().getProperty("to.dir")+"/file2.txt.bak");
+ File file3 = new File(buildRule.getProject().getProperty("to.dir")+"/file3.txt.bak");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}
+ @Test
public void testFileResourceWithFilter() {
- executeTarget("testFileResourceWithFilter");
- File file1 = new File(getProject().getProperty("to.dir")+"/fileNR.txt");
+ buildRule.executeTarget("testFileResourceWithFilter");
+ File file1 = new File(buildRule.getProject().getProperty("to.dir")+"/fileNR.txt");
assertTrue(file1.exists());
try {
String file1Content = FileUtils.readFully(new FileReader(file1));
@@ -185,44 +226,55 @@ public class CopyTest extends BuildFileTest {
}
}
+ @Test
public void testPathAsResource() {
- executeTarget("testPathAsResource");
- File file1 = new File(getProject().getProperty("to.dir")+"/file1.txt");
- File file2 = new File(getProject().getProperty("to.dir")+"/file2.txt");
- File file3 = new File(getProject().getProperty("to.dir")+"/file3.txt");
+ buildRule.executeTarget("testPathAsResource");
+ File file1 = new File(buildRule.getProject().getProperty("to.dir")+"/file1.txt");
+ File file2 = new File(buildRule.getProject().getProperty("to.dir")+"/file2.txt");
+ File file3 = new File(buildRule.getProject().getProperty("to.dir")+"/file3.txt");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}
+ @Test
public void testZipfileset() {
- executeTarget("testZipfileset");
- File file1 = new File(getProject().getProperty("to.dir")+"/file1.txt");
- File file2 = new File(getProject().getProperty("to.dir")+"/file2.txt");
- File file3 = new File(getProject().getProperty("to.dir")+"/file3.txt");
+ buildRule.executeTarget("testZipfileset");
+ File file1 = new File(buildRule.getProject().getProperty("to.dir")+"/file1.txt");
+ File file2 = new File(buildRule.getProject().getProperty("to.dir")+"/file2.txt");
+ File file3 = new File(buildRule.getProject().getProperty("to.dir")+"/file3.txt");
assertTrue(file1.exists());
assertTrue(file2.exists());
assertTrue(file3.exists());
}
+ @Test
public void testDirset() {
- executeTarget("testDirset");
+ buildRule.executeTarget("testDirset");
}
- public void _testResourcePlain() {
- executeTarget("testResourcePlain");
+ @Ignore("Previously ignored due to naming convention")
+ @Test
+ public void testResourcePlain() {
+ buildRule.executeTarget("testResourcePlain");
}
-
- public void _testResourcePlainWithMapper() {
- executeTarget("testResourcePlainWithMapper");
+
+ @Ignore("Previously ignored due to naming convention")
+ @Test
+ public void testResourcePlainWithMapper() {
+ buildRule.executeTarget("testResourcePlainWithMapper");
}
-
- public void _testResourcePlainWithFilter() {
- executeTarget("testResourcePlainWithFilter");
+
+ @Ignore("Previously ignored due to naming convention")
+ @Test
+ public void testResourcePlainWithFilter() {
+ buildRule.executeTarget("testResourcePlainWithFilter");
}
-
- public void _testOnlineResources() {
- executeTarget("testOnlineResources");
+
+ @Ignore("Previously ignored due to naming convention")
+ @Test
+ public void testOnlineResources() {
+ buildRule.executeTarget("testOnlineResources");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/CopydirTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/CopydirTest.java
index 3bfbf527f..a7fdd5cb9 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/CopydirTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/CopydirTest.java
@@ -18,48 +18,83 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Test;
-/**
- */
-public class CopydirTest extends BuildFileTest {
+import java.io.File;
- public CopydirTest(String name) {
- super(name);
- }
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+
+public class CopydirTest {
+
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/copydir.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/copydir.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ // TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ // TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument not specified");
+ try {
+ buildRule.executeTarget("test3");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ // TODO assert value
+ }
}
+ @Test
public void test4() {
- expectLog("test4", "DEPRECATED - The copydir task is deprecated. Use copy instead.Warning: src == dest");
+ buildRule.executeTarget("test4");
+ assertEquals("DEPRECATED - The copydir task is deprecated. Use copy instead.Warning: src == dest",
+ buildRule.getLog());
}
+ @Test
public void test5() {
- executeTarget("test5");
- java.io.File f = new java.io.File(getOutputDir(), "taskdefs.tmp");
+ buildRule.executeTarget("test5");
+ java.io.File f = new java.io.File(new File(buildRule.getProject().getProperty("output")), "taskdefs.tmp");
+
if (!f.exists() || !f.isDirectory()) {
fail("Copy failed");
}
// We keep this, so we have something to delete in later tests :-)
}
+ @Test
public void test6() {
- expectBuildException("test6", "target is file");
+ try {
+ buildRule.executeTarget("test6");
+ fail("target is file");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/CopyfileTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/CopyfileTest.java
index 20407bbae..a3d84eeb7 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/CopyfileTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/CopyfileTest.java
@@ -18,46 +18,83 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class CopyfileTest extends BuildFileTest {
+public class CopyfileTest {
- public void test6() {
- expectBuildException("test6", "target is directory");
- }
-
- public CopyfileTest(String name) {
- super(name);
- }
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/copyfile.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/copyfile.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ // TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ // TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument not specified");
+ try {
+ buildRule.executeTarget("test3");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ // TODO assert value
+ }
}
+ @Test
public void test4() {
- expectLog("test4", "DEPRECATED - The copyfile task is deprecated. Use copy instead.Warning: src == dest");
+ buildRule.executeTarget("test4");
+ assertEquals("DEPRECATED - The copyfile task is deprecated. Use copy instead.Warning: src == dest",
+ buildRule.getLog());
}
+ @Test
public void test5() {
- executeTarget("test5");
- java.io.File f = new java.io.File(getOutputDir(), "copyfile.tmp");
- if (!f.exists()) {
+ buildRule.executeTarget("test5");
+ File f = new File(new File(buildRule.getProject().getProperty("output")), "copyfile.tmp");
+ if (f.exists()) {
+ f.delete();
+ } else {
fail("Copy failed");
}
}
+
+ @Test
+ public void test6() {
+ try {
+ buildRule.executeTarget("test6");
+ fail("Required argument not specified");
+ } catch (BuildException ex) {
+ // TODO assert value
+ }
+ }
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/DefaultExcludesTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/DefaultExcludesTest.java
index 86efc6855..e093d4f76 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/DefaultExcludesTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/DefaultExcludesTest.java
@@ -18,26 +18,35 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.DirectoryScanner;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
/**
*/
-public class DefaultExcludesTest extends BuildFileTest {
+public class DefaultExcludesTest {
- public DefaultExcludesTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/defaultexcludes.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/defaultexcludes.xml");
}
+ @After
public void tearDown() {
- project.executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
// Output the default excludes
+ @Test
public void test1() {
String[] expected = {
"**/*~",
@@ -68,11 +77,12 @@ public class DefaultExcludesTest extends BuildFileTest {
"**/.bzr/**",
"**/.bzrignore",
"**/.DS_Store"};
- project.executeTarget("test1");
- assertEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
+ buildRule.getProject().executeTarget("test1");
+ assertArrayContentsEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
}
// adding something to the excludes'
+ @Test
public void test2() {
String[] expected = {
"**/*~",
@@ -104,11 +114,12 @@ public class DefaultExcludesTest extends BuildFileTest {
"**/.bzrignore",
"**/.DS_Store",
"foo"};
- project.executeTarget("test2");
- assertEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
+ buildRule.executeTarget("test2");
+ assertArrayContentsEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
}
// removing something from the defaults
+ @Test
public void test3() {
String[] expected = {
"**/*~",
@@ -139,10 +150,11 @@ public class DefaultExcludesTest extends BuildFileTest {
"**/.bzr/**",
"**/.bzrignore",
"**/.DS_Store"};
- project.executeTarget("test3");
- assertEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
+ buildRule.executeTarget("test3");
+ assertArrayContentsEquals("current default excludes", expected, DirectoryScanner.getDefaultExcludes());
}
- private void assertEquals(String message, String[] expected, String[] actual) {
+
+ private void assertArrayContentsEquals(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++) {
@@ -151,7 +163,7 @@ public class DefaultExcludesTest extends BuildFileTest {
found |= expected[counter].equals(actual[i]);
}
assertTrue(message + " : didn't find element "
- + expected[counter] + " in array match", found);
+ + expected[counter] + " in array match", found);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/DeleteTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/DeleteTest.java
index 1a4a52983..fb2442139 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/DeleteTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/DeleteTest.java
@@ -18,68 +18,95 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
*/
-public class DeleteTest extends BuildFileTest {
+public class DeleteTest {
- public DeleteTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/delete.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/delete.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- executeTarget("test2");
+ buildRule.executeTarget("test2");
}
//where oh where has my test case 3 gone?
+ @Test
public void test4() {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
+ @Test
public void test6() {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
}
+ @Test
public void test7() {
- executeTarget("test7");
+ buildRule.executeTarget("test7");
}
+ @Test
public void test8() {
- executeTarget("test8");
+ buildRule.executeTarget("test8");
}
+ @Test
public void test9() {
- executeTarget("test9");
+ buildRule.executeTarget("test9");
}
+ @Test
public void test10() {
- executeTarget("test10");
+ buildRule.executeTarget("test10");
}
+ @Test
public void test11() {
- executeTarget("test11");
+ buildRule.executeTarget("test11");
}
+ @Test
public void test12() {
- executeTarget("test12");
+ buildRule.executeTarget("test12");
}
+ @Test
public void test13() {
- executeTarget("test13");
+ buildRule.executeTarget("test13");
}
+ @Test
public void test14() {
- executeTarget("test14");
+ buildRule.executeTarget("test14");
}
+ @Test
public void test15() {
- executeTarget("test15");
+ buildRule.executeTarget("test15");
}
+ @Test
public void test16() {
- executeTarget("test16");
+ buildRule.executeTarget("test16");
}
+ @Test
public void test17() {
- executeTarget("test17");
+ buildRule.executeTarget("test17");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/DeltreeTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/DeltreeTest.java
index 62040a95e..b2dcc69eb 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/DeltreeTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/DeltreeTest.java
@@ -18,27 +18,38 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class DeltreeTest extends BuildFileTest {
+import static org.junit.Assert.fail;
- public DeltreeTest(String name) {
- super(name);
- }
+public class DeltreeTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/deltree.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/deltree.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
// We try to delete the directory created in CopydirTest
- executeTarget("test2");
+ buildRule.executeTarget("test2");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/DirnameTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/DirnameTest.java
index 7a5b929ce..96c6c4a17 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/DirnameTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/DirnameTest.java
@@ -18,53 +18,75 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.taskdefs.condition.Os;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
*/
-public class DirnameTest extends BuildFileTest {
-
- public DirnameTest(String name) {
- super(name);
- }
+public class DirnameTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/dirname.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/dirname.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "property attribute required");
+ try {
+ buildRule.executeTarget("test1");
+ fail("Build exception should have been thrown as property attribute is required");
+ } catch(BuildException ex) {
+ assertEquals("property attribute required", ex.getMessage());
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "file attribute required");
+ try {
+ buildRule.executeTarget("test2");
+ fail("Build exception should have been thrown as file attribute is required");
+ } catch(BuildException ex) {
+ assertEquals("file attribute required", ex.getMessage());
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "property attribute required");
+ try {
+ buildRule.executeTarget("test3");
+ fail("Build exception should have been thrown as property attribute is required");
+ } catch(BuildException ex) {
+ assertEquals("property attribute required", ex.getMessage());
+ }
}
+ @Test
public void test4() {
- if (Os.isFamily("netware") || Os.isFamily("dos")) {
- return;
- }
- executeTarget("test4");
+ Assume.assumeFalse("Test not possible on DOS or Netware family OS", Os.isFamily("netware") || Os.isFamily("dos"));
+ buildRule.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");
- }
+ String checkprop = buildRule.getProject().getProperty("local.dir");
+ assertEquals("dirname failed", expected, checkprop);
}
+ @Test
public void test5() {
- executeTarget("test5");
- String expected = project.getProperty("basedir");
- String checkprop = project.getProperty("base.dir");
- if (!checkprop.equals(expected)) {
- fail("dirname failed");
- }
+ buildRule.executeTarget("test5");
+ String expected = buildRule.getProject().getProperty("basedir");
+ String checkprop = buildRule.getProject().getProperty("base.dir");
+ assertEquals("dirname failed", expected, checkprop);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTest.java
index de4426155..615dd903e 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/DynamicTest.java
@@ -18,23 +18,29 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class DynamicTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
- public DynamicTest(String name) {
- super(name);
- }
+public class DynamicTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/dynamictask.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/dynamictask.xml");
}
+ @Test
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"));
+ buildRule.executeTarget("simple");
+ assertEquals("1", buildRule.getProject().getProperty("prop1"));
+ assertEquals("2", buildRule.getProject().getProperty("prop2"));
+ assertEquals("3", buildRule.getProject().getProperty("prop3"));
+ assertEquals("4", buildRule.getProject().getProperty("prop4"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/EchoTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/EchoTest.java
index 06dcdd046..5c2ae28e8 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/EchoTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/EchoTest.java
@@ -18,28 +18,29 @@
package org.apache.tools.ant.taskdefs;
-import java.io.*;
-
-import junit.framework.TestCase;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.After;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* Test Java-dependent parts of the Echo task.
*/
-public class EchoTest extends TestCase {
+public class EchoTest {
private File removeThis;
- /**
- * Create a new EchoTest.
- * @param name
- */
- public EchoTest(String name) {
- super(name);
- }
+ @Test
public void testLogBlankEcho() {
Project p = new Project();
p.init();
@@ -52,7 +53,8 @@ public class EchoTest extends TestCase {
assertEquals("[testLogBlankEcho] ", logger.lastLoggedMessage );
}
- public void testLogUTF8Echo() {
+ @Test
+ public void testLogUTF8Echo() throws IOException {
Project p = new Project();
p.init();
EchoTestLogger logger = new EchoTestLogger();
@@ -65,15 +67,11 @@ public class EchoTest extends TestCase {
echo.setFile(removeThis);
echo.setEncoding("UTF-8");
echo.execute();
- FileUtils fu = FileUtils.getFileUtils();
- try {
String x = FileUtils.readFully(new InputStreamReader(new FileInputStream(removeThis), "UTF-8" ));
- assertEquals(x,"\u00e4\u00a9");
- } catch (Exception exc) {
-
- }
+ assertEquals(x,"\u00e4\u00a9");
}
+ @After
public void tearDown() {
if (removeThis != null && removeThis.exists()) {
if (!removeThis.delete())
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/EchoXMLTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/EchoXMLTest.java
index 2cf2817d0..cc9ec24ec 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/EchoXMLTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/EchoXMLTest.java
@@ -18,32 +18,54 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class EchoXMLTest extends BuildFileTest {
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
- public EchoXMLTest(String name) {
- super(name);
- }
+public class EchoXMLTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/echoxml.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/echoxml.xml");
}
+ @After
public void tearDown() {
- executeTarget("tearDown");
+ buildRule.executeTarget("tearDown");
}
+ @Test
public void testPass() {
- executeTarget("testPass");
+ buildRule.executeTarget("testPass");
}
+ @Test
public void testFail() {
- expectBuildExceptionContaining("testFail", "must fail", "${foo}=bar");
+ try {
+ buildRule.executeTarget("testFail");
+ fail("BuildException expected: must fail");
+ } catch (BuildException ex) {
+ assertContains("${foo}=bar", ex.getMessage());
+ }
}
+ @Test
public void testEmpty() {
- expectBuildExceptionContaining("testEmpty", "must fail", "No nested XML specified");
+ try {
+ buildRule.executeTarget("testEmpty");
+ fail("BuildException expected: must fail");
+ } catch (BuildException ex) {
+ assertContains("No nested XML specified", ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ExecTaskTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ExecTaskTest.java
index 27a4a71ce..49135cf17 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ExecTaskTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ExecTaskTest.java
@@ -18,16 +18,31 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.*;
-import org.apache.tools.ant.util.FileUtils;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.GregorianCalendar;
+import org.apache.tools.ant.BuildEvent;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.BuildListener;
+import org.apache.tools.ant.Project;
+import org.apache.tools.ant.ProjectHelper;
+import org.apache.tools.ant.util.FileUtils;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
/**
* Unit test for the <exec> task.
*/
-public class ExecTaskTest extends BuildFileTest {
+public class ExecTaskTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
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;
@@ -44,21 +59,19 @@ public class ExecTaskTest extends BuildFileTest {
private MonitoredBuild myBuild = null;
volatile private boolean buildFinished = false;
- public ExecTaskTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject(BUILD_FILE);
+ buildRule.configureProject(BUILD_FILE);
}
- public void testspawn() {
- project.executeTarget("setUp");
- if (project.getProperty("test.can.run") == null) {
- return;
- }
+ @Test
+ public void testspawn() throws InterruptedException {
+ buildRule.getProject().executeTarget("setUp");
+ Assume.assumeNotNull(buildRule.getProject().getProperty("test.can.run"));
myBuild = new MonitoredBuild(new File(System.getProperty("root"), BUILD_FILE), "spawn");
- logFile = FILE_UTILS.createTempFile("spawn", "log", getOutputDir(), false, false);
+ logFile = FILE_UTILS.createTempFile("spawn", "log", new File(buildRule.getProject().getProperty("output")),
+ false, false);
// this is guaranteed by FileUtils#createTempFile
assertTrue("log file not existing", !logFile.exists());
// make the spawned process run 4 seconds
@@ -69,11 +82,7 @@ public class ExecTaskTest extends BuildFileTest {
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");
- }
+ Thread.sleep(10);
GregorianCalendar now = new GregorianCalendar();
// security
if (now.getTime().getTime() - startwait.getTime().getTime() > MAX_BUILD_TIME) {
@@ -84,11 +93,7 @@ public class ExecTaskTest extends BuildFileTest {
}
}
// 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");
- }
+ Thread.sleep((TIME_TO_WAIT) * 1000 + SECURITY_MARGIN);
// time of the build in milli seconds
long elapsed = myBuild.getTimeElapsed();
assertTrue("we waited more than the process lasted",
@@ -97,29 +102,26 @@ public class ExecTaskTest extends BuildFileTest {
assertTrue("log file found after spawn", logFile.exists());
}
- /* TODO #50507 - fails at least on Linux
+ @Test
+ @Ignore("#50507 - fails at least on Linux")
+ /* TODO #50507 - fails at least on Linux */
public void testOutAndErr() {
- project.executeTarget("test-out-and-err");
+ buildRule.getProject().executeTarget("test-out-and-err");
}
- */
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));
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteJavaTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteJavaTest.java
index abc94ada1..069645b3f 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteJavaTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteJavaTest.java
@@ -23,14 +23,17 @@ import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Commandline;
-import junit.framework.TestCase;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
/**
* Simple testcase for the ExecuteJava class - mostly stolen from
* ExecuteWatchdogTest.
*
*/
-public class ExecuteJavaTest extends TestCase {
+public class ExecuteJavaTest {
private final static int TIME_OUT = 5000;
@@ -41,13 +44,10 @@ public class ExecuteJavaTest extends TestCase {
private Project project;
private Path cp;
- public ExecuteJavaTest(String name) {
- super(name);
- }
-
- protected void setUp(){
+ @Before
+ public void setUp(){
ej = new ExecuteJava();
- ej.setTimeout(new Long(TIME_OUT));
+ ej.setTimeout((long)TIME_OUT);
project = new Project();
project.setBasedir(".");
project.setProperty(MagicNames.ANT_HOME, System.getProperty(MagicNames.ANT_HOME));
@@ -62,6 +62,7 @@ public class ExecuteJavaTest extends TestCase {
return cmd;
}
+ @Test
public void testNoTimeOut() throws Exception {
Commandline cmd = getCommandline(TIME_OUT/2);
ej.setJavaCommand(cmd);
@@ -70,6 +71,7 @@ public class ExecuteJavaTest extends TestCase {
}
// test that the watchdog ends the process
+ @Test
public void testTimeOut() throws Exception {
Commandline cmd = getCommandline(TIME_OUT*2);
ej.setJavaCommand(cmd);
@@ -86,7 +88,7 @@ public class ExecuteJavaTest extends TestCase {
elapsed < TIME_OUT*2);
}
-
+ @Test
public void testNoTimeOutForked() throws Exception {
Commandline cmd = getCommandline(TIME_OUT/2);
ej.setJavaCommand(cmd);
@@ -95,6 +97,7 @@ public class ExecuteJavaTest extends TestCase {
}
// test that the watchdog ends the process
+ @Test
public void testTimeOutForked() throws Exception {
Commandline cmd = getCommandline(TIME_OUT*2);
ej.setJavaCommand(cmd);
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteWatchdogTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteWatchdogTest.java
index 92c4a104c..79f43b5c3 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteWatchdogTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ExecuteWatchdogTest.java
@@ -18,17 +18,25 @@
package org.apache.tools.ant.taskdefs;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+
import org.apache.tools.ant.util.JavaEnvUtils;
-import junit.framework.*;
-import java.io.*;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.internal.AssumptionViolatedException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/**
* Simple testcase for the ExecuteWatchdog class.
*
*/
-public class ExecuteWatchdogTest extends TestCase {
+public class ExecuteWatchdogTest {
- private final static long TIME_OUT = 5000;
+ private final static long TIME_OUT = 500;
private final static String TEST_CLASSPATH = getTestClassPath();
@@ -37,17 +45,14 @@ public class ExecuteWatchdogTest extends TestCase {
private ExecuteWatchdog watchdog;
- public ExecuteWatchdogTest(String name) {
- super(name);
- }
-
- protected void setUp(){
+ @Before
+ public 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.
+ * severely tied to the build.xml properties.
*/
private static String getTestClassPath(){
String classpath = System.getProperty("build.tests");
@@ -90,6 +95,7 @@ public class ExecuteWatchdogTest extends TestCase {
return retcode;
}
+ @Test
public void testNoTimeOut() throws Exception {
Process process = getProcess(TIME_OUT/2);
watchdog.start(process);
@@ -99,6 +105,7 @@ public class ExecuteWatchdogTest extends TestCase {
}
// test that the watchdog ends the process
+ @Test
public void testTimeOut() throws Exception {
Process process = getProcess(TIME_OUT*2);
long now = System.currentTimeMillis();
@@ -112,6 +119,7 @@ public class ExecuteWatchdogTest extends TestCase {
}
// test a process that runs and failed
+ @Test
public void testFailed() throws Exception {
Process process = getProcess(-1); // process should abort
watchdog.start(process);
@@ -120,6 +128,7 @@ public class ExecuteWatchdogTest extends TestCase {
assertTrue("return code is invalid: " + retCode, retCode!=0);
}
+ @Test
public void testManualStop() throws Exception {
final Process process = getProcess(TIME_OUT*2);
watchdog.start(process);
@@ -131,7 +140,7 @@ public class ExecuteWatchdogTest extends TestCase {
process.waitFor();
} catch(InterruptedException e){
// not very nice but will do the job
- fail("process interrupted in thread");
+ throw new AssumptionViolatedException("process interrupted in thread", e);
}
}
};
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/FailTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/FailTest.java
index 5628fbb37..8883558d0 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/FailTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/FailTest.java
@@ -19,57 +19,79 @@
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class FailTest extends BuildFileTest {
+public class FailTest {
- public FailTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/fail.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/fail.xml");
}
+ @Test
public void test1() {
- expectBuildExceptionContaining("test1",
- "it is required to fail :-)",
- "No message");
+ try {
+ buildRule.executeTarget("test1");
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals("No message", ex.getMessage());
+ }
}
+ @Test
public void test2() {
- expectSpecificBuildException("test2",
- "it is required to fail :-)",
- "test2");
+ try {
+ buildRule.executeTarget("test2");
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals("test2", ex.getMessage());
+ }
}
+ @Test
public void testText() {
- expectSpecificBuildException("testText",
- "it is required to fail :-)",
- "testText");
+ try {
+ buildRule.executeTarget("testText");
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals("testText", ex.getMessage());
+ }
}
+ @Test
public void testIf() {
+ buildRule.executeTarget("testIf");
+ buildRule.getProject().setProperty("foo", "");
try {
- executeTarget("testIf");
- } catch (BuildException be) {
- fail("foo has not been defined, testIf must not fail");
+ buildRule.executeTarget("testIf");
+ fail("testIf must fail if foo has been set") ;
+ } catch (BuildException ex) {
+ //TODO assert result
}
- project.setProperty("foo", "");
- expectBuildException("testIf", "testIf must fail if foo has been set");
}
+ @Test
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");
+ buildRule.executeTarget("testUnless");
+ fail("testUnless must fail unless foo has been set") ;
+ } catch (BuildException ex) {
+ //TODO assert rules
}
+ buildRule.getProject().setProperty("foo", "");
+ buildRule.executeTarget("testUnless");
+
}
/**
@@ -77,51 +99,58 @@ public class FailTest extends BuildFileTest {
* that the autogenerated text contains information
* about which condition was not met
*/
+ @Test
public void testIfAndUnless() {
//neither
- executeTarget("testIfAndUnless");
- project.setProperty("if", "");
- expectBuildExceptionContaining("testIfAndUnless",
- "expect fail on defined(if)",
- "if=if and unless=unless");
- project.setProperty("unless", "");
+ buildRule.executeTarget("testIfAndUnless");
+ buildRule.getProject().setProperty("if", "");
+ try {
+ buildRule.executeTarget("testIfAndUnless");
+ fail("expect fail on defined(if)") ;
+ } catch (BuildException ex) {
+ assertEquals("if=if and unless=unless", ex.getMessage());
+ }
+ buildRule.getProject().setProperty("unless", "");
//this call should succeed as unless overrides if
- executeTarget("testIfAndUnless");
+ buildRule.executeTarget("testIfAndUnless");
}
/**
* see that the different combinations work, and
* that the autogenerated text contains information
* about which condition was not met
*/
+ @Test
public void testIfAndUnless2() {
- project.setProperty("unless", "");
- try {
- executeTarget("testIfAndUnless");
- } catch (BuildException be) {
- fail("defined(if) && !defined(unless); testIfAndUnless must not fail");
- }
+ buildRule.getProject().setProperty("unless", "");
+ buildRule.executeTarget("testIfAndUnless");
}
+ @Test
public void testNested1() {
- expectSpecificBuildException("testNested1",
- "it is required to fail :-)",
- "condition satisfied");
+ try {
+ buildRule.executeTarget("testNested1");
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals("condition satisfied", ex.getMessage());
+ }
}
+ @Test
public void testNested2() {
- try {
- executeTarget("testNested2");
- } catch (BuildException be) {
- fail("condition not satisfied; testNested2 must not fail");
- }
+ buildRule.executeTarget("testNested2");
}
+ @Test
public void testNested3() {
- expectSpecificBuildException("testNested3",
- "it is required to fail :-)",
- "testNested3");
+ try {
+ buildRule.executeTarget("testNested3");
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals("testNested3", ex.getMessage());
+ }
}
+ @Test
public void testNested4() {
String specificMessage = "Nested conditions "
+ "not permitted in conjunction with if/unless attributes";
@@ -131,23 +160,36 @@ public class FailTest extends BuildFileTest {
for (int i = 0; i < c.length; i++) {
target.setCharAt(target.length() - 1, c[i]);
- expectSpecificBuildException(target.toString(),
- "it is required to fail :-)", specificMessage);
+ try {
+ buildRule.executeTarget(target.toString());
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals(specificMessage, ex.getMessage());
+ }
}
}
+ @Test
public void testNested5() {
- expectSpecificBuildException("testNested5",
- "it is required to fail :-)",
- "Only one nested condition is allowed.");
+ try {
+ buildRule.executeTarget("testNested5");
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals("Only one nested condition is allowed.", ex.getMessage());
+ }
}
+ @Test
public void testNested6() {
- expectSpecificBuildException("testNested6",
- "it is required to fail :-)",
- "testNested6\ntestNested6\ntestNested6");
+ try {
+ buildRule.executeTarget("testNested6");
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals("testNested6\ntestNested6\ntestNested6", ex.getMessage());
+ }
}
+ @Test
public void testNested7() {
String specificMessage = "A single nested condition is required.";
@@ -156,8 +198,12 @@ public class FailTest extends BuildFileTest {
for (int i = 0; i < c.length; i++) {
target.setCharAt(target.length() - 1, c[i]);
- expectSpecificBuildException(target.toString(),
- "it is required to fail :-)", specificMessage);
+ try {
+ buildRule.executeTarget(target.toString());
+ fail("it is required to fail :-)") ;
+ } catch (BuildException ex) {
+ assertEquals(specificMessage, ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/FilterTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/FilterTest.java
index c4e9efbf4..fdbec6e84 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/FilterTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/FilterTest.java
@@ -23,67 +23,100 @@ 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 {
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
- public FilterTest(String name) {
- super(name);
- }
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+
+public class FilterTest {
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/filter.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/filter.xml");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument missing");
+ try {
+ buildRule.executeTarget("test2");
+ fail("required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument missing");
+ try {
+ buildRule.executeTarget("test3");
+ fail("required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test4() {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
assertEquals("2000",
getFilteredFile("5", "filtered.tmp"));
}
+ @Test
public void test6() {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
assertEquals("2000",
getFilteredFile("6", "taskdefs.tmp/filter1.txt"));
}
+ @Test
public void test7() {
- executeTarget("test7");
+ buildRule.executeTarget("test7");
assertEquals("<%@ include file=\"root/some/include.jsp\"%>",
getFilteredFile("7", "filtered.tmp"));
}
+ @Test
public void test8() {
- executeTarget("test8");
+ buildRule.executeTarget("test8");
assertEquals("<%@ include file=\"root/some/include.jsp\"%>",
getFilteredFile("8", "taskdefs.tmp/filter2.txt"));
}
+ @Test
public void test9() {
- executeTarget("test9");
+ buildRule.executeTarget("test9");
assertEquals("included",
getFilteredFile("9", "taskdefs.tmp/filter3.txt"));
}
@@ -91,7 +124,7 @@ public class FilterTest extends BuildFileTest {
private String getFilteredFile(String testNumber, String filteredFile) {
String line = null;
- File f = new File(getProjectDir(), filteredFile);
+ File f = new File(buildRule.getProject().getBaseDir(), filteredFile);
if (!f.exists()) {
fail("filter test"+testNumber+" failed");
} else {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/FixCrLfTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/FixCrLfTest.java
index b739b835b..06a18cc84 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/FixCrLfTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/FixCrLfTest.java
@@ -26,103 +26,136 @@ import java.io.InputStream;
import junit.framework.AssertionFailedError;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class FixCrLfTest extends BuildFileTest {
+public class FixCrLfTest {
- public FixCrLfTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/fixcrlf/build.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/fixcrlf/build.xml");
}
+ @Test
public void test1() throws IOException {
- executeTarget("test1");
+ buildRule.executeTarget("test1");
}
+ @Test
public void test2() throws IOException {
- executeTarget("test2");
+ buildRule.executeTarget("test2");
}
+ @Test
public void test3() throws IOException {
- executeTarget("test3");
+ buildRule.executeTarget("test3");
}
+ @Test
public void test4() throws IOException {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
}
+ @Test
public void test5() throws IOException {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
+ @Test
public void test6() throws IOException {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
}
+ @Test
public void test7() throws IOException {
- executeTarget("test7");
+ buildRule.executeTarget("test7");
}
+ @Test
public void test8() throws IOException {
- executeTarget("test8");
+ buildRule.executeTarget("test8");
}
+ @Test
public void test9() throws IOException {
- executeTarget("test9");
+ buildRule.executeTarget("test9");
}
+ @Test
public void testMacLines() throws IOException {
- executeTarget("testMacLines");
+ buildRule.executeTarget("testMacLines");
}
+ @Test
public void testNoOverwrite() throws IOException {
- executeTarget("testNoOverwrite");
+ buildRule.executeTarget("testNoOverwrite");
}
+ @Test
public void testEncoding() throws IOException {
- executeTarget("testEncoding");
+ buildRule.executeTarget("testEncoding");
}
+ @Test
public void testOutputEncoding() throws IOException {
- executeTarget("testOutputEncoding");
+ buildRule.executeTarget("testOutputEncoding");
}
+ @Test
public void testLongLines() throws IOException {
- executeTarget("testLongLines");
+ buildRule.executeTarget("testLongLines");
}
+ @Test
public void testCrCrLfSequenceUnix() throws IOException {
- executeTarget("testCrCrLfSequence-unix");
+ buildRule.executeTarget("testCrCrLfSequence-unix");
}
+ @Test
public void testCrCrLfSequenceDos() throws IOException {
- executeTarget("testCrCrLfSequence-dos");
+ buildRule.executeTarget("testCrCrLfSequence-dos");
}
+ @Test
public void testCrCrLfSequenceMac() throws IOException {
- executeTarget("testCrCrLfSequence-mac");
+ buildRule.executeTarget("testCrCrLfSequence-mac");
}
+ @Test
public void testFixlastDos() throws IOException {
- executeTarget("testFixlastDos");
+ buildRule.executeTarget("testFixlastDos");
}
+ @Test
public void testFixlastFalseMac() throws IOException {
- executeTarget("testFixlastFalseMac");
+ buildRule.executeTarget("testFixlastFalseMac");
}
+ @Test
public void testFixFile() throws Exception {
- executeTarget("testFixFile");
+ buildRule.executeTarget("testFixFile");
}
+ @Test
public void testFixFileExclusive() throws Exception {
- expectBuildExceptionContaining("testFixFileExclusive",
- FixCRLF.ERROR_FILE_AND_SRCDIR, FixCRLF.ERROR_FILE_AND_SRCDIR);
+ try {
+ buildRule.executeTarget("testFixFileExclusive");
+ fail(FixCRLF.ERROR_FILE_AND_SRCDIR);
+ } catch (BuildException ex) {
+ AntAssert.assertContains(FixCRLF.ERROR_FILE_AND_SRCDIR, ex.getMessage());
+ }
}
/**
@@ -131,59 +164,73 @@ public class FixCrLfTest extends BuildFileTest {
* Will fail with an exception if the parent directories do not
* get created.
*/
+ @Test
public void testCreateParentDirs() {
- executeTarget("createParentDirs");
+ buildRule.executeTarget("createParentDirs");
}
+ @Test
public void testPreserveLastModified() {
- executeTarget("testPreserveLastModified");
+ buildRule.executeTarget("testPreserveLastModified");
}
+ @Test
public void testFilter1() {
- executeTarget("testFilter1");
+ buildRule.executeTarget("testFilter1");
}
+ @Test
public void testFilter2() {
- executeTarget("testFilter2");
+ buildRule.executeTarget("testFilter2");
}
+ @Test
public void testFilter3() {
- executeTarget("testFilter3");
+ buildRule.executeTarget("testFilter3");
}
+ @Test
public void testFilter4() {
- executeTarget("testFilter4");
+ buildRule.executeTarget("testFilter4");
}
+ @Test
public void testFilter5() {
- executeTarget("testFilter5");
+ buildRule.executeTarget("testFilter5");
}
+ @Test
public void testFilter6() {
- executeTarget("testFilter6");
+ buildRule.executeTarget("testFilter6");
}
+ @Test
public void testFilter7() {
- executeTarget("testFilter7");
+ buildRule.executeTarget("testFilter7");
}
+ @Test
public void testFilter8() {
- executeTarget("testFilter8");
+ buildRule.executeTarget("testFilter8");
}
+ @Test
public void testFilter9() {
- executeTarget("testFilter9");
+ buildRule.executeTarget("testFilter9");
}
+ @Test
public void testCannotDoubleEof() {
- executeTarget("testCannotDoubleEof");
+ buildRule.executeTarget("testCannotDoubleEof");
}
+ @Test
public void testTabInLiteralInComment() {
- executeTarget("testTabInLiteralInComment");
+ buildRule.executeTarget("testTabInLiteralInComment");
}
// not used, but public so theoretically must remain for BC?
+ @Deprecated
public void assertEqualContent(File expect, File result)
throws AssertionFailedError, IOException {
if (!result.exists()) {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/GUnzipTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/GUnzipTest.java
index 57a819666..fc731f75d 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/GUnzipTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/GUnzipTest.java
@@ -17,54 +17,74 @@
*/
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class GUnzipTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
- /** Utilities used for file operations */
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+public class GUnzipTest {
- public GUnzipTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/gunzip.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/gunzip.xml");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "attribute src invalid");
+ try {
+ buildRule.executeTarget("test2");
+ fail("attribute src invalid");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testRealTest() throws java.io.IOException {
testRealTest("realTest");
}
+ @Test
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")));
+ buildRule.executeTarget(target);
+ assertEquals(FileUtilities.getFileContents(buildRule.getProject().resolveFile("../asf-logo.gif")),
+ FileUtilities.getFileContents(buildRule.getProject().resolveFile("asf-logo.gif")));
}
+ @Test
public void testTestGzipTask() throws java.io.IOException {
testRealTest("testGzipTask");
}
+ @Test
public void testDocumentationClaimsOnCopy() throws java.io.IOException {
testRealTest("testDocumentationClaimsOnCopy");
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/GetTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/GetTest.java
index a81c29c96..3e1157d8b 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/GetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/GetTest.java
@@ -18,58 +18,105 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
*/
-public class GetTest extends BuildFileTest {
+public class GetTest {
- public GetTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/get.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/get.xml");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument missing");
+ try {
+ buildRule.executeTarget("test2");
+ fail("required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument missing");
+ try {
+ buildRule.executeTarget("test3");
+ fail("required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test4() {
- expectBuildException("test4", "src invalid");
+ try {
+ buildRule.executeTarget("test4");
+ fail("src invalid");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test5() {
- expectBuildException("test5", "dest invalid (or no http-server on local machine)");
+ try {
+ buildRule.executeTarget("test5");
+ fail("dest invalid (or no http-server on local machine");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test6() {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
}
+ @Test
public void test7() {
- expectBuildException("test7", "userAgent may not be null or empty");
+ try {
+ buildRule.executeTarget("test7");
+ fail("userAgent may not be null or empty");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testUseTimestamp() {
- executeTarget("testUseTimestamp");
+ buildRule.executeTarget("testUseTimestamp");
}
+ @Test
public void testUseTomorrow() {
- executeTarget("testUseTomorrow");
+ buildRule.executeTarget("testUseTomorrow");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/GzipTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/GzipTest.java
index c2426fa3f..00ea06383 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/GzipTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/GzipTest.java
@@ -18,59 +18,96 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
*/
-public class GzipTest extends BuildFileTest {
+public class GzipTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
- public GzipTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/gzip.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/gzip.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument missing");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument missing");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test4() {
- expectBuildException("test4", "zipfile must not point to a directory");
+ try {
+ buildRule.executeTarget("test4");
+ fail("BuildException expected: zipfile must not point to a directory");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testGZip(){
- executeTarget("realTest");
- String log = getLog();
+ buildRule.executeTarget("realTest");
+ String log = buildRule.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"));
}
+ @Test
public void testResource(){
- executeTarget("realTestWithResource");
+ buildRule.executeTarget("realTestWithResource");
}
+ @Test
public void testDateCheck(){
- executeTarget("testDateCheck");
- String log = getLog();
+ buildRule.executeTarget("testDateCheck");
+ String log = buildRule.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."));
}
+ @After
public void tearDown(){
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ImportTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ImportTest.java
index ad4d05bcf..e64d6f8c3 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ImportTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ImportTest.java
@@ -18,141 +18,141 @@
package org.apache.tools.ant.taskdefs;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
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.BuildFileRule;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
+import org.junit.Assume;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class ImportTest extends BuildFileTest {
-
- public ImportTest(String name) {
- super(name);
- }
-
- public void setUp() {
- }
-
- public void tearDown() {
- }
+public class ImportTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Test
public void testSimpleImport() {
- configureProject("src/etc/testcases/taskdefs/import/import.xml");
- assertLogContaining("Before importIn imported topAfter import");
+ buildRule.configureProject("src/etc/testcases/taskdefs/import/import.xml");
+ assertContains("Before importIn imported topAfter import", buildRule.getLog());
}
+ @Test
public void testUnnamedNesting() {
- configureProject("src/etc/testcases/taskdefs/import/unnamedImport.xml",
+ buildRule.configureProject("src/etc/testcases/taskdefs/import/unnamedImport.xml",
Project.MSG_WARN);
- String log = getLog();
+ String log = buildRule.getLog();
assertTrue("Warnings logged when not expected: " + log,
log.length() == 0);
}
+ @Test
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);
+ buildRule.configureProject("src/etc/testcases/taskdefs/import/subdir/serial.xml");
+ assertContains("Unnamed2.xmlUnnamed1.xml", buildRule.getLog());
+ assertContains("Expected string was not found in log",
+ "Skipped already imported file", buildRule.getFullLog());
}
// 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"));
+ @Test
+ public void testImportInTargetNoEffect() {
+ buildRule.configureProject("src/etc/testcases/taskdefs/import/subdir/importintarget.xml");
+ buildRule.executeTarget("no-import");
+ assertNull(buildRule.getProject().getProperty("foo"));
+ assertNull(buildRule.getProject().getReference("baz"));
}
- // deactivate this test as imports within targets are not allowed
+ @Ignore("deactivate this test as imports within targets are not allowed")
+ @Test
public void notTestImportInTargetWithEffect() {
- configureProject("src/etc/testcases/taskdefs/import/subdir/importintarget.xml");
- expectPropertySet("do-import", "foo", "bar");
- assertNotNull(getProject().getReference("baz"));
+ buildRule.configureProject("src/etc/testcases/taskdefs/import/subdir/importintarget.xml");
+ buildRule.executeTarget("do-import");
+ assertEquals(buildRule.getProject().getProperty("foo"), "bar");
+ assertNotNull(buildRule.getProject().getReference("baz"));
}
+ @Test
public void testImportInTargetNotAllowed() {
- configureProject(
+ buildRule.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");
+ try {
+ buildRule.executeTarget("do-import");
+ fail("Build exception should have been thrown as import only allowed in top level task");
+ } catch(BuildException ex) {
+ assertContains( "not a top level task", "import only allowed as a top-level task", ex.getMessage());
+ }
}
+ @Test
public void testImportInSequential() {
- configureProject(
+ buildRule.configureProject(
"src/etc/testcases/taskdefs/import/subdir/importinsequential.xml");
- expectPropertySet("within-imported", "foo", "bar");
- assertNotNull(getProject().getReference("baz"));
+ buildRule.executeTarget("within-imported");
+ assertEquals(buildRule.getProject().getProperty("foo"), "bar");
+ assertNotNull(buildRule.getProject().getReference("baz"));
}
+ @Test
public void testImportSameTargets() {
try {
- configureProject(
+ buildRule.configureProject(
"src/etc/testcases/taskdefs/import/same_target.xml");
+ fail("Expected build exception");
} catch (BuildException ex) {
- String message = ex.getMessage();
- if (message.indexOf("Duplicate target") == -1) {
- assertTrue("Did not see 'Duplicate target' in '" + message +"'", false);
- }
- return;
+ assertContains("Message did not contain expected contents", "Duplicate target", ex.getMessage());
}
- assertTrue(
- "Did not see build exception",
- false);
}
+ @Test
public void testImportError() {
try {
- configureProject(
+ buildRule.configureProject(
"src/etc/testcases/taskdefs/import/import_bad_import.xml");
+ fail("Build exception should have been thrown");
} 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;
+ assertNotNull(
+ "expected location of build exception to be set", lo);
+ assertContains(
+ "expected location to contain calling file", "import_bad_import.xml", lo.getFileName());
+ assertContains(
+ "expected message of ex to contain called file", "bad.xml", ex.getMessage());
}
- assertTrue(
- "Did not see build exception",
- false);
}
+ @Test
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;
- }
+ Assume.assumeTrue("Current system does not support Symlinks", new File(ln).exists());
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(
+ buildRule.configureProject(
"src/etc/testcases/taskdefs/import/symlinks/d1/p1.xml");
- assertPropertyEquals(
- "ant.file.p2",
+ assertEquals(
+ buildRule.getProject().getProperty("ant.file.p2"),
new File(System.getProperty("root"), "src/etc/testcases/taskdefs/import/symlinks/d2/p2.xml")
.getAbsolutePath());
- assertPropertyEquals(
- "ant.file.p3",
+ assertEquals(
+ buildRule.getProject().getProperty("ant.file.p3"),
new File(System.getProperty("root"), "src/etc/testcases/taskdefs/import/symlinks/d3b/p3.xml")
.getAbsolutePath());
} finally {
@@ -160,13 +160,15 @@ public class ImportTest extends BuildFileTest {
}
}
+ @Test
public void testTargetFirst() {
- configureProject("src/etc/testcases/taskdefs/import/importtargetfirst.xml");
- assertLogContaining("Importing targetfirstAfter target firstAfter importing");
+ buildRule.configureProject("src/etc/testcases/taskdefs/import/importtargetfirst.xml");
+ assertContains("Importing targetfirstAfter target firstAfter importing", buildRule.getLog());
}
+ @Test
public void testTargetName() {
- configureProject("src/etc/testcases/taskdefs/import/c.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/import/c.xml");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/InitializeClassTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/InitializeClassTest.java
index 0994e1723..a44303f92 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/InitializeClassTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/InitializeClassTest.java
@@ -22,41 +22,54 @@ 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;
+
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* Test to see if static initializers are invoked the same way
* when is invoked in forked and unforked modes.
*
*/
-public class InitializeClassTest extends BuildFileTest {
+public class InitializeClassTest {
- /** Utilities used for file operations */
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
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);
- }
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/initializeclass.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/initializeclass.xml");
}
+ @Test
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));
+ buildRule.executeTarget("forked");
+ synchronized (System.out) {
+ PrintStream ps = System.out;
+ PrintStream newps = new PrintStream(new FileOutputStream(f2));
+ try {
+ System.setOut(newps);
+ buildRule.getProject().executeTarget("unforked");
+ } finally {
+ System.setOut(ps);
+
+ newps.close();
+ }
+ }
+ assertEquals(FileUtilities.getFileContents(f1), FileUtilities.getFileContents(f2));
}
+ @After
public void tearDown() {
f1.delete();
f2.delete();
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/InputTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/InputTest.java
index ccf413e6b..4b6efaa14 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/InputTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/InputTest.java
@@ -19,88 +19,108 @@
package org.apache.tools.ant.taskdefs;
import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.input.PropertyFileInputHandler;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
-public class InputTest extends BuildFileTest {
- public InputTest(String name) {
- super(name);
- }
+public class InputTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ private InputStream originalStdIn;
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/input.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/input.xml");
System.getProperties()
.put(PropertyFileInputHandler.FILE_NAME_KEY,
- getProject().resolveFile("input.properties")
+ buildRule.getProject().resolveFile("input.properties")
.getAbsolutePath());
- getProject().setInputHandler(new PropertyFileInputHandler());
+ buildRule.getProject().setInputHandler(new PropertyFileInputHandler());
+ originalStdIn = System.in;
+ }
+
+ @After
+ public void tearDown() {
+ System.setIn(originalStdIn);
}
+ @Test
public void test1() {
- executeTarget("test1");
+ buildRule.executeTarget("test1");
}
+ @Test
public void test2() {
- executeTarget("test2");
+ buildRule.executeTarget("test2");
}
+ @Test
public void test3() {
- expectSpecificBuildException("test3", "invalid input",
- "Found invalid input test for \'"
- + getKey("All data is"
- + " going to be deleted from DB"
- + " continue?")
- + "\'");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: invalid input");
+ } catch (BuildException ex) {
+ assertEquals("Found invalid input test for 'All data is going to be deleted from DB continue?'",
+ ex.getMessage());
+ }
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
+ @Test
public void test6() {
- executeTarget("test6");
- assertEquals("scott", project.getProperty("db.user"));
+ buildRule.executeTarget("test6");
+ assertEquals("scott", buildRule.getProject().getProperty("db.user"));
}
+ @Test
public void testPropertyFileInlineHandler() {
- executeTarget("testPropertyFileInlineHandler");
+ buildRule.executeTarget("testPropertyFileInlineHandler");
}
- public void testDefaultInlineHandler() {
+ @Test
+ public void testDefaultInlineHandler() throws IOException {
stdin();
- executeTarget("testDefaultInlineHandler");
+ buildRule.executeTarget("testDefaultInlineHandler");
}
- public void testGreedyInlineHandler() {
+ @Test
+ public void testGreedyInlineHandler() throws IOException {
stdin();
- executeTarget("testGreedyInlineHandler");
+ buildRule.executeTarget("testGreedyInlineHandler");
}
- public void testGreedyInlineHandlerClassname() {
+ @Test
+ public void testGreedyInlineHandlerClassname() throws IOException {
stdin();
- executeTarget("testGreedyInlineHandlerClassname");
+ buildRule.executeTarget("testGreedyInlineHandlerClassname");
}
- public void testGreedyInlineHandlerRefid() {
+ @Test
+ public void testGreedyInlineHandlerRefid() throws IOException {
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());
- }
+ buildRule.executeTarget("testGreedyInlineHandlerRefid");
}
- private String getKey(String key) {
- return key; // TODO what is this for?
+ private void stdin() throws IOException {
+ System.setIn(new FileInputStream(buildRule.getProject().resolveFile("input.stdin")));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java
index 10c1738f2..9b8ff1553 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/JarTest.java
@@ -28,29 +28,42 @@ 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.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
*/
-public class JarTest extends BuildFileTest {
-
- /** Utilities used for file operations */
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+public class JarTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
private static String tempJar = "tmp.jar";
private static String tempDir = "jartmp/";
private Reader r1, r2;
- public JarTest(String name) {
- super(name);
- }
-
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/jar.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/jar.xml");
+ buildRule.executeTarget("setUp");
}
+ @After
public void tearDown() {
if (r1 != null) {
try {
@@ -64,152 +77,192 @@ public class JarTest extends BuildFileTest {
} catch (IOException e) {
}
}
- try {
- super.tearDown();
- } catch (Exception exc) {
-
- }
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "manifest file does not exist");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: manifest file does not exist");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "Unrecognized whenempty attribute: format C: /y");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: Unrecognized whenempty attribute: format C: /y");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ private File getOutputDir() {
+ return new File(buildRule.getProject().getProperty("output"));
+ }
+
+ @Test
public void test4() {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
File jarFile = new File(getOutputDir(), tempJar);
+
assertTrue(jarFile.exists());
}
+ @Test
public void testNoRecreateWithoutUpdate() {
testNoRecreate("test4");
}
+ @Test
public void testNoRecreateWithUpdate() {
testNoRecreate("testNoRecreateWithUpdate");
}
private void testNoRecreate(String secondTarget) {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
File jarFile = new File(getOutputDir(), tempJar);
+
+ // move the modified date back a couple of seconds rather than delay the test on each run
+ Assume.assumeTrue(jarFile.setLastModified(jarFile.lastModified()
+ - (FileUtils.getFileUtils().getFileTimestampGranularity() * 3)));
long jarModifiedDate = jarFile.lastModified();
- try {
- Thread.sleep(2500);
- } catch (InterruptedException e) {
- } // end of try-catch
- executeTarget(secondTarget);
+
+ buildRule.executeTarget(secondTarget);
assertEquals("jar has not been recreated in " + secondTarget,
jarModifiedDate, jarFile.lastModified());
}
+ @Test
public void testRecreateWithoutUpdateAdditionalFiles() {
testRecreate("test4", "testRecreateWithoutUpdateAdditionalFiles");
}
+ @Test
public void testRecreateWithUpdateAdditionalFiles() {
testRecreate("test4", "testRecreateWithUpdateAdditionalFiles");
}
+ @Test
public void testRecreateWithoutUpdateNewerFile() {
testRecreate("testRecreateNewerFileSetup",
"testRecreateWithoutUpdateNewerFile");
}
+ @Test
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
+ //Move the modified date on all input back a couple of seconds rather then delay the test to achieve a similar effect
+ FileUtilities.rollbackTimetamps(buildRule.getProject().getBaseDir(), 5);
+
+ buildRule.executeTarget(firstTarget);
File jarFile = new File(getOutputDir(), tempJar);
+
+ //Move the modified date back a couple of seconds rather then delay the test to achieve a similar effect
+ FileUtilities.rollbackTimetamps(buildRule.getOutputDir(), 5);
+
long jarModifiedDate = jarFile.lastModified();
- executeTarget(secondTarget);
+ buildRule.executeTarget(secondTarget);
jarFile = new File(getOutputDir(), tempJar);
assertTrue("jar has been recreated in " + secondTarget,
jarModifiedDate < jarFile.lastModified());
}
+ @Test
public void testManifestStaysIntact()
throws IOException, ManifestException {
- executeTarget("testManifestStaysIntact");
+ buildRule.executeTarget("testManifestStaysIntact");
r1 = new FileReader(new File(getOutputDir(),
tempDir + "manifest"));
r2 = new FileReader(new File(getOutputDir(),
tempDir + "META-INF/MANIFEST.MF"));
+
Manifest mf1 = new Manifest(r1);
Manifest mf2 = new Manifest(r2);
assertEquals(mf1, mf2);
}
+ @Test
public void testNoRecreateBasedirExcludesWithUpdate() {
testNoRecreate("testNoRecreateBasedirExcludesWithUpdate");
}
+ @Test
public void testNoRecreateBasedirExcludesWithoutUpdate() {
testNoRecreate("testNoRecreateBasedirExcludesWithoutUpdate");
}
+ @Test
public void testNoRecreateZipfilesetExcludesWithUpdate() {
testNoRecreate("testNoRecreateZipfilesetExcludesWithUpdate");
}
+ @Test
public void testNoRecreateZipfilesetExcludesWithoutUpdate() {
testNoRecreate("testNoRecreateZipfilesetExcludesWithoutUpdate");
}
+ @Test
public void testRecreateZipfilesetWithoutUpdateAdditionalFiles() {
testRecreate("test4",
"testRecreateZipfilesetWithoutUpdateAdditionalFiles");
}
+ @Test
public void testRecreateZipfilesetWithUpdateAdditionalFiles() {
testRecreate("test4",
"testRecreateZipfilesetWithUpdateAdditionalFiles");
}
+ @Test
public void testRecreateZipfilesetWithoutUpdateNewerFile() {
testRecreate("testRecreateNewerFileSetup",
"testRecreateZipfilesetWithoutUpdateNewerFile");
}
+ @Test
public void testRecreateZipfilesetWithUpdateNewerFile() {
testRecreate("testRecreateNewerFileSetup",
"testRecreateZipfilesetWithUpdateNewerFile");
}
+ @Test
public void testCreateWithEmptyFileset() {
- executeTarget("testCreateWithEmptyFilesetSetUp");
- executeTarget("testCreateWithEmptyFileset");
- executeTarget("testCreateWithEmptyFileset");
+ buildRule.executeTarget("testCreateWithEmptyFilesetSetUp");
+ buildRule.executeTarget("testCreateWithEmptyFileset");
+ buildRule.executeTarget("testCreateWithEmptyFileset");
}
+ @Test
public void testUpdateIfOnlyManifestHasChanged() {
- executeTarget("testUpdateIfOnlyManifestHasChanged");
+ buildRule.executeTarget("testUpdateIfOnlyManifestHasChanged");
File jarXml = new File(getOutputDir(), tempDir + "jar.xml");
assertTrue(jarXml.exists());
}
// bugzilla report 10262
+ @Test
public void testNoDuplicateIndex() throws IOException {
ZipFile archive = null;
try {
- executeTarget("testIndexTests");
+ buildRule.executeTarget("testIndexTests");
archive = new ZipFile(new File(getOutputDir(), tempJar));
Enumeration e = archive.entries();
int numberOfIndexLists = 0;
@@ -228,10 +281,11 @@ public class JarTest extends BuildFileTest {
}
// bugzilla report 16972
+ @Test
public void testRootFilesInIndex() throws IOException {
ZipFile archive = null;
try {
- executeTarget("testIndexTests");
+ buildRule.executeTarget("testIndexTests");
archive = new ZipFile(new File(getOutputDir(), tempJar));
ZipEntry ze = archive.getEntry("META-INF/INDEX.LIST");
InputStream is = archive.getInputStream(ze);
@@ -262,46 +316,60 @@ public class JarTest extends BuildFileTest {
}
}
}
+ @Test
public void testManifestOnlyJar() {
- expectLogContaining("testManifestOnlyJar", "Building MANIFEST-only jar: ");
+
+ buildRule.executeTarget("testManifestOnlyJar");
+ assertContains("Building MANIFEST-only jar: ", buildRule.getLog());
File manifestFile = new File(getOutputDir(), tempDir + "META-INF" + File.separator + "MANIFEST.MF");
assertTrue(manifestFile.exists());
}
+ @Test
public void testIndexJarsPlusJarMarker() {
- executeTarget("testIndexJarsPlusJarMarker");
+ buildRule.executeTarget("testIndexJarsPlusJarMarker");
}
+ @Test
public void testNoVersionInfoFail() {
- expectBuildExceptionContaining("testNoVersionInfoFail", "Manifest Implemention information missing.", "No Implementation-Title set.");
+ try {
+ buildRule.executeTarget("testNoVersionInfoFail");
+ fail("BuildException expected: Manifest Implemention information missing.");
+ } catch (BuildException ex) {
+ assertContains("No Implementation-Title set.", ex.getMessage());
+ }
}
+ @Test
public void testNoVersionInfoIgnore() {
- executeTarget("testNoVersionInfoIgnore");
- assertTrue( getFullLog().indexOf("No Implementation-Title set.") > -1 );
- assertTrue( getFullLog().indexOf("No Implementation-Version set.") > -1 );
- assertTrue( getFullLog().indexOf("No Implementation-Vendor set.") > -1 );
+ buildRule.executeTarget("testNoVersionInfoIgnore");
+ assertTrue(buildRule.getFullLog().indexOf("No Implementation-Title set.") > -1 );
+ assertTrue(buildRule.getFullLog().indexOf("No Implementation-Version set.") > -1 );
+ assertTrue(buildRule.getFullLog().indexOf("No Implementation-Vendor set.") > -1 );
}
+ @Test
public void testNoVersionInfoWarn() {
- executeTarget("testNoVersionInfoWarn");
- assertTrue( getLog().indexOf("No Implementation-Title set.") > -1 );
- assertTrue( getLog().indexOf("No Implementation-Version set.") > -1 );
- assertTrue( getLog().indexOf("No Implementation-Vendor set.") > -1 );
+ buildRule.executeTarget("testNoVersionInfoWarn");
+ assertTrue(buildRule.getLog().indexOf("No Implementation-Title set.") > -1 );
+ assertTrue(buildRule.getLog().indexOf("No Implementation-Version set.") > -1 );
+ assertTrue(buildRule.getLog().indexOf("No Implementation-Vendor set.") > -1 );
}
+ @Test
public void testNoVersionInfoNoStrict() {
- executeTarget("testNoVersionInfoNoStrict");
- assertFalse( getLog().indexOf("No Implementation-Title set.") > -1 );
- assertFalse( getLog().indexOf("No Implementation-Version set.") > -1 );
- assertFalse( getLog().indexOf("No Implementation-Vendor set.") > -1 );
+ buildRule.executeTarget("testNoVersionInfoNoStrict");
+ assertFalse(buildRule.getLog().indexOf("No Implementation-Title set.") > -1 );
+ assertFalse(buildRule.getLog().indexOf("No Implementation-Version set.") > -1 );
+ assertFalse(buildRule.getLog().indexOf("No Implementation-Vendor set.") > -1 );
}
+ @Test
public void testHasVersionInfo() {
- executeTarget("testHasVersionInfo");
- assertFalse( getLog().indexOf("No Implementation-Title set.") > -1 );
- assertFalse( getLog().indexOf("No Implementation-Version set.") > -1 );
- assertFalse( getLog().indexOf("No Implementation-Vendor set.") > -1 );
+ buildRule.executeTarget("testHasVersionInfo");
+ assertFalse(buildRule.getLog().indexOf("No Implementation-Title set.") > -1 );
+ assertFalse(buildRule.getLog().indexOf("No Implementation-Version set.") > -1 );
+ assertFalse(buildRule.getLog().indexOf("No Implementation-Vendor set.") > -1 );
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/JavaTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/JavaTest.java
index 76669468f..d54b8f28e 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/JavaTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/JavaTest.java
@@ -29,15 +29,29 @@ import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.input.DefaultInputHandler;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.TeeOutputStream;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.internal.AssumptionViolatedException;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* stress out java task
* */
-public class JavaTest extends BuildFileTest {
+public class JavaTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
private static final int TIME_TO_WAIT = 1;
// wait 1 second extra to allow for java to start ...
@@ -49,18 +63,16 @@ public class JavaTest extends BuildFileTest {
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
*/
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/java.xml");
- project.executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/java.xml");
+ buildRule.executeTarget("setUp");
//final String propname="tests-classpath.value";
//String testClasspath=System.getProperty(propname);
@@ -70,32 +82,49 @@ public class JavaTest extends BuildFileTest {
runFatalTests=true;
}
+ @Test
public void testNoJarNoClassname(){
- expectBuildExceptionContaining("testNoJarNoClassname",
- "parameter validation",
- "Classname must not be null.");
+ try {
+ buildRule.executeTarget("testNoJarNoClassname");
+ fail("Build exception should have been thrown - parameter validation");
+ } catch (BuildException ex) {
+ assertContains("Classname must not be null.", ex.getMessage());
+ }
}
+ @Test
public void testJarNoFork() {
- expectBuildExceptionContaining("testJarNoFork",
- "parameter validation",
- "Cannot execute a jar in non-forked mode. "
- + "Please set fork='true'. ");
+ try {
+ buildRule.executeTarget("testJarNoFork");
+ fail("Build exception should have been thrown - parameter validation");
+ } catch (BuildException ex) {
+ assertContains("Cannot execute a jar in non-forked mode. Please set fork='true'. ", ex.getMessage());
+ }
}
+ @Test
public void testJarAndClassName() {
- expectBuildException("testJarAndClassName",
- "Should not be able to set both classname AND jar");
+ try {
+ buildRule.executeTarget("testJarAndClassName");
+ fail("Build exception should have been thrown - both classname and JAR are not allowed");
+ } catch (BuildException ex) {
+ assertEquals("Cannot use 'jar' and 'classname' attributes in same command", ex.getMessage());
+ }
}
-
+ @Test
public void testClassnameAndJar() {
- expectBuildException("testClassnameAndJar",
- "Should not be able to set both classname AND jar");
+ try {
+ buildRule.executeTarget("testClassnameAndJar");
+ fail("Build exception should have been thrown - both classname and JAR are not allowed");
+ } catch (BuildException ex) {
+ assertEquals("Cannot use 'jar' and 'classname' attributes in same command.", ex.getMessage());
+ }
}
+ @Test
public void testRun() {
- executeTarget("testRun");
+ buildRule.executeTarget("testRun");
}
@@ -103,90 +132,117 @@ public class JavaTest extends BuildFileTest {
/** this test fails but we ignore the return value;
* we verify that failure only matters when failonerror is set
*/
+ @Test
public void testRunFail() {
- if(runFatalTests) {
- executeTarget("testRunFail");
- }
+ Assume.assumeTrue("Fatal tests have not been set to run", runFatalTests);
+ buildRule.executeTarget("testRunFail");
}
+ @Test
public void testRunFailFoe() {
- if(runFatalTests) {
- expectBuildExceptionContaining("testRunFailFoe",
- "java failures being propagated",
- "Java returned:");
+ Assume.assumeTrue("Fatal tests have not been set to run", runFatalTests);
+ try {
+ buildRule.executeTarget("testRunFailFoe");
+ fail("Build exception should have been thrown - " + "java failures being propagated");
+ } catch (BuildException ex) {
+ assertContains("Java returned:", ex.getMessage());
}
-}
+ }
+ @Test
public void testRunFailFoeFork() {
- expectBuildExceptionContaining("testRunFailFoeFork",
- "java failures being propagated",
- "Java returned:");
+ try {
+ buildRule.executeTarget("testRunFailFoeFork");
+ fail("Build exception should have been thrown - " + "java failures being propagated");
+ } catch (BuildException ex) {
+ assertContains("Java returned:", ex.getMessage());
+ }
}
+ @Test
public void testExcepting() {
- expectLogContaining("testExcepting",
- "Exception raised inside called program");
+ buildRule.executeTarget("testExcepting");
+ assertContains("Exception raised inside called program", buildRule.getLog());
}
+ @Test
public void testExceptingFork() {
- expectLogContaining("testExceptingFork",
- "Java Result:");
+ buildRule.executeTarget("testExceptingFork");
+ assertContains("Java Result:", buildRule.getLog());
}
+ @Test
public void testExceptingFoe() {
- expectBuildExceptionContaining("testExceptingFoe",
- "passes exception through",
- "Exception raised inside called program");
+ try {
+ buildRule.executeTarget("testExceptingFoe");
+ fail("Build exception should have been thrown - " + "passes exception through");
+ } catch (BuildException ex) {
+ assertContains("Exception raised inside called program", ex.getMessage());
+ }
}
+ @Test
public void testExceptingFoeFork() {
- expectBuildExceptionContaining("testExceptingFoeFork",
- "exceptions turned into error codes",
- "Java returned:");
+ try {
+ buildRule.executeTarget("testExceptingFoeFork");
+ fail("Build exception should have been thrown - " + "exceptions turned into error codes");
+ } catch (BuildException ex) {
+ assertContains("Java returned:", ex.getMessage());
+ }
}
+ @Test
public void testResultPropertyZero() {
- executeTarget("testResultPropertyZero");
- assertEquals("0",project.getProperty("exitcode"));
+ buildRule.executeTarget("testResultPropertyZero");
+ assertEquals("0", buildRule.getProject().getProperty("exitcode"));
}
+ @Test
public void testResultPropertyNonZero() {
- executeTarget("testResultPropertyNonZero");
- assertEquals("2",project.getProperty("exitcode"));
+ buildRule.executeTarget("testResultPropertyNonZero");
+ assertEquals("2", buildRule.getProject().getProperty("exitcode"));
}
+ @Test
public void testResultPropertyZeroNoFork() {
- executeTarget("testResultPropertyZeroNoFork");
- assertEquals("0",project.getProperty("exitcode"));
+ buildRule.executeTarget("testResultPropertyZeroNoFork");
+ assertEquals("0", buildRule.getProject().getProperty("exitcode"));
}
+ @Test
public void testResultPropertyNonZeroNoFork() {
- executeTarget("testResultPropertyNonZeroNoFork");
- assertEquals("-1",project.getProperty("exitcode"));
+ buildRule.executeTarget("testResultPropertyNonZeroNoFork");
+ assertEquals("-1", buildRule.getProject().getProperty("exitcode"));
}
+ @Test
public void testRunFailWithFailOnError() {
- expectBuildExceptionContaining("testRunFailWithFailOnError",
- "non zero return code",
- "Java returned:");
+ try {
+ buildRule.executeTarget("testRunFailWithFailOnError");
+ fail("Build exception should have been thrown - " + "non zero return code");
+ } catch (BuildException ex) {
+ assertContains("Java returned:", ex.getMessage());
+ }
}
+ @Test
public void testRunSuccessWithFailOnError() {
- executeTarget("testRunSuccessWithFailOnError");
+ buildRule.executeTarget("testRunSuccessWithFailOnError");
}
- public void testSpawn() {
- File logFile = FILE_UTILS.createTempFile("spawn","log", getOutputDir(), false, false);
+ @Test
+ public void testSpawn() throws InterruptedException {
+ File logFile = FILE_UTILS.createTempFile("spawn", "log",
+ new File(buildRule.getProject().getProperty("output")), false, false);
// 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");
- }
+ buildRule.getProject().setProperty("logFile", logFile.getAbsolutePath());
+ buildRule.getProject().setProperty("timeToWait", Long.toString(TIME_TO_WAIT));
+ buildRule.getProject().executeTarget("testSpawn");
+
+ Thread.sleep(TIME_TO_WAIT * 1000 + SECURITY_MARGIN);
+
+
// let's be nice with the next generation of developers
if (!logFile.exists()) {
System.out.println("suggestion: increase the constant"
@@ -195,38 +251,44 @@ public class JavaTest extends BuildFileTest {
assertTrue("log file exists", logFile.exists());
}
+ @Test
public void testRedirect1() {
- executeTarget("redirect1");
+ buildRule.executeTarget("redirect1");
}
+ @Test
public void testRedirect2() {
- executeTarget("redirect2");
+ buildRule.executeTarget("redirect2");
}
+ @Test
public void testRedirect3() {
- executeTarget("redirect3");
+ buildRule.executeTarget("redirect3");
}
+ @Test
public void testRedirector1() {
- executeTarget("redirector1");
+ buildRule.executeTarget("redirector1");
}
+ @Test
public void testRedirector2() {
- executeTarget("redirector2");
+ buildRule.executeTarget("redirector2");
}
+ @Test
public void testReleasedInput() throws Exception {
PipedOutputStream out = new PipedOutputStream();
final PipedInputStream in = new PipedInputStream(out);
- project.setInputHandler(new DefaultInputHandler() {
+ buildRule.getProject().setInputHandler(new DefaultInputHandler() {
protected InputStream getInputStream() {
return in;
}
});
- project.setDefaultInputStream(in);
+ buildRule.getProject().setDefaultInputStream(in);
Java java = new Java();
- java.setProject(project);
+ java.setProject(buildRule.getProject());
java.setClassname("org.apache.tools.ant.Main");
java.setArgs("-version");
java.setFork(true);
@@ -237,7 +299,7 @@ public class JavaTest extends BuildFileTest {
Thread inputThread = new Thread(new Runnable() {
public void run() {
Input input = new Input();
- input.setProject(project);
+ input.setProject(buildRule.getProject());
input.setAddproperty("input.value");
input.execute();
}
@@ -259,18 +321,19 @@ public class JavaTest extends BuildFileTest {
inputThread.join(2000);
- assertEquals("foo", project.getProperty("input.value"));
+ assertEquals("foo", buildRule.getProject().getProperty("input.value"));
}
+ @Test
public void testFlushedInput() throws Exception {
final PipedOutputStream out = new PipedOutputStream();
final PipedInputStream in = new PipedInputStream(out);
- project.setInputHandler(new DefaultInputHandler() {
+ buildRule.getProject().setInputHandler(new DefaultInputHandler() {
protected InputStream getInputStream() {
return in;
}
});
- project.setDefaultInputStream(in);
+ buildRule.getProject().setDefaultInputStream(in);
final boolean[] timeout = new boolean[1];
timeout[0] = false;
@@ -281,7 +344,7 @@ public class JavaTest extends BuildFileTest {
// wait a little bit to have the target executed
Thread.sleep(500);
} catch (InterruptedException e) {
- // don't care
+ throw new AssumptionViolatedException("Thread interrupted", e);
}
try {
out.write("foo-FlushedInput\n".getBytes());
@@ -293,7 +356,7 @@ public class JavaTest extends BuildFileTest {
writingThread.setDaemon(true);
writingThread.start();
- executeTarget("flushedInput");
+ buildRule.executeTarget("flushedInput");
}
/**
@@ -348,7 +411,7 @@ public class JavaTest extends BuildFileTest {
* test class for spawn
*/
public static class SpawnEntryPoint {
- public static void main(String [] argv) {
+ public static void main(String [] argv) throws InterruptedException {
int sleepTime = 10;
String logFile = "spawn.log";
if (argv.length >= 1) {
@@ -359,11 +422,7 @@ public class JavaTest extends BuildFileTest {
logFile = argv[1];
}
OutputStreamWriter out = null;
- try {
- Thread.sleep(sleepTime * 1000);
- } catch (InterruptedException ex) {
- System.out.println("my sleep was interrupted");
- }
+ Thread.sleep(sleepTime * 1000);
try {
File dest = new File(logFile);
@@ -386,7 +445,7 @@ public class JavaTest extends BuildFileTest {
/**
* pipe input to specified output
*/
- public static void main(String[] args) {
+ public static void main(String[] args) throws InterruptedException {
OutputStream os = null;
if (args.length > 0) {
if ("out".equalsIgnoreCase(args[0])) {
@@ -401,10 +460,7 @@ public class JavaTest extends BuildFileTest {
Thread t = new Thread(new StreamPumper(System.in, os, true));
t.setName("PipeEntryPoint " + args[0]);
t.start();
- try {
- t.join();
- } catch (InterruptedException eyeEx) {
- }
+ t.join();
}
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/JavacTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/JavacTest.java
index 8e0697c2e..12ceea286 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/JavacTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/JavacTest.java
@@ -18,35 +18,31 @@
package org.apache.tools.ant.taskdefs;
-import java.io.File;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-
-import junit.framework.TestCase;
-
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.Javac13;
import org.apache.tools.ant.taskdefs.compilers.JavacExternal;
-import org.apache.tools.ant.types.Path;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
/**
* Testcase for .
*
*/
-public class JavacTest extends TestCase {
+public class JavacTest {
private Project project;
private Javac javac;
- public JavacTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
project = new Project();
project.init();
@@ -57,6 +53,7 @@ public class JavacTest extends TestCase {
/**
* Test setting the name of the javac executable.
*/
+ @Test
public void testForkedExecutableName() {
assertNull("no fork means no executable", javac.getJavacExecutable());
@@ -65,14 +62,13 @@ public class JavacTest extends TestCase {
javac.setFork(true);
assertNotNull("normal fork", javac.getJavacExecutable());
- assertTrue("name should contain \"javac\"",
- javac.getJavacExecutable().indexOf("javac") > -1);
+ assertContains("name should contain \"javac\"", "javac",
+ javac.getJavacExecutable());
project.setProperty("build.compiler", "extJavac");
javac.setFork(false);
assertNotNull("fork via property", javac.getJavacExecutable());
- assertTrue("name should contain \"javac\"",
- javac.getJavacExecutable().indexOf("javac") > -1);
+ assertContains("name should contain \"javac\"", "javac", javac.getJavacExecutable());
project.setProperty("build.compiler", "whatever");
assertNull("no fork and not extJavac means no executable",
@@ -87,6 +83,7 @@ public class JavacTest extends TestCase {
/**
* Test nested compiler args.
*/
+ @Test
public void testCompilerArg() {
String[] args = javac.getCurrentCompilerArgs();
assertNotNull(args);
@@ -129,6 +126,7 @@ public class JavacTest extends TestCase {
* Test nested compiler args in the fork="true" and
* implementation="extJavac" case.
*/
+ @Test
public void testCompilerArgForForkAndExtJavac() {
Javac.ImplementationSpecificArgument arg = javac.createCompilerArg();
String ford = "Ford";
@@ -145,6 +143,7 @@ public class JavacTest extends TestCase {
/**
* Test compiler attribute.
*/
+ @Test
public void testCompilerAttribute() {
// check defaults
String compiler = javac.getCompiler();
@@ -194,6 +193,7 @@ public class JavacTest extends TestCase {
assertEquals("jvc", compiler);
}
+ @Test
public void testCompilerAdapter() {
javac.setCompiler("javac1.4");
@@ -209,30 +209,36 @@ public class JavacTest extends TestCase {
assertTrue(adapter instanceof JavacExternal);
}
+ @Test
public void testSourceNoDefault() {
assertNull(javac.getSource());
}
+ @Test
public void testSourceWithDefault() {
project.setNewProperty("ant.build.javac.source", "1.4");
assertEquals("1.4", javac.getSource());
}
+ @Test
public void testSourceOverridesDefault() {
project.setNewProperty("ant.build.javac.source", "1.4");
javac.setSource("1.5");
assertEquals("1.5", javac.getSource());
}
+ @Test
public void testTargetNoDefault() {
assertNull(javac.getTarget());
}
+ @Test
public void testTargetWithDefault() {
project.setNewProperty("ant.build.javac.target", "1.4");
assertEquals("1.4", javac.getTarget());
}
+ @Test
public void testTargetOverridesDefault() {
project.setNewProperty("ant.build.javac.target", "1.4");
javac.setTarget("1.5");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/JavadocTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/JavadocTest.java
index e23386035..f7a287d51 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/JavadocTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/JavadocTest.java
@@ -18,122 +18,115 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class JavadocTest extends BuildFileTest {
+public class JavadocTest {
- public JavadocTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
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);
+ @Before
+ public void setUp() {
+ buildRule.configureProject(BUILD_FILE);
}
// PR 38370
- public void testDirsetPath() throws Exception {
- executeTarget("dirsetPath");
+ @Test
+ public void testDirsetPath() {
+ buildRule.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);
- }
+ @Test
+ public void testDirsetPathWithoutPackagenames() {
+ buildRule.executeTarget("dirsetPathWithoutPackagenames");
}
// PR 38370
- public void testNestedDirsetPath() throws Exception {
- executeTarget("nestedDirsetPath");
+ @Test
+ public void testNestedDirsetPath() {
+ buildRule.executeTarget("nestedDirsetPath");
}
// PR 38370
- public void testFilesetPath() throws Exception {
- try {
- executeTarget("filesetPath");
- } catch (BuildException e) {
- fail("A path can contain filesets: " + e);
- }
+ @Test
+ public void testFilesetPath() {
+ buildRule.executeTarget("filesetPath");
}
// PR 38370
- public void testNestedFilesetPath() throws Exception {
- try {
- executeTarget("nestedFilesetPath");
- } catch (BuildException e) {
- fail("A path can contain nested filesets: " + e);
- }
+ @Test
+ public void testNestedFilesetPath() {
+ buildRule.executeTarget("nestedFilesetPath");
}
// PR 38370
- public void testFilelistPath() throws Exception {
- try {
- executeTarget("filelistPath");
- } catch (BuildException e) {
- fail("A path can contain filelists: " + e);
- }
+ @Test
+ public void testFilelistPath() {
+ buildRule.executeTarget("filelistPath");
}
// PR 38370
- public void testNestedFilelistPath() throws Exception {
- try {
- executeTarget("nestedFilelistPath");
- } catch (BuildException e) {
- fail("A path can contain nested filelists: " + e);
- }
+ @Test
+ public void testNestedFilelistPath() {
+ buildRule.executeTarget("nestedFilelistPath");
}
// PR 38370
- public void testPathelementPath() throws Exception {
- executeTarget("pathelementPath");
+ @Test
+ public void testPathelementPath() {
+ buildRule.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);
- }
+ @Test
+ public void testPathelementLocationPath() {
+ buildRule.executeTarget("pathelementLocationPath");
}
// PR 38370
- public void testNestedSource() throws Exception {
- executeTarget("nestedSource");
+ @Test
+ public void testNestedSource() {
+ buildRule.executeTarget("nestedSource");
}
// PR 38370
- public void testNestedFilesetRef() throws Exception {
- executeTarget("nestedFilesetRef");
+ @Test
+ public void testNestedFilesetRef() {
+ buildRule.executeTarget("nestedFilesetRef");
}
// PR 38370
- public void testNestedFilesetRefInPath() throws Exception {
- executeTarget("nestedFilesetRefInPath");
+ @Test
+ public void testNestedFilesetRefInPath() {
+ buildRule.executeTarget("nestedFilesetRefInPath");
}
- public void testNestedFilesetNoPatterns() throws Exception {
- executeTarget("nestedFilesetNoPatterns");
+ @Test
+ public void testNestedFilesetNoPatterns() {
+ buildRule.executeTarget("nestedFilesetNoPatterns");
}
- public void testDoublyNestedFileset() throws Exception {
- executeTarget("doublyNestedFileset");
+ @Test
+ public void testDoublyNestedFileset() {
+ buildRule.executeTarget("doublyNestedFileset");
}
- public void testDoublyNestedFilesetNoPatterns() throws Exception {
- executeTarget("doublyNestedFilesetNoPatterns");
+ @Test
+ public void testDoublyNestedFilesetNoPatterns() {
+ buildRule.executeTarget("doublyNestedFilesetNoPatterns");
}
- public void testNonJavaIncludes() throws Exception { // #41264
- executeTarget("nonJavaIncludes");
+ @Test
+ public void testNonJavaIncludes() { // #41264
+ buildRule.executeTarget("nonJavaIncludes");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java
index 479a6c364..fd8c32813 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/LoadFileTest.java
@@ -18,83 +18,99 @@
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
/**
* 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);
- }
+public class LoadFileTest {
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/loadfile.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/loadfile.xml");
}
- /**
- * The teardown method for JUnit
- */
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
/**
* A unit test for JUnit
*/
+ @Test
public void testNoSourcefileDefined() {
- expectBuildException("testNoSourcefileDefined",
- "source file not defined");
+ try {
+ buildRule.executeTarget("testNoSourcefileDefined");
+ fail("BuildException expected: source file not defined");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
/**
* A unit test for JUnit
*/
+ @Test
public void testNoPropertyDefined() {
- expectBuildException("testNoPropertyDefined",
- "output property not defined");
+ try {
+ buildRule.executeTarget("testNoPropertyDefined");
+ fail("BuildException expected: output property not defined");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
/**
* A unit test for JUnit
*/
+ @Test
public void testNoSourcefilefound() {
- expectBuildExceptionContaining("testNoSourcefilefound",
- "File not found", " doesn't exist");
+ try {
+ buildRule.executeTarget("testNoSourcefilefound");
+ fail("BuildException expected: File not found");
+ } catch (BuildException ex) {
+ assertContains(" doesn't exist", ex.getMessage());
+ }
}
/**
* A unit test for JUnit
*/
+ @Test
public void testFailOnError()
throws BuildException {
- expectPropertyUnset("testFailOnError","testFailOnError");
+ buildRule.executeTarget("testFailOnError");
+ assertNull(buildRule.getProject().getProperty("testFailOnError"));
}
/**
* A unit test for JUnit
*/
+ @Test
public void testLoadAFile()
throws BuildException {
- executeTarget("testLoadAFile");
- if(project.getProperty("testLoadAFile").indexOf("eh?")<0) {
+ buildRule.executeTarget("testLoadAFile");
+ if(buildRule.getProject().getProperty("testLoadAFile").indexOf("eh?")<0) {
fail("property is not all in the file");
}
}
@@ -103,21 +119,21 @@ public class LoadFileTest extends BuildFileTest {
/**
* A unit test for JUnit
*/
+ @Test
public void testLoadAFileEnc()
throws BuildException {
- executeTarget("testLoadAFileEnc");
- if(project.getProperty("testLoadAFileEnc")==null) {
- fail("file load failed");
- }
+ buildRule.executeTarget("testLoadAFileEnc");
+ assertNotNull("file load files", buildRule.getProject().getProperty("testLoadAFileEnc"));
}
/**
* A unit test for JUnit
*/
+ @Test
public void testEvalProps()
throws BuildException {
- executeTarget("testEvalProps");
- if(project.getProperty("testEvalProps").indexOf("rain")<0) {
+ buildRule.executeTarget("testEvalProps");
+ if(buildRule.getProject().getProperty("testEvalProps").indexOf("rain")<0) {
fail("property eval broken");
}
}
@@ -125,10 +141,11 @@ public class LoadFileTest extends BuildFileTest {
/**
* Test FilterChain and FilterReaders
*/
+ @Test
public void testFilterChain()
throws BuildException {
- executeTarget("testFilterChain");
- if(project.getProperty("testFilterChain").indexOf("World!")<0) {
+ buildRule.executeTarget("testFilterChain");
+ if(buildRule.getProject().getProperty("testFilterChain").indexOf("World!")<0) {
fail("Filter Chain broken");
}
}
@@ -136,20 +153,18 @@ public class LoadFileTest extends BuildFileTest {
/**
* Test StripJavaComments filterreader functionality.
*/
+ @Test
public final void testStripJavaComments()
throws BuildException {
- executeTarget("testStripJavaComments");
- final String expected = project.getProperty("expected");
- final String generated = project.getProperty("testStripJavaComments");
+ buildRule.executeTarget("testStripJavaComments");
+ final String expected = buildRule.getProject().getProperty("expected");
+ final String generated = buildRule.getProject().getProperty("testStripJavaComments");
assertEquals(expected, generated);
}
- /**
- * A unit test for JUnit
- */
- public void testOneLine()
- throws BuildException {
- expectPropertySet("testOneLine","testOneLine","1,2,3,4");
-
+ @Test
+ public void testOneLine() {
+ buildRule.executeTarget("testOneLine");
+ assertEquals("1,2,3,4", buildRule.getProject().getProperty("testOneLine"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java
index d24096c40..18b9786b5 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/MacroDefTest.java
@@ -19,124 +19,167 @@
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class MacroDefTest extends BuildFileTest {
- public MacroDefTest(String name) {
- super(name);
- }
+public class MacroDefTest {
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/macrodef.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/macrodef.xml");
}
+ @Test
public void testSimple() {
- expectLog("simple", "Hello World");
+ buildRule.executeTarget("simple");
+ assertEquals("Hello World", buildRule.getLog());
}
+ @Test
public void testText() {
- expectLog("text", "Inner Text");
+ buildRule.executeTarget("text");
+ assertEquals("Inner Text", buildRule.getLog());
}
+ @Test
public void testDuplicateAttribute() {
- expectBuildException(
- "duplicate.attribute",
- "the attribute text has already been specified");
+ try {
+ buildRule.executeTarget("duplicate.attribute");
+ fail("BuildException expected: the attribute text has already been specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testDuplicateElement() {
- expectBuildException(
- "duplicate.element",
- "the element text has already been specified");
+ try {
+ buildRule.executeTarget("duplicate.element");
+ fail("BuildException expected: the element text has already been specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testUri() {
- expectLog("uri", "Hello World");
+ buildRule.executeTarget("uri");
+ assertEquals("Hello World", buildRule.getLog());
}
+ @Test
public void testNested() {
- expectLog("nested", "A nested element");
+ buildRule.executeTarget("nested");
+ assertEquals("A nested element", buildRule.getLog());
}
+ @Test
public void testDouble() {
- expectLog(
- "double",
- "@{prop} is 'property', value of ${property} is 'A property value'");
+ buildRule.executeTarget("double");
+ assertEquals("@{prop} is 'property', value of ${property} is 'A property value'", buildRule.getLog());
}
+ @Test
public void testIgnoreCase() {
- expectLog(
- "ignorecase",
- "a is ab is b");
+ buildRule.executeTarget("ignorecase");
+ assertEquals("a is ab is b", buildRule.getLog());
}
+ @Test
public void testIgnoreElementCase() {
- expectLog(
- "ignore-element-case",
- "nested elementnested element");
+ buildRule.executeTarget("ignore-element-case");
+ assertEquals("nested elementnested element", buildRule.getLog());
}
+ @Test
public void testTextElement() {
- expectLogContaining(
- "textelement", "Hello world");
+ buildRule.executeTarget("textelement");
+ assertContains("Hello world", buildRule.getLog());
}
+ @Test
public void testTextTrim() {
- expectLogContaining(
- "text.trim", "[Hello world]");
+ buildRule.executeTarget("text.trim");
+ assertContains("[Hello world]", buildRule.getLog());
}
+ @Test
public void testDuplicateTextName() {
- expectBuildException(
- "duplicatetextname",
- "the name \"text\" is already used as an attribute");
+ try {
+ buildRule.executeTarget("duplicatetextname");
+ fail("BuildException expected: the name \"text\" is already used as an attribute");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testDuplicateTextName2() {
- expectBuildException(
- "duplicatetextname2",
- "the attribute name \"text\" has already been used by the text element");
+ try {
+ buildRule.executeTarget("duplicatetextname2");
+ fail("BuildException expected: the attribute name \"text\" has already been used by the text element");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testEscape() {
- expectLog(
- "escape",
- "a@b or a@b is avalue@bvalue");
+ buildRule.executeTarget("escape");
+ assertEquals("a@b or a@b is avalue@bvalue", buildRule.getLog());
}
+ @Test
public void testAttributeDescription() {
- expectLog(
- "attribute.description",
- "description is hello world");
+ buildRule.executeTarget("attribute.description");
+ assertEquals("description is hello world", buildRule.getLog());
}
+ @Test
public void testOverrideDefault() {
- expectLog(
- "override.default",
- "value is new");
+ buildRule.executeTarget("override.default");
+ assertEquals("value is new", buildRule.getLog());
}
+ @Test
public void testImplicit() {
- expectLog(
- "implicit", "Before implicitIn implicitAfter implicit");
+ buildRule.executeTarget("implicit");
+ assertEquals("Before implicitIn implicitAfter implicit", buildRule.getLog());
}
+ @Test
public void testImplicitNotOptional() {
- expectSpecificBuildException(
- "implicit.notoptional",
- "Missing nested elements for implicit element implicit",
- "Missing nested elements for implicit element implicit");
+ try {
+ buildRule.executeTarget("implicit.notoptional");
+ fail("BuildException expected: Missing nested elements for implicit element implicit");
+ } catch (BuildException ex) {
+ assertEquals("Missing nested elements for implicit element implicit", ex.getMessage());
+ }
}
+ @Test
public void testImplicitOptional() {
- expectLog(
- "implicit.optional", "Before implicitAfter implicit");
+ buildRule.executeTarget("implicit.optional");
+ assertEquals("Before implicitAfter implicit", buildRule.getLog());
}
+ @Test
public void testImplicitExplicit() {
- expectSpecificBuildException(
- "implicit.explicit",
- "Only one element allowed when using implicit elements",
- "Only one element allowed when using implicit elements");
+ try {
+ buildRule.executeTarget("implicit.explicit");
+ fail("BuildException expected: Only one element allowed when using implicit elements");
+ } catch (BuildException ex) {
+ assertEquals("Only one element allowed when using implicit elements", ex.getMessage());
+ }
}
+ @Test
public void testBackTraceOff() {
try {
- executeTarget("backtraceoff");
+ buildRule.executeTarget("backtraceoff");
} catch (BuildException ex) {
if (ex.getMessage().indexOf("following error occurred") != -1) {
fail("error message contained backtrace - " + ex.getMessage());
@@ -144,15 +187,20 @@ public class MacroDefTest extends BuildFileTest {
}
}
+ @Test
public void testBackTrace() {
- expectBuildExceptionContaining(
- "backtraceon",
- "Checking if a back trace is created",
- "following error occurred");
+ try {
+ buildRule.executeTarget("backtraceon");
+ fail("BuildException expected: Checking if a back trace is created");
+ } catch (BuildException ex) {
+ assertContains("following error occurred", ex.getMessage());
+ }
}
+ @Test
public void testTopLevelText() {
- expectLogContaining("top-level-text", "Hello World");
+ buildRule.executeTarget("top-level-text");
+ assertContains("Hello World", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java
index 01c6115f4..8c2762a7f 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/MakeUrlTest.java
@@ -17,47 +17,82 @@
*/
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
-public class MakeUrlTest extends BuildFileTest {
- public MakeUrlTest(String s) {
- super(s);
- }
+public class MakeUrlTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/makeurl.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/makeurl.xml");
}
+ @Test
public void testEmpty() {
- expectBuildExceptionContaining("testEmpty", "missing property", "property");
+ try {
+ buildRule.executeTarget("testEmpty");
+ fail("BuildException expected: missing property");
+ } catch (BuildException ex) {
+ assertContains("property", ex.getMessage());
+ }
}
+ @Test
public void testNoProperty() {
- expectBuildExceptionContaining("testNoProperty", "missing property", "property");
+ try {
+ buildRule.executeTarget("testNoProperty");
+ fail("BuildException expected: missing property");
+ } catch (BuildException ex) {
+ assertContains("property", ex.getMessage());
+ }
}
+ @Test
public void testNoFile() {
- expectBuildExceptionContaining("testNoFile", "missing file", "file");
+ try {
+ buildRule.executeTarget("testNoFile");
+ fail("BuildException expected: missing file");
+ } catch (BuildException ex) {
+ assertContains("file", ex.getMessage());
+ }
}
+ @Test
public void testValidation() {
- expectBuildExceptionContaining("testValidation", MakeUrl.ERROR_MISSING_FILE, "file");
+ try {
+ buildRule.executeTarget("testValidation");
+ fail("BuildException expected: " + MakeUrl.ERROR_MISSING_FILE);
+ } catch (BuildException ex) {
+ assertContains("file", ex.getMessage());
+ }
}
+ @Test
public void testWorks() {
- executeTarget("testWorks");
+ buildRule.executeTarget("testWorks");
assertPropertyContains("testWorks", "file:");
assertPropertyContains("testWorks", "/foo");
}
+ @Test
public void testIllegalChars() {
- executeTarget("testIllegalChars");
+ buildRule.executeTarget("testIllegalChars");
assertPropertyContains("testIllegalChars", "file:");
assertPropertyContains("testIllegalChars", "fo%20o%25");
}
@@ -67,8 +102,9 @@ public class MakeUrlTest extends BuildFileTest {
*
* @throws IOException
*/
+ @Test
public void testRoundTrip() throws IOException {
- executeTarget("testRoundTrip");
+ buildRule.executeTarget("testRoundTrip");
assertPropertyContains("testRoundTrip", "file:");
String property = getProperty("testRoundTrip");
URL url = new URL(property);
@@ -76,26 +112,30 @@ public class MakeUrlTest extends BuildFileTest {
instream.close();
}
+ @Test
public void testIllegalCombinations() {
- executeTarget("testIllegalCombinations");
+ buildRule.executeTarget("testIllegalCombinations");
assertPropertyContains("testIllegalCombinations", "/foo");
assertPropertyContains("testIllegalCombinations", ".xml");
}
+ @Test
public void testFileset() {
- executeTarget("testFileset");
+ buildRule.executeTarget("testFileset");
assertPropertyContains("testFileset", ".xml ");
assertPropertyEndsWith("testFileset", ".xml");
}
+ @Test
public void testFilesetSeparator() {
- executeTarget("testFilesetSeparator");
+ buildRule.executeTarget("testFilesetSeparator");
assertPropertyContains("testFilesetSeparator", ".xml\",\"");
assertPropertyEndsWith("testFilesetSeparator", ".xml");
}
+ @Test
public void testPath() {
- executeTarget("testPath");
+ buildRule.executeTarget("testPath");
assertPropertyContains("testPath", "makeurl.xml");
}
@@ -131,6 +171,6 @@ public class MakeUrlTest extends BuildFileTest {
* @return
*/
protected String getProperty(String property) {
- return project.getProperty(property);
+ return buildRule.getProject().getProperty(property);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestClassPathTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestClassPathTest.java
index a2fd119b8..95d4f3de3 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestClassPathTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestClassPathTest.java
@@ -18,57 +18,96 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.taskdefs.condition.Os;
-import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.taskdefs.condition.Os;
+import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
/**
* Tests <bm:manifestclasspath>.
*/
-public class ManifestClassPathTest
- extends BuildFileTest {
+public class ManifestClassPathTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/manifestclasspath.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/manifestclasspath.xml");
}
+ @Test
public void testBadDirectory() {
- expectBuildExceptionContaining("test-bad-directory", "bad-jar-dir",
- "Jar's directory not found:");
- assertPropertyUnset("jar.classpath");
+ try {
+ buildRule.executeTarget("test-bad-directory");
+ fail("Build exception should have been thrown on bad directory");
+ } catch (BuildException ex) {
+ assertContains("Jar's directory not found:", ex.getMessage());
+ }
+ assertNull(buildRule.getProject().getProperty("jar.classpath"));
}
+ @Test
public void testBadNoProperty() {
- expectBuildExceptionContaining("test-bad-no-property", "no-property",
- "Missing 'property' attribute!");
- assertPropertyUnset("jar.classpath");
+ try {
+ buildRule.executeTarget("test-bad-no-property");
+ fail("Build exception should have been thrown on no property");
+ } catch (BuildException ex) {
+ assertContains("Missing 'property' attribute!", ex.getMessage());
+ }
+ assertNull(buildRule.getProject().getProperty("jar.classpath"));
}
+ @Test
public void testBadPropertyExists() {
- expectBuildExceptionContaining("test-bad-property-exists",
- "property-exits", "Property 'jar.classpath' already set!");
- assertPropertyEquals("jar.classpath", "exists");
+ try {
+ buildRule.executeTarget("test-bad-property-exists");
+ fail("Build exception should have been thrown on bad property");
+ } catch (BuildException ex) {
+ assertContains("Property 'jar.classpath' already set!", ex.getMessage());
+ }
+ assertEquals(buildRule.getProject().getProperty("jar.classpath"), "exists");
}
+ @Test
public void testBadNoJarfile() {
- expectBuildExceptionContaining("test-bad-no-jarfile", "no-jarfile",
- "Missing 'jarfile' attribute!");
- assertPropertyUnset("jar.classpath");
+ try {
+ buildRule.executeTarget("test-bad-no-jarfile");
+ fail("Build exception should have been thrown on bad jar file");
+ } catch (BuildException ex) {
+ assertContains("Missing 'jarfile' attribute!", ex.getMessage());
+ }
+ assertNull(buildRule.getProject().getProperty("jar.classpath"));
}
+ @Test
public void testBadNoClassPath() {
- expectBuildExceptionContaining("test-bad-no-classpath", "no-classpath",
- "Missing nested !");
- assertPropertyUnset("jar.classpath");
+ try {
+ buildRule.executeTarget("test-bad-no-classpath");
+ fail("Build exception should have been thrown on no classpath");
+ } catch (BuildException ex) {
+ assertContains("Missing nested !", ex.getMessage());
+ }
+ assertNull(buildRule.getProject().getProperty("jar.classpath"));
}
+ @Test
public void testParentLevel1() {
- executeTarget("test-parent-level1");
+ buildRule.executeTarget("test-parent-level1");
- assertPropertyEquals("jar.classpath", "dsp-core/ " +
+ assertEquals(buildRule.getProject().getProperty("jar.classpath"), "dsp-core/ " +
"dsp-pres/ " +
"dsp-void/ " +
"../generated/dsp-core/ " +
@@ -79,10 +118,11 @@ public class ManifestClassPathTest
"../resources/dsp-void/");
}
+ @Test
public void testParentLevel2() {
- executeTarget("test-parent-level2");
+ buildRule.executeTarget("test-parent-level2");
- assertPropertyEquals("jar.classpath", "../dsp-core/ " +
+ assertEquals(buildRule.getProject().getProperty("jar.classpath"), "../dsp-core/ " +
"../dsp-pres/ " +
"../dsp-void/ " +
"../../generated/dsp-core/ " +
@@ -93,19 +133,23 @@ public class ManifestClassPathTest
"../../resources/dsp-void/");
}
+ @Test
public void testParentLevel2TooDeep() {
- expectBuildExceptionContaining("test-parent-level2-too-deep", "nopath",
- "No suitable relative path from ");
- assertPropertyUnset("jar.classpath");
+ try {
+ buildRule.executeTarget("test-parent-level2-too-deep");
+ fail("Build exception should have been thrown on no suitable path");
+ } catch (BuildException ex) {
+ assertContains("No suitable relative path from ", ex.getMessage());
+ }
+ assertNull(buildRule.getProject().getProperty("jar.classpath"));
}
+ @Test
public void testPseudoTahoeRefid() {
- if (!RegexpMatcherFactory.regexpMatcherPresent(project)) {
- System.out.println("Test 'testPseudoTahoeRefid' skipped because no regexp matcher is present.");
- return;
- }
- executeTarget("test-pseudo-tahoe-refid");
- assertPropertyEquals("jar.classpath", "classes/dsp-core/ " +
+ Assume.assumeTrue("No regexp matcher is present", RegexpMatcherFactory.regexpMatcherPresent(buildRule.getProject()));
+
+ buildRule.executeTarget("test-pseudo-tahoe-refid");
+ assertEquals(buildRule.getProject().getProperty("jar.classpath"), "classes/dsp-core/ " +
"classes/dsp-pres/ " +
"classes/dsp-void/ " +
"generated/dsp-core/ " +
@@ -113,13 +157,12 @@ public class ManifestClassPathTest
"resources/dsp-pres/");
}
+ @Test
public void testPseudoTahoeNested() {
- if (!RegexpMatcherFactory.regexpMatcherPresent(project)) {
- System.out.println("Test 'testPseudoTahoeNested' skipped because no regexp matcher is present.");
- return;
- }
- executeTarget("test-pseudo-tahoe-nested");
- assertPropertyEquals("jar.classpath", "classes/dsp-core/ " +
+ Assume.assumeTrue("No regexp matcher is present", RegexpMatcherFactory.regexpMatcherPresent(buildRule.getProject()));
+
+ buildRule.executeTarget("test-pseudo-tahoe-nested");
+ assertEquals(buildRule.getProject().getProperty("jar.classpath"), "classes/dsp-core/ " +
"classes/dsp-pres/ " +
"classes/dsp-void/ " +
"generated/dsp-core/ " +
@@ -127,10 +170,11 @@ public class ManifestClassPathTest
"resources/dsp-pres/");
}
+ @Test
public void testParentLevel2WithJars() {
- executeTarget("test-parent-level2-with-jars");
+ buildRule.executeTarget("test-parent-level2-with-jars");
- assertPropertyEquals("jar.classpath", "../../lib/acme-core.jar " +
+ assertEquals(buildRule.getProject().getProperty("jar.classpath"), "../../lib/acme-core.jar " +
"../../lib/acme-pres.jar " +
"../dsp-core/ " +
"../dsp-pres/ " +
@@ -142,64 +186,64 @@ public class ManifestClassPathTest
"../../resources/dsp-pres/ " +
"../../resources/dsp-void/");
}
+
+ @Test
public void testInternationalGerman() {
- executeTarget("international-german");
- expectLogContaining("run-two-jars", "beta alpha");
+ buildRule.executeTarget("international-german");
+ buildRule.executeTarget("run-two-jars");
+ assertContains("beta alpha", buildRule.getLog());
}
+
+ @Test
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");
- }
-
+ Assume.assumeFalse("Test with hebrew path not attempted under Windows", Os.isFamily("windows"));
+ buildRule.executeTarget("international-hebrew");
+ buildRule.executeTarget("run-two-jars");
+ assertContains("beta alpha", buildRule.getLog());
}
+ @Test
public void testSameWindowsDrive() {
- if (!Os.isFamily("windows")) {
- System.out.println("Test with drive letters only run on windows");
- } else {
- executeTarget("testSameDrive");
- assertPropertyEquals("cp", "../a/b/x.jar");
- }
+ Assume.assumeTrue("Test with drive letters only run on windows", Os.isFamily("windows"));
+ buildRule.executeTarget("testSameDrive");
+ assertEquals(buildRule.getProject().getProperty("cp"), "../a/b/x.jar");
}
+ @Test
public void testDifferentWindowsDrive() {
- if (!Os.isFamily("windows")) {
- System.out.println("Test with drive letters only run on windows");
- } else {
- // the lines below try to find a drive name different than the one containing the temp dir
- // if the temp dir is C will try to use D
- // if the temp dir is on D or other will try to use C
- File tmpdir = new File(System.getProperty("java.io.tmpdir"));
- String driveLetter = "C";
- try {
- String tmpCanonicalPath = tmpdir.getCanonicalPath();
- driveLetter = tmpCanonicalPath.substring(1).toUpperCase();
- } catch (IOException ioe) {
- System.out.println("exception happened getting canonical path of java.io.tmpdir : " + ioe.getMessage());
- }
- String altDriveLetter = null;
- try {
- if ("C".equals(driveLetter)) {
- altDriveLetter = "D";
- } else {
- altDriveLetter = "C";
- }
- new java.io.File(altDriveLetter + ":/foo.txt").getCanonicalPath();
- } catch (java.io.IOException e) {
- System.out.println("drive " + altDriveLetter + ": doesn't exist or is not ready,"
- + " skipping test");
- return;
+ Assume.assumeTrue("Test with drive letters only run on windows", Os.isFamily("windows"));
+ // the lines below try to find a drive name different than the one containing the temp dir
+ // if the temp dir is C will try to use D
+ // if the temp dir is on D or other will try to use C
+ File tmpdir = new File(System.getProperty("java.io.tmpdir"));
+ String driveLetter = "C";
+ try {
+ String tmpCanonicalPath = tmpdir.getCanonicalPath();
+ driveLetter = tmpCanonicalPath.substring(0, 1).toUpperCase();
+ } catch (IOException ioe) {
+ System.out.println("exception happened getting canonical path of java.io.tmpdir : " + ioe.getMessage());
+ }
+ String altDriveLetter = null;
+ try {
+ if ("C".equals(driveLetter)) {
+ altDriveLetter = "D";
+ } else {
+ altDriveLetter = "C";
}
- project.setProperty("altDriveLetter", altDriveLetter);
- expectBuildExceptionContaining("testDifferentDrive",
- "different drive",
- "No suitable relative path from ");
- assertPropertyUnset("cp");
+ new java.io.File(altDriveLetter + ":/foo.txt").getCanonicalPath();
+ } catch (java.io.IOException e) {
+ Assume.assumeNoException("Drive " + altDriveLetter + ": doesn't exist or is not ready", e);
}
+ buildRule.getProject().setProperty("altDriveLetter", altDriveLetter);
+
+ try {
+ buildRule.executeTarget("testDifferentDrive");
+ fail("Build exception should have been thrown on no alternative drive");
+ } catch (BuildException ex) {
+ assertContains("No suitable relative path from ", ex.getMessage());
+ }
+
+ assertNull(buildRule.getProject().getProperty("cp"));
}
} // END class ManifestClassPathTest
-
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java
index a785c01bd..72bce1ba8 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ManifestTest.java
@@ -26,14 +26,28 @@ import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Testcase for the Manifest class used in the jar task.
*
*/
-public class ManifestTest extends BuildFileTest {
+public class ManifestTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
public static final String EXPANDED_MANIFEST
= "src/etc/testcases/taskdefs/manifests/META-INF/MANIFEST.MF";
@@ -53,23 +67,23 @@ public class ManifestTest extends BuildFileTest {
public static final String VALUE = "NOT_LONG";
- public ManifestTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/manifest.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/manifest.xml");
}
+ @After
public void tearDown() {
- executeTarget("clean");
+ buildRule.executeTarget("clean");
}
/**
* Empty manifest - is OK
*/
+ @Test
public void test1() throws ManifestException, IOException {
- executeTarget("test1");
+ buildRule.executeTarget("test1");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
String version = manifest.getManifestVersion();
assertEquals("Manifest was not created with correct version - ", "1.0", version);
@@ -78,8 +92,9 @@ public class ManifestTest extends BuildFileTest {
/**
* Simple Manifest with version 2.0
*/
+ @Test
public void test2() throws ManifestException, IOException {
- executeTarget("test2");
+ buildRule.executeTarget("test2");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
String version = manifest.getManifestVersion();
assertEquals("Manifest was not created with correct version - ", "2.0", version);
@@ -88,25 +103,36 @@ public class ManifestTest extends BuildFileTest {
/**
* Malformed manifest - no : on the line
*/
+ @Test
public void test3() {
- expectBuildExceptionContaining("test3", "Manifest is invalid - no colon on header line",
- "Invalid Manifest");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: Manifest is invalid - no colon on header line");
+ } catch (BuildException ex) {
+ assertContains("Invalid Manifest", ex.getMessage());
+ }
}
/**
* Malformed manifest - starts with continuation line
*/
+ @Test
public void test4() {
- expectBuildExceptionContaining("test4", "Manifest is invalid - section starts with continuation line",
- "Invalid Manifest");
+ try {
+ buildRule.executeTarget("test4");
+ fail("BuildException expected: Manifest is invalid - section starts with continuation line");
+ } catch (BuildException ex) {
+ assertContains("Invalid Manifest", ex.getMessage());
+ }
}
/**
* Malformed manifest - Name attribute in main section
*/
+ @Test
public void test5() {
- executeTarget("test5");
- String output = getLog();
+ buildRule.executeTarget("test5");
+ String output = buildRule.getLog();
boolean hasWarning = output.indexOf("Manifest warning: \"Name\" attributes should not occur in the main section") != -1;
assertTrue("Expected warning about Name in main section", hasWarning);
}
@@ -114,29 +140,37 @@ public class ManifestTest extends BuildFileTest {
/**
* New Section not starting with Name attribute.
*/
+ @Test
public void test6() {
- expectBuildExceptionContaining("test6", "Manifest is invalid - section starts with incorrect attribute",
- "Invalid Manifest");
- String output = getLog();
+ try {
+ buildRule.executeTarget("test6");
+ fail("BuildException expected: Manifest is invalid - section starts with incorrect attribute");
+ } catch (BuildException ex) {
+ assertContains("Invalid Manifest", ex.getMessage());
+ }
+ String output = buildRule.getLog();
boolean hasWarning = output.indexOf("Manifest sections should start with a \"Name\" attribute") != -1;
assertTrue("Expected warning about section not starting with Name: attribute", hasWarning);
}
+
/**
* From attribute is illegal
*/
+ @Test
public void test7() {
- executeTarget("test7");
+ buildRule.executeTarget("test7");
- boolean hasWarning = getLog().indexOf(Manifest.ERROR_FROM_FORBIDDEN) != -1;
+ boolean hasWarning = buildRule.getLog().indexOf(Manifest.ERROR_FROM_FORBIDDEN) != -1;
assertTrue("Expected warning about From: attribute", hasWarning);
}
/**
* Inline manifest - OK
*/
+ @Test
public void test8() throws IOException, ManifestException {
- executeTarget("test8");
+ buildRule.executeTarget("test8");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
Manifest.Section mainSection = manifest.getMainSection();
String classpath = mainSection.getAttributeValue("class-path");
@@ -150,48 +184,75 @@ public class ManifestTest extends BuildFileTest {
/**
* Inline manifest - Invalid since has a Name attribute in the section element
*/
+ @Test
public void test9() {
- expectBuildExceptionContaining("test9", "Construction is invalid - Name attribute should not be used",
- "Specify the section name using the \"name\" attribute of the element");
+ try {
+ buildRule.executeTarget("test9");
+ fail("BuildException expected: Construction is invalid - Name attribute should not be used");
+ } catch (BuildException ex) {
+ assertContains("Specify the section name using the \"name\" attribute of the element",
+ ex.getMessage());
+ }
}
/**
* Inline manifest - Invalid attribute without name
*/
+ @Test
public void test10() {
- expectBuildExceptionContaining("test10", "Attribute has no name",
- "Attributes must have name and value");
+ try {
+ buildRule.executeTarget("test10");
+ fail("BuildException expected: Attribute has no name");
+ } catch (BuildException ex) {
+ assertContains("Attributes must have name and value", ex.getMessage());
+ }
}
/**
* Inline manifest - Invalid attribute without value
*/
+ @Test
public void test11() {
- expectBuildExceptionContaining("test11", "Attribute has no value",
- "Attributes must have name and value");
+ try {
+ buildRule.executeTarget("test11");
+ fail("BuildException expected: Attribute has no value");
+ } catch (BuildException ex) {
+ assertContains("Attributes must have name and value", ex.getMessage());
+ }
}
/**
* Inline manifest - Invalid attribute without value
*/
+ @Test
public void test12() {
- expectBuildExceptionContaining("test12", "Section with no name",
- "Sections must have a name");
+ try {
+ buildRule.executeTarget("test12");
+ fail("BuildException expected: Section with no name");
+ } catch (BuildException ex) {
+ assertContains("Sections must have a name", ex.getMessage());
+ }
}
/**
* Inline manifest - Duplicate attribute
*/
+ @Test
public void test13() {
- expectBuildExceptionContaining("test13", "Duplicate Attribute",
- "The attribute \"Test\" may not occur more than once in the same section");
+ try {
+ buildRule.executeTarget("test13");
+ fail("BuildException expected: Duplicate Attribute");
+ } catch (BuildException ex) {
+ assertContains("The attribute \"Test\" may not occur more than once in the same section", ex.getMessage());
+ }
}
/**
* Inline manifest - OK since classpath entries can be duplicated.
*/
+ @Test
public void test14() throws IOException, ManifestException {
- executeTarget("test14");
+ buildRule.executeTarget("test14");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
Manifest.Section mainSection = manifest.getMainSection();
String classpath = mainSection.getAttributeValue("class-path");
@@ -202,14 +263,15 @@ public class ManifestTest extends BuildFileTest {
/**
* Tets long line wrapping
*/
+ @Test
public void testLongLine() throws IOException, ManifestException {
- Project p = getProject();
+ Project p = buildRule.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");
+ buildRule.executeTarget("testLongLine");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
Manifest.Section mainSection = manifest.getMainSection();
@@ -247,8 +309,9 @@ public class ManifestTest extends BuildFileTest {
/**
* Tests ordering of sections
*/
+ @Test
public void testOrder1() throws IOException, ManifestException {
- executeTarget("testOrder1");
+ buildRule.executeTarget("testOrder1");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
Enumeration e = manifest.getSectionNames();
@@ -270,8 +333,9 @@ public class ManifestTest extends BuildFileTest {
/**
* Tests ordering of sections
*/
+ @Test
public void testOrder2() throws IOException, ManifestException {
- executeTarget("testOrder2");
+ buildRule.executeTarget("testOrder2");
Manifest manifest = getManifest(EXPANDED_MANIFEST);
Enumeration e = manifest.getSectionNames();
@@ -293,15 +357,22 @@ public class ManifestTest extends BuildFileTest {
/**
* file attribute for manifest task is required.
*/
+ @Test
public void testNoFile() {
- expectBuildException("testNoFile", "file is required");
+ try {
+ buildRule.executeTarget("testNoFile");
+ fail("BuildException expected: file is required");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
/**
* replace changes Manifest-Version from 2.0 to 1.0
*/
+ @Test
public void testReplace() throws IOException, ManifestException {
- executeTarget("testReplace");
+ buildRule.executeTarget("testReplace");
Manifest mf = getManifest("src/etc/testcases/taskdefs/mftest.mf");
assertNotNull(mf);
assertEquals(Manifest.getDefaultManifest(), mf);
@@ -310,8 +381,9 @@ public class ManifestTest extends BuildFileTest {
/**
* update keeps the Manifest-Version and adds a new attribute Foo
*/
+ @Test
public void testUpdate() throws IOException, ManifestException {
- executeTarget("testUpdate");
+ buildRule.executeTarget("testUpdate");
Manifest mf = getManifest("src/etc/testcases/taskdefs/mftest.mf");
assertNotNull(mf);
assertTrue(!Manifest.getDefaultManifest().equals(mf));
@@ -328,28 +400,60 @@ public class ManifestTest extends BuildFileTest {
assertTrue(mfAsString.indexOf("Foo: Baz") > -1);
}
+ @Test
public void testFrom() {
- expectLogContaining("testFrom", Manifest.ERROR_FROM_FORBIDDEN);
+ buildRule.executeTarget("testFrom");
+ assertContains(Manifest.ERROR_FROM_FORBIDDEN, buildRule.getLog());
}
+ @Test
public void testIllegalName() {
- expectBuildException("testIllegalName", "Manifest attribute names must not contain ' '");
+ try {
+ buildRule.executeTarget("testIllegalName");
+ fail("BuildException expected: Manifest attribute names must not contain ' '");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testIllegalNameInSection() {
- expectBuildException("testIllegalNameInSection", "Manifest attribute names must not contain ' '");
+ try {
+ buildRule.executeTarget("testIllegalNameInSection");
+ fail("BuildException expected: Manifest attribute names must not contain ' '");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testIllegalNameBegin() {
- expectBuildException("testIllegalNameInSection", "Manifest attribute names must not start with '-' at the begin.");
+ try {
+ buildRule.executeTarget("testIllegalNameInSection");
+ fail("BuildException expected: Manifest attribute names must not start with '-' at the begin.");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testIllegalName2() {
- expectBuildException("testIllegalName", "Manifest attribute names must not contain '.'");
+ try {
+ buildRule.executeTarget("testIllegalName");
+ fail("BuildException expected: Manifest attribute names must not contain '.'");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testIllegalName3() {
- expectBuildException("testIllegalName", "Manifest attribute names must not contain '*'");
+ try {
+ buildRule.executeTarget("testIllegalName");
+ fail("BuildException expected: Manifest attribute names must not contain '*'");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
/**
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/MkdirTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/MkdirTest.java
index 5d9b416ae..d8f1bfc58 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/MkdirTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/MkdirTest.java
@@ -17,31 +17,50 @@
*/
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
*/
-public class MkdirTest extends BuildFileTest {
+public class MkdirTest {
- public MkdirTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/mkdir.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/mkdir.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "directory already exists as a file");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: directory already exists as a file");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- executeTarget("test3");
- java.io.File f = new java.io.File(getOutputDir(), "testdir.tmp");
+ buildRule.executeTarget("test3");
+ java.io.File f = new java.io.File(buildRule.getProject().getProperty("output"), "testdir.tmp");
if (!f.exists() || !f.isDirectory()) {
fail("mkdir failed");
} else {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/MoveTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/MoveTest.java
index 264e8298b..0537c0a00 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/MoveTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/MoveTest.java
@@ -18,126 +18,151 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
import java.io.File;
import java.io.IOException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
/**
* 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 class MoveTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/move.xml");
- project.executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/move.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void testFilterSet() throws IOException {
- executeTarget("testFilterSet");
- File tmp = new File(getOutputDir(), "move.filterset.tmp");
- File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
+ buildRule.executeTarget("testFilterSet");
+ File tmp = new File(buildRule.getProject().getProperty("output"), "move.filterset.tmp");
+ File check = new File(buildRule.getProject().getBaseDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
- assertTrue(FILE_UTILS.contentEquals(tmp, check));
+ assertEquals(FileUtilities.getFileContents(check), FileUtilities.getFileContents(tmp));
}
+ @Test
public void testFilterChain() throws IOException {
- executeTarget("testFilterChain");
- File tmp = new File(getOutputDir(), "move.filterchain.tmp");
- File check = new File(getProjectDir(), "expected/copy.filterset.filtered");
+ buildRule.executeTarget("testFilterChain");
+ File tmp = new File(buildRule.getProject().getProperty("output"), "move.filterchain.tmp");
+ File check = new File(buildRule.getProject().getBaseDir(), "expected/copy.filterset.filtered");
assertTrue(tmp.exists());
- assertTrue(FILE_UTILS.contentEquals(tmp, check));
+ assertEquals(FileUtilities.getFileContents(check), FileUtilities.getFileContents(tmp));
}
/** Bugzilla Report 11732 */
+ @Test
public void testDirectoryRemoval() throws IOException {
- executeTarget("testDirectoryRemoval");
- assertTrue(!new File(getOutputDir(),"E/B/1").exists());
- assertTrue(new File(getOutputDir(),"E/C/2").exists());
- assertTrue(new File(getOutputDir(),"E/D/3").exists());
- assertTrue(new File(getOutputDir(),"A/B/1").exists());
- assertTrue(!new File(getOutputDir(),"A/C/2").exists());
- assertTrue(!new File(getOutputDir(),"A/D/3").exists());
- assertTrue(!new File(getOutputDir(),"A/C").exists());
- assertTrue(!new File(getOutputDir(),"A/D").exists());
+
+ buildRule.executeTarget("testDirectoryRemoval");
+ String output = buildRule.getProject().getProperty("output");
+ assertTrue(!new File(output,"E/B/1").exists());
+ assertTrue(new File(output, "E/C/2").exists());
+ assertTrue(new File(output,"E/D/3").exists());
+ assertTrue(new File(output,"A/B/1").exists());
+ assertTrue(!new File(output,"A/C/2").exists());
+ assertTrue(!new File(output,"A/D/3").exists());
+ assertTrue(!new File(output,"A/C").exists());
+ assertTrue(!new File(output,"A/D").exists());
}
/** Bugzilla Report 18886 */
+ @Test
public void testDirectoryRetaining() throws IOException {
- executeTarget("testDirectoryRetaining");
- assertTrue(new File(getOutputDir(),"E").exists());
- assertTrue(new File(getOutputDir(),"E/1").exists());
- assertTrue(!new File(getOutputDir(),"A/1").exists());
- assertTrue(new File(getOutputDir(),"A").exists());
+ buildRule.executeTarget("testDirectoryRetaining");
+ String output = buildRule.getProject().getProperty("output");
+ assertTrue(new File(output,"E").exists());
+ assertTrue(new File(output,"E/1").exists());
+ assertTrue(!new File(output,"A/1").exists());
+ assertTrue(new File(output,"A").exists());
}
+ @Test
public void testCompleteDirectoryMove() throws IOException {
testCompleteDirectoryMove("testCompleteDirectoryMove");
}
+ @Test
public void testCompleteDirectoryMove2() throws IOException {
testCompleteDirectoryMove("testCompleteDirectoryMove2");
}
private void testCompleteDirectoryMove(String target) throws IOException {
- executeTarget(target);
- assertTrue(new File(getOutputDir(),"E").exists());
- assertTrue(new File(getOutputDir(),"E/1").exists());
- assertTrue(!new File(getOutputDir(),"A/1").exists());
+ buildRule.executeTarget(target);
+ String output = buildRule.getProject().getProperty("output");
+ assertTrue(new File(output,"E").exists());
+ assertTrue(new File(output,"E/1").exists());
+ assertTrue(!new File(output,"A/1").exists());
// swallows the basedir, it seems
//assertTrue(!new File(getOutputDir(),"A").exists());
}
+ @Test
public void testPathElementMove() throws IOException {
- executeTarget("testPathElementMove");
- assertTrue(new File(getOutputDir(),"E").exists());
- assertTrue(new File(getOutputDir(),"E/1").exists());
- assertTrue(!new File(getOutputDir(),"A/1").exists());
- assertTrue(new File(getOutputDir(),"A").exists());
+ buildRule.executeTarget("testPathElementMove");
+ String output = buildRule.getProject().getProperty("output");
+ assertTrue(new File(output,"E").exists());
+ assertTrue(new File(output,"E/1").exists());
+ assertTrue(!new File(output,"A/1").exists());
+ assertTrue(new File(output,"A").exists());
}
+ @Test
public void testMoveFileAndFileset() {
- executeTarget("testMoveFileAndFileset");
+ buildRule.executeTarget("testMoveFileAndFileset");
}
+ @Test
public void testCompleteDirectoryMoveToExistingDir() {
- executeTarget("testCompleteDirectoryMoveToExistingDir");
+ buildRule.executeTarget("testCompleteDirectoryMoveToExistingDir");
}
+ @Test
public void testCompleteDirectoryMoveFileToFile() {
- executeTarget("testCompleteDirectoryMoveFileToFile");
+ buildRule.executeTarget("testCompleteDirectoryMoveFileToFile");
}
+ @Test
public void testCompleteDirectoryMoveFileToDir() {
- executeTarget("testCompleteDirectoryMoveFileToDir");
+ buildRule.executeTarget("testCompleteDirectoryMoveFileToDir");
}
+ @Test
public void testCompleteDirectoryMoveFileAndFileset() {
- executeTarget("testCompleteDirectoryMoveFileAndFileset");
+ buildRule.executeTarget("testCompleteDirectoryMoveFileAndFileset");
}
+ @Test
public void testCompleteDirectoryMoveFileToExistingFile() {
- executeTarget("testCompleteDirectoryMoveFileToExistingFile");
+ buildRule.executeTarget("testCompleteDirectoryMoveFileToExistingFile");
}
+ @Test
public void testCompleteDirectoryMoveFileToExistingDir() {
- executeTarget("testCompleteDirectoryMoveFileToExistingDir");
+ buildRule.executeTarget("testCompleteDirectoryMoveFileToExistingDir");
}
+ @Test
public void testCompleteDirectoryMoveFileToDirWithExistingFile() {
- executeTarget("testCompleteDirectoryMoveFileToDirWithExistingFile");
+ buildRule.executeTarget("testCompleteDirectoryMoveFileToDirWithExistingFile");
}
+ @Test
public void testCompleteDirectoryMoveFileToDirWithExistingDir() {
- executeTarget("testCompleteDirectoryMoveFileToDirWithExistingDir");
+ buildRule.executeTarget("testCompleteDirectoryMoveFileToDirWithExistingDir");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/MultiMapTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/MultiMapTest.java
index 86620d5df..95f9eafde 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/MultiMapTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/MultiMapTest.java
@@ -18,44 +18,53 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileNameMapper;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
*/
-public class MultiMapTest extends BuildFileTest {
-
- public MultiMapTest(String name) {
- super(name);
- }
+public class MultiMapTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/multimap.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/multimap.xml");
}
+ @Test
public void testMultiCopy() {
- executeTarget("multicopy");
+ buildRule.executeTarget("multicopy");
}
+ @Test
public void testMultiMove() {
- executeTarget("multimove");
+ buildRule.executeTarget("multimove");
}
+ @Test
public void testSingleCopy() {
- executeTarget("singlecopy");
+ buildRule.executeTarget("singlecopy");
}
+ @Test
public void testSingleMove() {
- executeTarget("singlemove");
+ buildRule.executeTarget("singlemove");
}
+ @Test
public void testCopyWithEmpty() {
- executeTarget("copywithempty");
+ buildRule.executeTarget("copywithempty");
}
+ @Test
public void testMoveWithEmpty() {
- executeTarget("movewithempty");
+ buildRule.executeTarget("movewithempty");
}
public static class TestMapper implements FileNameMapper {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/NiceTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/NiceTest.java
index 26d483afa..98d9fa581 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/NiceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/NiceTest.java
@@ -18,45 +18,66 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
/**
* test nice
*/
-public class NiceTest extends BuildFileTest {
+public class NiceTest {
- public NiceTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/nice.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/nice.xml");
}
+ @Test
public void testNoop() {
- executeTarget("noop");
+ buildRule.executeTarget("noop");
}
+ @Test
public void testCurrent() {
- executeTarget("current");
+ buildRule.executeTarget("current");
}
+ @Test
public void testFaster() {
- executeTarget("faster");
+ buildRule.executeTarget("faster");
}
+ @Test
public void testSlower() {
- executeTarget("slower");
+ buildRule.executeTarget("slower");
}
+ @Test
public void testTooSlow() {
- expectBuildExceptionContaining(
- "too_slow","out of range","out of the range 1-10");
+ try {
+ buildRule.executeTarget("too_slow");
+ fail("BuildException expected: out of range");
+ } catch (BuildException ex) {
+ assertContains("out of the range 1-10", ex.getMessage());
+ }
}
+ @Test
public void testTooFast() {
- expectBuildExceptionContaining(
- "too_fast", "out of range", "out of the range 1-10");
+ try {
+ buildRule.executeTarget("too_fast");
+ fail("BuildException expected: out of range");
+ } catch (BuildException ex) {
+ assertContains("out of the range 1-10", ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java
index fcd67bd7b..3ca7cf78d 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java
@@ -19,19 +19,26 @@ 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.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.DemuxOutputStream;
import org.apache.tools.ant.ExitStatusException;
import org.apache.tools.ant.Project;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Test of the parallel TaskContainer
- *
- * @created 21 February 2002
*/
-public class ParallelTest extends BuildFileTest {
+public class ParallelTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
/** Standard property value for the basic test */
public final static String DIRECT_MESSAGE = "direct";
/** Standard property value for the basic and fail test */
@@ -43,41 +50,40 @@ public class ParallelTest extends BuildFileTest {
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 */
+ @Before
public void setUp() {
- configureProject(TEST_BUILD_FILE);
+ buildRule.configureProject(TEST_BUILD_FILE);
}
/** tests basic operation of the parallel task */
+ @Test
public void testBasic() {
// should get no output at all
- Project p = getProject();
+ Project p = buildRule.getProject();
p.setUserProperty("test.direct", DIRECT_MESSAGE);
p.setUserProperty("test.delayed", DELAYED_MESSAGE);
- expectOutputAndError("testBasic", "", "");
- String log = getLog();
+ buildRule.executeTarget("testBasic");
+ assertEquals("", buildRule.getOutput());
+ assertEquals("", buildRule.getError());
+ String log = buildRule.getLog();
assertEquals("parallel tasks didn't output correct data", log,
DIRECT_MESSAGE + DELAYED_MESSAGE);
}
/** tests basic operation of the parallel task */
+ @Test
public void testThreadCount() {
// should get no output at all
- Project p = getProject();
+ Project p = buildRule.getProject();
p.setUserProperty("test.direct", DIRECT_MESSAGE);
p.setUserProperty("test.delayed", DELAYED_MESSAGE);
- expectOutputAndError("testThreadCount", "", "");
- String log = getLog();
+ buildRule.executeTarget("testThreadCount");
+ assertEquals("", buildRule.getOutput());
+ assertEquals("", buildRule.getError());
+ String log = buildRule.getLog();
int pos = 0;
while (pos > -1) {
pos = countThreads(log, pos);
@@ -89,9 +95,8 @@ public class ParallelTest extends BuildFileTest {
* ^(\|\d+\/(+-)*)+\|$
for someting like
* |3/++--+-|5/+++++-----|
*
- *@returns -1 no more tests
+ *@return -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);
@@ -113,12 +118,12 @@ public class ParallelTest extends BuildFileTest {
current--;
break;
default:
- throw new AssertionFailedError("Only expect '+-' in result count, found "
- + s.charAt(--pos) + " at position " + pos);
+ fail("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);
+ fail("Number of executing threads exceeded number allowed: "
+ + current + " > " + max);
}
}
return lastPipe;
@@ -126,38 +131,48 @@ public class ParallelTest extends BuildFileTest {
/** tests the failure of a task within a parallel construction */
+ @Test
public void testFail() {
// should get no output at all
- Project p = getProject();
+ Project p = buildRule.getProject();
p.setUserProperty("test.failure", FAILURE_MESSAGE);
p.setUserProperty("test.delayed", DELAYED_MESSAGE);
- expectBuildExceptionContaining("testFail",
- "fail task in one parallel branch", FAILURE_MESSAGE);
+ try {
+ buildRule.executeTarget("testFail");
+ fail("fail task in one parallel branch");
+ } catch (BuildException ex) {
+ assertEquals(FAILURE_MESSAGE, ex.getMessage());
+ }
}
/** tests the demuxing of output streams in a multithreaded situation */
+ @Test
public void testDemux() {
- Project p = getProject();
+ Project p = buildRule.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);
+ synchronized (System.out) {
+ 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);
+ }
}
}
/**
* @see "https://issues.apache.org/bugzilla/show_bug.cgi?id=55539"
*/
+ @Test
public void testSingleExit() {
try {
- executeTarget("testSingleExit");
+ buildRule.executeTarget("testSingleExit");
+ fail("ExitStatusException should have been thrown");
} catch (ExitStatusException ex) {
assertEquals(42, ex.getStatus());
}
@@ -166,9 +181,11 @@ public class ParallelTest extends BuildFileTest {
/**
* @see "https://issues.apache.org/bugzilla/show_bug.cgi?id=55539"
*/
+ @Test
public void testExitAndOtherException() {
try {
- executeTarget("testExitAndOtherException");
+ buildRule.executeTarget("testExitAndOtherException");
+ fail("ExitStatusException should have been thrown");
} catch (ExitStatusException ex) {
assertEquals(42, ex.getStatus());
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/PathConvertTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/PathConvertTest.java
index 2f8428ccb..31a516e3c 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/PathConvertTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/PathConvertTest.java
@@ -18,39 +18,48 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* Unit test for the <pathconvert> task.
*/
-public class PathConvertTest extends BuildFileTest {
+public class PathConvertTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
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);
- }
-
+ @Before
public void setUp() {
- configureProject(BUILD_FILE);
+ buildRule.configureProject(BUILD_FILE);
}
+ @Test
public void testMap() {
test("testmap");
}
+ @Test
public void testMapper() {
test("testmapper");
}
+ @Test
public void testNoTargetOs() {
- executeTarget("testnotargetos");
+ buildRule.executeTarget("testnotargetos");
}
private void test(String target) {
- executeTarget(target);
- assertPropertyEquals("result", "test#" + BUILD_FILENAME);
+ buildRule.executeTarget(target);
+ assertEquals("test#" + BUILD_FILENAME, buildRule.getProject().getProperty("result"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/PreSetDefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/PreSetDefTest.java
index f0a25ba52..8c7c1f3fc 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/PreSetDefTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/PreSetDefTest.java
@@ -19,70 +19,107 @@
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class PreSetDefTest extends BuildFileTest {
- public PreSetDefTest(String name) {
- super(name);
- }
-
+public class PreSetDefTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/presetdef.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/presetdef.xml");
}
+ @Test
public void testSimple() {
- expectLog("simple", "Hello world");
+ buildRule.executeTarget("simple");
+ assertEquals("Hello world", buildRule.getLog());
}
+ @Test
public void testText() {
- expectLog("text", "Inner Text");
+ buildRule.executeTarget("text");
+ assertEquals("Inner Text", buildRule.getLog());
}
+ @Test
public void testUri() {
- expectLog("uri", "Hello world");
+ buildRule.executeTarget("uri");
+ assertEquals("Hello world", buildRule.getLog());
}
+ @Test
public void testDefaultTest() {
- expectLog("defaulttest", "attribute is false");
+ buildRule.executeTarget("defaulttest");
+ assertEquals("attribute is false", buildRule.getLog());
}
+ @Test
public void testDoubleDefault() {
- expectLog("doubledefault", "attribute is falseattribute is true");
+ buildRule.executeTarget("doubledefault");
+ assertEquals("attribute is falseattribute is true", buildRule.getLog());
}
+ @Test
public void testTextOptional() {
- expectLog("text.optional", "MyTextoverride text");
+ buildRule.executeTarget("text.optional");
+ assertEquals("MyTextoverride text", buildRule.getLog());
}
+ @Test
public void testElementOrder() {
- expectLog("element.order", "Line 1Line 2");
+ buildRule.executeTarget("element.order");
+ assertEquals("Line 1Line 2", buildRule.getLog());
}
+ @Test
public void testElementOrder2() {
- expectLog("element.order2", "Line 1Line 2Line 3");
+ buildRule.executeTarget("element.order2");
+ assertEquals("Line 1Line 2Line 3", buildRule.getLog());
}
+ @Test
public void testAntTypeTest() {
- expectLog("antTypeTest", "");
+ buildRule.executeTarget("antTypeTest");
+ assertEquals("", buildRule.getLog());
}
+ @Test
public void testCorrectTaskNameBadAttr() {
- expectBuildExceptionContaining(
- "correct_taskname_badattr", "attribute message", "javac doesn't support the");
+ try {
+ buildRule.executeTarget("correct_taskname_badattr");
+ fail("BuildException expected: attribute message");
+ } catch (BuildException ex) {
+ assertContains("javac doesn't support the", ex.getMessage());
+ }
}
+ @Test
public void testCorrectTaskNameBadEl() {
- expectBuildExceptionContaining(
- "correct_taskname_badel", "element message", "javac doesn't support the");
+ try {
+ buildRule.executeTarget("correct_taskname_badel");
+ fail("BuildException expected: element message");
+ } catch (BuildException ex) {
+ assertContains("javac doesn't support the", ex.getMessage());
+ }
}
+ @Test
public void testPresetdefWithNestedElementTwice() { // #38056
- executeTarget("presetdef-with-nested-element-twice");
- executeTarget("presetdef-with-nested-element-twice");
+ buildRule.executeTarget("presetdef-with-nested-element-twice");
+ buildRule.executeTarget("presetdef-with-nested-element-twice");
}
/**
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ProcessDestroyerTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ProcessDestroyerTest.java
index 0ac0c36c8..eadac4067 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ProcessDestroyerTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ProcessDestroyerTest.java
@@ -23,57 +23,46 @@ package org.apache.tools.ant.taskdefs;
import java.io.IOException;
+import org.junit.Test;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/**
*/
-public class ProcessDestroyerTest extends TestCase {
+//TODO this test seems really unsafe due to the infinite loop
+public class ProcessDestroyerTest {
- /**
- * Constructor for ProcessDestroyerTest.
- * @param arg0
- */
- public ProcessDestroyerTest(String arg0) {
- super(arg0);
- }
+ @Test
+ public void testProcessDestroyer() throws IOException {
+ ProcessDestroyer processDestroyer = new ProcessDestroyer();
+ Process process =
+ Runtime.getRuntime().exec(
+ "java -cp "
+ + System.getProperty("java.class.path")
+ + " "
+ + getClass().getName());
- public void testProcessDestroyer(){
- 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());
- assertFalse("Not registered as shutdown hook",
- processDestroyer.isAddedAsShutdownHook());
+ processDestroyer.add(process);
- processDestroyer.add(process);
+ assertTrue("Registered as shutdown hook",
+ processDestroyer.isAddedAsShutdownHook());
+ try {
+ process.destroy();
+ } finally {
+ processDestroyer.remove(process);
+ }
- assertTrue("Registered as shutdown hook",
- processDestroyer.isAddedAsShutdownHook());
- try {
- process.destroy();
- } finally {
- processDestroyer.remove(process);
- }
+ assertFalse("Not registered as shutdown hook",
+ processDestroyer.isAddedAsShutdownHook());
- 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();
- }
+ public static void main(String[] args) throws IOException, InterruptedException {
+ new ProcessDestroyerTest().testProcessDestroyer();
+ Thread.sleep(60000);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java
index aa1e4a79f..52b762d0f 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/PropertyTest.java
@@ -18,106 +18,124 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
*/
-public class PropertyTest extends BuildFileTest {
+public class PropertyTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public PropertyTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/property.xml");
- project.executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/property.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void test1() {
// should get no output at all
- expectOutputAndError("test1", "", "");
+ buildRule.executeTarget("test1");
+ assertEquals("System output should have been empty", "", buildRule.getOutput());
+ assertEquals("System error should have been empty", "", buildRule.getError());
}
+ @Test
public void test2() {
- expectLog("test2", "testprop1=aa, testprop3=xxyy, testprop4=aazz");
+ buildRule.executeTarget("test2");
+ assertContains("testprop1=aa, testprop3=xxyy, testprop4=aazz", buildRule.getLog());
}
+ @Test
public void test3() {
try {
- executeTarget("test3");
+ buildRule.executeTarget("test3");
+ fail("Did not throw exception on circular exception");
}
catch (BuildException e) {
assertTrue("Circular definition not detected - ",
e.getMessage().indexOf("was circularly defined") != -1);
- return;
}
- fail("Did not throw exception on circular exception");
+
}
+ @Test
public void test4() {
- expectLog("test4", "http.url is http://localhost:999");
+ buildRule.executeTarget("test4");
+ assertContains("http.url is http://localhost:999", buildRule.getLog());
}
+ @Test
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");
+ String baseDir = buildRule.getProject().getProperty("basedir");
+ String uri = FILE_UTILS.toURI(baseDir + "/property3.properties");
+ buildRule.getProject().setNewProperty("test5.url", uri);
+
+ buildRule.executeTarget("test5");
+ assertContains("http.url is http://localhost:999", buildRule.getLog());
}
+ @Test
public void testPrefixSuccess() {
- executeTarget("prefix.success");
- assertEquals("80", project.getProperty("server1.http.port"));
+ buildRule.executeTarget("prefix.success");
+ assertEquals("80", buildRule.getProject().getProperty("server1.http.port"));
}
+ @Test
public void testPrefixFailure() {
try {
- executeTarget("prefix.fail");
+ buildRule.executeTarget("prefix.fail");
+ fail("Did not throw exception on invalid use of prefix");
}
catch (BuildException e) {
- assertTrue("Prefix allowed on non-resource/file load - ",
- e.getMessage().indexOf("Prefix is only valid") != -1);
- return;
+ assertContains("Prefix allowed on non-resource/file load - ",
+ "Prefix is only valid", e.getMessage());
}
- fail("Did not throw exception on invalid use of prefix");
}
+ @Test
public void testCircularReference() {
try {
- executeTarget("testCircularReference");
+ buildRule.executeTarget("testCircularReference");
+ fail("Did not throw exception on circular exception");
} catch (BuildException e) {
- assertTrue("Circular definition not detected - ",
- e.getMessage().indexOf("was circularly defined")
- != -1);
- return;
+ assertContains("Circular definition not detected - ",
+ "was circularly defined", e.getMessage());
}
- fail("Did not throw exception on circular exception");
}
+ @Test
public void testThisIsNotACircularReference() {
- expectLog("thisIsNotACircularReference", "b is A/A/A");
+ buildRule.executeTarget("thisIsNotACircularReference");
+ assertContains("b is A/A/A", buildRule.getLog());
}
+ @Test
public void testXmlProperty() {
try {
Class.forName("java.lang.Iterable");
- executeTarget("testXmlProperty");
- assertEquals("ONE", project.getProperty("xml.one"));
- assertEquals("TWO", project.getProperty("xml.two"));
} catch (ClassNotFoundException e) {
- // Xml-Loading only on Java5+
+ Assume.assumeNoException("XML Loading only on Java 5+", e);
}
+ buildRule.executeTarget("testXmlProperty");
+ assertEquals("ONE", buildRule.getProject().getProperty("xml.one"));
+ assertEquals("TWO", buildRule.getProject().getProperty("xml.two"));
+
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ProtectedJarMethodsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ProtectedJarMethodsTest.java
index d8bd4befb..27b3c8c8d 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ProtectedJarMethodsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ProtectedJarMethodsTest.java
@@ -21,26 +21,35 @@ package org.apache.tools.ant.taskdefs;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
-import org.apache.tools.ant.BuildFileTest;
+
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
/**
*/
-public class ProtectedJarMethodsTest extends BuildFileTest {
+public class ProtectedJarMethodsTest {
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
private static String tempJar = "tmp.jar";
- public ProtectedJarMethodsTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/jar.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/jar.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void testGrabFilesAndDirs() throws IOException {
- executeTarget("testIndexTests");
- String archive = getProject().getProperty(tempJar);
+ buildRule.executeTarget("testIndexTests");
+ String archive = buildRule.getProject().getProperty(tempJar);
ArrayList dirs = new ArrayList();
ArrayList files = new ArrayList();
String[] expectedDirs = new String[] {
@@ -63,16 +72,19 @@ public class ProtectedJarMethodsTest extends BuildFileTest {
}
}
+ @Test
public void testFindJarNameNoClasspath() {
assertEquals("foo", Jar.findJarName("foo", null));
assertEquals("foo", Jar.findJarName("lib" + File.separatorChar + "foo",
null));
}
+ @Test
public void testFindJarNameNoMatch() {
assertNull(Jar.findJarName("foo", new String[] {"bar"}));
}
+ @Test
public void testFindJarNameSimpleMatches() {
assertEquals("foo", Jar.findJarName("foo", new String[] {"foo"}));
assertEquals("lib/foo", Jar.findJarName("foo",
@@ -84,6 +96,7 @@ public class ProtectedJarMethodsTest extends BuildFileTest {
new String[] {"lib/foo"}));
}
+ @Test
public void testFindJarNameLongestMatchWins() {
assertEquals("lib/foo",
Jar.findJarName("lib/foo",
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/RecorderTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/RecorderTest.java
index a057e50e6..c4806cd80 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/RecorderTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/RecorderTest.java
@@ -18,77 +18,86 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
import java.io.IOException;
+import static org.junit.Assert.assertTrue;
+
/**
*/
-public class RecorderTest extends BuildFileTest {
+public class RecorderTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
private static final String REC_IN = "recorder/";
- private static final String REC_DIR = "recorder-out/";
/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public RecorderTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/recorder.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/recorder.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void testNoAppend() throws IOException {
- executeTarget("noappend");
+ buildRule.executeTarget("noappend");
assertTrue(FILE_UTILS
- .contentEquals(project.resolveFile(REC_IN
+ .contentEquals(buildRule.getProject().resolveFile(REC_IN
+ "rectest1.result"),
- new File(getOutputDir(),
+ new File(buildRule.getOutputDir(),
"rectest1.log"), true));
}
+ @Test
public void testAppend() throws IOException {
- executeTarget("append");
+ buildRule.executeTarget("append");
assertTrue(FILE_UTILS
- .contentEquals(project.resolveFile(REC_IN
+ .contentEquals(buildRule.getProject().resolveFile(REC_IN
+ "rectest2.result"),
- new File(getOutputDir(),
+ new File(buildRule.getOutputDir(),
"rectest2.log"), true));
}
+ @Test
public void testRestart() throws IOException {
- executeTarget("restart");
+ buildRule.executeTarget("restart");
assertTrue(FILE_UTILS
- .contentEquals(project.resolveFile(REC_IN
+ .contentEquals(buildRule.getProject().resolveFile(REC_IN
+ "rectest3.result"),
- new File(getOutputDir(), "rectest3.log"), true));
+ new File(buildRule.getOutputDir(), "rectest3.log"), true));
}
+ @Test
public void testDeleteRestart() throws IOException {
- executeTarget("deleterestart");
+ buildRule.executeTarget("deleterestart");
assertTrue(FILE_UTILS
- .contentEquals(project.resolveFile(REC_IN
+ .contentEquals(buildRule.getProject().resolveFile(REC_IN
+ "rectest4.result"),
- new File(getOutputDir(),
+ new File(buildRule.getOutputDir(),
"rectest4.log"), true));
}
+ @Test
public void testSubBuild() throws IOException {
- executeTarget("subbuild");
+ buildRule.executeTarget("subbuild");
assertTrue(FILE_UTILS
- .contentEquals(project.resolveFile(REC_IN
+ .contentEquals(buildRule.getProject().resolveFile(REC_IN
+ "rectest5.result"),
- new File(getOutputDir(), "rectest5.log"), true));
+ new File(buildRule.getOutputDir(), "rectest5.log"), true));
assertTrue(FILE_UTILS
- .contentEquals(project.resolveFile(REC_IN
+ .contentEquals(buildRule.getProject().resolveFile(REC_IN
+ "rectest6.result"),
- new File(getOutputDir(), "rectest6.log"), true));
-
+ new File(buildRule.getOutputDir(), "rectest6.log"), true));
+
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/RenameTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/RenameTest.java
index 8460fc1cf..0cb134410 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/RenameTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/RenameTest.java
@@ -17,39 +17,72 @@
*/
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class RenameTest extends BuildFileTest {
+import static org.junit.Assert.fail;
- public RenameTest(String name) {
- super(name);
- }
+public class RenameTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/rename.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/rename.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException should have been thrown: required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument missing");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException should have been thrown: required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument missing");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException should have been thrown: required argument missing");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
-/*
+
+ @Test
+ @Ignore("Previously commented out")
public void test4() {
- expectBuildException("test4", "source and destination the same");
+ try {
+ buildRule.executeTarget("test4");
+ fail("BuildException should have been thrown: source and destination the same");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+
+ @Test
+ @Ignore("Previously commented out")
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
- */
+ @Test
public void test6() {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ReplaceTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ReplaceTest.java
index ccefcd19b..387c54dcd 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ReplaceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ReplaceTest.java
@@ -18,77 +18,136 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-
-import java.io.*;
+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.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
/**
*/
-public class ReplaceTest extends BuildFileTest {
-
- public ReplaceTest(String name) {
- super(name);
- }
+public class ReplaceTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/replace.xml");
- project.executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/replace.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument not specified");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test4() {
- expectBuildException("test4", "empty token not allowed");
+ try {
+ buildRule.executeTarget("test4");
+ fail("BuildException expected: empty token not allowed");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
+ @Test
public void test6() {
- expectBuildException("test6", "required argument not specified");
+ try {
+ buildRule.executeTarget("test6");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test7() {
- expectBuildException("test7", "empty token not allowed");
+ try {
+ buildRule.executeTarget("test7");
+ fail("BuildException expected: empty token not allowed");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test8() {
- executeTarget("test8");
+ buildRule.executeTarget("test8");
}
+ @Test
public void test9() throws IOException {
- executeTarget("test9");
- assertEqualContent(new File(getOutputDir(), "result.txt"),
- new File(getOutputDir(), "output.txt"));
+
+ buildRule.executeTarget("test9");
+ assertEqualContent(new File(buildRule.getOutputDir(), "result.txt"),
+ new File(buildRule.getOutputDir(), "output.txt"));
}
+ @Test
public void testNoPreserveLastModified() throws Exception {
- executeTarget("lastModifiedSetup");
- long ts1 = new File(getOutputDir(), "test.txt").lastModified();
- Thread.sleep(3000);
- executeTarget("testNoPreserve");
- assertTrue(ts1 < new File(getOutputDir(), "test.txt").lastModified());
+ buildRule.executeTarget("lastModifiedSetup");
+ File testFile = new File(buildRule.getOutputDir(), "test.txt");
+ assumeTrue("Could not change file modification time",
+ testFile.setLastModified(testFile.lastModified() - (FileUtils.getFileUtils().getFileTimestampGranularity() * 5)));
+ long ts1 = testFile.lastModified();
+ buildRule.executeTarget("testNoPreserve");
+ assertTrue(ts1 < new File(buildRule.getOutputDir(), "test.txt").lastModified());
}
+ @Test
public void testPreserveLastModified() throws Exception {
- executeTarget("lastModifiedSetup");
- long ts1 = new File(getOutputDir(), "test.txt").lastModified();
- Thread.sleep(3000);
- executeTarget("testPreserve");
- assertTrue(ts1 == new File(getOutputDir(), "test.txt").lastModified());
+ buildRule.executeTarget("lastModifiedSetup");
+ File testFile = new File(buildRule.getOutputDir(), "test.txt");
+ assumeTrue("Could not change file modification time",
+ testFile.setLastModified(testFile.lastModified() - (FileUtils.getFileUtils().getFileTimestampGranularity() * 5)));
+ long ts1 = testFile.lastModified();buildRule.executeTarget("testPreserve");
+ assertTrue(ts1 == new File(buildRule.getOutputDir(), "test.txt").lastModified());
}
public void assertEqualContent(File expect, File result)
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java
index c31556ff5..c9d251469 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/RmicAdvancedTest.java
@@ -19,222 +19,272 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.rmic.RmicAdapterFactory;
import org.apache.tools.ant.taskdefs.rmic.DefaultRmicAdapter;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
* Date: 04-Aug-2004
* Time: 22:15:46
*/
-public class RmicAdvancedTest extends BuildFileTest {
-
- public RmicAdvancedTest(String name) {
- super(name);
- }
+public class RmicAdvancedTest {
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/rmic/";
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
/**
* The JUnit setup method
*/
+ @Before
public void setUp() throws Exception {
- super.setUp();
- configureProject(TASKDEFS_DIR + "rmic.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "rmic.xml");
}
/**
* verify that "default" binds us to the default compiler
*/
+ @Test
public void testDefault() throws Exception {
- executeTarget("testDefault");
+ buildRule.executeTarget("testDefault");
}
/**
* verify that "default" binds us to the default compiler
*/
+ @Test
public void testDefaultDest() throws Exception {
- executeTarget("testDefaultDest");
+ buildRule.executeTarget("testDefaultDest");
}
/**
* verify that "" binds us to the default compiler
*/
+ @Test
public void testEmpty() throws Exception {
- executeTarget("testEmpty");
+ buildRule.executeTarget("testEmpty");
}
/**
* verify that "" binds us to the default compiler
*/
+ @Test
public void testEmptyDest() throws Exception {
- executeTarget("testEmptyDest");
+ buildRule.executeTarget("testEmptyDest");
}
/**
* test sun's rmic compiler
*/
+ @Test
public void testRmic() throws Exception {
- executeTarget("testRmic");
+ buildRule.executeTarget("testRmic");
}
/**
* test sun's rmic compiler
*/
+ @Test
public void testRmicDest() throws Exception {
- executeTarget("testRmicDest");
+ buildRule.executeTarget("testRmicDest");
}
/**
* test sun's rmic compiler strips
* out -J arguments when not forking
*/
+ @Test
public void testRmicJArg() throws Exception {
- executeTarget("testRmicJArg");
+ buildRule.executeTarget("testRmicJArg");
}
/**
* test sun's rmic compiler strips
* out -J arguments when not forking
*/
+ @Test
public void testRmicJArgDest() throws Exception {
- executeTarget("testRmicJArgDest");
+ buildRule.executeTarget("testRmicJArgDest");
}
/**
* A unit test for JUnit
*/
+ @Test
public void testKaffe() throws Exception {
- executeTarget("testKaffe");
+ buildRule.executeTarget("testKaffe");
}
/**
* A unit test for JUnit
*/
+ @Test
public void testKaffeDest() throws Exception {
- executeTarget("testKaffeDest");
+ buildRule.executeTarget("testKaffeDest");
}
// WLrmic tests don't work
/**
* test weblogic
*/
+ @Test
+ @Ignore("WLRmin tests don't work")
public void XtestWlrmic() throws Exception {
- executeTarget("testWlrmic");
+ buildRule.executeTarget("testWlrmic");
}
/**
* test weblogic's stripping of -J args
*/
+ @Test
+ @Ignore("WLRmin tests don't work")
public void XtestWlrmicJArg() throws Exception {
- executeTarget("testWlrmicJArg");
+ buildRule.executeTarget("testWlrmicJArg");
}
/**
* test the forking compiler
*/
+ @Test
+ @Ignore("WLRmin tests don't work")
public void NotestForking() throws Exception {
- executeTarget("testForking");
+ buildRule.executeTarget("testForking");
}
/**
* test the forking compiler
*/
+ @Test
public void testForkingAntClasspath() throws Exception {
- executeTarget("testForkingAntClasspath");
+ buildRule.executeTarget("testForkingAntClasspath");
}
/**
* test the forking compiler
*/
+ @Test
public void testForkingAntClasspathDest() throws Exception {
- executeTarget("testForkingAntClasspathDest");
+ buildRule.executeTarget("testForkingAntClasspathDest");
}
/**
* test the forking compiler
*/
+ @Test
public void testAntClasspath() throws Exception {
- executeTarget("testAntClasspath");
+ buildRule.executeTarget("testAntClasspath");
}
/**
* test the forking compiler
*/
+ @Test
public void testAntClasspathDest() throws Exception {
- executeTarget("testAntClasspathDest");
+ buildRule.executeTarget("testAntClasspathDest");
}
/**
* A unit test for JUnit
*/
+ @Test
public void testBadName() throws Exception {
- expectBuildExceptionContaining("testBadName",
- "compiler not known",
- RmicAdapterFactory.ERROR_UNKNOWN_COMPILER);
+ try {
+ buildRule.executeTarget("testBadName");
+ fail("Compile not known");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(RmicAdapterFactory.ERROR_UNKNOWN_COMPILER, ex.getMessage());
+ }
}
/**
* load an adapter by name
*/
+ @Test
public void testExplicitClass() throws Exception {
- executeTarget("testExplicitClass");
+ buildRule.executeTarget("testExplicitClass");
}
/**
* A unit test for JUnit
*/
+ @Test
public void testWrongClass() throws Exception {
- expectBuildExceptionContaining("testWrongClass",
- "class not an RMIC adapter",
- RmicAdapterFactory.ERROR_NOT_RMIC_ADAPTER);
+ try {
+ buildRule.executeTarget("testWrongClass");
+ fail("Class not an RMIC adapter");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(RmicAdapterFactory.ERROR_NOT_RMIC_ADAPTER, ex.getMessage());
+ }
}
/**
* A unit test for JUnit
*/
+ @Test
public void testDefaultBadClass() throws Exception {
- expectBuildExceptionContaining("testDefaultBadClass",
- "expected the class to fail",
- Rmic.ERROR_RMIC_FAILED);
+ try {
+ buildRule.executeTarget("testDefaultBadClass");
+ fail("expected the class to fail");
+ } catch(BuildException ex) {
+ AntAssert.assertContains(Rmic.ERROR_RMIC_FAILED, ex.getMessage());
+ }
//dont look for much text here as it is vendor and version dependent
- assertLogContaining("unimplemented.class");
+ AntAssert.assertContains("unimplemented.class", buildRule.getLog());
}
/**
* A unit test for JUnit
*/
+ @Test
public void testMagicProperty() throws Exception {
- expectBuildExceptionContaining("testMagicProperty",
- "magic property not working",
- RmicAdapterFactory.ERROR_UNKNOWN_COMPILER);
+ try {
+ buildRule.executeTarget("testMagicProperty");
+ fail("Magic property not working");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(RmicAdapterFactory.ERROR_UNKNOWN_COMPILER, ex.getMessage());
+ }
}
/**
* A unit test for JUnit
*/
+ @Test
public void testMagicPropertyOverridesEmptyString() throws Exception {
- expectBuildExceptionContaining("testMagicPropertyOverridesEmptyString",
- "magic property not working",
- RmicAdapterFactory.ERROR_UNKNOWN_COMPILER);
+ try {
+ buildRule.executeTarget("testMagicPropertyOverridesEmptyString");
+ fail("Magic property not working");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(RmicAdapterFactory.ERROR_UNKNOWN_COMPILER, ex.getMessage());
+ }
}
- /**
- *
- */
+ @Test
public void testMagicPropertyIsEmptyString() throws Exception {
- executeTarget("testMagicPropertyIsEmptyString");
+ buildRule.executeTarget("testMagicPropertyIsEmptyString");
}
+ @Test
+ @Ignore("Previously named to prevent execution")
public void NotestFailingAdapter() throws Exception {
- expectBuildExceptionContaining("testFailingAdapter",
- "expected failures to propagate",
- Rmic.ERROR_RMIC_FAILED);
+ try {
+ buildRule.executeTarget("testFailingAdapter");
+ fail("Expected failures to propogate");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(Rmic.ERROR_RMIC_FAILED, ex.getMessage());
+ }
}
@@ -242,16 +292,18 @@ public class RmicAdvancedTest extends BuildFileTest {
* test that version 1.1 stubs are good
* @throws Exception
*/
+ @Test
public void testVersion11() throws Exception {
- executeTarget("testVersion11");
+ buildRule.executeTarget("testVersion11");
}
/**
* test that version 1.1 stubs are good
* @throws Exception
*/
+ @Test
public void testVersion11Dest() throws Exception {
- executeTarget("testVersion11Dest");
+ buildRule.executeTarget("testVersion11Dest");
}
/**
@@ -259,8 +311,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testVersion12() throws Exception {
- executeTarget("testVersion12");
+ buildRule.executeTarget("testVersion12");
}
/**
@@ -268,8 +321,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testVersion12Dest() throws Exception {
- executeTarget("testVersion12Dest");
+ buildRule.executeTarget("testVersion12Dest");
}
/**
@@ -277,8 +331,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testVersionCompat() throws Exception {
- executeTarget("testVersionCompat");
+ buildRule.executeTarget("testVersionCompat");
}
/**
@@ -286,8 +341,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testVersionCompatDest() throws Exception {
- executeTarget("testVersionCompatDest");
+ buildRule.executeTarget("testVersionCompatDest");
}
/**
@@ -295,8 +351,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testXnew() throws Exception {
- executeTarget("testXnew");
+ buildRule.executeTarget("testXnew");
}
/**
@@ -304,8 +361,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testXnewDest() throws Exception {
- executeTarget("testXnewDest");
+ buildRule.executeTarget("testXnewDest");
}
/**
@@ -313,8 +371,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testXnewForked() throws Exception {
- executeTarget("testXnewForked");
+ buildRule.executeTarget("testXnewForked");
}
/**
@@ -322,8 +381,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testXnewForkedDest() throws Exception {
- executeTarget("testXnewForkedDest");
+ buildRule.executeTarget("testXnewForkedDest");
}
/**
@@ -331,8 +391,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testXnewCompiler() throws Exception {
- executeTarget("testXnewCompiler");
+ buildRule.executeTarget("testXnewCompiler");
}
/**
@@ -340,8 +401,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testXnewCompilerDest() throws Exception {
- executeTarget("testXnewCompilerDest");
+ buildRule.executeTarget("testXnewCompilerDest");
}
/**
@@ -349,8 +411,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testIDL() throws Exception {
- executeTarget("testIDL");
+ buildRule.executeTarget("testIDL");
}
/**
@@ -358,8 +421,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testIDLDest() throws Exception {
- executeTarget("testIDLDest");
+ buildRule.executeTarget("testIDLDest");
}
/**
@@ -367,8 +431,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testIIOP() throws Exception {
- executeTarget("testIIOP");
+ buildRule.executeTarget("testIIOP");
}
/**
@@ -376,8 +441,9 @@ public class RmicAdvancedTest extends BuildFileTest {
*
* @throws Exception
*/
+ @Test
public void testIIOPDest() throws Exception {
- executeTarget("testIIOPDest");
+ buildRule.executeTarget("testIIOPDest");
}
/**
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/RmicTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/RmicTest.java
index 78f07d189..8d3200c37 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/RmicTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/RmicTest.java
@@ -19,7 +19,11 @@
package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.Project;
-import junit.framework.TestCase;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
/**
@@ -27,15 +31,12 @@ import junit.framework.TestCase;
*
* @since Ant 1.5
*/
-public class RmicTest extends TestCase {
+public class RmicTest {
private Project project;
private Rmic rmic;
- public RmicTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
project = new Project();
project.init();
@@ -46,6 +47,7 @@ public class RmicTest extends TestCase {
/**
* Test nested compiler args.
*/
+ @Test
public void testCompilerArg() {
String[] args = rmic.getCurrentCompilerArgs();
assertNotNull(args);
@@ -81,6 +83,7 @@ public class RmicTest extends TestCase {
/**
* Test compiler attribute.
*/
+ @Test
public void testCompilerAttribute() {
// check defaults
String compiler = rmic.getCompiler();
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java
index 0de451abd..fbce8a6d5 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/SQLExecTest.java
@@ -26,10 +26,17 @@ import java.io.File;
import java.net.URL;
import java.util.logging.Logger;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.Project;
import org.apache.tools.ant.BuildException;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Simple testcase to test for driver caching.
@@ -40,7 +47,7 @@ import org.apache.tools.ant.BuildException;
* as the test db, so that a db is really used.
*
*/
-public class SQLExecTest extends TestCase {
+public class SQLExecTest {
// some database keys, see #getProperties(int)
public final static int NULL = 0;
@@ -55,23 +62,22 @@ public class SQLExecTest extends TestCase {
public final static String PATH = "path";
public final static String SQL = "sql";
- public SQLExecTest(String s) {
- super(s);
- }
-
- protected void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
// make sure the cache is cleared.
JDBCTask.getLoaderMap().clear();
}
// simple test to ensure that the caching does work...
+ @Test
public void testDriverCaching(){
SQLExec sql = createTask(getProperties(NULL));
assertTrue(!SQLExec.getLoaderMap().containsKey(NULL_DRIVER));
try {
sql.execute();
+ fail("BuildException should have been thrown");
} catch (BuildException e){
- assertTrue(e.getCause().getMessage().indexOf("No suitable Driver") != -1);
+ assertContains("No suitable Driver", e.getMessage());
}
assertTrue(SQLExec.getLoaderMap().containsKey(NULL_DRIVER));
assertSame(sql.getLoader(), JDBCTask.getLoaderMap().get(NULL_DRIVER));
@@ -91,19 +97,22 @@ public class SQLExecTest extends TestCase {
assertSame(loader1, sql.getLoader());
}
+ @Test
public void testNull() throws Exception {
doMultipleCalls(1000, NULL, true, true);
}
- /*
+ @Ignore
+ @Test
public void testOracle(){
doMultipleCalls(1000, ORACLE, true, false);
- }*/
+ }
- /*
+ @Ignore
+ @Test
public void testMySQL(){
doMultipleCalls(1000, MYSQL, true, false);
- }*/
+ }
/**
@@ -239,6 +248,7 @@ public class SQLExecTest extends TestCase {
}
}
+ @Test
public void testLastDelimiterPositionNormalModeStrict() {
SQLExec s = new SQLExec();
assertEquals(-1,
@@ -258,6 +268,7 @@ public class SQLExecTest extends TestCase {
s.lastDelimiterPosition(new StringBuffer("GO"), null));
}
+ @Test
public void testLastDelimiterPositionNormalModeNonStrict() {
SQLExec s = new SQLExec();
s.setStrictDelimiterMatching(false);
@@ -278,6 +289,7 @@ public class SQLExecTest extends TestCase {
s.lastDelimiterPosition(new StringBuffer("GO"), null));
}
+ @Test
public void testLastDelimiterPositionRowModeStrict() {
SQLExec s = new SQLExec();
SQLExec.DelimiterType t = new SQLExec.DelimiterType();
@@ -293,6 +305,7 @@ public class SQLExecTest extends TestCase {
assertEquals(0, s.lastDelimiterPosition(new StringBuffer("ab"), "GO"));
}
+ @Test
public void testLastDelimiterPositionRowModeNonStrict() {
SQLExec s = new SQLExec();
SQLExec.DelimiterType t = new SQLExec.DelimiterType();
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/SignJarTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/SignJarTest.java
index daf6a9440..95585fde6 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/SignJarTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/SignJarTest.java
@@ -19,25 +19,32 @@
package org.apache.tools.ant.taskdefs;
import java.io.File;
-import org.apache.tools.ant.BuildFileTest;
+
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.JavaEnvUtils;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Testcase for the Signjar task
*
*/
-public class SignJarTest extends BuildFileTest {
-
- public static final String EXPANDED_MANIFEST
- = "src/etc/testcases/taskdefs/manifests/META-INF/MANIFEST.MF";
+public class SignJarTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- public SignJarTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/signjar.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/signjar.xml");
}
/**
@@ -48,13 +55,14 @@ public class SignJarTest extends BuildFileTest {
return Boolean.getBoolean("offline");
}
+ @Test
public void testSigFile() {
- executeTarget("sigfile");
+ buildRule.executeTarget("sigfile");
SignJarChild sj = new SignJarChild();
sj.setAlias("testonly");
sj.setKeystore("testkeystore");
sj.setStorepass("apacheant");
- File jar = new File(getProject().getProperty("test.jar"));
+ File jar = new File(buildRule.getProject().getProperty("test.jar"));
sj.setJar(jar);
assertFalse("mustn't find signature without sigfile attribute",
sj.isSigned());
@@ -63,13 +71,14 @@ public class SignJarTest extends BuildFileTest {
sj.isSigned());
}
+ @Test
public void testInvalidChars() {
- executeTarget("invalidchars");
+ buildRule.executeTarget("invalidchars");
SignJarChild sj = new SignJarChild();
sj.setAlias("test@nly");
sj.setKeystore("testkeystore");
sj.setStorepass("apacheant");
- File jar = new File(getProject().getProperty("test.jar"));
+ File jar = new File(buildRule.getProject().getProperty("test.jar"));
sj.setJar(jar);
assertTrue(sj.isSigned());
}
@@ -84,31 +93,35 @@ public class SignJarTest extends BuildFileTest {
}
}
+ @Test
public void testURLKeystoreFile() {
- executeTarget("urlKeystoreFile");
+ buildRule.executeTarget("urlKeystoreFile");
}
+ @Test
public void testURLKeystoreHTTP() {
- if(!isOffline()) {
- executeTarget("urlKeystoreHTTP");
- }
+ Assume.assumeFalse("Test is set offline", isOffline());
+ buildRule.executeTarget("urlKeystoreHTTP");
}
+ @Test
public void testTsaLocalhost() {
- //only test on java1.5+
- if(JavaEnvUtils.getJavaVersionNumber()>=15) {
- expectBuildException("testTsaLocalhost",
- "no TSA at localhost:0");
- assertLogContaining("java.net.ConnectException");
+ Assume.assumeTrue("Only runs on Java 1.5+", JavaEnvUtils.getJavaVersionNumber()>=15);
+ try {
+ buildRule.executeTarget("testTsaLocalhost");
+ fail("Should have thrown exception - no TSA at localhost:0");
+ } catch(BuildException ex) {
+ assertEquals("jarsigner returned: 1", ex.getMessage());
}
}
/**
* @see bug 50081
*/
+ @Test
public void testSignUnnormalizedJar() throws Exception {
- executeTarget("jar");
- File testJar = new File(getProject().getProperty("test.jar"));
+ buildRule.executeTarget("jar");
+ File testJar = new File(buildRule.getProject().getProperty("test.jar"));
File testJarParent = testJar.getParentFile();
File f = new File(testJarParent,
"../" + testJarParent.getName() + "/"
@@ -116,7 +129,7 @@ public class SignJarTest extends BuildFileTest {
assertFalse(testJar.equals(f));
assertEquals(testJar.getCanonicalPath(), f.getCanonicalPath());
SignJar s = new SignJar();
- s.setProject(getProject());
+ s.setProject(buildRule.getProject());
s.setJar(f);
s.setAlias("testonly");
s.setStorepass("apacheant");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/SleepTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/SleepTest.java
index 63b61afcf..d1487df97 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/SleepTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/SleepTest.java
@@ -18,67 +18,76 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-/**
- * @created 01 May 2001
- */
-public class SleepTest extends BuildFileTest {
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class SleepTest {
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/";
- private final static boolean TRACE=false;
private final static int ERROR_RANGE=1000;
- public SleepTest(String name) {
- super(name);
- }
-
+
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "sleep.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "sleep.xml");
}
+ @Test
public void test1() {
Timer timer=new Timer();
- executeTarget("test1");
+ buildRule.executeTarget("test1");
timer.stop();
- if(TRACE) System.out.println(" test1 elapsed time="+timer.time());
assertTrue(timer.time()>=0);
}
+ @Test
public void test2() {
Timer timer=new Timer();
- executeTarget("test2");
+ buildRule.executeTarget("test2");
timer.stop();
- if(TRACE) System.out.println(" test2 elapsed time="+timer.time());
assertTrue(timer.time()>=0);
}
+ @Test
public void test3() {
Timer timer=new Timer();
- executeTarget("test3");
+ buildRule.executeTarget("test3");
timer.stop();
- if(TRACE) System.out.println(" test3 elapsed time="+timer.time());
assertTrue(timer.time()>=(2000-ERROR_RANGE));
}
+ @Test
public void test4() {
Timer timer=new Timer();
- executeTarget("test3");
+ buildRule.executeTarget("test3");
timer.stop();
- if(TRACE) System.out.println(" test4 elapsed time="+timer.time());
assertTrue(timer.time()>=(2000-ERROR_RANGE) && timer.time()<60000);
}
+ @Test
public void test5() {
- expectBuildException("test5",
- "Negative sleep periods are not supported");
+ try {
+ buildRule.executeTarget("test5");
+ fail("Negative sleep periods are not supported");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test6() {
Timer timer=new Timer();
- executeTarget("test6");
+ buildRule.executeTarget("test6");
timer.stop();
- if(TRACE) System.out.println(" test6 elapsed time="+timer.time());
assertTrue(timer.time()<2000);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java
index 34f356abb..24c4e9de7 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/StyleTest.java
@@ -19,151 +19,177 @@ package org.apache.tools.ant.taskdefs;
import java.io.File;
-import java.io.FileReader;
import java.io.IOException;
-import java.io.Reader;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* TestCases for {@link XSLTProcess} task.
- * TODO merge with {@link XsltTest}?
+ * TODO merge with {@link org.apache.tools.ant.taskdefs.optional.XsltTest}?
* @version 2003-08-05
*/
-public class StyleTest extends BuildFileTest {
-
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+public class StyleTest {
- public StyleTest(String s) {
- super(s);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
- protected void setUp() throws Exception {
- configureProject("src/etc/testcases/taskdefs/style/build.xml");
- //executeTarget("setup");
- //commented out for performance while target is empty
+ @Before
+ public void setUp() throws Exception {
+ buildRule.configureProject("src/etc/testcases/taskdefs/style/build.xml");
}
+ @Test
public void testStyleIsSet() throws Exception {
- expectSpecificBuildException("testStyleIsSet",
- "no stylesheet specified", "specify the " +
- "stylesheet either as a filename in style " +
- "attribute or as a nested resource");
+
+ try {
+ buildRule.executeTarget("testStyleIsSet");
+ fail("Must throws a BuildException: no stylesheet specified");
+ } catch (BuildException ex) {
+ assertEquals("specify the stylesheet either as a filename in style attribute or as a nested resource",
+ ex.getMessage());
+ }
}
+ @Test
public void testTransferParameterSet() throws Exception {
expectFileContains("testTransferParameterSet", // target
- getOutputDir().getAbsoluteFile() + "/out.xml", // file
+ buildRule.getOutputDir().getAbsoluteFile() + "/out.xml", // file
"set='myvalue'"); // exptected string
}
+ @Test
public void testTransferParameterEmpty() throws Exception {
expectFileContains("testTransferParameterEmpty",
- getOutputDir().getAbsoluteFile() + "/out.xml",
+ buildRule.getOutputDir().getAbsoluteFile() + "/out.xml",
"empty=''");
}
+ @Test
public void testTransferParameterUnset() throws Exception {
expectFileContains("testTransferParameterUnset",
- getOutputDir().getAbsoluteFile() + "/out.xml",
+ buildRule.getOutputDir().getAbsoluteFile() + "/out.xml",
"undefined='${value}'");
}
+ @Test
public void testTransferParameterUnsetWithIf() throws Exception {
expectFileContains("testTransferParameterUnsetWithIf",
- getOutputDir().getAbsoluteFile() + "/out.xml",
+ buildRule.getOutputDir().getAbsoluteFile() + "/out.xml",
"undefined='undefined default value'");
}
+ @Test
public void testNewerStylesheet() throws Exception {
expectFileContains("testNewerStylesheet",
- getOutputDir().getAbsoluteFile() + "/out.xml",
+ buildRule.getOutputDir().getAbsoluteFile() + "/out.xml",
"new-value");
}
+ @Test
public void testDefaultMapper() throws Exception {
testDefaultMapper("testDefaultMapper");
}
+ @Test
public void testExplicitFileset() throws Exception {
testDefaultMapper("testExplicitFileset");
}
public void testDefaultMapper(String target) throws Exception {
assertTrue(!(
- new File(getOutputDir().getAbsoluteFile(), "data.html").exists()));
+ new File(buildRule.getOutputDir().getAbsoluteFile(), "data.html").exists()));
expectFileContains(target,
- getOutputDir().getAbsoluteFile() + "/data.html",
+ buildRule.getOutputDir().getAbsoluteFile() + "/data.html",
"set='myvalue'");
}
+ @Test
public void testCustomMapper() throws Exception {
- assertTrue(!new File(getOutputDir().getAbsoluteFile(), "out.xml").exists());
+ assertTrue(!new File(buildRule.getOutputDir().getAbsoluteFile(), "out.xml").exists());
expectFileContains("testCustomMapper",
- getOutputDir().getAbsoluteFile() + "/out.xml",
+ buildRule.getOutputDir().getAbsoluteFile() + "/out.xml",
"set='myvalue'");
}
+ @Test
public void testTypedMapper() throws Exception {
- assertTrue(!new File(getOutputDir().getAbsoluteFile(), "out.xml").exists());
+ assertTrue(!new File(buildRule.getOutputDir().getAbsoluteFile(), "out.xml").exists());
expectFileContains("testTypedMapper",
- getOutputDir().getAbsoluteFile() + "/out.xml",
+ buildRule.getOutputDir().getAbsoluteFile() + "/out.xml",
"set='myvalue'");
}
+ @Test
public void testDirectoryHierarchyWithDirMatching() throws Exception {
- executeTarget("testDirectoryHierarchyWithDirMatching");
- assertTrue(new File(getOutputDir().getAbsoluteFile(), "dest/level1/data.html")
+ buildRule.executeTarget("testDirectoryHierarchyWithDirMatching");
+ assertTrue(new File(buildRule.getOutputDir().getAbsoluteFile(), "dest/level1/data.html")
.exists());
}
+ @Test
public void testDirsWithSpaces() throws Exception {
- executeTarget("testDirsWithSpaces");
- assertTrue(new File(getOutputDir().getAbsoluteFile(), "d est/data.html")
+ buildRule.executeTarget("testDirsWithSpaces");
+ assertTrue(new File(buildRule.getOutputDir().getAbsoluteFile(), "d est/data.html")
.exists());
}
- public void testWithStyleAttrAndResource() throws Exception {
- expectSpecificBuildException("testWithStyleAttrAndResource",
- "Must throws a BuildException", "specify the " +
- "stylesheet either as a filename in style " +
- "attribute or as a nested resource but not " +
- "as both");
+ @Test
+ public void testWithStyleAttrAndResource() {
+ try {
+ buildRule.executeTarget("testWithStyleAttrAndResource");
+ fail("Must throws a BuildException");
+ } catch (BuildException ex) {
+ assertEquals("specify the stylesheet either as a filename in style attribute or as a "
+ + "nested resource but not as both", ex.getMessage());
+ }
}
+ @Test
public void testWithFileResource() throws Exception {
- expectFileContains("testWithFileResource", getOutputDir().getAbsoluteFile() + "/out.xml", "set='value'");
+ expectFileContains("testWithFileResource", buildRule.getOutputDir().getAbsoluteFile() + "/out.xml", "set='value'");
}
+ @Test
public void testWithUrlResource() throws Exception {
- expectFileContains("testWithUrlResource", getOutputDir().getAbsoluteFile() + "/out.xml", "set='value'");
+ expectFileContains("testWithUrlResource", buildRule.getOutputDir().getAbsoluteFile() + "/out.xml", "set='value'");
}
+ @Test
public void testFilenameAsParam() throws Exception {
- executeTarget("testFilenameAsParam");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/one.txt", "filename='one.xml'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/two.txt", "filename='two.xml'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/three.txt", "filename='three.xml'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filename='four.xml'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filedir ='-not-set-'");
+ buildRule.executeTarget("testFilenameAsParam");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/one.txt", "filename='one.xml'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/two.txt", "filename='two.xml'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/three.txt", "filename='three.xml'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filename='four.xml'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filedir ='-not-set-'");
}
+ @Test
public void testFilenameAsParamNoSetting() throws Exception {
- executeTarget("testFilenameAsParamNoSetting");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/one.txt", "filename='-not-set-'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/two.txt", "filename='-not-set-'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/three.txt", "filename='-not-set-'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filename='-not-set-'");
+ buildRule.executeTarget("testFilenameAsParamNoSetting");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/one.txt", "filename='-not-set-'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/two.txt", "filename='-not-set-'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/three.txt", "filename='-not-set-'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filename='-not-set-'");
}
+ @Test
public void testFilenameAndFiledirAsParam() throws Exception {
- executeTarget("testFilenameAndFiledirAsParam");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/one.txt", "filename='one.xml'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/one.txt", "filedir ='.'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filename='four.xml'");
- assertFileContains(getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filedir ='dir'");
+ buildRule.executeTarget("testFilenameAndFiledirAsParam");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/one.txt", "filename='one.xml'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/one.txt", "filedir ='.'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filename='four.xml'");
+ assertFileContains(buildRule.getOutputDir().getAbsoluteFile() + "/dir/four.txt", "filedir ='dir'");
}
@@ -176,21 +202,14 @@ public class StyleTest extends 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);
- }
+ return FileUtilities.getFileContents(new File(filename));
}
private void expectFileContains(
String target, String filename, String contains)
throws IOException
{
- executeTarget(target);
+ buildRule.executeTarget(target);
assertFileContains(filename, contains);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/SubAntTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/SubAntTest.java
index ede8b0e5b..58ee4f3e9 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/SubAntTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/SubAntTest.java
@@ -23,30 +23,40 @@ 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.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.BuildListener;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
-public class SubAntTest extends BuildFileTest {
- public SubAntTest(String name) {
- super(name);
- }
+public class SubAntTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/subant.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/subant.xml");
}
+ @Test
public void testnodirs() {
- project.executeTarget("testnodirs");
- expectLog("testnodirs", "No sub-builds to iterate on");
+ buildRule.executeTarget("testnodirs");
+ assertEquals("No sub-builds to iterate on",buildRule.getLog());
}
// target must be specified
+ @Test
public void testgenericantfile() {
- File dir1 = project.resolveFile(".");
- File dir2 = project.resolveFile("subant/subant-test1");
- File dir3 = project.resolveFile("subant/subant-test2");
+ File dir1 = buildRule.getProject().resolveFile(".");
+ File dir2 = buildRule.getProject().resolveFile("subant/subant-test1");
+ File dir3 = buildRule.getProject().resolveFile("subant/subant-test2");
testBaseDirs("testgenericantfile",
new String[] { dir1.getAbsolutePath(),
@@ -56,14 +66,15 @@ public class SubAntTest extends BuildFileTest {
});
}
+ @Test
public void testantfile() {
- File dir1 = project.resolveFile(".");
+ File dir1 = buildRule.getProject().resolveFile(".");
// basedir of subant/subant-test1/subant.xml is ..
// therefore we expect here the subant/subant-test1 subdirectory
- File dir2 = project.resolveFile("subant/subant-test1");
+ File dir2 = buildRule.getProject().resolveFile("subant/subant-test1");
// basedir of subant/subant-test2/subant.xml is ..
// therefore we expect here the subant subdirectory
- File dir3 = project.resolveFile("subant");
+ File dir3 = buildRule.getProject().resolveFile("subant");
testBaseDirs("testantfile",
new String[] { dir1.getAbsolutePath(),
@@ -74,34 +85,40 @@ public class SubAntTest extends BuildFileTest {
}
+ @Test
public void testMultipleTargets() {
- executeTarget("multipleTargets");
- assertLogContaining("test1-one");
- assertLogContaining("test1-two");
- assertLogContaining("test2-one");
- assertLogContaining("test2-two");
+ buildRule.executeTarget("multipleTargets");
+ assertContains("test1-one", buildRule.getLog());
+ assertContains("test1-two", buildRule.getLog());
+ assertContains("test2-one", buildRule.getLog());
+ assertContains("test2-two", buildRule.getLog());
}
+ @Test
public void testMultipleTargetsOneDoesntExist_FOEfalse() {
- executeTarget("multipleTargetsOneDoesntExist_FOEfalse");
- assertLogContaining("Target \"three\" does not exist in the project \"subant\"");
+ buildRule.executeTarget("multipleTargetsOneDoesntExist_FOEfalse");
+ assertContains("Target \"three\" does not exist in the project \"subant\"", buildRule.getLog());
}
+ @Test
public void testMultipleTargetsOneDoesntExist_FOEtrue() {
- expectBuildExceptionContaining("multipleTargetsOneDoesntExist_FOEtrue",
- "Calling not existent target",
- "Target \"three\" does not exist in the project \"subant\"");
+ try {
+ buildRule.executeTarget("multipleTargetsOneDoesntExist_FOEtrue");
+ fail("BuildException expected: Calling not existent target");
+ } catch (BuildException ex) {
+ assertContains("Target \"three\" does not exist in the project \"subant\"", ex.getMessage());
+ }
}
protected void testBaseDirs(String target, String[] dirs) {
SubAntTest.BasedirChecker bc = new SubAntTest.BasedirChecker(dirs);
- project.addBuildListener(bc);
- executeTarget(target);
+ buildRule.getProject().addBuildListener(bc);
+ buildRule.executeTarget(target);
AssertionFailedError ae = bc.getError();
if (ae != null) {
throw ae;
}
- project.removeBuildListener(bc);
+ buildRule.getProject().removeBuildListener(bc);
}
private class BasedirChecker implements BuildListener {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java
index 331528086..93431dcbc 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/SyncTest.java
@@ -18,115 +18,131 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class SyncTest extends BuildFileTest {
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertTrue;
- public SyncTest(String name) {
- super(name);
- }
+public class SyncTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/sync.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/sync.xml");
}
+ @Test
public void testSimpleCopy() {
- executeTarget("simplecopy");
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget("simplecopy");
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsPresent(d);
- assertTrue(getFullLog().indexOf("dangling") == -1);
+ assertTrue(buildRule.getFullLog().indexOf("dangling") == -1);
}
+ @Test
public void testEmptyCopy() {
- executeTarget("emptycopy");
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget("emptycopy");
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsNotPresent(d);
- String c = getProject().getProperty("dest") + "/a/b/c";
+ String c = buildRule.getProject().getProperty("dest") + "/a/b/c";
assertFileIsNotPresent(c);
- assertTrue(getFullLog().indexOf("dangling") == -1);
+ assertTrue(buildRule.getFullLog().indexOf("dangling") == -1);
}
+ @Test
public void testEmptyDirCopy() {
- executeTarget("emptydircopy");
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget("emptydircopy");
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsNotPresent(d);
- String c = getProject().getProperty("dest") + "/a/b/c";
+ String c = buildRule.getProject().getProperty("dest") + "/a/b/c";
assertFileIsPresent(c);
- assertTrue(getFullLog().indexOf("dangling") == -1);
+ assertTrue(buildRule.getFullLog().indexOf("dangling") == -1);
}
+ @Test
public void testCopyAndRemove() {
testCopyAndRemove("copyandremove");
}
+ @Test
public void testCopyAndRemoveWithFileList() {
testCopyAndRemove("copyandremove-with-filelist");
}
+ @Test
public void testCopyAndRemoveWithZipfileset() {
testCopyAndRemove("copyandremove-with-zipfileset");
}
private void testCopyAndRemove(String target) {
- executeTarget(target);
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget(target);
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsPresent(d);
- String f = getProject().getProperty("dest") + "/e/f";
+ String f = buildRule.getProject().getProperty("dest") + "/e/f";
assertFileIsNotPresent(f);
- assertTrue(getFullLog().indexOf("Removing orphan file:") > -1);
- assertDebuglogContaining("Removed 1 dangling file from");
- assertDebuglogContaining("Removed 1 dangling directory from");
+ assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") > -1);
+ assertContains("Removed 1 dangling file from", buildRule.getFullLog());
+ assertContains("Removed 1 dangling directory from", buildRule.getFullLog());
}
+ @Test
public void testCopyAndRemoveEmptyPreserve() {
- executeTarget("copyandremove-emptypreserve");
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget("copyandremove-emptypreserve");
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsPresent(d);
- String f = getProject().getProperty("dest") + "/e/f";
+ String f = buildRule.getProject().getProperty("dest") + "/e/f";
assertFileIsNotPresent(f);
- assertTrue(getFullLog().indexOf("Removing orphan file:") > -1);
- assertDebuglogContaining("Removed 1 dangling file from");
- assertDebuglogContaining("Removed 1 dangling directory from");
+ assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") > -1);
+ assertContains("Removed 1 dangling file from", buildRule.getFullLog());
+ assertContains("Removed 1 dangling directory from", buildRule.getFullLog());
}
+ @Test
public void testEmptyDirCopyAndRemove() {
- executeTarget("emptydircopyandremove");
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget("emptydircopyandremove");
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsNotPresent(d);
- String c = getProject().getProperty("dest") + "/a/b/c";
+ String c = buildRule.getProject().getProperty("dest") + "/a/b/c";
assertFileIsPresent(c);
- String f = getProject().getProperty("dest") + "/e/f";
+ String f = buildRule.getProject().getProperty("dest") + "/e/f";
assertFileIsNotPresent(f);
- assertTrue(getFullLog().indexOf("Removing orphan directory:") > -1);
- assertDebuglogContaining("NO dangling file to remove from");
- assertDebuglogContaining("Removed 2 dangling directories from");
+ assertTrue(buildRule.getFullLog().indexOf("Removing orphan directory:") > -1);
+ assertContains("NO dangling file to remove from", buildRule.getFullLog());
+ assertContains("Removed 2 dangling directories from", buildRule.getFullLog());
}
+ @Test
public void testCopyNoRemove() {
- executeTarget("copynoremove");
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget("copynoremove");
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsPresent(d);
- String f = getProject().getProperty("dest") + "/e/f";
+ String f = buildRule.getProject().getProperty("dest") + "/e/f";
assertFileIsPresent(f);
- assertTrue(getFullLog().indexOf("Removing orphan file:") == -1);
+ assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") == -1);
}
+ @Test
public void testCopyNoRemoveSelectors() {
- executeTarget("copynoremove-selectors");
- String d = getProject().getProperty("dest") + "/a/b/c/d";
+ buildRule.executeTarget("copynoremove-selectors");
+ String d = buildRule.getProject().getProperty("dest") + "/a/b/c/d";
assertFileIsPresent(d);
- String f = getProject().getProperty("dest") + "/e/f";
+ String f = buildRule.getProject().getProperty("dest") + "/e/f";
assertFileIsPresent(f);
- assertTrue(getFullLog().indexOf("Removing orphan file:") == -1);
+ assertTrue(buildRule.getFullLog().indexOf("Removing orphan file:") == -1);
}
public void assertFileIsPresent(String f) {
assertTrue("Expected file " + f,
- getProject().resolveFile(f).exists());
+ buildRule.getProject().resolveFile(f).exists());
}
public void assertFileIsNotPresent(String f) {
assertTrue("Didn't expect file " + f,
- !getProject().resolveFile(f).exists());
+ !buildRule.getProject().resolveFile(f).exists());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TStampTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TStampTest.java
index 8f915468b..ed7403c7c 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TStampTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TStampTest.java
@@ -22,24 +22,25 @@ import java.util.TimeZone;
import java.util.Date;
import java.text.SimpleDateFormat;
-import junit.framework.TestCase;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Location;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
/**
*
*/
-public class TStampTest extends TestCase {
+public class TStampTest {
protected Tstamp tstamp;
protected Project project;
protected Location location;
- public TStampTest(String s) {
- super(s);
- }
-
- protected void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
location = new Location("test.xml");
project = new Project();
tstamp = new Tstamp();
@@ -47,6 +48,7 @@ public class TStampTest extends TestCase {
tstamp.setProject(project);
}
+ @Test
public void testTimeZone() throws Exception {
Tstamp.CustomFormat format = tstamp.createFormat();
format.setProperty("today");
@@ -68,6 +70,7 @@ public class TStampTest extends TestCase {
* originals
* @throws Exception
*/
+ @Test
public void testWriteOrder() throws Exception {
Tstamp.CustomFormat format = tstamp.createFormat();
format.setProperty("TODAY");
@@ -90,6 +93,7 @@ public class TStampTest extends TestCase {
* originals
* @throws Exception
*/
+ @Test
public void testPrefix() throws Exception {
tstamp.setPrefix("prefix");
tstamp.execute();
@@ -97,8 +101,9 @@ public class TStampTest extends TestCase {
assertNotNull(prop);
}
+ @Test
public void testFormatPrefix() throws Exception {
- Tstamp.CustomFormat format = tstamp.createFormat();
+ Tstamp.CustomFormat format = tstamp.createFormat();
format.setProperty("format");
format.setPattern("HH:mm:ss z");
format.setTimezone("GMT");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TarTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TarTest.java
index ba5aa14a0..c5ba12004 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TarTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TarTest.java
@@ -20,138 +20,190 @@ package org.apache.tools.ant.taskdefs;
import java.io.IOException;
import java.io.File;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.util.FileUtils;
-/**
- */
-public class TarTest extends BuildFileTest {
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
- public TarTest(String name) {
- super(name);
- }
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+public class TarTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/tar.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/tar.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument not specified");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test4() {
- expectBuildException("test4", "tar cannot include itself");
+ try {
+ buildRule.executeTarget("test4");
+ fail("BuildException expected: tar cannot include itself");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
File f
- = new File(getProject().getProperty("output"), "test5.tar");
+ = new File(buildRule.getProject().getProperty("output"), "test5.tar");
if (!f.exists()) {
fail("Tarring a directory failed");
}
}
+ @Test
public void test6() {
- expectBuildException("test6", "Invalid value specified for longfile attribute.");
+ try {
+ buildRule.executeTarget("test6");
+ fail("BuildException expected: Invalid value specified for longfile attribute.");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test7() {
test7("test7");
}
+ @Test
public void test7UsingPlainFileSet() {
test7("test7UsingPlainFileSet");
}
+ @Test
public void test7UsingFileList() {
test7("test7UsingFileList");
}
private void test7(String target) {
- executeTarget(target);
+ buildRule.executeTarget(target);
File f1
- = new File(getProject().getProperty("output"), "untar/test7-prefix");
+ = new File(buildRule.getProject().getProperty("output"), "untar/test7-prefix");
if (!(f1.exists() && f1.isDirectory())) {
fail("The prefix attribute is not working properly.");
}
File f2
- = new File(getProject().getProperty("output"), "untar/test7dir");
+ = new File(buildRule.getProject().getProperty("output"), "untar/test7dir");
if (!(f2.exists() && f2.isDirectory())) {
fail("The prefix attribute is not working properly.");
}
}
+ @Test
public void test8() {
test8("test8");
}
+ @Test
public void test8UsingZipFileset() {
test8("test8UsingZipFileset");
}
+ @Test
public void test8UsingZipFilesetSrc() {
test8("test8UsingZipFilesetSrc");
}
+ @Test
public void test8UsingTarFilesetSrc() {
test8("test8UsingTarFilesetSrc");
}
+ @Test
public void test8UsingZipEntry() {
test8("test8UsingZipEntry");
}
private void test8(String target) {
- executeTarget(target);
+ buildRule.executeTarget(target);
File f1
- = new File(getProject().getProperty("output"), "untar/test8.xml");
+ = new File(buildRule.getProject().getProperty("output"), "untar/test8.xml");
if (! f1.exists()) {
fail("The fullpath attribute or the preserveLeadingSlashes attribute does not work propertly");
}
}
+ @Test
public void test9() {
- expectBuildException("test9", "Invalid value specified for compression attribute.");
+ try {
+ buildRule.executeTarget("test9");
+ fail("BuildException expected: Invalid value specified for compression attribute.");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test10() {
- executeTarget("test10");
+ buildRule.executeTarget("test10");
File f1
- = new File(getProject().getProperty("output"), "untar/test10.xml");
+ = new File(buildRule.getProject().getProperty("output"), "untar/test10.xml");
if (! f1.exists()) {
fail("The fullpath attribute or the preserveLeadingSlashes attribute does not work propertly");
}
}
+ @Test
public void test11() {
- executeTarget("test11");
+ buildRule.executeTarget("test11");
File f1
- = new File(getProject().getProperty("output"), "untar/test11.xml");
+ = new File(buildRule.getProject().getProperty("output"), "untar/test11.xml");
if (! f1.exists()) {
fail("The fullpath attribute or the preserveLeadingSlashes attribute does not work propertly");
}
}
+ @Test
public void testGZipResource() throws IOException {
- executeTarget("testGZipResource");
- assertTrue(FileUtils.getFileUtils()
- .contentEquals(getProject().resolveFile("../asf-logo.gif"),
- new File(getProject().getProperty("output"), "untar/asf-logo.gif.gz")));
+ buildRule.executeTarget("testGZipResource");
+ assertEquals(FileUtilities.getFileContents(buildRule.getProject().resolveFile("../asf-logo.gif")),
+ FileUtilities.getFileContents(new File(buildRule.getProject().getProperty("output"), "untar/asf-logo.gif.gz")));
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java
index 091a39312..eaa8a667d 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefTest.java
@@ -18,60 +18,106 @@
package org.apache.tools.ant.taskdefs;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
-import org.apache.tools.ant.BuildFileTest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
*/
-public class TaskdefTest extends BuildFileTest {
+public class TaskdefTest {
- public TaskdefTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/taskdef.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/taskdef.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument not specified");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test4() {
- expectBuildException("test4", "classname specified doesn't exist");
+ try {
+ buildRule.executeTarget("test4");
+ fail("BuildException expected: classname specified doesn't exist");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test5() {
- expectBuildException("test5", "No public execute() in " + Project.class);
+ try {
+ buildRule.executeTarget("test5");
+ fail("BuildException expected: No public execute() in " + Project.class);
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test5a() {
- executeTarget("test5a");
+ buildRule.executeTarget("test5a");
}
+ @Test
public void test6() {
- expectLog("test6", "simpletask: worked");
+ buildRule.executeTarget("test6");
+ assertEquals("simpletask: worked", buildRule.getLog());
}
+ @Test
public void test7() {
- expectLog("test7", "worked");
+ buildRule.executeTarget("test7");
+ assertEquals("worked", buildRule.getLog());
}
+ @Test
public void testGlobal() {
- expectLog("testGlobal", "worked");
+ buildRule.executeTarget("testGlobal");
+ assertEquals("worked", buildRule.getLog());
}
+ @Test
public void testOverride() {
- executeTarget("testOverride");
- String log = getLog();
+ buildRule.executeTarget("testOverride");
+ String log = buildRule.getLog();
assertTrue("override warning sent",
log.indexOf("Trying to override old definition of task copy") > -1);
assertTrue("task inside target worked",
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefsTest.java
index 5de5ef4e5..9316059ca 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TaskdefsTest.java
@@ -21,7 +21,7 @@ package org.apache.tools.ant.taskdefs;
import org.apache.tools.ant.BuildFileTest;
/**
- * @deprecated use BuildFileTest instead.
+ * @deprecated use {@link org.apache.tools.ant.BuildFileRule} instead.
*/
public abstract class TaskdefsTest extends BuildFileTest {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TestProcess.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TestProcess.java
index 00ebe4b8c..062003fa6 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TestProcess.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TestProcess.java
@@ -18,6 +18,8 @@
package org.apache.tools.ant.taskdefs;
+import org.junit.internal.AssumptionViolatedException;
+
/**
* Interactive Testcase for Processdestroyer.
*
@@ -39,7 +41,11 @@ public class TestProcess
{
while (!done)
{
- try { wait(); } catch (InterruptedException ie) {}
+ try {
+ wait();
+ } catch (InterruptedException ie) {
+ throw new AssumptionViolatedException("Thread interrupted", ie);
+ }
}
}
@@ -53,7 +59,11 @@ public class TestProcess
{
System.out.println(Thread.currentThread().getName());
- try { Thread.sleep(2000); } catch (InterruptedException ie) {}
+ try {
+ Thread.sleep(2000);
+ } catch (InterruptedException ie) {
+ throw new AssumptionViolatedException("Thread interrupted", ie);
+ }
}
synchronized(this)
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TouchTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TouchTest.java
index ea7d499fb..0a968b25a 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TouchTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TouchTest.java
@@ -18,29 +18,39 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
-public class TouchTest extends BuildFileTest {
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class TouchTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
private static String TOUCH_FILE = "src/etc/testcases/taskdefs/touchtest";
/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public TouchTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/touch.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/touch.xml");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
public long getTargetTime() {
@@ -56,22 +66,25 @@ public class TouchTest extends BuildFileTest {
* No real test, simply checks whether the dateformat without
* seconds is accepted - by erroring out otherwise.
*/
+ @Test
public void testNoSeconds() {
- executeTarget("noSeconds");
- long time = getTargetTime();
+ buildRule.executeTarget("noSeconds");
+ getTargetTime();
}
/**
* No real test, simply checks whether the dateformat with
* seconds is accepted - by erroring out otherwise.
*/
+ @Test
public void testSeconds() {
- executeTarget("seconds");
- long time=getTargetTime();
+ buildRule.executeTarget("seconds");
+ getTargetTime();
}
/**
* verify that the millis test sets things up
*/
+ @Test
public void testMillis() {
touchFile("testMillis", 662256000000L);
}
@@ -79,15 +92,17 @@ public class TouchTest extends BuildFileTest {
/**
* verify that the default value defaults to now
*/
+ @Test
public void testNow() {
long now=System.currentTimeMillis();
- executeTarget("testNow");
+ buildRule.executeTarget("testNow");
long time = getTargetTime();
assertTimesNearlyMatch(time,now,5000);
}
/**
* verify that the millis test sets things up
*/
+ @Test
public void test2000() {
touchFile("test2000", 946080000000L);
}
@@ -95,6 +110,7 @@ public class TouchTest extends BuildFileTest {
/**
* test the file list
*/
+ @Test
public void testFilelist() {
touchFile("testFilelist", 662256000000L);
}
@@ -102,6 +118,7 @@ public class TouchTest extends BuildFileTest {
/**
* test the file set
*/
+ @Test
public void testFileset() {
touchFile("testFileset", 946080000000L);
}
@@ -109,6 +126,7 @@ public class TouchTest extends BuildFileTest {
/**
* test the resource collection
*/
+ @Test
public void testResourceCollection() {
touchFile("testResourceCollection", 1662256000000L);
}
@@ -116,37 +134,47 @@ public class TouchTest extends BuildFileTest {
/**
* test the mapped file set
*/
+ @Test
public void testMappedFileset() {
- executeTarget("testMappedFileset");
+ buildRule.executeTarget("testMappedFileset");
}
/**
* test the explicit mapped file set
*/
+ @Test
public void testExplicitMappedFileset() {
- executeTarget("testExplicitMappedFileset");
+ buildRule.executeTarget("testExplicitMappedFileset");
}
/**
* test the mapped file list
*/
+ @Test
public void testMappedFilelist() {
- executeTarget("testMappedFilelist");
+ buildRule.executeTarget("testMappedFilelist");
}
/**
* test the pattern attribute
*/
+ @Test
public void testGoodPattern() {
- executeTarget("testGoodPattern");
+ buildRule.executeTarget("testGoodPattern");
}
/**
* test the pattern attribute again
*/
+ @Test
public void testBadPattern() {
- expectBuildExceptionContaining("testBadPattern",
- "No parsing exception thrown", "Unparseable");
+ try {
+ buildRule.executeTarget("testBadPattern");
+ fail("No parsing exception thrown");
+ } catch (BuildException ex) {
+ assertContains("Unparseable", ex.getMessage());
+ }
+
}
/**
@@ -155,7 +183,7 @@ public class TouchTest extends BuildFileTest {
* @param timestamp
*/
private void touchFile(String targetName, long timestamp) {
- executeTarget(targetName);
+ buildRule.executeTarget(targetName);
long time = getTargetTime();
assertTimesNearlyMatch(timestamp, time);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TypeAdapterTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TypeAdapterTest.java
index 191acabbf..3488f3991 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TypeAdapterTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TypeAdapterTest.java
@@ -20,49 +20,71 @@ package org.apache.tools.ant.taskdefs;
import java.lang.reflect.Method;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.TypeAdapter;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class TypeAdapterTest extends BuildFileTest {
+public class TypeAdapterTest {
- public TypeAdapterTest(String name) {
- super(name);
- }
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/typeadapter.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/typeadapter.xml");
}
+ @Test
public void testTaskAdapter() {
- expectLogContaining("taskadapter", "MyExec called");
+ buildRule.executeTarget("taskadapter");
+ assertContains("MyExec called", buildRule.getLog());
}
+ @Test
public void testRunAdapter() {
- expectLogContaining("runadapter", "MyRunnable called");
+ buildRule.executeTarget("runadapter");
+ assertContains("MyRunnable called", buildRule.getLog());
}
+ @Test
public void testRunAdapterError() {
- expectBuildExceptionContaining(
- "runadaptererror", "xx", "No public run() method in");
+ try {
+ buildRule.executeTarget("runadaptererror");
+ fail("BuildException expected: no public run method");
+ } catch (BuildException ex) {
+ assertContains("No public run() method in", ex.getMessage());
+ }
}
+ @Test
public void testDelay() {
- expectLogContaining("delay", "MyTask called");
+ buildRule.executeTarget("delay");
+ assertContains("MyTask called", buildRule.getLog());
}
+ @Test
public void testOnErrorReport() {
- expectLogContaining("onerror.report",
- "MyTaskNotPresent cannot be found");
+ buildRule.executeTarget("onerror.report");
+ assertContains("MyTaskNotPresent cannot be found", buildRule.getLog());
}
+ @Test
public void testOnErrorIgnore() {
- expectLog("onerror.ignore","");
+ buildRule.executeTarget("onerror.ignore");
+ assertEquals("", buildRule.getLog());
}
public static class MyTask extends Task {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/TypedefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/TypedefTest.java
index 5c2c041b1..bfc11dd48 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/TypedefTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/TypedefTest.java
@@ -18,48 +18,85 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
/**
*/
-public class TypedefTest extends BuildFileTest {
+public class TypedefTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
- public TypedefTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/typedef.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/typedef.xml");
}
+ @Test
public void testEmpty() {
- expectBuildException("empty", "required argument not specified");
+ try {
+ buildRule.executeTarget("empty");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testNoName() {
- expectBuildException("noName", "required argument not specified");
+ try {
+ buildRule.executeTarget("noName");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testNoClassname() {
- expectBuildException("noClassname", "required argument not specified");
+ try {
+ buildRule.executeTarget("noClassname");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testClassNotFound() {
- expectBuildException("classNotFound",
- "classname specified doesn't exist");
+ try {
+ buildRule.executeTarget("classNotFound");
+ fail("BuildException expected: classname specified doesn't exist");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testGlobal() {
- expectLog("testGlobal", "");
- Object ref = project.getReferences().get("global");
+ buildRule.executeTarget("testGlobal");
+ assertEquals("", buildRule.getLog());
+ Object ref = buildRule.getProject().getReferences().get("global");
assertNotNull("ref is not null", ref);
assertEquals("org.example.types.TypedefTestType",
ref.getClass().getName());
}
+ @Test
public void testLocal() {
- expectLog("testLocal", "");
- Object ref = project.getReferences().get("local");
+ buildRule.executeTarget("testLocal");
+ assertEquals("", buildRule.getLog());
+ Object ref = buildRule.getProject().getReferences().get("local");
assertNotNull("ref is not null", ref);
assertEquals("org.example.types.TypedefTestType",
ref.getClass().getName());
@@ -69,19 +106,31 @@ public class TypedefTest extends BuildFileTest {
* test to make sure that one can define a not present
* optional type twice and then have a valid definition.
*/
+ @Test
public void testDoubleNotPresent() {
- expectLogContaining("double-notpresent", "hi");
+ buildRule.executeTarget("double-notpresent");
+ assertContains("hi", buildRule.getLog());
}
+ @Test
public void testNoResourceOnErrorFailAll(){
- this.expectBuildExceptionContaining("noresourcefailall","the requested resource does not exist","Could not load definitions from resource ");
+ try {
+ buildRule.executeTarget("noresourcefailall");
+ fail("BuildException expected: the requested resource does not exist");
+ } catch (BuildException ex) {
+ assertContains("Could not load definitions from resource ", ex.getMessage());
+ }
}
+ @Test
public void testNoResourceOnErrorFail(){
- expectLogContaining("noresourcefail","Could not load definitions from resource ");
+ buildRule.executeTarget("noresourcefail");
+ assertContains("Could not load definitions from resource ", buildRule.getLog());
}
+ @Test
public void testNoResourceOnErrorNotFail(){
- expectLogContaining("noresourcenotfail","Could not load definitions from resource ");
+ buildRule.executeTarget("noresourcenotfail");
+ assertContains("Could not load definitions from resource ", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/UntarTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/UntarTest.java
index ae7176adf..5e197dfbf 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/UntarTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/UntarTest.java
@@ -17,75 +17,97 @@
*/
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
-/**
- */
-public class UntarTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
- /** Utilities used for file operations */
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public UntarTest(String name) {
- super(name);
- }
+public class UntarTest {
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/untar.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/untar.xml");
}
+ @Test
public void testRealTest() throws java.io.IOException {
testLogoExtraction("realTest");
}
+ @Test
public void testRealGzipTest() throws java.io.IOException {
testLogoExtraction("realGzipTest");
}
+ @Test
public void testRealBzip2Test() throws java.io.IOException {
testLogoExtraction("realBzip2Test");
}
+ @Test
public void testTestTarTask() throws java.io.IOException {
testLogoExtraction("testTarTask");
}
+ @Test
public void testTestGzipTarTask() throws java.io.IOException {
testLogoExtraction("testGzipTarTask");
}
+ @Test
public void testTestBzip2TarTask() throws java.io.IOException {
testLogoExtraction("testBzip2TarTask");
}
+ @Test
public void testSrcDirTest() {
- expectBuildException("srcDirTest", "Src cannot be a directory.");
+ try {
+ buildRule.executeTarget("srcDirTest");
+ fail("Src cannot be a directory.");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testEncoding() {
- expectSpecificBuildException("encoding",
- " overrides setEncoding.",
- "The untar task doesn't support the "
- + "encoding attribute");
+ try {
+ buildRule.executeTarget("encoding");
+ fail(" overrides setEncoding.");
+ } catch (BuildException ex) {
+ assertEquals("The untar task doesn't support the encoding attribute", ex.getMessage());
+ }
}
+ @Test
public void testResourceCollection() throws java.io.IOException {
testLogoExtraction("resourceCollection");
}
private void testLogoExtraction(String target) throws java.io.IOException {
- executeTarget(target);
- assertTrue(FILE_UTILS.contentEquals(project.resolveFile("../asf-logo.gif"),
- new File(getProject().getProperty("output"), "untar/" +
- "asf-logo.gif")));
+ buildRule.executeTarget(target);
+ assertEquals(FileUtilities.getFileContents(buildRule.getProject().resolveFile("../asf-logo.gif")),
+ FileUtilities.getFileContents(new File(buildRule.getProject().getProperty("output"), "untar/asf-logo.gif")));
+
}
+ @Test
public void testDocumentationClaimsOnCopy() {
- executeTarget("testDocumentationClaimsOnCopy");
- assertFalse(new File(getProject().getProperty("output"), "untar/1/foo").exists());
- assertTrue(new File(getProject().getProperty("output"), "untar/2/bar").exists());
+ buildRule.executeTarget("testDocumentationClaimsOnCopy");
+ assertFalse(new File(buildRule.getProject().getProperty("output"), "untar/1/foo").exists());
+ assertTrue(new File(buildRule.getProject().getProperty("output"), "untar/2/bar").exists());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/UnzipTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/UnzipTest.java
index 21edc0cc9..ad99620ea 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/UnzipTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/UnzipTest.java
@@ -17,42 +17,65 @@
*/
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
import java.io.IOException;
-/**
- */
-public class UnzipTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
- /** Utilities used for file operations */
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
+public class UnzipTest {
- public UnzipTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/unzip.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/unzip.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "required argument not specified");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testRealTest() throws java.io.IOException {
- executeTarget("realTest");
+ buildRule.executeTarget("realTest");
assertLogoUncorrupted();
}
@@ -61,100 +84,113 @@ public class UnzipTest extends BuildFileTest {
* @throws IOException
*/
private void assertLogoUncorrupted() throws IOException {
- assertTrue(FILE_UTILS.contentEquals(project.resolveFile("../asf-logo.gif"),
- new File(getProject().getProperty("output"), "asf-logo.gif")));
+ assertEquals(FileUtilities.getFileContents(buildRule.getProject().resolveFile("../asf-logo.gif")),
+ FileUtilities.getFileContents(new File(buildRule.getProject().getProperty("output"), "asf-logo.gif")));
+
}
+ @Test
public void testTestZipTask() throws java.io.IOException {
- executeTarget("testZipTask");
+ buildRule.executeTarget("testZipTask");
assertLogoUncorrupted();
}
+ @Test
public void testTestUncompressedZipTask() throws java.io.IOException {
- executeTarget("testUncompressedZipTask");
+ buildRule.executeTarget("testUncompressedZipTask");
assertLogoUncorrupted();
}
/*
* PR 11100
*/
+ @Test
public void testPatternSetExcludeOnly() {
- executeTarget("testPatternSetExcludeOnly");
- assertFileMissing("1/foo is excluded", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileExists("2/bar is not excluded", getProject().getProperty("output") + "/unziptestout/2/bar");
+ buildRule.executeTarget("testPatternSetExcludeOnly");
+ assertFileMissing("1/foo is excluded", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileExists("2/bar is not excluded", buildRule.getProject().getProperty("output") + "/unziptestout/2/bar");
}
/*
* PR 11100
*/
+ @Test
public void testPatternSetIncludeOnly() {
- executeTarget("testPatternSetIncludeOnly");
- assertFileMissing("1/foo is not included", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileExists("2/bar is included", getProject().getProperty("output") + "/unziptestout/2/bar");
+ buildRule.executeTarget("testPatternSetIncludeOnly");
+ assertFileMissing("1/foo is not included", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileExists("2/bar is included", buildRule.getProject().getProperty("output") + "/unziptestout/2/bar");
}
/*
* PR 11100
*/
+ @Test
public void testPatternSetIncludeAndExclude() {
- executeTarget("testPatternSetIncludeAndExclude");
- assertFileMissing("1/foo is not included", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileMissing("2/bar is excluded", getProject().getProperty("output") + "/unziptestout/2/bar");
+ buildRule.executeTarget("testPatternSetIncludeAndExclude");
+ assertFileMissing("1/foo is not included", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileMissing("2/bar is excluded", buildRule.getProject().getProperty("output") + "/unziptestout/2/bar");
}
/*
* PR 38973
*/
+ @Test
public void testTwoPatternSets() {
- executeTarget("testTwoPatternSets");
- assertFileMissing("1/foo is not included", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileExists("2/bar is included", getProject().getProperty("output") + "/unziptestout/2/bar");
+ buildRule.executeTarget("testTwoPatternSets");
+ assertFileMissing("1/foo is not included", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileExists("2/bar is included", buildRule.getProject().getProperty("output") + "/unziptestout/2/bar");
}
/*
* PR 38973
*/
+ @Test
public void testTwoPatternSetsWithExcludes() {
- executeTarget("testTwoPatternSetsWithExcludes");
- assertFileMissing("1/foo is not included", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileMissing("2/bar is excluded", getProject().getProperty("output") + "/unziptestout/2/bar");
+ buildRule.executeTarget("testTwoPatternSetsWithExcludes");
+ assertFileMissing("1/foo is not included", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileMissing("2/bar is excluded", buildRule.getProject().getProperty("output") + "/unziptestout/2/bar");
}
/*
* PR 16213
*/
- public void XtestSelfExtractingArchive() {
+ @Test
+ @Ignore("we lack a self extracting archive that we are allowed to distribute - see PR 49080")
+ public void testSelfExtractingArchive() {
// disabled because we lack a self extracting archive that we
// are allowed to distribute - see PR 49080
- executeTarget("selfExtractingArchive");
+ buildRule.executeTarget("selfExtractingArchive");
}
/*
* PR 20969
*/
+ @Test
public void testPatternSetSlashOnly() {
- executeTarget("testPatternSetSlashOnly");
- assertFileMissing("1/foo is not included", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileExists("\"2/bar is included", getProject().getProperty("output") + "/unziptestout/2/bar");
+ buildRule.executeTarget("testPatternSetSlashOnly");
+ assertFileMissing("1/foo is not included", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileExists("\"2/bar is included", buildRule.getProject().getProperty("output") + "/unziptestout/2/bar");
}
/*
* PR 10504
*/
+ @Test
public void testEncoding() {
- executeTarget("encodingTest");
- assertFileExists("foo has been properly named", getProject().getProperty("output") + "/unziptestout/foo");
+ buildRule.executeTarget("encodingTest");
+ assertFileExists("foo has been properly named", buildRule.getProject().getProperty("output") + "/unziptestout/foo");
}
/*
* PR 21996
*/
+ @Test
public void testFlattenMapper() {
- executeTarget("testFlattenMapper");
- assertFileMissing("1/foo is not flattened", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileExists("foo is flattened", getProject().getProperty("output") + "/unziptestout/foo");
+ buildRule.executeTarget("testFlattenMapper");
+ assertFileMissing("1/foo is not flattened", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileExists("foo is flattened", buildRule.getProject().getProperty("output") + "/unziptestout/foo");
}
/**
@@ -164,7 +200,7 @@ public class UnzipTest extends BuildFileTest {
*/
private void assertFileExists(String message, String filename) {
assertTrue(message,
- getProject().resolveFile(filename).exists());
+ buildRule.getProject().resolveFile(filename).exists());
}
/**
@@ -175,31 +211,40 @@ public class UnzipTest extends BuildFileTest {
*/
private void assertFileMissing(String message, String filename) {
assertTrue(message,
- !getProject().resolveFile(filename).exists());
+ !buildRule.getProject().resolveFile(filename).exists());
}
/**
* PR 21996
*/
+ @Test
public void testGlobMapper() {
- executeTarget("testGlobMapper");
- assertFileMissing("1/foo is not mapped", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileExists("1/foo is mapped", getProject().getProperty("output") + "/unziptestout/1/foo.txt");
+ buildRule.executeTarget("testGlobMapper");
+ assertFileMissing("1/foo is not mapped", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileExists("1/foo is mapped", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo.txt");
}
+ @Test
public void testTwoMappers() {
- expectBuildException("testTwoMappers",Expand.ERROR_MULTIPLE_MAPPERS);
+ try {
+ buildRule.executeTarget("testTwoMappers");
+ fail("BuildException expected: " + Expand.ERROR_MULTIPLE_MAPPERS);
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void testResourceCollections() {
- executeTarget("testResourceCollection");
+ buildRule.executeTarget("testResourceCollection");
assertFileExists("junit.jar has been extracted",
- getProject().getProperty("output") + "/unziptestout/junit/framework/Assert.class");
+ buildRule.getProject().getProperty("output") + "/unziptestout/junit/framework/Assert.class");
}
+ @Test
public void testDocumentationClaimsOnCopy() {
- executeTarget("testDocumentationClaimsOnCopy");
- assertFileMissing("1/foo is excluded", getProject().getProperty("output") + "/unziptestout/1/foo");
- assertFileExists("2/bar is not excluded", getProject().getProperty("output") + "/unziptestout/2/bar");
+ buildRule.executeTarget("testDocumentationClaimsOnCopy");
+ assertFileMissing("1/foo is excluded", buildRule.getProject().getProperty("output") + "/unziptestout/1/foo");
+ assertFileExists("2/bar is not excluded", buildRule.getProject().getProperty("output") + "/unziptestout/2/bar");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/UpToDateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/UpToDateTest.java
index 2e8ffa44f..b9677c4b7 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/UpToDateTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/UpToDateTest.java
@@ -18,35 +18,60 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.util.FileUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class UpToDateTest extends BuildFileTest {
+import java.io.File;
- public UpToDateTest(String name) {
- super(name);
- }
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assume.assumeTrue;
+
+public class UpToDateTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/uptodate.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/uptodate.xml");
+ buildRule.executeTarget("setUp");
+ File srcDir = buildRule.getProject().resolveFile("source");
+ assumeTrue("Could not change modification timestamp of source directory",
+ srcDir.setLastModified(srcDir.lastModified()
+ - (3 * FileUtils.getFileUtils().getFileTimestampGranularity())));
}
+ @After
public void tearDown() {
- executeTarget("tearDown");
+ buildRule.executeTarget("tearDown");
}
+ @Test
public void testFilesetUpToDate() {
- expectPropertySet("testFilesetUpToDate", "foo");
+ buildRule.executeTarget("testFilesetUpToDate");
+ assertEquals("true", buildRule.getProject().getProperty("foo"));
}
+ @Test
public void testFilesetOutOfDate() {
- expectPropertyUnset("testFilesetOutOfDate", "foo");
+ buildRule.executeTarget("testFilesetOutOfDate");
+ assertNull(buildRule.getProject().getProperty("foo"));
}
+ @Test
public void testRCUpToDate() {
- expectPropertySet("testRCUpToDate", "foo");
+ buildRule.executeTarget("testRCUpToDate");
+ assertEquals("true", buildRule.getProject().getProperty("foo"));
}
+ @Test
public void testRCOutOfDate() {
- expectPropertyUnset("testRCOutOfDate", "foo");
+ buildRule.executeTarget("testRCOutOfDate");
+ assertNull(buildRule.getProject().getProperty("foo"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/WarTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/WarTest.java
index d3554ca90..1513ac753 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/WarTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/WarTest.java
@@ -20,30 +20,36 @@ package org.apache.tools.ant.taskdefs;
import java.io.File;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
/**
* Testcase for the war task
*
*/
-public class WarTest extends BuildFileTest {
+public class WarTest {
public static final String TEST_BUILD_FILE
= "src/etc/testcases/taskdefs/war.xml";
- public WarTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(TEST_BUILD_FILE);
+ buildRule.configureProject(TEST_BUILD_FILE);
}
/**
* Test direct dependency removal
*/
+ @Test
public void testLibRefs() {
- executeTarget("testlibrefs");
- File f = new File(getOutputDir(), "WEB-INF/lib/war.xml");
+ buildRule.executeTarget("testlibrefs");
+ File f = new File(buildRule.getOutputDir(), "WEB-INF/lib/war.xml");
assertTrue("File has been put into lib", f.exists());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/WhichResourceTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/WhichResourceTest.java
index 61854e53f..8e282b3a0 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/WhichResourceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/WhichResourceTest.java
@@ -18,32 +18,41 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class WhichResourceTest extends BuildFileTest {
+import static org.junit.Assert.assertNotNull;
+
+public class WhichResourceTest {
public static final String TEST_BUILD_FILE
= "src/etc/testcases/taskdefs/whichresource.xml";
- public WhichResourceTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject(TEST_BUILD_FILE);
+ buildRule.configureProject(TEST_BUILD_FILE);
}
+ @Test
public void testClassname() {
- executeTarget("testClassname");
- assertNotNull(getProject().getProperty("antmain"));
+ buildRule.executeTarget("testClassname");
+ assertNotNull(buildRule.getProject().getProperty("antmain"));
}
+ @Test
public void testResourcename() {
- executeTarget("testResourcename");
- assertNotNull(getProject().getProperty("defaults"));
+ buildRule.executeTarget("testResourcename");
+ assertNotNull(buildRule.getProject().getProperty("defaults"));
}
+ @Test
public void testResourcenameWithLeadingSlash() {
- executeTarget("testResourcenameWithLeadingSlash");
- assertNotNull(getProject().getProperty("defaults"));
+ buildRule.executeTarget("testResourcenameWithLeadingSlash");
+ assertNotNull(buildRule.getProject().getProperty("defaults"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java
index 1a9f39f1f..89069173b 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java
@@ -27,95 +27,116 @@ import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class XmlPropertyTest extends BuildFileTest {
+public class XmlPropertyTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public XmlPropertyTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/xmlproperty.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/xmlproperty.xml");
}
+ @Test
public void testFile() {
testProperties("test");
}
+ @Test
public void testResource() {
testProperties("testResource");
}
private void testProperties(String target) {
- executeTarget(target);
- assertEquals("true", getProject().getProperty("root-tag(myattr)"));
- assertEquals("Text", getProject().getProperty("root-tag.inner-tag"));
+ buildRule.executeTarget(target);
+ assertEquals("true", buildRule.getProject().getProperty("root-tag(myattr)"));
+ assertEquals("Text", buildRule.getProject().getProperty("root-tag.inner-tag"));
assertEquals("val",
- getProject().getProperty("root-tag.inner-tag(someattr)"));
- assertEquals("false", getProject().getProperty("root-tag.a2.a3.a4"));
+ buildRule.getProject().getProperty("root-tag.inner-tag(someattr)"));
+ assertEquals("false", buildRule.getProject().getProperty("root-tag.a2.a3.a4"));
assertEquals("CDATA failed",
- "", getProject().getProperty("root-tag.cdatatag"));
+ "", buildRule.getProject().getProperty("root-tag.cdatatag"));
}
+ @Test
public void testDTD() {
- executeTarget("testdtd");
- assertEquals("Text", getProject().getProperty("root-tag.inner-tag"));
+ buildRule.executeTarget("testdtd");
+ assertEquals("Text", buildRule.getProject().getProperty("root-tag.inner-tag"));
}
- public void testNone () {
+ @Test
+ public void testNone () throws IOException {
doTest("testNone", false, false, false, false, false);
}
- public void testKeeproot() {
+ @Test
+ public void testKeeproot() throws IOException {
doTest("testKeeproot", true, false, false, false, false);
}
- public void testCollapse () {
+ @Test
+ public void testCollapse () throws IOException {
doTest("testCollapse", false, true, false, false, false);
}
- public void testSemantic () {
+ @Test
+ public void testSemantic () throws IOException {
doTest("testSemantic", false, false, true, false, false);
}
- public void testKeeprootCollapse () {
+ @Test
+ public void testKeeprootCollapse () throws IOException {
doTest("testKeeprootCollapse", true, true, false, false, false);
}
- public void testKeeprootSemantic () {
+ @Test
+ public void testKeeprootSemantic () throws IOException {
doTest("testKeeprootSemantic", true, false, true, false, false);
}
- public void testCollapseSemantic () {
+ @Test
+ public void testCollapseSemantic () throws IOException {
doTest("testCollapseSemantic", false, true, true, false, false);
}
- public void testKeeprootCollapseSemantic () {
+ @Test
+ public void testKeeprootCollapseSemantic () throws IOException {
doTest("testKeeprootCollapseSemantic", true, true, true, false, false);
}
- public void testInclude () {
+ @Test
+ public void testInclude () throws IOException {
doTest("testInclude", false, false, false, true, false);
}
- public void testSemanticInclude () {
+ @Test
+ public void testSemanticInclude () throws IOException {
doTest("testSemanticInclude", false, false, true, true, false);
}
- public void testSemanticLocal () {
+ @Test
+ public void testSemanticLocal () throws IOException {
doTest("testSemanticInclude", false, false, true, false, true);
}
+ @Test
public void testNeedsCatalog() {
- executeTarget("testneedscat");
- assertEquals("true", getProject().getProperty("skinconfig.foo"));
+ buildRule.executeTarget("testneedscat");
+ assertEquals("true", buildRule.getProject().getProperty("skinconfig.foo"));
}
/**
@@ -123,7 +144,7 @@ public class XmlPropertyTest extends BuildFileTest {
* goldfile)
*/
private void doTest(String msg, boolean keepRoot, boolean collapse,
- boolean semantic, boolean include, boolean localRoot) {
+ boolean semantic, boolean include, boolean localRoot) throws IOException {
Enumeration iter =
getFiles(new File(System.getProperty("root"), "src/etc/testcases/taskdefs/xmlproperty/inputs"));
while (iter.hasMoreElements()) {
@@ -137,49 +158,45 @@ public class XmlPropertyTest extends BuildFileTest {
workingDir = FILE_UTILS.resolveFile(new File("."), ".");
}
- try {
- File propertyFile = getGoldfile(inputFile, keepRoot, collapse,
- semantic, include, localRoot);
- if (!propertyFile.exists()) {
+ File propertyFile = getGoldfile(inputFile, keepRoot, collapse,
+ semantic, include, localRoot);
+ if (!propertyFile.exists()) {
// System.out.println("Skipping as "
// + propertyFile.getAbsolutePath()
// + ") doesn't exist.");
- continue;
- }
+ continue;
+ }
- // System.out.println(msg + " (" + propertyFile.getName() + ") in (" + workingDir + ")");
+ // System.out.println(msg + " (" + propertyFile.getName() + ") in (" + workingDir + ")");
- Project p = new Project();
+ Project p = new Project();
- XmlProperty xmlproperty = new XmlProperty();
- xmlproperty.setProject(p);
- xmlproperty.setFile(inputFile);
+ XmlProperty xmlproperty = new XmlProperty();
+ xmlproperty.setProject(p);
+ xmlproperty.setFile(inputFile);
- xmlproperty.setKeeproot(keepRoot);
- xmlproperty.setCollapseAttributes(collapse);
- xmlproperty.setSemanticAttributes(semantic);
- xmlproperty.setIncludeSemanticAttribute(include);
- xmlproperty.setRootDirectory(workingDir);
+ xmlproperty.setKeeproot(keepRoot);
+ xmlproperty.setCollapseAttributes(collapse);
+ xmlproperty.setSemanticAttributes(semantic);
+ xmlproperty.setIncludeSemanticAttribute(include);
+ xmlproperty.setRootDirectory(workingDir);
- // Set a property on the project to make sure that loading
- // a property with the same name from an xml file will
- // *not* change it.
- p.setNewProperty("override.property.test", "foo");
+ // Set a property on the project to make sure that loading
+ // a property with the same name from an xml file will
+ // *not* change it.
+ p.setNewProperty("override.property.test", "foo");
- xmlproperty.execute();
+ xmlproperty.execute();
- Properties props = new Properties();
- props.load(new FileInputStream(propertyFile));
+ Properties props = new Properties();
+ props.load(new FileInputStream(propertyFile));
- //printProperties(p.getProperties());
+ //printProperties(p.getProperties());
- ensureProperties(msg, inputFile, workingDir, p, props);
- ensureReferences(msg, inputFile, p.getReferences());
+ ensureProperties(msg, inputFile, workingDir, p, props);
+ ensureReferences(msg, inputFile, p.getReferences());
- } catch (IOException ex) {
- fail(ex.toString());
- }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/XmlnsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/XmlnsTest.java
index 7ba1050bd..590a4db9e 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/XmlnsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/XmlnsTest.java
@@ -18,44 +18,65 @@
package org.apache.tools.ant.taskdefs;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Task;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
-/**
- */
-public class XmlnsTest extends BuildFileTest {
- public XmlnsTest(String name) {
- super(name);
- }
+public class XmlnsTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/xmlns.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/xmlns.xml");
}
+ @Test
public void testXmlns() {
- expectLog("xmlns", "MyTask called");
+ buildRule.executeTarget("xmlns");
+ assertEquals("MyTask called", buildRule.getLog());
}
+ @Test
public void testXmlnsFile() {
- expectLog("xmlns.file", "MyTask called");
+ buildRule.executeTarget("xmlns.file");
+ assertEquals("MyTask called", buildRule.getLog());
}
+ @Test
public void testCore() {
- expectLog("core", "MyTask called");
+ buildRule.executeTarget("core");
+ assertEquals("MyTask called", buildRule.getLog());
}
+ @Test
public void testExcluded() {
- expectBuildExceptionContaining(
- "excluded", "excluded uri",
- "Attempt to use a reserved URI ant:notallowed");
+ try {
+ buildRule.executeTarget("excluded");
+ fail("BuildException expected: excluded uri");
+ } catch (BuildException ex) {
+ assertEquals("Attempt to use a reserved URI ant:notallowed", ex.getMessage());
+ }
}
+ @Test
public void testOther() {
- expectLog("other", "a message");
+ buildRule.executeTarget("other");
+ assertEquals("a message", buildRule.getLog());
}
+ @Test
public void testNsAttributes() {
- expectLog("ns.attributes", "hello world");
+ buildRule.executeTarget("ns.attributes");
+ assertEquals("hello world", buildRule.getLog());
}
public static class MyTask extends Task {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ZipExtraFieldTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ZipExtraFieldTest.java
index da1b23d7a..c5a42162e 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ZipExtraFieldTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ZipExtraFieldTest.java
@@ -22,11 +22,9 @@ import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
-import junit.framework.TestCase;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceCollection;
@@ -36,9 +34,15 @@ import org.apache.tools.zip.Zip64ExtendedInformationExtraField;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipExtraField;
import org.apache.tools.zip.ZipFile;
+import org.junit.Test;
-public class ZipExtraFieldTest extends TestCase {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+public class ZipExtraFieldTest {
+
+ @Test
public void testPreservesExtraFields() throws IOException {
testExtraField(new Zip(), true);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/ZipTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/ZipTest.java
index b9e9cf496..5a7a35905 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/ZipTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/ZipTest.java
@@ -24,39 +24,81 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.zip.UnixStat;
-
-/**
- */
-public class ZipTest extends BuildFileTest {
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+
+public class ZipTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
//instance variable to allow cleanup
ZipFile zfPrefixAddsDir = null;
- public ZipTest(String name) {
- super(name);
- }
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/zip.xml");
- executeTarget("setUp");
+ buildRule.configureProject("src/etc/testcases/taskdefs/zip.xml");
+ buildRule.executeTarget("setUp");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "required argument not specified");
+ try {
+ buildRule.executeTarget("test2");
+ fail("BuildException expected: required argument not specified");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "zip cannot include itself");
+ try {
+ buildRule.executeTarget("test3");
+ fail("BuildException expected: zip cannot include itself");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
}
- // public void test4() {
- // expectBuildException("test4", "zip cannot include itself");
- // }
+ @Test
+ @Ignore("Previously commented out")
+ public void test4() {
+ try {
+ buildRule.executeTarget("test4");
+ fail("BuildException expected: zip cannot include itself");
+ } catch (BuildException ex) {
+ //TODO assert value
+ }
+ }
+ @After
public void tearDown() {
try {
if ( zfPrefixAddsDir != null) {
@@ -66,35 +108,35 @@ public class ZipTest extends BuildFileTest {
} catch (IOException e) {
//ignored
}
- try {
- super.tearDown();
- } catch (Exception exc) {
- System.err.println(exc.getMessage());
- }
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
+ @Test
public void test6() {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
}
+ @Test
public void test7() {
- executeTarget("test7");
+ buildRule.executeTarget("test7");
}
+ @Test
public void test8() {
- executeTarget("test8");
+ buildRule.executeTarget("test8");
}
+ @Test
public void testZipgroupfileset() throws IOException {
- executeTarget("testZipgroupfileset");
+ buildRule.executeTarget("testZipgroupfileset");
- ZipFile zipFile = new ZipFile(new File(getProject().getProperty("output"), "zipgroupfileset.zip"));
+ ZipFile zipFile = new ZipFile(new File(buildRule.getProject().getProperty("output"), "zipgroupfileset.zip"));
assertTrue(zipFile.getEntry("ant.xml") != null);
assertTrue(zipFile.getEntry("optional/jspc.xml") != null);
@@ -106,19 +148,23 @@ public class ZipTest extends BuildFileTest {
zipFile.close();
}
+ @Test
public void testUpdateNotNecessary() {
- executeTarget("testUpdateNotNecessary");
- assertEquals(-1, getLog().indexOf("Updating"));
+ buildRule.executeTarget("testUpdateNotNecessary");
+ assertEquals(-1, buildRule.getLog().indexOf("Updating"));
}
+ @Test
public void testUpdateIsNecessary() {
- expectLogContaining("testUpdateIsNecessary", "Updating");
+ buildRule.executeTarget("testUpdateIsNecessary");
+ assertContains("Updating", buildRule.getLog());
}
// Bugzilla Report 18403
+ @Test
public void testPrefixAddsDir() throws IOException {
- executeTarget("testPrefixAddsDir");
- File archive = new File(getProject().getProperty("output"), "test3.zip");
+ buildRule.executeTarget("testPrefixAddsDir");
+ File archive = new File(buildRule.getProject().getProperty("output"), "test3.zip");
zfPrefixAddsDir = new ZipFile(archive);
ZipEntry ze = zfPrefixAddsDir.getEntry("test/");
assertNotNull("test/ has been added", ze);
@@ -126,42 +172,52 @@ public class ZipTest extends BuildFileTest {
}
// Bugzilla Report 19449
- public void testFilesOnlyDoesntCauseRecreate()
- throws InterruptedException {
- executeTarget("testFilesOnlyDoesntCauseRecreateSetup");
- long l = new File(getProject().getProperty("output"), "test3.zip").lastModified();
- Thread.sleep(3000);
- executeTarget("testFilesOnlyDoesntCauseRecreate");
- assertEquals(l, new File(getProject().getProperty("output"), "test3.zip").lastModified());
+ @Test
+ public void testFilesOnlyDoesntCauseRecreate() {
+ buildRule.executeTarget("testFilesOnlyDoesntCauseRecreateSetup");
+ File testFile = new File(buildRule.getOutputDir(), "test3.zip");
+ assumeTrue("Could not change file modification time",
+ testFile.setLastModified(testFile.lastModified() - (FileUtils.getFileUtils().getFileTimestampGranularity() * 5)));
+ long l = testFile.lastModified();
+
+ buildRule.executeTarget("testFilesOnlyDoesntCauseRecreate");
+ assertEquals(l, testFile.lastModified());
}
// Bugzilla Report 22865
+ @Test
public void testEmptySkip() {
- executeTarget("testEmptySkip");
+ buildRule.executeTarget("testEmptySkip");
}
// Bugzilla Report 30365
+ @Test
public void testZipEmptyDir() {
- executeTarget("zipEmptyDir");
+ buildRule.executeTarget("zipEmptyDir");
}
// Bugzilla Report 40258
+ @Test
public void testZipEmptyDirFilesOnly() {
- executeTarget("zipEmptyDirFilesOnly");
+ buildRule.executeTarget("zipEmptyDirFilesOnly");
}
+ @Test
public void testZipEmptyCreate() {
- expectLogContaining("zipEmptyCreate", "Note: creating empty");
+ buildRule.executeTarget("zipEmptyCreate");
+ assertContains("Note: creating empty", buildRule.getLog());
}
// Bugzilla Report 25513
+ @Test
public void testCompressionLevel() {
- executeTarget("testCompressionLevel");
+ buildRule.executeTarget("testCompressionLevel");
}
// Bugzilla Report 33412
- public void testDefaultExcludesAndUpdate()
+ @Test
+ public void testDefaultExcludesAndUpdate()
throws ZipException, IOException {
- executeTarget("testDefaultExcludesAndUpdate");
+ buildRule.executeTarget("testDefaultExcludesAndUpdate");
ZipFile f = null;
try {
- f = new ZipFile(new File(getProject().getProperty("output"), "test3.zip"));
+ f = new ZipFile(new File(buildRule.getProject().getProperty("output"), "test3.zip"));
assertNotNull("ziptest~ should be included",
f.getEntry("ziptest~"));
} finally {
@@ -171,19 +227,22 @@ public class ZipTest extends BuildFileTest {
}
}
+ @Test
public void testFileResource() {
- executeTarget("testFileResource");
+ buildRule.executeTarget("testFileResource");
}
+ @Test
public void testNonFileResource() {
- executeTarget("testNonFileResource");
+ buildRule.executeTarget("testNonFileResource");
}
+ @Test
public void testTarFileSet() throws IOException {
- executeTarget("testTarFileSet");
+ buildRule.executeTarget("testTarFileSet");
org.apache.tools.zip.ZipFile zf = null;
try {
- zf = new org.apache.tools.zip.ZipFile(new File(getProject().getProperty("output"), "test3.zip"));
+ zf = new org.apache.tools.zip.ZipFile(new File(buildRule.getProject().getProperty("output"), "test3.zip"));
org.apache.tools.zip.ZipEntry ze = zf.getEntry("asf-logo.gif");
assertEquals(UnixStat.FILE_FLAG | 0446, ze.getUnixMode());
} finally {
@@ -193,11 +252,12 @@ public class ZipTest extends BuildFileTest {
}
}
+ @Test
public void testRewriteZeroPermissions() throws IOException {
- executeTarget("rewriteZeroPermissions");
+ buildRule.executeTarget("rewriteZeroPermissions");
org.apache.tools.zip.ZipFile zf = null;
try {
- zf = new org.apache.tools.zip.ZipFile(new File(getProject().getProperty("output"), "test3.zip"));
+ zf = new org.apache.tools.zip.ZipFile(new File(buildRule.getProject().getProperty("output"), "test3.zip"));
org.apache.tools.zip.ZipEntry ze = zf.getEntry("testdir/test.txt");
assertEquals(UnixStat.FILE_FLAG | 0644, ze.getUnixMode());
} finally {
@@ -207,11 +267,12 @@ public class ZipTest extends BuildFileTest {
}
}
+ @Test
public void testAcceptZeroPermissions() throws IOException {
- executeTarget("acceptZeroPermissions");
+ buildRule.executeTarget("acceptZeroPermissions");
org.apache.tools.zip.ZipFile zf = null;
try {
- zf = new org.apache.tools.zip.ZipFile(new File(getProject().getProperty("output"), "test3.zip"));
+ zf = new org.apache.tools.zip.ZipFile(new File(buildRule.getProject().getProperty("output"), "test3.zip"));
org.apache.tools.zip.ZipEntry ze = zf.getEntry("testdir/test.txt");
assertEquals(0000, ze.getUnixMode());
} finally {
@@ -221,11 +282,12 @@ public class ZipTest extends BuildFileTest {
}
}
+ @Test
public void testForBugzilla34764() throws IOException {
- executeTarget("testForBugzilla34764");
+ buildRule.executeTarget("testForBugzilla34764");
org.apache.tools.zip.ZipFile zf = null;
try {
- zf = new org.apache.tools.zip.ZipFile(new File(getProject().getProperty("output"), "test3.zip"));
+ zf = new org.apache.tools.zip.ZipFile(new File(buildRule.getProject().getProperty("output"), "test3.zip"));
org.apache.tools.zip.ZipEntry ze = zf.getEntry("file1");
assertEquals(UnixStat.FILE_FLAG | 0644, ze.getUnixMode());
} finally {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapterTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapterTest.java
index bbefb87a8..e3c262886 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapterTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/compilers/DefaultCompilerAdapterTest.java
@@ -21,9 +21,12 @@ package org.apache.tools.ant.taskdefs.compilers;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.Commandline;
-import junit.framework.TestCase;
+import org.junit.Test;
-public class DefaultCompilerAdapterTest extends TestCase {
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+
+public class DefaultCompilerAdapterTest {
private static class LogCapturingJavac extends Javac {
private StringBuffer sb = new StringBuffer();
@@ -54,6 +57,7 @@ public class DefaultCompilerAdapterTest extends TestCase {
}
}
+ @Test
public void testSourceIsIgnoredForJavac13() {
testSource(null, "javac1.3", "", null, "1.1");
testSource(null, "javac1.3", "", null, "1.2");
@@ -61,6 +65,7 @@ public class DefaultCompilerAdapterTest extends TestCase {
testSource(null, "javac1.3", "", null, "1.4");
}
+ @Test
public void testSource11IsUpgradedTo13() {
testSource("1.3", "javac1.4", "", null, "1.1");
testSource("1.3", "javac1.5", "", null, "1.1");
@@ -69,6 +74,7 @@ public class DefaultCompilerAdapterTest extends TestCase {
testSource("1.3", "javac1.8", "", null, "1.1");
}
+ @Test
public void testSource12IsUpgradedTo13() {
testSource("1.3", "javac1.4", "", null, "1.2");
testSource("1.3", "javac1.5", "", null, "1.2");
@@ -77,12 +83,14 @@ public class DefaultCompilerAdapterTest extends TestCase {
testSource("1.3", "javac1.8", "", null, "1.2");
}
+ @Test
public void testImplicitSourceForJava15() {
commonSourceDowngrades("javac1.5");
testSource(null, "javac1.5", "", "1.5");
testSource(null, "javac1.5", "", "5");
}
+ @Test
public void testImplicitSourceForJava16() {
commonSourceDowngrades("javac1.6");
testSource(null, "javac1.6", "", "1.5");
@@ -91,6 +99,7 @@ public class DefaultCompilerAdapterTest extends TestCase {
testSource(null, "javac1.6", "", "6");
}
+ @Test
public void testImplicitSourceForJava17() {
commonSourceDowngrades("javac1.7");
testSource("1.5", "javac1.7",
@@ -109,6 +118,7 @@ public class DefaultCompilerAdapterTest extends TestCase {
testSource(null, "javac1.7", "", "7");
}
+ @Test
public void testImplicitSourceForJava18() {
commonSourceDowngrades("javac1.8");
testSource("1.5", "javac1.8",
@@ -133,6 +143,7 @@ public class DefaultCompilerAdapterTest extends TestCase {
testSource(null, "javac1.8", "", "8");
}
+ @Test
public void testImplicitSourceForJava19() {
commonSourceDowngrades("javac1.9");
testSource("1.5", "javac1.9",
@@ -204,8 +215,7 @@ public class DefaultCompilerAdapterTest extends TestCase {
assertEquals("", javac.getLog());
} else {
String l = javac.getLog();
- assertTrue("expected to find '" + expectedLog + "' in '" + l + "'",
- l.indexOf(expectedLog) > -1);
+ assertContains(expectedLog, l);
}
String[] args = cmd.getCommandline();
assertEquals(expectedSource == null ? 0 : 2, args.length);
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/AntVersionTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/AntVersionTest.java
index a2c5e440a..b70a1381f 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/AntVersionTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/AntVersionTest.java
@@ -17,27 +17,32 @@
*/
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Testcases for the <antversion> condition.
*
*/
-public class AntVersionTest extends BuildFileTest {
-
- public AntVersionTest(String name) {
- super(name);
- }
-
+public class AntVersionTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() throws Exception {
- configureProject("src/etc/testcases/taskdefs/conditions/antversion.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/antversion.xml");
}
-
+
+ @Test
public void testAtLeast() {
- executeTarget("testatleast");
+ buildRule.executeTarget("testatleast");
}
-
+
+ @Test
public void testExactly() {
- executeTarget("testexactly");
+ buildRule.executeTarget("testexactly");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ContainsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ContainsTest.java
index 0cbe1fae1..a45b511a5 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ContainsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ContainsTest.java
@@ -18,18 +18,17 @@
package org.apache.tools.ant.taskdefs.condition;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
/**
* Testcase for the <contains> condition.
*
*/
-public class ContainsTest extends TestCase {
-
- public ContainsTest(String name) {
- super(name);
- }
+public class ContainsTest {
+ @Test
public void testCaseSensitive() {
Contains con = new Contains();
con.setString("abc");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/EqualsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/EqualsTest.java
index 9980a80fe..5f9b996ac 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/EqualsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/EqualsTest.java
@@ -18,18 +18,17 @@
package org.apache.tools.ant.taskdefs.condition;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
/**
* Testcase for the <equals> condition.
*
*/
-public class EqualsTest extends TestCase {
-
- public EqualsTest(String name) {
- super(name);
- }
+public class EqualsTest {
+ @Test
public void testTrim() {
Equals eq = new Equals();
eq.setArg1("a");
@@ -43,6 +42,7 @@ public class EqualsTest extends TestCase {
assertTrue(eq.eval());
}
+ @Test
public void testCaseSensitive() {
Equals eq = new Equals();
eq.setArg1("a");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/HttpTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/HttpTest.java
index af98b0840..15a9d2d34 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/HttpTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/HttpTest.java
@@ -17,45 +17,60 @@
*/
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
/**
* Testcases for the <http> condition. All these tests require
* us to be online as they attempt to get the status of various pages
* on the Ant Apache web site.
*/
-public class HttpTest extends BuildFileTest {
+public class HttpTest {
- public HttpTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/http.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/http.xml");
}
+ @Test
public void testNoMethod() {
- expectPropertySet("basic-no-method", "basic-no-method");
- assertPropertyUnset("basic-no-method-bad-url");
+ buildRule.executeTarget("basic-no-method");
+ assertEquals("true", buildRule.getProject().getProperty("basic-no-method"));
+ assertNull(buildRule.getProject().getProperty("basic-no-method-bad-url"));
}
+ @Test
public void testHeadRequest() {
- expectPropertySet("test-head-request", "test-head-request");
- assertPropertyUnset("test-head-request-bad-url");
+ buildRule.executeTarget("test-head-request");
+ assertEquals("true", buildRule.getProject().getProperty("test-head-request"));
+ assertNull(buildRule.getProject().getProperty("test-head-request-bad-url"));
}
+ @Test
public void testGetRequest() {
- expectPropertySet("test-get-request", "test-get-request");
- assertPropertyUnset("test-get-request-bad-url");
+ buildRule.executeTarget("test-get-request");
+ assertEquals("true", buildRule.getProject().getProperty("test-get-request"));
+ assertNull(buildRule.getProject().getProperty("test-get-request-bad-url"));
}
+ @Test
public void testBadRequestMethod() {
- expectSpecificBuildException("bad-request-method",
- "invalid HTTP request method specified",
- null);
+ try {
+ buildRule.executeTarget("bad-request-method");
+ fail("Exception should have been thrown as invalid HTTP request method specified");
+ } catch (BuildException ex) {
+ //TODO we should assert the correct build exception was thrown
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFailureTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFailureTest.java
index 1d0e22249..865947653 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFailureTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFailureTest.java
@@ -17,27 +17,28 @@
*/
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Testcases for the <isfailure> condition.
*
*/
-public class IsFailureTest extends BuildFileTest {
+public class IsFailureTest {
- public IsFailureTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/isfailure.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/isfailure.xml");
}
+ @Test
public void testIsFailure() {
- executeTarget("testisfailure");
+ buildRule.executeTarget("testisfailure");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFileSelectedTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFileSelectedTest.java
index 66aba8014..84d88a554 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFileSelectedTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsFileSelectedTest.java
@@ -18,36 +18,57 @@
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
* Testcase for the <isfileselected> condition.
*
*/
-public class IsFileSelectedTest extends BuildFileTest {
+public class IsFileSelectedTest {
- public IsFileSelectedTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/isfileselected.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/isfileselected.xml");
}
+ @Test
public void testSimple() {
- executeTarget("simple");
+ buildRule.executeTarget("simple");
}
+
+ @Test
public void testName() {
- executeTarget("name");
+ buildRule.executeTarget("name");
}
+
+ @Test
public void testBaseDir() {
- executeTarget("basedir");
+ buildRule.executeTarget("basedir");
}
+
+ @Test
public void testType() {
- executeTarget("type");
+ buildRule.executeTarget("type");
}
+
+ @Test
public void testNotSelector() {
- expectBuildExceptionContaining(
- "not.selector", "checking for use as a selector (not allowed)",
- "fileset doesn't support the nested \"isfile");
+ try {
+ buildRule.executeTarget("not.selector");
+ fail("Exception should have been thrown: checking for use as a selector (not allowed)");
+ } catch(BuildException ex) {
+ AntAssert.assertContains("fileset doesn't support the nested \"isfile",
+ ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReachableTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReachableTest.java
index 3078c0e5e..d036834ce 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReachableTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReachableTest.java
@@ -17,66 +17,100 @@
*/
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* test for reachable things
*/
-public class IsReachableTest extends BuildFileTest {
+public class IsReachableTest {
- public IsReachableTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(
+ buildRule.configureProject(
"src/etc/testcases/taskdefs/conditions/isreachable.xml");
}
+ @Test
public void testLocalhost() throws Exception {
- executeTarget("testLocalhost");
+ buildRule.executeTarget("testLocalhost");
}
+ @Test
public void testLocalhostURL() throws Exception {
- executeTarget("testLocalhostURL");
+ buildRule.executeTarget("testLocalhostURL");
}
+ @Test
public void testIpv4localhost() throws Exception {
- executeTarget("testIpv4localhost");
+ buildRule.executeTarget("testIpv4localhost");
}
+ @Test
public void testFTPURL() throws Exception {
- executeTarget("testFTPURL");
+ buildRule.executeTarget("testFTPURL");
}
+ @Test
public void testBoth() throws Exception {
- expectBuildExceptionContaining("testBoth",
- "error on two targets",
- IsReachable.ERROR_BOTH_TARGETS);
+ try {
+ buildRule.executeTarget("testBoth");
+ fail("Build exception expected: error on two targets");
+ } catch(BuildException ex) {
+ assertEquals(IsReachable.ERROR_BOTH_TARGETS, ex.getMessage());
+ }
}
+ @Test
public void testNoTargets() throws Exception {
- expectBuildExceptionContaining("testNoTargets",
- "no params",
- IsReachable.ERROR_NO_HOSTNAME);
+ try {
+ buildRule.executeTarget("testNoTargets");
+ fail("Build exception expected: no params");
+ } catch(BuildException ex) {
+ assertEquals(IsReachable.ERROR_NO_HOSTNAME, ex.getMessage());
+ }
}
+ @Test
public void testBadTimeout() throws Exception {
- expectBuildExceptionContaining("testBadTimeout",
- "error on -ve timeout",
- IsReachable.ERROR_BAD_TIMEOUT);
+ try {
+ buildRule.executeTarget("testBadTimeout");
+ fail("Build exception expected: error on -ve timeout");
+ } catch(BuildException ex) {
+ assertEquals(IsReachable.ERROR_BAD_TIMEOUT, ex.getMessage());
+ }
}
+ @Test
+ @Ignore("Previously named in a way to prevent execution")
public void NotestFile() throws Exception {
- expectBuildExceptionContaining("testFile",
- "error on file URL",
- IsReachable.ERROR_NO_HOST_IN_URL);
+ try {
+ buildRule.executeTarget("testFile");
+ fail("Build exception expected: error on file URL");
+ } catch(BuildException ex) {
+ assertEquals(IsReachable.ERROR_NO_HOST_IN_URL, ex.getMessage());
+ }
}
+ @Test
public void testBadURL() throws Exception {
- expectBuildExceptionContaining("testBadURL",
- "error in URL",
- IsReachable.ERROR_BAD_URL);
+ try {
+ buildRule.executeTarget("testBadURL");
+ fail("Build exception expected: error in URL");
+ } catch(BuildException ex) {
+ AntAssert.assertContains(IsReachable.ERROR_BAD_URL, ex.getMessage());
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReferenceTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReferenceTest.java
index ba775c40d..01b6b47c8 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReferenceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsReferenceTest.java
@@ -17,43 +17,55 @@
*/
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNull;
/**
* Testcases for the <isreference> condition.
*
*/
-public class IsReferenceTest extends BuildFileTest {
+public class IsReferenceTest {
- public IsReferenceTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/isreference.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/isreference.xml");
}
+ @Test
public void testBasic() {
- expectPropertySet("basic", "global-path");
- assertPropertySet("target-path");
- assertPropertyUnset("undefined");
+ buildRule.executeTarget("basic");
+ assertEquals("true", buildRule.getProject().getProperty("global-path"));
+ assertEquals("true", buildRule.getProject().getProperty("target-path"));
+ assertNull(buildRule.getProject().getProperty("undefined"));
}
+ @Test
public void testNotEnoughArgs() {
- expectSpecificBuildException("isreference-incomplete",
- "refid attribute has been omitted",
- "No reference specified for isreference "
- + "condition");
+ try {
+ buildRule.executeTarget("isreference-incomplete");
+ fail("Build exception expected: refid attirbute has been omitted");
+ } catch(BuildException ex) {
+ assertEquals("No reference specified for isreference condition", ex.getMessage());
+ }
}
+ @Test
public void testType() {
- expectPropertySet("type", "global-path");
- assertPropertyUnset("global-path-as-fileset");
- assertPropertyUnset("global-path-as-foo");
- assertPropertySet("global-echo");
+ buildRule.executeTarget("type");
+ assertEquals("true", buildRule.getProject().getProperty("global-path"));
+ assertNull(buildRule.getProject().getProperty("global-path-as-fileset"));
+ assertNull(buildRule.getProject().getProperty("global-path-as-foo"));
+ assertEquals("true", buildRule.getProject().getProperty("global-echo"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsSignedTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsSignedTest.java
index f2f9486f3..0f4001c3b 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsSignedTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/IsSignedTest.java
@@ -18,31 +18,42 @@
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Testcase for the <issigned> condition.
*
*/
-public class IsSignedTest extends BuildFileTest {
+public class IsSignedTest {
- public IsSignedTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/issigned.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/issigned.xml");
}
+ @Test
public void testPass() {
- executeTarget("pass");
+ buildRule.executeTarget("pass");
}
+
+ @Test
public void testPassword() {
- executeTarget("password");
+ buildRule.executeTarget("password");
}
+
+ @Test
public void testAPassword() {
- executeTarget("apassword");
+ buildRule.executeTarget("apassword");
}
+
+ @Test
public void testAllSigned() {
- executeTarget("allsigned");
+ buildRule.executeTarget("allsigned");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ParserSupportsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ParserSupportsTest.java
index fc4f13113..2a2354ffe 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ParserSupportsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/ParserSupportsTest.java
@@ -18,53 +18,78 @@
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
*/
-public class ParserSupportsTest extends BuildFileTest {
+public class ParserSupportsTest {
- public ParserSupportsTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/parsersupports.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/parsersupports.xml");
}
- public void testEmpty() throws Exception {
- expectBuildExceptionContaining("testEmpty",
- ParserSupports.ERROR_NO_ATTRIBUTES,
- ParserSupports.ERROR_NO_ATTRIBUTES);
+ @Test
+ public void testEmpty() {
+ try {
+ buildRule.executeTarget("testEmpty");
+ fail("Build exception expected: " + ParserSupports.ERROR_NO_ATTRIBUTES);
+ } catch(BuildException ex) {
+ assertEquals(ParserSupports.ERROR_NO_ATTRIBUTES, ex.getMessage());
+ }
}
- public void testBoth() throws Exception {
- expectBuildExceptionContaining("testBoth",
- ParserSupports.ERROR_BOTH_ATTRIBUTES,
- ParserSupports.ERROR_BOTH_ATTRIBUTES);
+ @Test
+ public void testBoth() {
+ try {
+ buildRule.executeTarget("testBoth");
+ fail("Build exception expected: " + ParserSupports.ERROR_BOTH_ATTRIBUTES);
+ } catch(BuildException ex) {
+ assertEquals(ParserSupports.ERROR_BOTH_ATTRIBUTES, ex.getMessage());
+ }
}
- public void testNamespaces() throws Exception {
- executeTarget("testNamespaces");
+ @Test
+ public void testNamespaces() {
+ buildRule.executeTarget("testNamespaces");
}
- public void testPropertyNoValue() throws Exception {
- expectBuildExceptionContaining("testPropertyNoValue",
- ParserSupports.ERROR_NO_VALUE,
- ParserSupports.ERROR_NO_VALUE);
+ @Test
+ public void testPropertyNoValue() {
+ try {
+ buildRule.executeTarget("testPropertyNoValue");
+ fail("Build exception expected: " + ParserSupports.ERROR_NO_VALUE);
+ } catch(BuildException ex) {
+ assertEquals(ParserSupports.ERROR_NO_VALUE, ex.getMessage());
+ }
}
- public void testUnknownProperty() throws Exception {
- executeTarget("testUnknownProperty");
+ @Test
+ public void testUnknownProperty() {
+ buildRule.executeTarget("testUnknownProperty");
}
- public void NotestPropertyInvalid() throws Exception {
- executeTarget("testPropertyInvalid");
+
+ @Test
+ @Ignore("Previously named in a manner to prevent execution")
+ public void NotestPropertyInvalid() {
+ buildRule.executeTarget("testPropertyInvalid");
}
- public void NotestXercesProperty() throws Exception {
- executeTarget("testXercesProperty");
+
+ @Test
+ @Ignore("Previously named in a manner to prevent execution")
+ public void NotestXercesProperty() {
+ buildRule.executeTarget("testXercesProperty");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/TypeFoundTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/TypeFoundTest.java
index a0d497129..ab2849430 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/TypeFoundTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/TypeFoundTest.java
@@ -17,50 +17,74 @@
*/
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNull;
/**
* test the typeexists condition
*/
-public class TypeFoundTest extends BuildFileTest {
+public class TypeFoundTest {
- public TypeFoundTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/typefound.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/typefound.xml");
}
+ @Test
public void testTask() {
- expectPropertySet("testTask", "testTask");
+ buildRule.executeTarget("testTask");
+ assertEquals("true", buildRule.getProject().getProperty("testTask"));
}
+ @Test
public void testUndefined() {
- expectBuildExceptionContaining("testUndefined","left out the name attribute", "No type specified");
+ try {
+ buildRule.executeTarget("testUndefined");
+ fail("Build exception expected: left out the name attribute");
+ } catch(BuildException ex) {
+ AntAssert.assertContains("No type specified", ex.getMessage());
+ }
}
+ @Test
public void testTaskThatIsntDefined() {
- expectPropertyUnset("testTaskThatIsntDefined", "testTaskThatIsntDefined");
+ buildRule.executeTarget("testTaskThatIsntDefined");
+ assertNull(buildRule.getProject().getProperty("testTaskThatIsntDefined"));
}
+ @Test
public void testTaskThatDoesntReallyExist() {
- expectPropertyUnset("testTaskThatDoesntReallyExist", "testTaskThatDoesntReallyExist");
+ buildRule.executeTarget("testTaskThatDoesntReallyExist");
+ assertNull(buildRule.getProject().getProperty("testTaskThatDoesntReallyExist"));
}
+ @Test
public void testType() {
- expectPropertySet("testType", "testType");
+ buildRule.executeTarget("testType");
+ assertEquals("true", buildRule.getProject().getProperty("testType"));
}
+ @Test
public void testPreset() {
- expectPropertySet("testPreset", "testPreset");
+ buildRule.executeTarget("testPreset");
+ assertEquals("true", buildRule.getProject().getProperty("testPreset"));
}
+ @Test
public void testMacro() {
- expectPropertySet("testMacro", "testMacro");
+ buildRule.executeTarget("testMacro");
+ assertEquals("true", buildRule.getProject().getProperty("testMacro"));
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/XorTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/XorTest.java
index 0003c854e..4f04c3571 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/condition/XorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/condition/XorTest.java
@@ -17,52 +17,59 @@
*/
package org.apache.tools.ant.taskdefs.condition;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Test that Xor follows the conventional boolean logic semantics
* (a ^ b) === (a||b)&!(a&&b)
*/
-public class XorTest extends BuildFileTest {
+public class XorTest {
- public XorTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/conditions/xor.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/conditions/xor.xml");
}
+ @Test
public void testEmpty() {
- executeTarget("testEmpty");
+ buildRule.executeTarget("testEmpty");
}
+ @Test
public void test0() {
- executeTarget("test0");
+ buildRule.executeTarget("test0");
}
+ @Test
public void test1() {
- executeTarget("test1");
+ buildRule.executeTarget("test1");
}
+ @Test
public void test00() {
- executeTarget("test00");
+ buildRule.executeTarget("test00");
}
+ @Test
public void test10() {
- executeTarget("test10");
+ buildRule.executeTarget("test10");
}
+ @Test
public void test01() {
- executeTarget("test01");
+ buildRule.executeTarget("test01");
}
+ @Test
public void test11() {
- executeTarget("test11");
+ buildRule.executeTarget("test11");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParserTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParserTest.java
index b9add9be3..3dfaf8dd2 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParserTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogParserTest.java
@@ -17,20 +17,23 @@
*/
package org.apache.tools.ant.taskdefs.cvslib;
-import junit.framework.TestCase;
+import org.junit.Test;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Date;
+import static org.junit.Assert.assertEquals;
+
/**
* Minimal test of the parser implementation
*/
-public class ChangeLogParserTest extends TestCase {
+public class ChangeLogParserTest {
protected ChangeLogParser parser = new ChangeLogParser();
+ @Test
public void testOldCvsFormat() throws Exception {
parser.stdout("Working file: build.xml");
parser.stdout("revision 1.475");
@@ -46,6 +49,7 @@ public class ChangeLogParserTest extends TestCase {
assertEquals(date, entries[0].getDate());
}
+ @Test
public void testCvs112Format() throws Exception {
parser.stdout("Working file: build.xml");
parser.stdout("revision 1.475");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriterTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriterTest.java
index 9b2f5a705..a2531d8e9 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriterTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/cvslib/ChangeLogWriterTest.java
@@ -17,8 +17,6 @@
*/
package org.apache.tools.ant.taskdefs.cvslib;
-import junit.framework.TestCase;
-
import java.util.Date;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
@@ -27,6 +25,7 @@ import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.tools.ant.util.JAXPUtils;
+import org.junit.Test;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.ContentHandler;
@@ -37,10 +36,11 @@ import org.xml.sax.Attributes;
/**
* Test for the cvslib ChangeLogWriter
*/
-public class ChangeLogWriterTest extends TestCase {
+public class ChangeLogWriterTest {
private ChangeLogWriter writer = new ChangeLogWriter();
+ @Test
public void testNonUTF8Characters() throws Exception {
CVSEntry entry = new CVSEntry(new Date(), "Se\u00f1orita", "2003 < 2004 && 3 > 5");
entry.addFile("Medicare & review.doc", "1.1");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailAddressTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailAddressTest.java
index 72c87a301..31ecafbae 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailAddressTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailAddressTest.java
@@ -18,68 +18,77 @@
package org.apache.tools.ant.taskdefs.email;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
/**
* @since Ant 1.6
*/
-public class EmailAddressTest extends TestCase {
-
- public EmailAddressTest(String name) {
- super(name);
- }
-
- public void setUp() {
- }
+public class EmailAddressTest {
+ @Test
public void test1() {
expectNameAddress( new EmailAddress("address (name)") );
}
+ @Test
public void test2() {
expectNameAddress( new EmailAddress("(name) address") );
}
+ @Test
public void test3() {
expectNameAddress( new EmailAddress("name ") );
}
+ @Test
public void test4() {
expectNameAddress( new EmailAddress(" name") );
}
+ @Test
public void test5() {
expectNameAddress( new EmailAddress(" (name)") );
}
+ @Test
public void test6() {
expectNameAddress( new EmailAddress("(name) ") );
}
+ @Test
public void test7() {
expectNameAddress2( new EmailAddress("address ()") );
}
+ @Test
public void test8() {
expectNameAddress2( new EmailAddress("() address") );
}
+ @Test
public void test9() {
expectNameAddress3( new EmailAddress("address") );
}
+ @Test
public void testA() {
expectNameAddress3( new EmailAddress("") );
}
+ @Test
public void testB() {
expectNameAddress3( new EmailAddress(" ") );
}
+ @Test
public void testC() {
expectNameAddress3( new EmailAddress("< address >") );
}
+ @Test
public void testD() {
expectNameAddress3( new EmailAddress(" < address > ") );
}
@@ -97,8 +106,7 @@ public class EmailAddressTest extends TestCase {
// where only an address is supplied
private void expectNameAddress3(EmailAddress e) {
- assertTrue( "Expected null, found <" + e.getName() + ">",
- e.getName() == null );
+ assertNull("Expected null, found <" + e.getName() + ">", e.getName());
assertEquals( "address", e.getAddress() );
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailTaskTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailTaskTest.java
index 66b89cd27..6363f90d0 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailTaskTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/email/EmailTaskTest.java
@@ -18,28 +18,46 @@
package org.apache.tools.ant.taskdefs.email;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
* TODO : develop these testcases - the email task needs to have attributes allowing
* to simulate sending mail and to catch the output in text files or streams
*/
-public class EmailTaskTest extends BuildFileTest {
+public class EmailTaskTest {
- public EmailTaskTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/email/mail.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/email/mail.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "SMTP auth only possible with MIME mail");
+ try {
+ buildRule.executeTarget("test1");
+ fail("Build exception expected: SMTP auth only possibly with MIME mail");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "SSL only possible with MIME mail");
+ try {
+ buildRule.executeTarget("test2");
+ fail("Build exception expected: SSL only possibly with MIME mail");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/email/MessageTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/email/MessageTest.java
index d75b766e4..df75067fd 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/email/MessageTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/email/MessageTest.java
@@ -23,18 +23,19 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.Project;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.After;
+import org.junit.Test;
-public class MessageTest extends TestCase {
- private File f = new File(System.getProperty("java.io.tmpdir"),
+public class MessageTest {
+ private static final File f = new File(System.getProperty("java.io.tmpdir"),
"message.txt");
/**
* test for bugzilla 48932
*/
- public void testPrintStreamDoesNotGetClosed() {
+ @Test
+ public void testPrintStreamDoesNotGetClosed() throws IOException {
Message ms = new Message();
Project p = new Project();
ms.setProject(p);
@@ -44,14 +45,13 @@ public class MessageTest extends TestCase {
fis = new FileOutputStream(f);
ms.print(new PrintStream(fis));
fis.write(120);
- } catch (IOException ioe) {
- fail("we should not have issues writing after having called Message.print");
} finally {
FileUtils.close(fis);
}
}
+ @After
public void tearDown() {
if (f.exists()) {
FileUtils fu = FileUtils.getFileUtils();
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ANTLRTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ANTLRTest.java
index 389b7673a..925844830 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ANTLRTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ANTLRTest.java
@@ -18,8 +18,20 @@
package org.apache.tools.ant.taskdefs.optional;
-import java.io.*;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.FilenameFilter;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.apache.tools.ant.AntAssert.assertNotContains;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* If you want to run tests, it is highly recommended
@@ -32,70 +44,106 @@ import org.apache.tools.ant.BuildFileTest;
* system classpath. (see ANTLR install.html)
*
*/
-public class ANTLRTest extends BuildFileTest {
+public class ANTLRTest {
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/antlr/";
- public ANTLRTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "antlr.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "antlr.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "required argument, target, missing");
+ try {
+ buildRule.executeTarget("test1");
+ fail("required argument, target, missing");
+ } catch (BuildException ex) {
+ //TODO should check exception message
+ }
}
+ @Test
public void test2() {
- expectBuildException("test2", "Invalid output directory");
+ try {
+ buildRule.executeTarget("test2");
+ fail("Invalid output directory");
+ } catch (BuildException ex) {
+ //TODO should check exception message
+ }
}
+ @Test
public void test3() {
- executeTarget("test3");
+ buildRule.executeTarget("test3");
}
+ @Test
public void test4() {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
}
+ @Test
public void test5() {
// should print "panic: Cannot find importVocab file 'JavaTokenTypes.txt'"
// since it needs to run java.g first before java.tree.g
- expectBuildException("test5", "ANTLR returned: 1");
+ try {
+ buildRule.executeTarget("test5");
+ fail("ANTLR returned: 1");
+ } catch (BuildException ex) {
+ //TODO should check exception message
+ }
}
+ @Test
public void test6() {
- executeTarget("test6");
+ buildRule.executeTarget("test6");
}
+ @Test
public void test7() {
- expectBuildException("test7", "Unable to determine generated class");
+ try {
+ buildRule.executeTarget("test7");
+ fail("Unable to determine generated class");
+ } catch (BuildException ex) {
+ //TODO should check exception message
+ }
}
/**
* This is a negative test for the super grammar (glib) option.
*/
+ @Test
public void test8() {
- expectBuildException("test8", "Invalid super grammar file");
+ try {
+ buildRule.executeTarget("test8");
+ fail("Invalid super grammar file");
+ } catch (BuildException ex) {
+ //TODO should check exception message
+ }
}
/**
* This is a positive test for the super grammar (glib) option. ANTLR
* will throw an error if everything is not correct.
*/
+ @Test
public void test9() {
- executeTarget("test9");
+ buildRule.executeTarget("test9");
}
/**
* This test creates an html-ized version of the calculator grammar.
* The sanity check is simply whether or not an html file was generated.
*/
+ @Test
public void test10() {
- executeTarget("test10");
- String[] calcFiles = getOutputDir().list(new HTMLFilter());
+ buildRule.executeTarget("test10");
+ File outputDirectory = new File(buildRule.getProject().getProperty("output"));
+ String[] calcFiles = outputDirectory.list(new HTMLFilter());
assertTrue(calcFiles.length > 0);
}
@@ -103,16 +151,18 @@ public class ANTLRTest extends BuildFileTest {
* This is just a quick sanity check to run the diagnostic option and
* make sure that it doesn't throw any funny exceptions.
*/
+ @Test
public void test11() {
- executeTarget("test11");
+ buildRule.executeTarget("test11");
}
/**
* This is just a quick sanity check to run the trace option and
* make sure that it doesn't throw any funny exceptions.
*/
+ @Test
public void test12() {
- executeTarget("test12");
+ buildRule.executeTarget("test12");
}
/**
@@ -120,37 +170,43 @@ public class ANTLRTest extends BuildFileTest {
* trace options (traceLexer, traceParser, and traceTreeWalker) to
* make sure that they don't throw any funny exceptions.
*/
+ @Test
public void test13() {
- executeTarget("test13");
+ buildRule.executeTarget("test13");
}
+ @Test
public void testNoRecompile() {
- executeTarget("test9");
- assertEquals(-1, getFullLog().indexOf("Skipped grammar file."));
- executeTarget("noRecompile");
- assertTrue(-1 != getFullLog().indexOf("Skipped grammar file."));
+ buildRule.executeTarget("test9");
+ assertNotContains("Skipped grammar file.", buildRule.getFullLog());
+ buildRule.executeTarget("noRecompile");
+ assertContains("Skipped grammar file.", buildRule.getFullLog());
}
+ @Test
public void testNormalRecompile() {
- executeTarget("test9");
- assertEquals(-1, getFullLog().indexOf("Skipped grammar file."));
- executeTarget("normalRecompile");
- assertEquals(-1, getFullLog().indexOf("Skipped grammar file."));
+ buildRule.executeTarget("test9");
+ assertNotContains("Skipped grammar file.", buildRule.getFullLog());
+
+ FileUtilities.rollbackTimetamps(buildRule.getOutputDir(), 5);
+
+ buildRule.executeTarget("normalRecompile");
+ assertNotContains("Skipped grammar file.", buildRule.getFullLog());
}
+ @Test
// Bugzilla Report 12961
public void testSupergrammarChangeRecompile() {
- executeTarget("test9");
- assertEquals(-1, getFullLog().indexOf("Skipped grammar file."));
- executeTarget("supergrammarChangeRecompile");
- assertEquals(-1, getFullLog().indexOf("Skipped grammar file."));
- }
-}
+ buildRule.executeTarget("test9");
+ assertNotContains("Skipped grammar file.", buildRule.getFullLog());
+
+ FileUtilities.rollbackTimetamps(buildRule.getOutputDir(), 5);
+
+ buildRule.executeTarget("supergrammarChangeRecompile");
+ assertNotContains("Skipped grammar file.", buildRule.getFullLog());
-class CalcFileFilter implements FilenameFilter {
- public boolean accept(File dir, String name) {
- return name.startsWith("Calc");
}
+
}
class HTMLFilter implements FilenameFilter {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/AbstractXSLTLiaisonTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/AbstractXSLTLiaisonTest.java
index 72139e144..434e81f51 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/AbstractXSLTLiaisonTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/AbstractXSLTLiaisonTest.java
@@ -18,14 +18,19 @@
package org.apache.tools.ant.taskdefs.optional;
+import static org.junit.Assert.assertEquals;
+
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
+
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
-import junit.framework.TestCase;
+
import org.apache.tools.ant.taskdefs.XSLTLiaison;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Test;
import org.w3c.dom.Document;
/**
@@ -34,17 +39,14 @@ import org.w3c.dom.Document;
*
* Stephane Bailliez
*/
-public abstract class AbstractXSLTLiaisonTest extends TestCase {
+public abstract class AbstractXSLTLiaisonTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
protected XSLTLiaison liaison;
- protected AbstractXSLTLiaisonTest(String name){
- super(name);
- }
-
- protected void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
liaison = createLiaison();
}
@@ -61,6 +63,7 @@ public abstract class AbstractXSLTLiaisonTest extends TestCase {
}
/** keep it simple stupid */
+ @Test
public void testTransform() throws Exception {
File xsl = getFile("/taskdefs/optional/xsltliaison-in.xsl");
liaison.setStylesheet(xsl);
@@ -75,6 +78,7 @@ public abstract class AbstractXSLTLiaisonTest extends TestCase {
}
}
+ @Test
public void testEncoding() throws Exception {
File xsl = getFile("/taskdefs/optional/xsltliaison-encoding-in.xsl");
liaison.setStylesheet(xsl);
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/BeanShellScriptTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/BeanShellScriptTest.java
index 77358cd35..880202293 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/BeanShellScriptTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/BeanShellScriptTest.java
@@ -17,28 +17,32 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* Tests the examples of the <script> task docs.
*
* @since Ant 1.5.2
*/
-public class BeanShellScriptTest extends BuildFileTest {
+public class BeanShellScriptTest {
- public BeanShellScriptTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/script.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/script.xml");
}
+ @Test
public void testCanLoad() {
- expectLog("useBeanshell", "I'm here");
+ buildRule.executeTarget("useBeanshell");
+ assertEquals("I'm here", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java
index d62c8cc16..925777c5d 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/EchoPropertiesTest.java
@@ -18,25 +18,37 @@
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
-import java.io.IOException;
-import java.io.File;
-import java.io.InputStream;
import java.io.BufferedInputStream;
+import java.io.BufferedReader;
+import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
-import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.Properties;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
/**
* Tests the EchoProperties task.
*
* @created 17-Jan-2002
* @since Ant 1.5
*/
-public class EchoPropertiesTest extends BuildFileTest {
+public class EchoPropertiesTest {
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/";
private static final String GOOD_OUTFILE = "test.properties";
@@ -44,144 +56,166 @@ public class EchoPropertiesTest extends BuildFileTest {
private static final String PREFIX_OUTFILE = "test-prefix.properties";
private static final String TEST_VALUE = "isSet";
- public EchoPropertiesTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "echoproperties.xml");
- project.setProperty( "test.property", TEST_VALUE );
+ buildRule.configureProject(TASKDEFS_DIR + "echoproperties.xml");
+ buildRule.getProject().setProperty("test.property", TEST_VALUE);
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
+ @Test
public void testEchoToLog() {
- expectLogContaining("testEchoToLog", "test.property="+TEST_VALUE);
+ buildRule.executeTarget("testEchoToLog");
+ assertContains("test.property=" + TEST_VALUE, buildRule.getLog());
}
+ @Test
public void testEchoWithEmptyPrefixToLog() {
- expectLogContaining("testEchoWithEmptyPrefixToLog", "test.property="+TEST_VALUE);
+ buildRule.executeTarget("testEchoWithEmptyPrefixToLog");
+ assertContains("test.property="+TEST_VALUE, buildRule.getLog());
}
+ @Test
public void testReadBadFile() {
- expectBuildExceptionContaining( "testReadBadFile",
- "srcfile is a directory", "srcfile is a directory!" );
- }
-
-
- public void testReadBadFileFail() {
- expectBuildExceptionContaining( "testReadBadFile",
- "srcfile is a directory", "srcfile is a directory!" );
+ try {
+ buildRule.executeTarget("testReadBadFile");
+ fail("BuildException should have been thrown on bad file");
+ }
+ catch(BuildException ex) {
+ assertContains("srcfile is a directory","srcfile is a directory!", ex.getMessage());
+ }
}
-
+ @Test
public void testReadBadFileNoFail() {
- expectLog( "testReadBadFileNoFail", "srcfile is a directory!" );
+ buildRule.executeTarget("testReadBadFileNoFail");
+ assertContains("srcfile is a directory!", buildRule.getLog());
}
+ @Test
public void testEchoToBadFile() {
- expectBuildExceptionContaining( "testEchoToBadFile",
- "destfile is a directory", "destfile is a directory!" );
- }
-
-
- public void testEchoToBadFileFail() {
- expectBuildExceptionContaining( "testEchoToBadFileFail",
- "destfile is a directory", "destfile is a directory!" );
+ try {
+ buildRule.executeTarget("testEchoToBadFile");
+ fail("BuildException should have been thrown on destination file being a directory");
+ } catch(BuildException ex) {
+ assertContains("destfile is a directory", "destfile is a directory!", ex.getMessage());
+ }
}
+ @Test
public void testEchoToBadFileNoFail() {
- expectLog( "testEchoToBadFileNoFail", "destfile is a directory!");
+ buildRule.executeTarget("testEchoToBadFileNoFail");
+ assertContains("destfile is a directory!", buildRule.getLog());
}
+ @Test
public void testEchoToGoodFile() throws Exception {
- executeTarget( "testEchoToGoodFile" );
+ buildRule.executeTarget("testEchoToGoodFile");
assertGoodFile();
}
+ @Test
public void testEchoToGoodFileXml() throws Exception {
- executeTarget( "testEchoToGoodFileXml" );
+ buildRule.executeTarget("testEchoToGoodFileXml");
// read in the file
- File f = createRelativeFile( GOOD_OUTFILE_XML );
- FileReader fr = new FileReader( f );
+ File f = createRelativeFile(GOOD_OUTFILE_XML);
+ FileReader fr = new FileReader(f);
+ BufferedReader br = new BufferedReader(fr);
try {
- BufferedReader br = new BufferedReader( fr );
String read = null;
- while ( (read = br.readLine()) != null) {
+ while ((read = br.readLine()) != null) {
if (read.indexOf(" ") >= 0) {
// found the property we set - it's good.
return;
}
}
- fail( "did not encounter set property in generated file." );
+ fail("did not encounter set property in generated file.");
} finally {
try {
fr.close();
} catch(IOException e) {}
+ try {
+ br.close();
+ } catch(IOException e) {}
}
}
+ @Test
public void testEchoToGoodFileFail() throws Exception {
- executeTarget( "testEchoToGoodFileFail" );
+ buildRule.executeTarget("testEchoToGoodFileFail");
assertGoodFile();
}
+ @Test
public void testEchoToGoodFileNoFail() throws Exception {
- executeTarget( "testEchoToGoodFileNoFail" );
+ buildRule.executeTarget("testEchoToGoodFileNoFail");
assertGoodFile();
}
-
+ @Test
public void testEchoPrefix() throws Exception {
testEchoPrefixVarious("testEchoPrefix");
}
+ @Test
public void testEchoPrefixAsPropertyset() throws Exception {
testEchoPrefixVarious("testEchoPrefixAsPropertyset");
}
+ @Test
public void testEchoPrefixAsNegatedPropertyset() throws Exception {
testEchoPrefixVarious("testEchoPrefixAsNegatedPropertyset");
}
+ @Test
public void testEchoPrefixAsDoublyNegatedPropertyset() throws Exception {
testEchoPrefixVarious("testEchoPrefixAsDoublyNegatedPropertyset");
}
+ @Test
public void testWithPrefixAndRegex() throws Exception {
- expectSpecificBuildException("testWithPrefixAndRegex",
- "The target must fail with prefix and regex attributes set",
- "Please specify either prefix or regex, but not both");
+ try {
+ buildRule.executeTarget("testWithPrefixAndRegex");
+ fail("BuildException should have been thrown on Prefix and RegEx beng set");
+ } catch (BuildException ex) {
+ assertEquals("The target must fail with prefix and regex attributes set", "Please specify either prefix or regex, but not both", ex.getMessage());
+ }
}
+ @Test
public void testWithEmptyPrefixAndRegex() throws Exception {
- expectLogContaining("testEchoWithEmptyPrefixToLog", "test.property="+TEST_VALUE);
+ buildRule.executeTarget("testEchoWithEmptyPrefixToLog");
+ assertContains("test.property="+TEST_VALUE, buildRule.getLog());
}
+ @Test
public void testWithRegex() throws Exception {
- if (!RegexpMatcherFactory.regexpMatcherPresent(project)) {
- System.out.println("Test 'testWithRegex' skipped because no regexp matcher is present.");
- return;
- }
- executeTarget("testWithRegex");
- assertDebuglogContaining("ant.home=");
+ assumeTrue("Test skipped because no regexp matcher is present.", RegexpMatcherFactory.regexpMatcherPresent(buildRule.getProject()));
+ buildRule.executeTarget("testWithRegex");
+ // the following line has been changed from checking ant.home to ant.version so the test will still work when run outside of an ant script
+ assertContains("ant.version=", buildRule.getFullLog());
}
private void testEchoPrefixVarious(String target) throws Exception {
- executeTarget(target);
+ buildRule.executeTarget(target);
Properties props = loadPropFile(PREFIX_OUTFILE);
assertEquals("prefix didn't include 'a.set' property",
"true", props.getProperty("a.set"));
@@ -191,7 +225,7 @@ public class EchoPropertiesTest extends BuildFileTest {
protected Properties loadPropFile(String relativeFilename)
throws IOException {
- File f = createRelativeFile( relativeFilename );
+ File f = createRelativeFile(relativeFilename);
Properties props=new Properties();
InputStream in=null;
try {
@@ -206,47 +240,27 @@ public class EchoPropertiesTest extends BuildFileTest {
}
protected void assertGoodFile() throws Exception {
- File f = createRelativeFile( GOOD_OUTFILE );
- assertTrue(
- "Did not create "+f.getAbsolutePath(),
- f.exists() );
+ File f = createRelativeFile(GOOD_OUTFILE);
+ assertTrue("Did not create "+f.getAbsolutePath(),
+ f.exists());
Properties props=loadPropFile(GOOD_OUTFILE);
props.list(System.out);
assertEquals("test property not found ",
TEST_VALUE, props.getProperty("test.property"));
-/*
- // read in the file
- FileReader fr = new FileReader( f );
- try {
- BufferedReader br = new BufferedReader( fr );
- String read = null;
- while ( (read = br.readLine()) != null)
- {
- if (read.indexOf("test.property" + TEST_VALUE) >= 0)
- {
- // found the property we set - it's good.
- return;
- }
- }
- fail( "did not encounter set property in generated file." );
- } finally {
- try { fr.close(); } catch(IOException e) {}
- }
-*/
}
- protected String toAbsolute( String filename ) {
- return createRelativeFile( filename ).getAbsolutePath();
+ protected String toAbsolute(String filename) {
+ return createRelativeFile(filename).getAbsolutePath();
}
- protected File createRelativeFile( String filename ) {
- if (filename.equals( "." )) {
- return getProjectDir();
+ protected File createRelativeFile(String filename) {
+ if (filename.equals(".")) {
+ return buildRule.getProject().getBaseDir();
}
// else
- return new File( getProjectDir(), filename );
+ return new File(buildRule.getProject().getBaseDir(), filename);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JavahTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JavahTest.java
index 883477cb8..8b02fff5f 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JavahTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JavahTest.java
@@ -17,32 +17,44 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
-public class JavahTest extends BuildFileTest {
+import static org.junit.Assert.assertTrue;
+
+public class JavahTest {
private final static String BUILD_XML =
"src/etc/testcases/taskdefs/optional/javah/build.xml";
- public JavahTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(BUILD_XML);
+ buildRule.configureProject(BUILD_XML);
+ }
+
+ @After
+ public void tearDown() {
+ buildRule.executeTarget("tearDown");
}
+ @Test
public void testSimpleCompile() {
- executeTarget("simple-compile");
- assertTrue(new File(getProject().getProperty("output"), "org_example_Foo.h")
+ buildRule.executeTarget("simple-compile");
+ assertTrue(new File(buildRule.getProject().getProperty("output"), "org_example_Foo.h")
.exists());
}
+ @Test
public void testCompileFileset() {
- executeTarget("test-fileset");
- assertTrue(new File(getProject().getProperty("output"), "org_example_Foo.h")
- .exists());
+ buildRule.executeTarget("test-fileset");
+ assertTrue(new File(buildRule.getProject().getProperty("output"), "org_example_Foo.h").exists());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JspcTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JspcTest.java
index 4954af7ef..57475cc10 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JspcTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/JspcTest.java
@@ -19,64 +19,56 @@ package org.apache.tools.ant.taskdefs.optional;
import java.io.File;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.taskdefs.optional.jsp.Jasper41Mangler;
import org.apache.tools.ant.taskdefs.optional.jsp.JspMangler;
import org.apache.tools.ant.taskdefs.optional.jsp.JspNameMangler;
import org.apache.tools.ant.taskdefs.optional.jsp.compilers.JspCompilerAdapter;
import org.apache.tools.ant.taskdefs.optional.jsp.compilers.JspCompilerAdapterFactory;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Tests the Jspc task.
*
- * @created 07 March 2002
+ * created 07 March 2002
* @since Ant 1.5
*/
-public class JspcTest extends BuildFileTest {
+public class JspcTest {
- /**
- * Description of the Field
- */
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/";
- /**
- * Constructor for the JspcTest object
- *
- * @param name Description of Parameter
- */
- public JspcTest(String name) {
- super(name);
- }
-
-
- /**
- * The JUnit setup method
- */
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "jspc.xml");
- }
+ buildRule.configureProject(TASKDEFS_DIR + "jspc.xml");
+ }
- /**
- * A unit test for JUnit
- */
- public void testSimple() throws Exception {
+
+ @Test
+ public void testSimple() {
executeJspCompile("testSimple", "simple_jsp.java");
}
- /**
- * A unit test for JUnit
- */
+ @Test
public void testUriroot() throws Exception {
executeJspCompile("testUriroot", "uriroot_jsp.java");
}
- /**
- * A unit test for JUnit
- */
+ @Test
public void testXml() throws Exception {
executeJspCompile("testXml", "xml_jsp.java");
}
@@ -85,6 +77,7 @@ public class JspcTest extends BuildFileTest {
/**
* try a keyword in a file
*/
+ @Test
public void testKeyword() throws Exception {
executeJspCompile("testKeyword", "default_jsp.java");
}
@@ -93,51 +86,47 @@ public class JspcTest extends BuildFileTest {
/**
* what happens to 1nvalid-classname
*/
+ @Test
public void testInvalidClassname() throws Exception {
executeJspCompile("testInvalidClassname",
"_1nvalid_0002dclassname_jsp.java");
}
- /**
- * A unit test for JUnit
- */
+ @Test
public void testNoTld() throws Exception {
-// expectBuildExceptionContaining("testNoTld",
-// "Jasper found an error in a file",
-// "Java returned: 9");
- expectBuildExceptionContaining("testNoTld",
- "not found",
- "Java returned: 9");
+ try {
+ buildRule.executeTarget("testNoTld");
+ fail("Not found");
+ } catch (BuildException ex) {
+ assertEquals("Java returned: 9", ex.getMessage());
+ }
}
- /**
- * A unit test for JUnit
- */
+ @Test
public void testNotAJspFile() throws Exception {
- executeTarget("testNotAJspFile");
+ buildRule.executeTarget("testNotAJspFile");
}
/**
* webapp test is currently broken, because it picks up
* on the missing_tld file, and bails.
*/
-/*
+ @Ignore("picks up on the missing_tld file, and incorrectly bails")
+ @Test
public void testWebapp() throws Exception {
- executeTarget("testWebapp");
+ buildRule.executeTarget("testWebapp");
}
-*/
+
/**
* run a target then verify the named file gets created
*
* @param target Description of Parameter
* @param javafile Description of Parameter
- * @exception Exception trouble
*/
- protected void executeJspCompile(String target, String javafile)
- throws Exception {
- executeTarget(target);
+ protected void executeJspCompile(String target, String javafile) {
+ buildRule.executeTarget(target);
assertJavaFileCreated(javafile);
}
@@ -146,10 +135,8 @@ public class JspcTest extends BuildFileTest {
* verify that a named file was created
*
* @param filename Description of Parameter
- * @exception Exception trouble
*/
- protected void assertJavaFileCreated(String filename)
- throws Exception {
+ protected void assertJavaFileCreated(String filename) {
File file = getOutputFile(filename);
assertTrue("file " + filename + " not found", file.exists());
assertTrue("file " + filename + " is empty", file.length() > 0);
@@ -162,12 +149,13 @@ public class JspcTest extends BuildFileTest {
* @return The OutputFile value
*/
protected File getOutputFile(String subpath) {
- return new File(getOutputDir(), subpath);
+ return new File(buildRule.getProject().getProperty("output"), subpath);
}
/**
* verify that we select the appropriate mangler
*/
+ @Test
public void testJasperNameManglerSelection() {
JspCompilerAdapter adapter=
JspCompilerAdapterFactory.getCompiler("jasper", null,null);
@@ -178,6 +166,7 @@ public class JspcTest extends BuildFileTest {
assertTrue(mangler instanceof Jasper41Mangler);
}
+ @Test
public void testJasper41() {
JspMangler mangler = new Jasper41Mangler();
//java keywords are not special
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/Native2AsciiTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/Native2AsciiTest.java
index c6886d4f3..53da2af41 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/Native2AsciiTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/Native2AsciiTest.java
@@ -19,26 +19,39 @@
package org.apache.tools.ant.taskdefs.optional;
import java.io.File;
-import org.apache.tools.ant.BuildFileTest;
+
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
-public class Native2AsciiTest extends BuildFileTest {
+public class Native2AsciiTest {
private final static String BUILD_XML =
"src/etc/testcases/taskdefs/optional/native2ascii/build.xml";
- public Native2AsciiTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(BUILD_XML);
+ buildRule.configureProject(BUILD_XML);
+ }
+
+ @After
+ public void tearDown() {
+ buildRule.executeTarget("tearDown");
}
+ @Test
public void testIso8859_1() throws java.io.IOException {
- executeTarget("testIso8859-1");
- File in = getProject().resolveFile("expected/iso8859-1.test");
- File out = new File(getProject().getProperty("output"), "iso8859-1.test");
+ buildRule.executeTarget("testIso8859-1");
+ File in = buildRule.getProject().resolveFile("expected/iso8859-1.test");
+ File out = new File(buildRule.getProject().getProperty("output"), "iso8859-1.test");
assertTrue(FileUtils.getFileUtils().contentEquals(in, out, true));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PropertyFileTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PropertyFileTest.java
index 3e6c4b9b0..7056ca90d 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PropertyFileTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PropertyFileTest.java
@@ -20,41 +20,49 @@ package org.apache.tools.ant.taskdefs.optional;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.util.Properties;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
/**
* JUnit testcase that exercises the optional PropertyFile task in ant.
* (this is really more of a functional test so far.., but it's enough to let
* me start refactoring...)
*
- *@created October 2, 2001
+ *created October 2, 2001
*/
-public class PropertyFileTest extends BuildFileTest {
-
- public PropertyFileTest(String name) {
- super(name);
- }
+public class PropertyFileTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() throws Exception {
- configureProject(projectFilePath);
- executeTarget("setUp");
+ buildRule.configureProject(projectFilePath);
+ buildRule.executeTarget("setUp");
initTestPropFile();
initBuildPropFile();
- configureProject(projectFilePath);
- project.setProperty(valueDoesNotGetOverwrittenPropertyFileKey,valueDoesNotGetOverwrittenPropertyFile);
+ buildRule.configureProject(projectFilePath);
+ buildRule.getProject().setProperty(valueDoesNotGetOverwrittenPropertyFileKey,
+ valueDoesNotGetOverwrittenPropertyFile);
}
+ @Test
public void testNonExistingFile() {
PropertyFile props = new PropertyFile();
- props.setProject( getProject() );
+ props.setProject( buildRule.getProject() );
File file = new File("this-file-does-not-exist.properties");
props.setFile(file);
assertFalse("Properties file exists before test.", file.exists());
@@ -67,6 +75,7 @@ public class PropertyFileTest extends BuildFileTest {
* A unit test for JUnit- Exercises the propertyfile tasks ability to
* update properties that are already defined-
*/
+ @Test
public void testUpdatesExistingProperties() throws Exception {
Properties beforeUpdate = getTestProperties();
assertEquals(FNAME, beforeUpdate.getProperty(FNAME_KEY));
@@ -77,7 +86,7 @@ public class PropertyFileTest extends BuildFileTest {
assertEquals(null, beforeUpdate.getProperty(DATE_KEY));
// ask ant to update the properties...
- executeTarget("update-existing-properties");
+ buildRule.executeTarget("update-existing-properties");
Properties afterUpdate = getTestProperties();
assertEquals(NEW_FNAME, afterUpdate.getProperty(FNAME_KEY));
@@ -87,7 +96,8 @@ public class PropertyFileTest extends BuildFileTest {
assertEquals(NEW_AGE, afterUpdate.getProperty(AGE_KEY));
assertEquals(NEW_DATE, afterUpdate.getProperty(DATE_KEY));
}
-
+
+ @Test
public void testDeleteProperties() throws Exception {
Properties beforeUpdate = getTestProperties();
assertEquals("Property '" + FNAME_KEY + "' should exist before deleting",
@@ -95,7 +105,7 @@ public class PropertyFileTest extends BuildFileTest {
assertEquals("Property '" + LNAME_KEY + "' should exist before deleting",
LNAME, beforeUpdate.getProperty(LNAME_KEY));
- executeTarget("delete-properties");
+ buildRule.executeTarget("delete-properties");
Properties afterUpdate = getTestProperties();
assertEquals("Property '" + LNAME_KEY + "' should exist after deleting",
@@ -104,49 +114,77 @@ public class PropertyFileTest extends BuildFileTest {
afterUpdate.getProperty(FNAME_KEY));
}
+ @Test
public void testExerciseDefaultAndIncrement() throws Exception {
- executeTarget("exercise");
- assertEquals("3",project.getProperty("int.with.default"));
- assertEquals("1",project.getProperty("int.without.default"));
- assertEquals("-->",project.getProperty("string.with.default"));
- assertEquals(".",project.getProperty("string.without.default"));
- assertEquals("2002/01/21 12:18", project.getProperty("ethans.birth"));
- assertEquals("2003/01/21", project.getProperty("first.birthday"));
- assertEquals("0124", project.getProperty("olderThanAWeek"));
- assertEquals("37", project.getProperty("existing.prop"));
- assertEquals("6",project.getProperty("int.without.value"));
+ buildRule.executeTarget("exercise");
+ assertEquals("3",buildRule.getProject().getProperty("int.with.default"));
+ assertEquals("1",buildRule.getProject().getProperty("int.without.default"));
+ assertEquals("-->",buildRule.getProject().getProperty("string.with.default"));
+ assertEquals(".",buildRule.getProject().getProperty("string.without.default"));
+ assertEquals("2002/01/21 12:18", buildRule.getProject().getProperty("ethans.birth"));
+ assertEquals("2003/01/21", buildRule.getProject().getProperty("first.birthday"));
+ assertEquals("0124", buildRule.getProject().getProperty("olderThanAWeek"));
+ assertEquals("37", buildRule.getProject().getProperty("existing.prop"));
+ assertEquals("6",buildRule.getProject().getProperty("int.without.value"));
}
+ @Test
public void testValueDoesNotGetOverwritten() {
// this test shows that the bug report 21505 is fixed
- executeTarget("bugDemo1");
- executeTarget("bugDemo2");
- assertEquals("5", project.getProperty("foo"));
+ buildRule.executeTarget("bugDemo1");
+ buildRule.executeTarget("bugDemo2");
+ assertEquals("5", buildRule.getProject().getProperty("foo"));
}
+
+ @Test
+ @Ignore("Previously commented out")
+ public void testDirect() throws Exception {
+ PropertyFile pf = new PropertyFile();
+ pf.setProject(buildRule.getProject());
+ pf.setFile(new File(System.getProperty("root"), testPropsFilePath));
+ PropertyFile.Entry entry = pf.createEntry();
+
+ entry.setKey("date");
+ entry.setValue("123");
+ PropertyFile.Entry.Type type = new PropertyFile.Entry.Type();
+ type.setValue("date");
+ entry.setType(type);
+
+ entry.setPattern("yyyy/MM/dd");
+
+ PropertyFile.Entry.Operation operation = new PropertyFile.Entry.Operation();
+ operation.setValue("+");
+ pf.execute();
+
+ Properties props = getTestProperties();
+ assertEquals("yeehaw", props.getProperty("date"));
+ }
+
+
private Properties getTestProperties() throws Exception {
Properties testProps = new Properties();
- FileInputStream propsFile = new FileInputStream(new File(getOutputDir(), testPropsFilePath));
+ FileInputStream propsFile = new FileInputStream(new File(buildRule.getOutputDir(), testPropsFilePath));
testProps.load(propsFile);
propsFile.close();
return testProps;
}
- private void initTestPropFile() throws Exception {
+ private void initTestPropFile() throws IOException {
Properties testProps = new Properties();
testProps.put(FNAME_KEY, FNAME);
testProps.put(LNAME_KEY, LNAME);
testProps.put(EMAIL_KEY, EMAIL);
testProps.put("existing.prop", "37");
- FileOutputStream fos = new FileOutputStream(new File(getOutputDir(), testPropsFilePath));
+ FileOutputStream fos = new FileOutputStream(new File(buildRule.getOutputDir(), testPropsFilePath));
testProps.store(fos, "defaults");
fos.close();
}
- private void initBuildPropFile() throws Exception {
+ private void initBuildPropFile() throws IOException {
Properties buildProps = new Properties();
buildProps.put(testPropertyFileKey, testPropertyFile);
buildProps.put(FNAME_KEY, NEW_FNAME);
@@ -156,14 +194,11 @@ public class PropertyFileTest extends BuildFileTest {
buildProps.put(AGE_KEY, NEW_AGE);
buildProps.put(DATE_KEY, NEW_DATE);
- FileOutputStream fos = new FileOutputStream(new File(getOutputDir(), buildPropsFilePath));
+ FileOutputStream fos = new FileOutputStream(new File(buildRule.getOutputDir(), buildPropsFilePath));
buildProps.store(fos, null);
fos.close();
}
-
-
-
private static final String
projectFilePath = "src/etc/testcases/taskdefs/optional/propertyfile.xml",
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PvcsTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PvcsTest.java
index 0dc1d7092..cd7a43168 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PvcsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/PvcsTest.java
@@ -18,41 +18,62 @@
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-/**
- */
-public class PvcsTest extends BuildFileTest {
+import static org.junit.Assert.fail;
- public PvcsTest(String name) {
- super(name);
- }
+public class PvcsTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/pvcs.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/pvcs.xml");
}
+ @Test
public void test1() {
- expectBuildException("test1", "Required argument repository not specified");
+ try {
+ buildRule.executeTarget("test1");
+ fail("Required argument repository not specified");
+ } catch (BuildException ex) {
+ //TODO check exception message
+ }
}
+ @Test
public void test2() {
- executeTarget("test2");
+ buildRule.executeTarget("test2");
}
+ @Test
public void test3() {
- executeTarget("test3");
+ buildRule.executeTarget("test3");
}
+ @Test
public void test4() {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
}
+ @Test
public void test5() {
- executeTarget("test5");
+ buildRule.executeTarget("test5");
}
+ @Test
public void test6() {
- expectBuildException("test6", "Failed executing: /never/heard/of/a/directory/structure/like/this/pcli lvf -z -aw -pr//ct4serv2/pvcs/monitor /. Exception: /never/heard/of/a/directory/structure/like/this/pcli: not found");
+ try {
+ buildRule.executeTarget("test6");
+ fail("Failed executing: /never/heard/of/a/directory/structure/like/this/pcli lvf -z " +
+ "-aw -pr//ct4serv2/pvcs/monitor /. Exception: /never/heard/of/a/directory/structure/like/this/pcli: not found");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ReplaceRegExpTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ReplaceRegExpTest.java
index 126acd1d9..b6c09a5cf 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ReplaceRegExpTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ReplaceRegExpTest.java
@@ -17,35 +17,44 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.FileUtilities;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.util.Properties;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assume.assumeTrue;
+
/**
* JUnit Testcase for the optional replaceregexp task.
*
*/
-public class ReplaceRegExpTest extends BuildFileTest {
+public class ReplaceRegExpTest {
private static final String PROJECT_PATH = "src/etc/testcases/taskdefs/optional";
- private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public ReplaceRegExpTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(PROJECT_PATH + "/replaceregexp.xml");
+ buildRule.configureProject(PROJECT_PATH + "/replaceregexp.xml");
}
+ @Test
public void testReplace() throws IOException {
Properties original = new Properties();
FileInputStream propsFile = null;
try {
- propsFile = new FileInputStream(new File(project.getBaseDir() + "/replaceregexp.properties"));
+ propsFile = new FileInputStream(new File(buildRule.getProject().getBaseDir() + "/replaceregexp.properties"));
original.load(propsFile);
} finally {
if (propsFile != null) {
@@ -56,62 +65,68 @@ public class ReplaceRegExpTest extends BuildFileTest {
assertEquals("Def", original.get("OldAbc"));
- executeTarget("testReplace");
+ buildRule.executeTarget("testReplace");
Properties after = new Properties();
try {
- propsFile = new FileInputStream(new File(getOutputDir(), "test.properties"));
+ propsFile = new FileInputStream(new File(buildRule.getOutputDir(), "test.properties"));
after.load(propsFile);
} finally {
if (propsFile != null) {
propsFile.close();
- propsFile = null;
}
}
assertNull(after.get("OldAbc"));
assertEquals("AbcDef", after.get("NewProp"));
}
+
// inspired by bug 22541
+ @Test
public void testDirectoryDateDoesNotChange() {
- executeTarget("touchDirectory");
- File myFile = getOutputDir();
+ buildRule.executeTarget("touchDirectory");
+ File myFile = buildRule.getOutputDir();
long timeStampBefore = myFile.lastModified();
- executeTarget("testDirectoryDateDoesNotChange");
+ buildRule.executeTarget("testDirectoryDateDoesNotChange");
long timeStampAfter = myFile.lastModified();
assertEquals("directory date should not change",
timeStampBefore, timeStampAfter);
}
+
+ @Test
public void testDontAddNewline1() throws IOException {
- executeTarget("testDontAddNewline1");
- assertTrue("Files match",
- FILE_UTILS
- .contentEquals(new File(getOutputDir(), "test.properties"),
- new File(getProjectDir(), "replaceregexp2.result.properties")));
+ buildRule.executeTarget("testDontAddNewline1");
+ assertEquals(FileUtilities.getFileContents(new File(buildRule.getOutputDir(), "test.properties")),
+ FileUtilities.getFileContents(new File(buildRule.getProject().getBaseDir(), "replaceregexp2.result.properties")));
}
+ @Test
public void testDontAddNewline2() throws IOException {
- executeTarget("testDontAddNewline2");
- assertTrue("Files match",
- FILE_UTILS
- .contentEquals(new File(getOutputDir(), "test.properties"),
- new File(getProjectDir(), "replaceregexp2.result.properties")));
+ buildRule.executeTarget("testDontAddNewline2");
+ assertEquals(FileUtilities.getFileContents(new File(buildRule.getOutputDir(), "test.properties")),
+ FileUtilities.getFileContents(new File(buildRule.getProject().getBaseDir(), "replaceregexp2.result.properties")));
}
+ @Test
public void testNoPreserveLastModified() throws Exception {
- executeTarget("lastModifiedSetup");
- long ts1 = new File(getOutputDir(), "test.txt").lastModified();
- Thread.sleep(3000);
- executeTarget("testNoPreserve");
- assertTrue(ts1 < new File(getOutputDir(), "test.txt").lastModified());
+ buildRule.executeTarget("lastModifiedSetup");
+ File testFile = new File(buildRule.getOutputDir(), "test.txt");
+ assumeTrue(testFile.setLastModified(testFile.lastModified()
+ - (FileUtils.getFileUtils().getFileTimestampGranularity() * 3)));
+ long ts1 = testFile.lastModified();
+ buildRule.executeTarget("testNoPreserve");
+ assertTrue(ts1 < testFile.lastModified());
}
+ @Test
public void testPreserveLastModified() throws Exception {
- executeTarget("lastModifiedSetup");
- long ts1 = new File(getOutputDir(), "test.txt").lastModified();
- Thread.sleep(3000);
- executeTarget("testPreserve");
- assertTrue(ts1 == new File(getOutputDir(), "test.txt").lastModified());
+ buildRule.executeTarget("lastModifiedSetup");
+ File testFile = new File(buildRule.getOutputDir(), "test.txt");
+ assumeTrue(testFile.setLastModified(testFile.lastModified()
+ - (FileUtils.getFileUtils().getFileTimestampGranularity() * 3)));
+ long ts1 = testFile.lastModified();
+ buildRule.executeTarget("testPreserve");
+ assertEquals(ts1 , testFile.lastModified());
}
}// ReplaceRegExpTest
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoReferenceTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoReferenceTest.java
index 64ae4f4a7..41803de64 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoReferenceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoReferenceTest.java
@@ -17,28 +17,29 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Tests using an undefined reference.
*
* @since Ant 1.6
*/
-public class RhinoReferenceTest extends BuildFileTest {
+public class RhinoReferenceTest {
- public RhinoReferenceTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject(
- "src/etc/testcases/taskdefs/optional/script_reference.xml");
+ buildRule.configureProject(
+ "src/etc/testcases/taskdefs/optional/script_reference.xml");
}
+ @Test
public void testScript() {
- executeTarget("script");
+ buildRule.executeTarget("script");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java
index f3f3a4943..35576dcb6 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java
@@ -17,47 +17,50 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
/**
* Tests the examples of the <script> task docs.
*
* @since Ant 1.5.2
*/
-public class RhinoScriptTest extends BuildFileTest {
-
- public RhinoScriptTest(String name) {
- super(name);
- }
+public class RhinoScriptTest {
- /**
- * The JUnit setup method
- */
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/script.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/script.xml");
}
+ @Test
public void testExample1() {
- executeTarget("example1");
- int index = getLog().indexOf("1");
+ buildRule.executeTarget("example1");
+ int index = buildRule.getLog().indexOf("1");
assertTrue(index > -1);
- index = getLog().indexOf("4", index);
+ index = buildRule.getLog().indexOf("4", index);
assertTrue(index > -1);
- index = getLog().indexOf("9", index);
+ index = buildRule.getLog().indexOf("9", index);
assertTrue(index > -1);
- index = getLog().indexOf("16", index);
+ index = buildRule.getLog().indexOf("16", index);
assertTrue(index > -1);
- index = getLog().indexOf("25", index);
+ index = buildRule.getLog().indexOf("25", index);
assertTrue(index > -1);
- index = getLog().indexOf("36", index);
+ index = buildRule.getLog().indexOf("36", index);
assertTrue(index > -1);
- index = getLog().indexOf("49", index);
+ index = buildRule.getLog().indexOf("49", index);
assertTrue(index > -1);
- index = getLog().indexOf("64", index);
+ index = buildRule.getLog().indexOf("64", index);
assertTrue(index > -1);
- index = getLog().indexOf("81", index);
+ index = buildRule.getLog().indexOf("81", index);
assertTrue(index > -1);
- index = getLog().indexOf("100", index);
+ index = buildRule.getLog().indexOf("100", index);
assertTrue(index > -1);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RpmTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RpmTest.java
index 17cf95322..ac4462d53 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RpmTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/RpmTest.java
@@ -21,10 +21,15 @@ import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.ExecuteStreamHandler;
import org.apache.tools.ant.types.Commandline;
-import junit.framework.TestCase;
-public class RpmTest extends TestCase {
+import org.junit.Test;
+import static org.junit.Assert.fail;
+import static org.apache.tools.ant.AntAssert.assertContains;
+
+public class RpmTest {
+
+ @Test
public void testShouldThrowExceptionWhenRpmFails() throws Exception {
Rpm rpm = new MyRpm();
rpm.setProject(new org.apache.tools.ant.Project());
@@ -34,11 +39,11 @@ public class RpmTest extends TestCase {
rpm.execute();
fail("should have thrown a build exception");
} catch (BuildException ex) {
- assertTrue(ex.getMessage()
- .indexOf("' failed with exit code 2") != -1);
+ assertContains("' failed with exit code 2", ex.getMessage());
}
}
+ @Test
public void testShouldNotThrowExceptionWhenRpmFails() throws Exception {
Rpm rpm = new MyRpm();
rpm.execute();
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/SchemaValidateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/SchemaValidateTest.java
index 3793e2fdc..667c8904c 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/SchemaValidateTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/SchemaValidateTest.java
@@ -17,13 +17,20 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
* Test schema validation
*/
-public class SchemaValidateTest extends BuildFileTest {
+public class SchemaValidateTest {
/**
* where tasks run
@@ -31,69 +38,91 @@ public class SchemaValidateTest extends BuildFileTest {
private final static String TASKDEFS_DIR =
"src/etc/testcases/taskdefs/optional/";
- /**
- * Constructor
- *
- * @param name testname
- */
- public SchemaValidateTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "schemavalidate.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "schemavalidate.xml");
}
/**
* test with no namespace
*/
+ @Test
public void testNoNamespace() throws Exception {
- executeTarget("testNoNamespace");
+ buildRule.executeTarget("testNoNamespace");
}
/**
* add namespace awareness.
*/
+ @Test
public void testNSMapping() throws Exception {
- executeTarget("testNSMapping");
+ buildRule.executeTarget("testNSMapping");
}
+ @Test
public void testNoEmptySchemaNamespace() throws Exception {
- expectBuildExceptionContaining("testNoEmptySchemaNamespace",
- "empty namespace URI",SchemaValidate.SchemaLocation.ERROR_NO_URI);
+ try {
+ buildRule.executeTarget("testNoEmptySchemaNamespace");
+ fail("Empty namespace URI");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(SchemaValidate.SchemaLocation.ERROR_NO_URI, ex.getMessage());
+ }
}
+ @Test
public void testNoEmptySchemaLocation() throws Exception {
- expectBuildExceptionContaining("testNoEmptySchemaLocation",
- "empty schema location",
- SchemaValidate.SchemaLocation.ERROR_NO_LOCATION);
+ try {
+ buildRule.executeTarget("testNoEmptySchemaLocation");
+ fail("Empty schema location");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(SchemaValidate.SchemaLocation.ERROR_NO_LOCATION,
+ ex.getMessage());
+ }
}
+ @Test
public void testNoFile() throws Exception {
- expectBuildExceptionContaining("testNoFile",
- "no file at file attribute",
- SchemaValidate.SchemaLocation.ERROR_NO_FILE);
+ try {
+ buildRule.executeTarget("testNoFile");
+ fail("No file at file attribute");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(SchemaValidate.SchemaLocation.ERROR_NO_FILE,
+ ex.getMessage());
+ }
}
+ @Test
public void testNoDoubleSchemaLocation() throws Exception {
- expectBuildExceptionContaining("testNoDoubleSchemaLocation",
- "two locations for schemas",
- SchemaValidate.SchemaLocation.ERROR_TWO_LOCATIONS);
+ try {
+ buildRule.executeTarget("testNoDoubleSchemaLocation");
+ fail("Two locations for schemas");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(SchemaValidate.SchemaLocation.ERROR_TWO_LOCATIONS,
+ ex.getMessage());
+ }
}
+
+ @Test
public void testNoDuplicateSchema() throws Exception {
- expectBuildExceptionContaining("testNoDuplicateSchema",
- "duplicate schemas with different values",
- SchemaValidate.ERROR_DUPLICATE_SCHEMA);
+ try {
+ buildRule.executeTarget("testNoDuplicateSchema");
+ fail("duplicate schemas with different values");
+ } catch (BuildException ex) {
+ AntAssert.assertContains(SchemaValidate.ERROR_DUPLICATE_SCHEMA,
+ ex.getMessage());
+ }
}
+ @Test
public void testEqualsSchemasOK() throws Exception {
- executeTarget("testEqualsSchemasOK");
+ buildRule.executeTarget("testEqualsSchemasOK");
}
+ @Test
public void testFileset() throws Exception {
- executeTarget("testFileset");
+ buildRule.executeTarget("testFileset");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/TraXLiaisonTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/TraXLiaisonTest.java
index 8a50fba66..02281eb65 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/TraXLiaisonTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/TraXLiaisonTest.java
@@ -1,9 +1,6 @@
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.taskdefs.XSLTLiaison;
-import org.apache.tools.ant.taskdefs.XSLTLogger;
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.util.JAXPUtils;
+import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -12,6 +9,14 @@ import java.security.Permission;
import junit.framework.AssertionFailedError;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.taskdefs.XSLTLiaison;
+import org.apache.tools.ant.taskdefs.XSLTLogger;
+import org.apache.tools.ant.util.JAXPUtils;
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Test;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -36,10 +41,8 @@ import junit.framework.AssertionFailedError;
public class TraXLiaisonTest extends AbstractXSLTLiaisonTest
implements XSLTLogger {
- public TraXLiaisonTest(String name){
- super(name);
- }
+ @After
public void tearDown() {
File f = new File("xalan2-redirect-out.tmp");
if (f.exists()) {
@@ -53,16 +56,12 @@ public class TraXLiaisonTest extends AbstractXSLTLiaisonTest
return l;
}
+ @Test
public void testXalan2Redirect() throws Exception {
- Class clazz = null;
try {
- clazz = getClass().getClassLoader().loadClass("org.apache.xalan.lib.Redirect");
+ getClass().getClassLoader().loadClass("org.apache.xalan.lib.Redirect");
} catch (Exception exc) {
- // ignore
- }
- if (clazz == null) {
- System.out.println("xalan redirect is not on the classpath");
- return;
+ Assume.assumeNoException("xalan redirect is not on the classpath", exc);
}
File xsl = getFile("/taskdefs/optional/xalan-redirect-in.xsl");
liaison.setStylesheet(xsl);
@@ -91,6 +90,7 @@ public class TraXLiaisonTest extends AbstractXSLTLiaisonTest
}
}
+ @Test
public void testMultipleTransform() throws Exception {
File xsl = getFile("/taskdefs/optional/xsltliaison-in.xsl");
liaison.setStylesheet(xsl);
@@ -109,6 +109,7 @@ public class TraXLiaisonTest extends AbstractXSLTLiaisonTest
}
}
+ @Test
public void testSystemId(){
File file = null;
if ( File.separatorChar == '\\' ){
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateCatalogTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateCatalogTest.java
index 64db8e742..c9948bb9a 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateCatalogTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateCatalogTest.java
@@ -17,7 +17,10 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Tests the XMLValidate optional task with nested external catalogs.
@@ -25,39 +28,22 @@ import org.apache.tools.ant.BuildFileTest;
* @see XmlValidateTest
* @since Ant 1.6
*/
-public class XmlValidateCatalogTest extends BuildFileTest {
+public class XmlValidateCatalogTest {
/**
* where tasks run
*/
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/";
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * Constructor
- *
- * @param name testname
- */
- public XmlValidateCatalogTest(String name) {
- super(name);
- }
-
-
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "xmlvalidate.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "xmlvalidate.xml");
}
- /**
- * The teardown method for JUnit
- */
- public void tearDown() {
-
- }
-
/**
* catalogfiles fileset should be ignored
* if resolver.jar is not present, but will
@@ -65,8 +51,9 @@ public class XmlValidateCatalogTest extends BuildFileTest {
* work b/c we have a nested dtd with the same
* entity
*/
+ @Test
public void testXmlCatalogFiles() {
- executeTarget("xmlcatalogfiles");
+ buildRule.executeTarget("xmlcatalogfiles");
}
/**
@@ -76,8 +63,9 @@ public class XmlValidateCatalogTest extends BuildFileTest {
* way, test should work b/c we have a nested
* dtd with the same entity
*/
+ @Test
public void testXmlCatalogPath() {
- executeTarget("xmlcatalogpath");
+ buildRule.executeTarget("xmlcatalogpath");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java
index 27be8a415..58f7a4b1f 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XmlValidateTest.java
@@ -18,7 +18,14 @@
package org.apache.tools.ant.taskdefs.optional;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.internal.AssumptionViolatedException;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Tests the XMLValidate optional task, by running targets in the test script
@@ -28,7 +35,7 @@ import org.apache.tools.ant.BuildFileTest;
* @see XmlValidateCatalogTest
* @since Ant 1.5
*/
-public class XmlValidateTest extends BuildFileTest {
+public class XmlValidateTest {
/**
* where tasks run
@@ -36,61 +43,47 @@ public class XmlValidateTest extends BuildFileTest {
private final static String TASKDEFS_DIR =
"src/etc/testcases/taskdefs/optional/";
- /**
- * Constructor
- *
- * @param name testname
- */
- public XmlValidateTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "xmlvalidate.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "xmlvalidate.xml");
}
- /**
- * The teardown method for JUnit
- */
- public void tearDown() {}
-
/**
* Basic inline 'dtd' element test.
*/
+ @Test
public void testValidate() throws Exception {
- executeTarget("testValidate");
+ buildRule.executeTarget("testValidate");
}
/**
* Test indirect validation.
*/
+ @Test
public void testDeepValidate() throws Exception {
- executeTarget("testDeepValidate");
+ buildRule.executeTarget("testDeepValidate");
}
- /**
- *
- */
+ @Test
public void testXmlCatalog() {
- executeTarget("xmlcatalog");
+ buildRule.executeTarget("xmlcatalog");
}
- /**
- *
- */
+ @Test
public void testXmlCatalogViaRefid() {
- executeTarget("xmlcatalogViaRefid");
+ buildRule.executeTarget("xmlcatalogViaRefid");
}
/**
* Test that the nested dtd element is used when resolver.jar is not
* present. This test should pass either way.
*/
+ @Test
public void testXmlCatalogFiles() {
- executeTarget("xmlcatalogfiles-override");
+ buildRule.executeTarget("xmlcatalogfiles-override");
}
/**
@@ -98,30 +91,33 @@ public class XmlValidateTest extends BuildFileTest {
* Test that the nested dtd element is used when resolver.jar is not
* present. This test should pass either way.
*/
+ @Test
public void testXmlCatalogPath() {
- executeTarget("xmlcatalogpath-override");
+ buildRule.executeTarget("xmlcatalogpath-override");
}
/**
* Test nested xmlcatalog definitions
*/
+ @Test
public void testXmlCatalogNested() {
- executeTarget("xmlcatalognested");
+ buildRule.executeTarget("xmlcatalognested");
}
/**
* Test xml schema validation
*/
+ @Test
public void testXmlSchemaGood() throws BuildException {
try {
- executeTarget("testSchemaGood");
+ buildRule.executeTarget("testSchemaGood");
} catch (BuildException e) {
if (e
.getMessage()
.endsWith(" doesn't recognize feature http://apache.org/xml/features/validation/schema")
|| e.getMessage().endsWith(
" doesn't support feature http://apache.org/xml/features/validation/schema")) {
- System.err.println(" skipped, parser doesn't support schema");
+ throw new AssumptionViolatedException("parser doesn't support schema");
} else {
throw e;
}
@@ -130,22 +126,19 @@ public class XmlValidateTest extends BuildFileTest {
/**
* Test xml schema validation
*/
+ @Test
public void testXmlSchemaBad() {
try {
- executeTarget("testSchemaBad");
+ buildRule.executeTarget("testSchemaBad");
fail("Should throw BuildException because 'Bad Schema Validation'");
- expectBuildExceptionContaining(
- "testSchemaBad",
- "Bad Schema Validation",
- "not a valid XML document");
} catch (BuildException e) {
if (e
.getMessage()
.endsWith(" doesn't recognize feature http://apache.org/xml/features/validation/schema")
|| e.getMessage().endsWith(
" doesn't support feature http://apache.org/xml/features/validation/schema")) {
- System.err.println(" skipped, parser doesn't support schema");
+ throw new AssumptionViolatedException("parser doesn't support schema");
} else {
assertTrue(
e.getMessage().indexOf("not a valid XML document") > -1);
@@ -159,8 +152,9 @@ public class XmlValidateTest extends BuildFileTest {
*
* Bug 11279
*/
+ @Test
public void testIso2022Jp() {
- executeTarget("testIso2022Jp");
+ buildRule.executeTarget("testIso2022Jp");
}
/**
@@ -170,20 +164,30 @@ public class XmlValidateTest extends BuildFileTest {
*
* Bug 11279
*/
+ @Test
public void testUtf8() {
- expectBuildException("testUtf8", "invalid characters in file");
+ try {
+ buildRule.executeTarget("testUtf8");
+ fail("Invalid characters in file");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
// Tests property element, using XML schema properties as an example.
-
+ @Test
public void testPropertySchemaForValidXML() {
- executeTarget("testProperty.validXML");
+ buildRule.executeTarget("testProperty.validXML");
}
+ @Test
public void testPropertySchemaForInvalidXML() {
- expectBuildException(
- "testProperty.invalidXML",
- "XML file does not satisfy schema.");
+ try {
+ buildRule.executeTarget("testProperty.invalidXML");
+ fail("XML file does not satisfy schema");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java
index a23afd4ca..a5b71def9 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/XsltTest.java
@@ -17,71 +17,68 @@
*/
package org.apache.tools.ant.taskdefs.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
- * Tests the {@link XSLTProcess} task.
- * TODO merge with {@link StyleTest}?
+ * Tests the {@link org.apache.tools.ant.taskdefs.XSLTProcess} task.
+ * TODO merge with {@link org.apache.tools.ant.taskdefs.StyleTest}?
* @since Ant 1.5
*/
-public class XsltTest extends BuildFileTest {
+public class XsltTest {
/**
* where tasks run
*/
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/";
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * Constructor
- *
- * @param name testname
- */
- public XsltTest(String name) {
- super(name);
- }
-
-
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "xslt.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "xslt.xml");
}
-
- /**
- * A unit test for JUnit
- */
- public void testCatchNoDtd() throws Exception {
- expectBuildExceptionContaining("testCatchNoDtd",
- "expected failure",
- /* actually: "chemical" */null);
+ @Test
+ public void testCatchNoDtd() {
+ try {
+ buildRule.executeTarget("testCatchNoDtd");
+ fail("Expected failure");
+ } catch(BuildException ex) {
+ //TODO assert exception message
+ }
}
- /**
- * A unit test for JUnit
- */
+ @Test
public void testCatalog() throws Exception {
- executeTarget("testCatalog");
+ buildRule.executeTarget("testCatalog");
}
+ @Test
public void testOutputProperty() throws Exception {
- executeTarget("testOutputProperty");
+ buildRule.executeTarget("testOutputProperty");
}
+ @Test
public void testXMLWithEntitiesInNonAsciiPath() throws Exception {
- executeTarget("testXMLWithEntitiesInNonAsciiPath");
+ buildRule.executeTarget("testXMLWithEntitiesInNonAsciiPath");
}
/**
* check that the system id gets set properly on stylesheets.
* @throws Exception if something goes wrong.
*/
+ @Test
public void testStyleSheetWithInclude() throws Exception {
- executeTarget("testStyleSheetWithInclude");
- if (getLog().indexOf("java.io.FileNotFoundException") != -1) {
+ buildRule.executeTarget("testStyleSheetWithInclude");
+ if (buildRule.getLog().indexOf("java.io.FileNotFoundException") != -1) {
fail("xsl:include was not found");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/depend/DependTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/depend/DependTest.java
index 020dcb7aa..95c1eb0b1 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/depend/DependTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/depend/DependTest.java
@@ -18,35 +18,53 @@
package org.apache.tools.ant.taskdefs.optional.depend;
+import java.io.File;
import java.util.Hashtable;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.DirectoryScanner;
+import org.apache.tools.ant.FileUtilities;
import org.apache.tools.ant.types.FileSet;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* Testcase for the Depend optional task.
*
*/
-public class DependTest extends BuildFileTest {
+public class DependTest {
public static final String RESULT_FILESET = "result";
public static final String TEST_BUILD_FILE
= "src/etc/testcases/taskdefs/optional/depend/depend.xml";
- public DependTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(TEST_BUILD_FILE);
+ buildRule.configureProject(TEST_BUILD_FILE);
}
/**
* Test direct dependency removal
*/
+ @Test
public void testDirect() {
- executeTarget("testdirect");
+ buildRule.executeTarget("src1setup");
+ buildRule.executeTarget("compile");
+
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("tempsrc.dir")), 5);
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("classes.dir")), 5);
+
+ buildRule.executeTarget("testdirect");
Hashtable files = getResultFiles();
assertEquals("Depend did not leave correct number of files", 3,
files.size());
@@ -59,8 +77,15 @@ public class DependTest extends BuildFileTest {
/**
* Test dependency traversal (closure)
*/
+ @Test
public void testClosure() {
- executeTarget("testclosure");
+ buildRule.executeTarget("src1setup");
+ buildRule.executeTarget("compile");
+
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("tempsrc.dir")), 5);
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("classes.dir")), 5);
+
+ buildRule.executeTarget("testclosure");
Hashtable files = getResultFiles();
assertTrue("Depend did not leave correct number of files",
files.size() <= 2);
@@ -71,8 +96,16 @@ public class DependTest extends BuildFileTest {
/**
* Test that inner class dependencies trigger deletion of the outer class
*/
+ @Test
public void testInner() {
- executeTarget("testinner");
+ buildRule.executeTarget("src2setup");
+ buildRule.executeTarget("compile");
+
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("tempsrc.dir")), 5);
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("classes.dir")), 5);
+
+
+ buildRule.executeTarget("testinner");
assertEquals("Depend did not leave correct number of files", 0,
getResultFiles().size());
}
@@ -81,8 +114,15 @@ public class DependTest extends BuildFileTest {
* Test that multi-leve inner class dependencies trigger deletion of
* the outer class
*/
+ @Test
public void testInnerInner() {
- executeTarget("testinnerinner");
+ buildRule.executeTarget("src3setup");
+ buildRule.executeTarget("compile");
+
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("tempsrc.dir")), 5);
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("classes.dir")), 5);
+
+ buildRule.executeTarget("testinnerinner");
assertEquals("Depend did not leave correct number of files", 0,
getResultFiles().size());
}
@@ -90,17 +130,27 @@ public class DependTest extends BuildFileTest {
/**
* Test that an exception is thrown when there is no source
*/
+ @Test
public void testNoSource() {
- expectBuildExceptionContaining("testnosource",
- "No source specified", "srcdir attribute must be set");
+ try {
+ buildRule.executeTarget("testnosource");
+ fail("Build exception expected: No source specified");
+ } catch(BuildException ex) {
+ assertContains("srcdir attribute must be set", ex.getMessage());
+ }
}
/**
* Test that an exception is thrown when the source attribute is empty
*/
+ @Test
public void testEmptySource() {
- expectBuildExceptionContaining("testemptysource",
- "No source specified", "srcdir attribute must be non-empty");
+ try {
+ buildRule.executeTarget("testemptysource");
+ fail("Build exception expected: No source specified");
+ } catch(BuildException ex) {
+ assertContains("srcdir attribute must be non-empty", ex.getMessage());
+ }
}
/**
@@ -110,8 +160,8 @@ public class DependTest extends BuildFileTest {
* fileset
*/
private Hashtable getResultFiles() {
- FileSet resultFileSet = (FileSet) project.getReference(RESULT_FILESET);
- DirectoryScanner scanner = resultFileSet.getDirectoryScanner(project);
+ FileSet resultFileSet = (FileSet) buildRule.getProject().getReference(RESULT_FILESET);
+ DirectoryScanner scanner = resultFileSet.getDirectoryScanner(buildRule.getProject());
String[] scannedFiles = scanner.getIncludedFiles();
Hashtable files = new Hashtable();
for (int i = 0; i < scannedFiles.length; ++i) {
@@ -125,8 +175,9 @@ public class DependTest extends BuildFileTest {
* Test mutual dependency between inner and outer do not cause both to be
* deleted
*/
+ @Test
public void testInnerClosure() {
- executeTarget("testinnerclosure");
+ buildRule.executeTarget("testinnerclosure");
assertEquals("Depend did not leave correct number of files", 4,
getResultFiles().size());
}
@@ -134,21 +185,29 @@ public class DependTest extends BuildFileTest {
/**
* Test the operation of the cache
*/
+ @Test
public void testCache() {
- executeTarget("testcache");
+ buildRule.executeTarget("testcache");
}
/**
* Test the detection and warning of non public classes
*/
+ @Test
public void testNonPublic() {
- executeTarget("testnonpublic");
- String log = getLog();
- assertTrue("Expected warning about APrivate",
- log.indexOf("The class APrivate in file") != -1);
- assertTrue("but has not been deleted because its source file "
+ buildRule.executeTarget("src5setup");
+ buildRule.executeTarget("compile");
+
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("tempsrc.dir")), 5);
+ FileUtilities.rollbackTimetamps(new File(buildRule.getProject().getProperty("classes.dir")), 5);
+
+ buildRule.executeTarget("testnonpublic");
+ String log = buildRule.getLog();
+ assertContains("Expected warning about APrivate",
+ "The class APrivate in file", log);
+ assertContains("but has not been deleted because its source file "
+ "could not be determined",
- log.indexOf("The class APrivate in file") != -1);
+ "The class APrivate in file", log);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/i18n/TranslateTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/i18n/TranslateTest.java
index 311e7714b..6abc4f2d7 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/i18n/TranslateTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/i18n/TranslateTest.java
@@ -18,73 +18,70 @@
package org.apache.tools.ant.taskdefs.optional.i18n;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
+import static org.junit.Assert.assertTrue;
+
/**
* Tests the Translate task.
*
* @since Ant 1.6
*/
-public class TranslateTest extends BuildFileTest {
+public class TranslateTest {
+
+ @Rule
+ public final BuildFileRule buildRule = new BuildFileRule();
+
static private final int BUF_SIZE = 32768;
private final static String TASKDEFS_DIR = "src/etc/testcases/taskdefs/optional/i18n/translate";
- public TranslateTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "/translate.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "/translate.xml");
}
- public void test1() {
- executeTarget("test1");
- assertTrue("translation of "+ TASKDEFS_DIR + "/input/template.txt",compareFiles(new File(getProjectDir(), "expected/de/template.txt"),
- new File(getOutputDir(), "de/template.txt")));
+ @Test
+ public void test1() throws IOException {
+ buildRule.executeTarget("test1");
+ assertTrue("translation of "+ TASKDEFS_DIR + "/input/template.txt",compareFiles(new File(buildRule.getProject().getBaseDir(), "expected/de/template.txt"),
+ new File(buildRule.getOutputDir(), "de/template.txt")));
}
- private boolean compareFiles(File file1, File file2) {
- try {
- if (!file1.exists() || !file2.exists()) {
- System.out.println("One or both files do not exist:" + file1.getAbsoluteFile() + ", " + file2.getAbsoluteFile());
- return false;
- }
+ private boolean compareFiles(File file1, File file2) throws IOException {
+ if (!file1.exists() || !file2.exists()) {
+ return false;
+ }
- if (file1.length() != file2.length()) {
- System.out.println("File size mismatch:" + file1.getAbsoluteFile() + "(" + file1.length() + "), " +
- file2.getAbsoluteFile() + "(" + file2.length() + ")");
- return false;
- }
+ if (file1.length() != file2.length()) {
+ return false;
+ }
- // byte - byte compare
- byte[] buffer1 = new byte[BUF_SIZE];
- byte[] buffer2 = new byte[BUF_SIZE];
-
- FileInputStream fis1 = new FileInputStream(file1);
- FileInputStream fis2 = new FileInputStream(file2);
- int index = 0;
- int read = 0;
- while ((read = fis1.read(buffer1)) != -1) {
- fis2.read(buffer2);
- for (int i = 0; i < read; ++i, ++index) {
- if (buffer1[i] != buffer2[i]) {
- System.out.println("Bytes mismatch:" + file1.getAbsoluteFile() + ", " + file2.getAbsoluteFile() +
- " at byte " + index);
- return false;
- }
+ // byte - byte compare
+ byte[] buffer1 = new byte[BUF_SIZE];
+ byte[] buffer2 = new byte[BUF_SIZE];
+
+ FileInputStream fis1 = new FileInputStream(file1);
+ FileInputStream fis2 = new FileInputStream(file2);
+ int index = 0;
+ int read = 0;
+ while ((read = fis1.read(buffer1)) != -1) {
+ fis2.read(buffer2);
+ for (int i = 0; i < read; ++i, ++index) {
+ if (buffer1[i] != buffer2[i]) {
+ return false;
}
}
- return true;
- }
- catch (IOException e) {
- System.out.println("IOException comparing files: " + file1.getAbsoluteFile() + ", " + file2.getAbsoluteFile());
- return false;
}
+ return true;
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java
index a1f2947fa..be79262d0 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/image/ImageTest.java
@@ -18,18 +18,26 @@
package org.apache.tools.ant.taskdefs.optional.image;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
/**
* Tests the Image task.
*
* @since Ant 1.5
*/
-public class ImageTest extends BuildFileTest {
+public class ImageTest {
private final static String TASKDEFS_DIR =
"src/etc/testcases/taskdefs/optional/image/";
@@ -37,69 +45,80 @@ public class ImageTest extends BuildFileTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public ImageTest(String name) {
- super(name);
- }
-
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(TASKDEFS_DIR + "image.xml");
+ buildRule.configureProject(TASKDEFS_DIR + "image.xml");
}
+ @Test
public void testEchoToLog() {
- expectLogContaining("testEchoToLog", "Processing File");
+ buildRule.executeTarget("testEchoToLog");
+ AntAssert.assertContains("Processing File", buildRule.getLog());
}
+ @Test
public void testSimpleScale(){
- expectLogContaining("testSimpleScale", "Processing File");
- File f = new File(getOutputDir(), LARGEIMAGE);
+ buildRule.executeTarget("testSimpleScale");
+ AntAssert.assertContains("Processing File", buildRule.getLog());
+
+ File f = new File(buildRule.getOutputDir(), LARGEIMAGE);
assertTrue(
"Did not create "+f.getAbsolutePath(),
f.exists());
}
- public void testOverwriteTrue() {
- expectLogContaining("testSimpleScale", "Processing File");
- File f = new File(getOutputDir(), LARGEIMAGE);
+ @Test
+ public void testOverwriteTrue() throws InterruptedException {
+ buildRule.executeTarget("testSimpleScale");
+ AntAssert.assertContains("Processing File", buildRule.getLog());
+ File f = new File(buildRule.getOutputDir(), LARGEIMAGE);
+ assumeTrue("Could not change file modificaiton date",
+ f.setLastModified(f.lastModified() - (FILE_UTILS.getFileTimestampGranularity() * 2)));
long lastModified = f.lastModified();
- try {
- Thread.sleep(FILE_UTILS
- .getFileTimestampGranularity());
- }
- catch (InterruptedException e) {}
- expectLogContaining("testOverwriteTrue", "Processing File");
- f = new File(getOutputDir(), LARGEIMAGE);
+ buildRule.executeTarget("testOverwriteTrue");
+ AntAssert.assertContains("Processing File", buildRule.getLog());
+ f = new File(buildRule.getOutputDir(), LARGEIMAGE);
long overwrittenLastModified = f.lastModified();
assertTrue("File was not overwritten.",
lastModified < overwrittenLastModified);
}
+ @Test
public void testOverwriteFalse() {
- expectLogContaining("testSimpleScale", "Processing File");
- File f = new File(getOutputDir(), LARGEIMAGE);
+ buildRule.executeTarget("testSimpleScale");
+ AntAssert.assertContains("Processing File", buildRule.getLog());
+ File f = new File(buildRule.getOutputDir(), LARGEIMAGE);
long lastModified = f.lastModified();
- expectLogContaining("testOverwriteFalse", "Processing File");
- f = new File(getOutputDir(), LARGEIMAGE);
+ buildRule.executeTarget("testOverwriteFalse");
+ AntAssert.assertContains("Processing File", buildRule.getLog());
+ f = new File(buildRule.getOutputDir(), LARGEIMAGE);
long overwrittenLastModified = f.lastModified();
assertTrue("File was overwritten.",
lastModified == overwrittenLastModified);
}
+ @Test
public void testSimpleScaleWithMapper() {
- expectLogContaining("testSimpleScaleWithMapper", "Processing File");
- File f = new File(getOutputDir(), "scaled-" + LARGEIMAGE);
+ buildRule.executeTarget("testSimpleScaleWithMapper");
+ AntAssert.assertContains("Processing File", buildRule.getLog());
+ File f = new File(buildRule.getOutputDir(), "scaled-" + LARGEIMAGE);
assertTrue(
"Did not create "+f.getAbsolutePath(),
f.exists());
}
- public void off_testFailOnError() {
+ @Test
+ @Ignore("Previously named in a manner to prevent execution")
+ public void testFailOnError() {
try {
- expectLogContaining("testFailOnError",
- "Unable to process image stream");
+ buildRule.executeTarget("testFailOnError");
+ AntAssert.assertContains("Unable to process image stream", buildRule.getLog());
}
catch (RuntimeException re){
assertTrue("Run time exception should say "
@@ -109,5 +128,6 @@ public class ImageTest extends BuildFileTest {
.indexOf("Unable to process image stream") > -1);
}
}
+
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTest.java
index 4e91d9c60..545b7cbc0 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/jdepend/JDependTest.java
@@ -18,80 +18,82 @@
package org.apache.tools.ant.taskdefs.optional.jdepend;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Testcase for the JDepend optional task.
*
*/
-public class JDependTest extends BuildFileTest {
- public static final String RESULT_FILESET = "result";
+public class JDependTest {
- public JDependTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject(
- "src/etc/testcases/taskdefs/optional/jdepend/jdepend.xml");
+ buildRule.configureProject(
+ "src/etc/testcases/taskdefs/optional/jdepend/jdepend.xml");
}
/**
* Test simple
*/
+ @Test
public void testSimple() {
- expectOutputContaining(
- "simple", "Package: org.apache.tools.ant.util.facade");
+ buildRule.executeTarget("simple");
+ AntAssert.assertContains("Package: org.apache.tools.ant.util.facade",
+ buildRule.getOutput());
}
/**
* Test xml
*/
+ @Test
public void testXml() {
- expectOutputContaining(
- "xml", "");
+ buildRule.executeTarget("xml");
+ AntAssert.assertContains("", buildRule.getOutput());
}
/**
* Test fork
* - forked output goes to log
*/
+ @Test
public void testFork() {
- expectLogContaining(
- "fork", "Package: org.apache.tools.ant.util.facade");
+ buildRule.executeTarget("fork");
+ AntAssert.assertContains("Package: org.apache.tools.ant.util.facade", buildRule.getLog());
}
/**
* Test fork xml
*/
+ @Test
public void testForkXml() {
- expectLogContaining(
- "fork-xml", "");
+ buildRule.executeTarget("fork-xml");
+ AntAssert.assertContains("", buildRule.getLog());
}
/**
* Test timeout
*/
+ @Test
public void testTimeout() {
- expectLogContaining(
- "fork-timeout", "JDepend FAILED - Timed out");
+ buildRule.executeTarget("fork-xml");
+ AntAssert.assertContains( "JDepend FAILED - Timed out", buildRule.getLog());
}
/**
* Test timeout without timing out
*/
+ @Test
public void testTimeoutNot() {
- expectLogContaining(
- "fork-timeout-not", "Package: org.apache.tools.ant.util.facade");
- }
-
- /**
- * Assert that the given message has been outputted
- */
- protected void expectOutputContaining(String target, String substring) {
- executeTarget(target);
- assertOutputContaining(substring);
+ buildRule.executeTarget("fork-timeout-not");
+ AntAssert.assertContains("Package: org.apache.tools.ant.util.facade", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/BatchTestTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/BatchTestTest.java
index 33745ef69..52a12ecc0 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/BatchTestTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/BatchTestTest.java
@@ -18,20 +18,19 @@
package org.apache.tools.ant.taskdefs.optional.junit;
-import junit.framework.ComparisonFailure;
-import junit.framework.TestCase;
+
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertArrayEquals;
+
+import org.junit.Test;
/**
*
* @author Marian Petras
*/
-public class BatchTestTest extends TestCase {
+public class BatchTestTest {
- public BatchTestTest(String testName) {
- super(testName);
- }
-
-
+ @Test
public void testParseTestMethodNamesList() {
try {
JUnitTest.parseTestMethodNamesList(null);
@@ -40,9 +39,9 @@ public class BatchTestTest extends TestCase {
//this is an expected exception
}
- assertEquals(new String[0], JUnitTest.parseTestMethodNamesList(""));
- assertEquals(new String[0], JUnitTest.parseTestMethodNamesList(" "));
- assertEquals(new String[0], JUnitTest.parseTestMethodNamesList(" "));
+ assertArrayEquals(new String[0], JUnitTest.parseTestMethodNamesList(""));
+ assertArrayEquals(new String[0], JUnitTest.parseTestMethodNamesList(" "));
+ assertArrayEquals(new String[0], JUnitTest.parseTestMethodNamesList(" "));
checkParseCausesIAE(",");
checkParseCausesIAE(" ,");
@@ -60,24 +59,24 @@ public class BatchTestTest extends TestCase {
checkParseCausesIAE("ab, ,cd,");
checkParseCausesIAE(",ab, ,cd,");
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc"));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc "));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList(" abc"));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList(" abc "));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc "));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc,"));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc, "));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc ,"));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc , "));
- assertEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList(" abc ,"));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc"));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc "));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList(" abc"));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList(" abc "));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc "));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc,"));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc, "));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc ,"));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList("abc , "));
+ assertArrayEquals(new String[] {"abc"}, JUnitTest.parseTestMethodNamesList(" abc ,"));
/* legal Java identifiers: */
- assertEquals(new String[] {"a"}, JUnitTest.parseTestMethodNamesList("a"));
- assertEquals(new String[] {"a1"}, JUnitTest.parseTestMethodNamesList("a1"));
- assertEquals(new String[] {"a$"}, JUnitTest.parseTestMethodNamesList("a$"));
- assertEquals(new String[] {"a$1"}, JUnitTest.parseTestMethodNamesList("a$1"));
- assertEquals(new String[] {"_bc"}, JUnitTest.parseTestMethodNamesList("_bc"));
- assertEquals(new String[] {"___"}, JUnitTest.parseTestMethodNamesList("___"));
+ assertArrayEquals(new String[] {"a"}, JUnitTest.parseTestMethodNamesList("a"));
+ assertArrayEquals(new String[] {"a1"}, JUnitTest.parseTestMethodNamesList("a1"));
+ assertArrayEquals(new String[] {"a$"}, JUnitTest.parseTestMethodNamesList("a$"));
+ assertArrayEquals(new String[] {"a$1"}, JUnitTest.parseTestMethodNamesList("a$1"));
+ assertArrayEquals(new String[] {"_bc"}, JUnitTest.parseTestMethodNamesList("_bc"));
+ assertArrayEquals(new String[] {"___"}, JUnitTest.parseTestMethodNamesList("___"));
/* illegal Java identifiers: */
checkParseCausesIAE("1");
@@ -90,24 +89,24 @@ public class BatchTestTest extends TestCase {
checkParseCausesIAE("1abc def,");
checkParseCausesIAE(",1abc def");
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc,def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc,def,"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc,def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc, def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc, def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc ,def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc ,def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc , def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc , def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc,def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc,def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc, def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc, def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc ,def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc ,def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc , def"));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc , def "));
- assertEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc , def ,"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc,def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc,def,"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc,def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc, def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc, def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc ,def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc ,def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc , def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList("abc , def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc,def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc,def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc, def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc, def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc ,def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc ,def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc , def"));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc , def "));
+ assertArrayEquals(new String[] {"abc", "def"}, JUnitTest.parseTestMethodNamesList(" abc , def ,"));
}
private static void checkParseCausesIAE(String param) {
@@ -119,24 +118,4 @@ public class BatchTestTest extends TestCase {
}
}
- private static void assertEquals(String[] expected, String[] actual) {
- assertEquals(null, expected, actual);
- }
-
- private static void assertEquals(String message,
- String[] expected,
- String[] actual) {
- if ((expected == null) && (actual == null)) {
- return;
- }
- if (expected.length != actual.length) {
- throw new ComparisonFailure(message,
- expected.toString(),
- actual.toString());
- }
- for (int i = 0; i < expected.length; i++) {
- assertEquals(expected[i], actual[i]);
- }
- }
-
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/DOMUtilTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/DOMUtilTest.java
index 9f173dabd..b72f69cc6 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/DOMUtilTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/DOMUtilTest.java
@@ -17,20 +17,23 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
+import static org.junit.Assert.assertEquals;
+
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.util.JAXPUtils;
+import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
-public class DOMUtilTest extends TestCase {
+public class DOMUtilTest {
+
+ @Test
public void testListChildNodes() throws SAXException, IOException {
DocumentBuilder db = JAXPUtils.getDocumentBuilder();
InputStream is = this.getClass().getClassLoader().getResourceAsStream("taskdefs/optional/junit/matches.xml");
@@ -38,6 +41,7 @@ public class DOMUtilTest extends TestCase {
NodeList nl = DOMUtil.listChildNodes(doc.getDocumentElement(), new FooNodeFilter(), true);
assertEquals("expecting 3", 3, nl.getLength());
}
+
public class FooNodeFilter implements DOMUtil.NodeFilter {
public boolean accept(Node node) {
if (node.getNodeName().equals("foo")) {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitClassLoaderTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitClassLoaderTest.java
index 36f5d6efd..4baf74181 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitClassLoaderTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitClassLoaderTest.java
@@ -17,19 +17,18 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertSame;
+
+import org.junit.Test;
/**
* Test to ensure that the classloader loading JUnit testcase
* is also the context classloader.
*
*/
-public class JUnitClassLoaderTest extends TestCase {
-
- public JUnitClassLoaderTest(String s) {
- super(s);
- }
+public class JUnitClassLoaderTest {
+ @Test
public void testContextClassLoader(){
ClassLoader context = Thread.currentThread().getContextClassLoader();
ClassLoader caller = getClass().getClassLoader();
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitReportTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitReportTest.java
index e99f246ea..c5b6feb97 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitReportTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitReportTest.java
@@ -18,26 +18,35 @@
package org.apache.tools.ant.taskdefs.optional.junit;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
+
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.net.URL;
-import org.apache.tools.ant.BuildFileTest;
+
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Small testcase for the junitreporttask.
* First test added to reproduce an fault, still a lot to improve
*
*/
-public class JUnitReportTest extends BuildFileTest {
-
- public JUnitReportTest(String name){
- super(name);
- }
+public class JUnitReportTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- protected void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/junitreport.xml");
+ @Before
+ public void setUp() {
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/junitreport.xml");
}
/**
@@ -45,62 +54,53 @@ public class JUnitReportTest extends BuildFileTest {
* output is selected via the default.
* Needs reports1 task from junitreport.xml.
*/
+ @Test
public void testNoFileJUnitNoFrames() {
- executeTarget("reports1");
- if (new File(getOutputDir(), "html/junit-noframes.html").exists())
- {
- fail("No file junit-noframes.html expected");
- }
+ buildRule.executeTarget("reports1");
+ assertFalse("No file junit-noframes.html expected", (new File(System.getProperty("root"), "src/etc/testcases/taskdefs/optional/junitreport/test/html/junit-noframes.html").exists()));
+
}
public void assertIndexCreated() {
- if (!new File(getOutputDir(), "html/index.html").exists()) {
+ if (!new File(buildRule.getProject().getProperty("output"), "html/index.html").exists()) {
fail("No file index file found");
}
}
- /**
- * run a target, assert the index file is there, look for text in the log
- * @param targetName target
- * @param text optional text to look for
- */
- private void expectReportWithText(String targetName, String text) {
- executeTarget(targetName);
- assertIndexCreated();
- if(text!=null) {
- assertLogContaining(text);
- }
- }
-
+ @Test
public void testEmptyFile() throws Exception {
- expectReportWithText("testEmptyFile",
- XMLResultAggregator.WARNING_EMPTY_FILE);
+ buildRule.executeTarget("testEmptyFile");
+ assertIndexCreated();
+ assertContains("Required text not found in log", XMLResultAggregator.WARNING_EMPTY_FILE, buildRule.getLog());
}
+ @Test
public void testIncompleteFile() throws Exception {
- expectReportWithText("testIncompleteFile",
- XMLResultAggregator.WARNING_IS_POSSIBLY_CORRUPTED);
+ buildRule.executeTarget("testIncompleteFile");
+ assertIndexCreated();
+ assertContains("Required text not found in log", XMLResultAggregator.WARNING_IS_POSSIBLY_CORRUPTED, buildRule.getLog());
}
+
+ @Test
public void testWrongElement() throws Exception {
- expectReportWithText("testWrongElement",
- XMLResultAggregator.WARNING_INVALID_ROOT_ELEMENT);
+ buildRule.executeTarget("testWrongElement");
+ assertIndexCreated();
+ assertContains("Required text not found in log", XMLResultAggregator.WARNING_INVALID_ROOT_ELEMENT, buildRule.getLog());
}
// Bugzilla Report 34963
+ @Test
public void testStackTraceLineBreaks() throws Exception {
- expectReportWithText("testStackTraceLineBreaks", null);
+ buildRule.executeTarget("testStackTraceLineBreaks");
+ assertIndexCreated();
FileReader r = null;
try {
- r = new FileReader(new File(getOutputDir(), "html/sampleproject/coins/0_CoinTest.html"));
+ r = new FileReader(new File(buildRule.getOutputDir(), "html/sampleproject/coins/0_CoinTest.html"));
String report = FileUtils.readFully(r);
- assertTrue("output must contain :\n" + report,
- report.indexOf("junit.framework.AssertionFailedError: DOEG ")
- > -1);
- assertTrue("#51049: output must translate line breaks:\n" + report,
- report.indexOf("cur['line.separator'] = '\\r\\n';")
- > -1);
+ assertContains("output must contain :\n" + report, "junit.framework.AssertionFailedError: DOEG ", report);
+ assertContains("#51049: output must translate line breaks:\n" + report, "cur['line.separator'] = '\\r\\n';", report);
} finally {
FileUtils.close(r);
}
@@ -108,96 +108,104 @@ public class JUnitReportTest extends BuildFileTest {
// Bugzilla Report 38477
+ @Test
public void testSpecialSignsInSrcPath() throws Exception {
- executeTarget("testSpecialSignsInSrcPath");
- File reportFile = new File(getOutputDir(), "html/index.html");
+ buildRule.executeTarget("testSpecialSignsInSrcPath");
+ File reportFile = new File(buildRule.getOutputDir(), "html/index.html");
// tests one the file object
assertTrue("No index.html present. Not generated?", reportFile.exists() );
assertTrue("Cant read the report file.", reportFile.canRead() );
- assertTrue("File shouldnt be empty.", reportFile.length() > 0 );
+ assertTrue("File shouldn't be empty.", reportFile.length() > 0 );
// conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report
URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) );
InputStream reportStream = reportUrl.openStream();
- assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0);
+ assertTrue("This shouldn't be an empty stream.", reportStream.available() > 0);
}
+ @Test
public void testSpecialSignsInHtmlPath() throws Exception {
- executeTarget("testSpecialSignsInHtmlPath");
- File reportFile = new File(getOutputDir(), "html# $%\u00A7&-!report/index.html");
+ buildRule.executeTarget("testSpecialSignsInHtmlPath");
+ File reportFile = new File(buildRule.getOutputDir(), "html# $%\u00A7&-!report/index.html");
// tests one the file object
assertTrue("No index.html present. Not generated?", reportFile.exists() );
assertTrue("Cant read the report file.", reportFile.canRead() );
- assertTrue("File shouldnt be empty.", reportFile.length() > 0 );
+ assertTrue("File shouldn't be empty.", reportFile.length() > 0 );
// conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report
URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) );
InputStream reportStream = reportUrl.openStream();
- assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0);
+ assertTrue("This shouldn't be an empty stream.", reportStream.available() > 0);
}
//Bugzilla Report 39708
+ @Test
public void testWithStyleFromDir() throws Exception {
- executeTarget("testWithStyleFromDir");
- File reportFile = new File(getOutputDir(), "html/index.html");
+ buildRule.executeTarget("testWithStyleFromDir");
+ File reportFile = new File(buildRule.getOutputDir(), "html/index.html");
// tests one the file object
assertTrue("No index.html present. Not generated?", reportFile.exists() );
assertTrue("Cant read the report file.", reportFile.canRead() );
- assertTrue("File shouldnt be empty.", reportFile.length() > 0 );
+ assertTrue("File shouldn't be empty.", reportFile.length() > 0 );
// conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report
URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) );
InputStream reportStream = reportUrl.openStream();
- assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0);
+ assertTrue("This shouldn't be an empty stream.", reportStream.available() > 0);
}
//Bugzilla Report 40021
+ @Test
public void testNoFrames() throws Exception {
- executeTarget("testNoFrames");
- File reportFile = new File(getOutputDir(), "html/junit-noframes.html");
+ buildRule.executeTarget("testNoFrames");
+ File reportFile = new File(buildRule.getOutputDir(), "html/junit-noframes.html");
// tests one the file object
assertTrue("No junit-noframes.html present. Not generated?", reportFile.exists() );
assertTrue("Cant read the report file.", reportFile.canRead() );
- assertTrue("File shouldnt be empty.", reportFile.length() > 0 );
+ assertTrue("File shouldn't be empty.", reportFile.length() > 0 );
// conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report
URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) );
InputStream reportStream = reportUrl.openStream();
- assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0);
+ assertTrue("This shouldn't be an empty stream.", reportStream.available() > 0);
}
//Bugzilla Report 39708
+ @Test
public void testWithStyleFromDirAndXslImport() throws Exception {
- executeTarget("testWithStyleFromDirAndXslImport");
- File reportFile = new File(getOutputDir(), "html/index.html");
+ buildRule.executeTarget("testWithStyleFromDirAndXslImport");
+ File reportFile = new File(buildRule.getOutputDir(), "html/index.html");
// tests one the file object
assertTrue("No index.html present. Not generated?", reportFile.exists() );
assertTrue("Cant read the report file.", reportFile.canRead() );
- assertTrue("File shouldnt be empty.", reportFile.length() > 0 );
+ assertTrue("File shouldn't be empty.", reportFile.length() > 0 );
// conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report
URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) );
InputStream reportStream = reportUrl.openStream();
- assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0);
+ assertTrue("This shouldn't be an empty stream.", reportStream.available() > 0);
}
+ @Test
public void testWithStyleFromClasspath() throws Exception {
- executeTarget("testWithStyleFromClasspath");
- File reportFile = new File(getOutputDir(), "html/index.html");
+ buildRule.executeTarget("testWithStyleFromClasspath");
+ File reportFile = new File(buildRule.getOutputDir(), "html/index.html");
// tests one the file object
assertTrue("No index.html present. Not generated?", reportFile.exists() );
assertTrue("Cant read the report file.", reportFile.canRead() );
- assertTrue("File shouldnt be empty.", reportFile.length() > 0 );
+ assertTrue("File shouldn't be empty.", reportFile.length() > 0 );
// conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report
URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) );
InputStream reportStream = reportUrl.openStream();
- assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0);
+ assertTrue("This shouldn't be an empty stream.", reportStream.available() > 0);
}
+ @Test
public void testWithParams() throws Exception {
- expectLogContaining("testWithParams", "key1=value1,key2=value2");
- File reportFile = new File(getOutputDir(), "html/index.html");
+ buildRule.executeTarget("testWithParams");
+ assertContains("key1=value1,key2=value2", buildRule.getLog());
+ File reportFile = new File(buildRule.getOutputDir(), "html/index.html");
// tests one the file object
assertTrue("No index.html present. Not generated?", reportFile.exists() );
assertTrue("Cant read the report file.", reportFile.canRead() );
- assertTrue("File shouldnt be empty.", reportFile.length() > 0 );
+ assertTrue("File shouldn't be empty.", reportFile.length() > 0 );
// conversion to URL via FileUtils like in XMLResultAggregator, not as suggested in the bug report
URL reportUrl = new URL( FileUtils.getFileUtils().toURI(reportFile.getAbsolutePath()) );
InputStream reportStream = reportUrl.openStream();
- assertTrue("This shouldnt be an empty stream.", reportStream.available() > 0);
+ assertTrue("This shouldn't be an empty stream.", reportStream.available() > 0);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java
index 30f624a19..61504ad16 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTaskTest.java
@@ -17,75 +17,96 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import static org.apache.tools.ant.AntAssert.assertNotContains;
+import static org.apache.tools.ant.AntAssert.assertContains;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.JavaEnvUtils;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
-public class JUnitTaskTest extends BuildFileTest {
+import org.apache.tools.ant.BuildFileRule;
+import org.apache.tools.ant.util.JavaEnvUtils;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
- /**
- * Constructor for the JUnitTaskTest object.
- */
- public JUnitTaskTest(String name) {
- super(name);
- }
+public class JUnitTaskTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
/**
* The JUnit setup method.
*/
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/junit.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/junit.xml");
}
+ @Test
public void testCrash() {
- expectPropertySet("crash", "crashed");
+ buildRule.executeTarget("crash");
+ assertEquals("true", buildRule.getProject().getProperty("crashed"));
}
+ @Test
public void testNoCrash() {
- expectPropertyUnset("nocrash", "crashed");
+ buildRule.executeTarget("nocrash");
+ assertNull(buildRule.getProject().getProperty("crashed"));
}
+ @Test
public void testTimeout() {
- expectPropertySet("timeout", "timeout");
+ buildRule.executeTarget("timeout");
+ assertEquals("true", buildRule.getProject().getProperty("timeout"));
}
+ @Test
public void testNoTimeout() {
- expectPropertyUnset("notimeout", "timeout");
+ buildRule.executeTarget("notimeout");
+ assertNull(buildRule.getProject().getProperty("timeout"));
}
+ @Test
public void testNonForkedCapture() throws IOException {
- executeTarget("capture");
- assertNoPrint(getLog(), "log");
- assertNoPrint(getFullLog(), "debug log");
+ buildRule.executeTarget("capture");
+ assertNoPrint(buildRule.getLog(), "log");
+ assertNoPrint(buildRule.getFullLog(), "debug log");
}
+ @Test
public void testForkedCapture() throws IOException {
- getProject().setProperty("fork", "true");
+ buildRule.getProject().setProperty("fork", "true");
testNonForkedCapture();
- // those would fail because of the way BuildFileTest captures output
- assertNoPrint(getOutput(), "output");
- assertNoPrint(getError(), "error output");
+ // those would fail because of the way BuildFileRule captures output
+ assertNoPrint(buildRule.getOutput(), "output");
+ assertNoPrint(buildRule.getError(), "error output");
assertOutput();
}
+ @Test
public void testBatchTestForkOnceToDir() {
assertResultFilesExist("testBatchTestForkOnceToDir", ".xml");
}
/** Bugzilla Report 32973 */
+ @Test
public void testBatchTestForkOnceExtension() {
assertResultFilesExist("testBatchTestForkOnceExtension", ".foo");
}
@@ -101,140 +122,157 @@ public class JUnitTaskTest extends BuildFileTest {
// $ ant -f junit.xml failureRecorder.runtest
// $ ant -f junit.xml failureRecorder.runtest
// But running the JUnit testcase fails in 4th run.
+ @Test
public void testFailureRecorder() {
if (JavaEnvUtils.isAtLeastJavaVersion(JavaEnvUtils.JAVA_1_5)) {
try {
- Class.forName("junit.framework.JUnit4TestAdapter");
- System.err.println("skipping tests since it fails when"
- + " using JUnit 4");
- return;
+ Class> clazz =Class.forName("junit.framework.JUnit4TestAdapter");
+ Assume.assumeFalse("Skipping test since it fails with JUnit 4", clazz != null);
} catch (ClassNotFoundException e) {
// OK, this is JUnit3, can run test
}
}
- try {
- File testDir = new File(getOutputDir(), "out");
- File collectorFile = new File(getOutputDir(),
- "out/FailedTests.java");
-
- // ensure that there is a clean test environment
- assertFalse("Test directory '" + testDir.getAbsolutePath()
- + "' must not exist before the test preparation.",
- testDir.exists());
- assertFalse("The collector file '"
- + collectorFile.getAbsolutePath()
- + "'must not exist before the test preparation.",
- collectorFile.exists());
-
-
- // prepare the test environment
- executeTarget("failureRecorder.prepare");
- assertTrue("Test directory '" + testDir.getAbsolutePath()
- + "' was not created.", testDir.exists());
- assertTrue("There should be one class.",
- (new File(testDir, "A.class")).exists());
- assertFalse("The collector file '"
- + collectorFile.getAbsolutePath()
- + "' should not exist before the 1st run.",
- collectorFile.exists());
-
-
- // 1st junit run: should do all tests - failing and not failing tests
- executeTarget("failureRecorder.runtest");
- assertTrue("The collector file '" + collectorFile.getAbsolutePath()
- + "' should exist after the 1st run.",
- collectorFile.exists());
- // the passing test cases
- assertOutputContaining("1st run: should run A.test01", "A.test01");
- assertOutputContaining("1st run: should run B.test05", "B.test05");
- assertOutputContaining("1st run: should run B.test06", "B.test06");
- assertOutputContaining("1st run: should run C.test07", "C.test07");
- assertOutputContaining("1st run: should run C.test08", "C.test08");
- assertOutputContaining("1st run: should run C.test09", "C.test09");
- // the failing test cases
- assertOutputContaining("1st run: should run A.test02", "A.test02");
- assertOutputContaining("1st run: should run A.test03", "A.test03");
- assertOutputContaining("1st run: should run B.test04", "B.test04");
- assertOutputContaining("1st run: should run D.test10", "D.test10");
-
-
- // 2nd junit run: should do only failing tests
- executeTarget("failureRecorder.runtest");
- assertTrue("The collector file '" + collectorFile.getAbsolutePath()
- + "' should exist after the 2nd run.",
- collectorFile.exists());
- // the passing test cases
- assertOutputNotContaining("2nd run: should not run A.test01",
- "A.test01");
- assertOutputNotContaining("2nd run: should not run A.test05",
- "B.test05");
- assertOutputNotContaining("2nd run: should not run B.test06",
- "B.test06");
- assertOutputNotContaining("2nd run: should not run C.test07",
- "C.test07");
- assertOutputNotContaining("2nd run: should not run C.test08",
- "C.test08");
- assertOutputNotContaining("2nd run: should not run C.test09",
- "C.test09");
- // the failing test cases
- assertOutputContaining("2nd run: should run A.test02", "A.test02");
- assertOutputContaining("2nd run: should run A.test03", "A.test03");
- assertOutputContaining("2nd run: should run B.test04", "B.test04");
- assertOutputContaining("2nd run: should run D.test10", "D.test10");
-
-
- // "fix" errors in class A
- executeTarget("failureRecorder.fixing");
-
- // 3rd run: four running tests with two errors
- executeTarget("failureRecorder.runtest");
- assertTrue("The collector file '" + collectorFile.getAbsolutePath()
- + "' should exist after the 3rd run.",
- collectorFile.exists());
- assertOutputContaining("3rd run: should run A.test02", "A.test02");
- assertOutputContaining("3rd run: should run A.test03", "A.test03");
- assertOutputContaining("3rd run: should run B.test04", "B.test04");
- assertOutputContaining("3rd run: should run D.test10", "D.test10");
-
-
- // 4rd run: two running tests with errors
- executeTarget("failureRecorder.runtest");
- assertTrue("The collector file '" + collectorFile.getAbsolutePath()
- + "' should exist after the 4th run.",
- collectorFile.exists());
- //TODO: these two statements fail
- //assertOutputNotContaining("4th run: should not run A.test02", "A.test02");
- //assertOutputNotContaining("4th run: should not run A.test03", "A.test03");
- assertOutputContaining("4th run: should run B.test04", "B.test04");
- assertOutputContaining("4th run: should run D.test10", "D.test10");
- } catch (BuildException be) {
- be.printStackTrace();
- System.err.println("nested build's log: " + getLog());
- System.err.println("nested build's System.out: " + getOutput());
- System.err.println("nested build's System.err: " + getError());
- fail("Ant execution failed: " + be.getMessage());
- }
+ File testDir = new File(buildRule.getOutputDir(), "out");
+ File collectorFile = new File(buildRule.getOutputDir(),
+ "out/FailedTests.java");
+
+ // ensure that there is a clean test environment
+ assertFalse("Test directory '" + testDir.getAbsolutePath()
+ + "' must not exist before the test preparation.",
+ testDir.exists());
+ assertFalse("The collector file '"
+ + collectorFile.getAbsolutePath()
+ + "'must not exist before the test preparation.",
+ collectorFile.exists());
+
+
+ // prepare the test environment
+ buildRule.executeTarget("failureRecorder.prepare");
+ assertTrue("Test directory '" + testDir.getAbsolutePath()
+ + "' was not created.", testDir.exists());
+ assertTrue("There should be one class.",
+ (new File(testDir, "A.class")).exists());
+ assertFalse("The collector file '"
+ + collectorFile.getAbsolutePath()
+ + "' should not exist before the 1st run.",
+ collectorFile.exists());
+
+
+ // 1st junit run: should do all tests - failing and not failing tests
+ buildRule.executeTarget("failureRecorder.runtest");
+ assertTrue("The collector file '" + collectorFile.getAbsolutePath()
+ + "' should exist after the 1st run.",
+ collectorFile.exists());
+ // the passing test cases
+ buildRule.executeTarget("A.test01");
+ assertContains("1st run: should run A.test01", buildRule.getOutput());
+ buildRule.executeTarget("B.test05");
+ assertContains("1st run: should run B.test05", buildRule.getOutput());
+ buildRule.executeTarget("B.test06");
+ assertContains("1st run: should run B.test06", buildRule.getOutput());
+ buildRule.executeTarget("C.test07");
+ assertContains("1st run: should run C.test07", buildRule.getOutput());
+ buildRule.executeTarget("C.test08");
+ assertContains("1st run: should run C.test08", buildRule.getOutput());
+ buildRule.executeTarget("C.test09");
+ assertContains("1st run: should run C.test09", buildRule.getOutput());
+ // the failing test cases
+ buildRule.executeTarget("A.test02");
+ assertContains("1st run: should run A.test02", buildRule.getOutput());
+ buildRule.executeTarget("A.test03");
+ assertContains("1st run: should run A.test03", buildRule.getOutput());
+ buildRule.executeTarget("B.test04");
+ assertContains("1st run: should run B.test04", buildRule.getOutput());
+ buildRule.executeTarget("D.test10");
+ assertContains("1st run: should run D.test10", buildRule.getOutput());
+
+
+ // 2nd junit run: should do only failing tests
+ buildRule.executeTarget("failureRecorder.runtest");
+ assertTrue("The collector file '" + collectorFile.getAbsolutePath()
+ + "' should exist after the 2nd run.",
+ collectorFile.exists());
+ // the passing test cases
+ buildRule.executeTarget("A.test01");
+ assertNotContains("2nd run: should not run A.test01", buildRule.getOutput());
+ buildRule.executeTarget("B.test05");
+ assertNotContains("2nd run: should not run A.test05", buildRule.getOutput());
+ buildRule.executeTarget("B.test06");
+ assertNotContains("2nd run: should not run B.test06", buildRule.getOutput());
+ buildRule.executeTarget("C.test07");
+ assertNotContains("2nd run: should not run C.test07", buildRule.getOutput());
+ buildRule.executeTarget("C.test08");
+ assertNotContains("2nd run: should not run C.test08", buildRule.getOutput());
+ buildRule.executeTarget("C.test09");
+ assertNotContains("2nd run: should not run C.test09", buildRule.getOutput());
+ // the failing test cases
+ buildRule.executeTarget("A.test02");
+ assertContains("2nd run: should run A.test02", buildRule.getOutput());
+ buildRule.executeTarget("A.test03");
+ assertContains("2nd run: should run A.test03", buildRule.getOutput());
+ buildRule.executeTarget("B.test04");
+ assertContains("2nd run: should run B.test04", buildRule.getOutput());
+ buildRule.executeTarget("D.test10");
+ assertContains("2nd run: should run D.test10", buildRule.getOutput());
+
+
+ // "fix" errors in class A
+ buildRule.executeTarget("failureRecorder.fixing");
+
+ // 3rd run: four running tests with two errors
+ buildRule.executeTarget("failureRecorder.runtest");
+ assertTrue("The collector file '" + collectorFile.getAbsolutePath()
+ + "' should exist after the 3rd run.",
+ collectorFile.exists());
+ buildRule.executeTarget("A.test02");
+ assertContains("3rd run: should run A.test02", buildRule.getOutput());
+ buildRule.executeTarget("A.test03");
+ assertContains("3rd run: should run A.test03", buildRule.getOutput());
+ buildRule.executeTarget("B.test04");
+ assertContains("3rd run: should run B.test04", buildRule.getOutput());
+ buildRule.executeTarget("D.test10");
+ assertContains("3rd run: should run D.test10", buildRule.getOutput());
+
+
+ // 4rd run: two running tests with errors
+ buildRule.executeTarget("failureRecorder.runtest");
+ assertTrue("The collector file '" + collectorFile.getAbsolutePath()
+ + "' should exist after the 4th run.",
+ collectorFile.exists());
+ //TODO: these two statements fail
+ //buildRule.executeTarget("A.test02");assertNotContains("4th run: should not run A.test02", buildRule.getOutput());
+ //buildRule.executeTarget("A.test03");assertNotContains("4th run: should not run A.test03", buildRule.getOutput());
+ buildRule.executeTarget("B.test04");
+ assertContains("4th run: should run B.test04", buildRule.getOutput());
+ buildRule.executeTarget("D.test10");
+ assertContains("4th run: should run D.test10", buildRule.getOutput());
+
}
+ @Test
public void testBatchTestForkOnceCustomFormatter() {
assertResultFilesExist("testBatchTestForkOnceCustomFormatter", "foo");
}
// Bugzilla Issue 45411
+ @Test
public void testMultilineAssertsNoFork() {
- expectLogNotContaining("testMultilineAssertsNoFork", "messed up)");
- assertLogNotContaining("crashed)");
+ buildRule.executeTarget("testMultilineAssertsNoFork");
+ assertNotContains("messaged up", buildRule.getLog());
+ assertNotContains("crashed)", buildRule.getLog());
}
// Bugzilla Issue 45411
+ @Test
public void testMultilineAssertsFork() {
- expectLogNotContaining("testMultilineAssertsFork", "messed up)");
- assertLogNotContaining("crashed)");
+ buildRule.executeTarget("testMultilineAssertsFork");
+ assertNotContains("messaged up", buildRule.getLog());
+ assertNotContains("crashed)", buildRule.getLog());
}
private void assertResultFilesExist(String target, String extension) {
- executeTarget(target);
+ buildRule.executeTarget(target);
assertResultFileExists("JUnitClassLoader", extension);
assertResultFileExists("JUnitTestRunner", extension);
assertResultFileExists("JUnitVersionHelper", extension);
@@ -242,19 +280,20 @@ public class JUnitTaskTest extends BuildFileTest {
private void assertResultFileExists(String classNameFragment, String ext) {
assertTrue("result for " + classNameFragment + "Test" + ext + " exists",
- new File(getOutputDir(), "TEST-org.apache.tools.ant."
+
+ new File(buildRule.getOutputDir(), "TEST-org.apache.tools.ant."
+ "taskdefs.optional.junit."
+ classNameFragment + "Test" + ext)
.exists());
}
private void assertNoPrint(String result, String where) {
- assertTrue(where + " '" + result + "' must not contain print statement",
- result.indexOf("print to System.") == -1);
+ assertNotContains(where + " '" + result + "' must not contain print statement",
+ "print to System.", result);
}
private void assertOutput() throws IOException {
- FileReader inner = new FileReader(new File(getOutputDir(),
+ FileReader inner = new FileReader(new File(buildRule.getOutputDir(),
"testlog.txt"));
BufferedReader reader = new BufferedReader(inner);
try {
@@ -297,12 +336,13 @@ public class JUnitTaskTest extends BuildFileTest {
assertEquals(search, line);
}
+ @Test
public void testJUnit4Skip() throws Exception {
- executeTarget("testSkippableTests");
+ buildRule.executeTarget("testSkippableTests");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc = dBuilder.parse(new File(getOutputDir(), "TEST-org.example.junit.JUnit4Skippable.xml"));
+ Document doc = dBuilder.parse(new File(buildRule.getOutputDir(), "TEST-org.example.junit.JUnit4Skippable.xml"));
assertEquals("Incorrect number of nodes created", 8, doc.getElementsByTagName("testcase").getLength());
@@ -322,32 +362,36 @@ public class JUnitTaskTest extends BuildFileTest {
}
+ @Test
public void testTestMethods() throws Exception {
- executeTarget("testTestMethods");
+ buildRule.executeTarget("testTestMethods");
}
+ @Test
public void testNonTestsSkipped() throws Exception {
- executeTarget("testNonTests");
- assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.NonTestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.NonTestMissed.xml").exists());
- assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.JUnit3NonTestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.JUnit3TestMissed.xml").exists());
- assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.AbstractTestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.AbstractTestMissed.xml").exists());
- assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.AbstractJUnit3TestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.AbstractJUnit3TestMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractTestNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.AbstractTestNotMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractJUnit3TestNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.AbstractJUnit3TestNotMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.TestNotMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3TestNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.JUnit3TestNotMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestWithSuiteNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.TestWithSuiteNotMissed.xml").exists());
-
- executeTarget("testNonTestsRun");
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.NonTestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.NonTestMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3NonTestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.JUnit3NonTestMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.TestNotMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3TestNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.JUnit3TestNotMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractTestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.AbstractTestMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractTestNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.AbstractTestNotMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractJUnit3TestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.AbstractJUnit3TestMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3NonTestMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.JUnit3NonTestMissed.xml").exists());
- assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestWithSuiteNotMissed.xml", new File(getOutputDir(), "TEST-org.example.junit.TestWithSuiteNotMissed.xml").exists());
+
+ buildRule.executeTarget("testNonTests");
+ assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.NonTestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.NonTestMissed.xml").exists());
+ assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.JUnit3NonTestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.JUnit3TestMissed.xml").exists());
+ assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.AbstractTestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.AbstractTestMissed.xml").exists());
+ assertFalse("Test result should not exist as test was skipped - TEST-org.example.junit.AbstractJUnit3TestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.AbstractJUnit3TestMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractTestNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.AbstractTestNotMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractJUnit3TestNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.AbstractJUnit3TestNotMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.TestNotMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3TestNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.JUnit3TestNotMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestWithSuiteNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.TestWithSuiteNotMissed.xml").exists());
+
+ buildRule.executeTarget("testNonTestsRun");
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.NonTestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.NonTestMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3NonTestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.JUnit3NonTestMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.TestNotMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3TestNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.JUnit3TestNotMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractTestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.AbstractTestMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractTestNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.AbstractTestNotMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.AbstractJUnit3TestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.AbstractJUnit3TestMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.JUnit3NonTestMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.JUnit3NonTestMissed.xml").exists());
+ assertTrue("Test result should exist as test was not skipped - TEST-org.example.junit.TestWithSuiteNotMissed.xml", new File(buildRule.getOutputDir(), "TEST-org.example.junit.TestWithSuiteNotMissed.xml").exists());
+
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestListenerTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestListenerTest.java
index faeb7368a..38eaa142b 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestListenerTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestListenerTest.java
@@ -18,9 +18,18 @@
package org.apache.tools.ant.taskdefs.optional.junit;
-import org.apache.tools.ant.BuildFileTest;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.apache.tools.ant.AntAssert.assertNotContains;
-public class JUnitTestListenerTest extends BuildFileTest {
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+public class JUnitTestListenerTest{
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
// The captureToSummary test writes to stdout and stderr, good for
// verifying that the TestListener support doesn't break anything.
@@ -29,78 +38,74 @@ public class JUnitTestListenerTest extends BuildFileTest {
// testNoCrash is the test invoked by the captureToSummary's junit task
private static final String PASS_TEST = "testNoCrash";
- public JUnitTestListenerTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/junit.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/junit.xml");
}
+
+ @Test
public void testFullLogOutput() {
- getProject().setProperty("enableEvents", "true");
- executeTarget(PASS_TEST_TARGET);
- assertTrue("expecting full log to have BuildListener events",
- hasBuildListenerEvents(getFullLog()));
+ buildRule.getProject().setProperty("enableEvents", "true");
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertContains("expecting full log to have BuildListener events",
+ JUnitTask.TESTLISTENER_PREFIX, buildRule.getFullLog());
}
+ @Test
public void testNoLogOutput() {
- getProject().setProperty("enableEvents", "true");
- executeTarget(PASS_TEST_TARGET);
- assertFalse("expecting log to not have BuildListener events",
- hasBuildListenerEvents(getLog()));
+ buildRule.getProject().setProperty("enableEvents", "true");
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertNotContains("expecting log to not have BuildListener events",
+ JUnitTask.TESTLISTENER_PREFIX, buildRule.getLog());
}
+ @Test
public void testTestCountFired() {
- getProject().setProperty("enableEvents", "true");
- executeTarget(PASS_TEST_TARGET);
- assertTrue("expecting test count message",
- hasEventMessage(JUnitTask.TESTLISTENER_PREFIX +
- "tests to run: "));
+ buildRule.getProject().setProperty("enableEvents", "true");
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertContains("expecting test count message", JUnitTask.TESTLISTENER_PREFIX +
+ "tests to run: ", buildRule.getFullLog());
}
+ @Test
public void testStartTestFired() {
- getProject().setProperty("enableEvents", "true");
- executeTarget(PASS_TEST_TARGET);
- assertTrue("expecting test started message",
- hasEventMessage(JUnitTask.TESTLISTENER_PREFIX +
- "startTest(" + PASS_TEST + ")"));
+ buildRule.getProject().setProperty("enableEvents", "true");
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertContains("expecting test started message", JUnitTask.TESTLISTENER_PREFIX +
+ "startTest(" + PASS_TEST + ")", buildRule.getFullLog());
}
+ @Test
public void testEndTestFired() {
- getProject().setProperty("enableEvents", "true");
- executeTarget(PASS_TEST_TARGET);
- assertTrue("expecting test ended message",
- hasEventMessage(JUnitTask.TESTLISTENER_PREFIX +
- "endTest(" + PASS_TEST + ")"));
+ buildRule.getProject().setProperty("enableEvents", "true");
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertContains("expecting test ended message", JUnitTask.TESTLISTENER_PREFIX +
+ "endTest(" + PASS_TEST + ")", buildRule.getFullLog());
}
+ @Test
public void testNoFullLogOutputByDefault() {
- executeTarget(PASS_TEST_TARGET);
- assertFalse("expecting full log to not have BuildListener events",
- hasBuildListenerEvents(getFullLog()));
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertNotContains("expecting full log to not have BuildListener events",
+ JUnitTask.TESTLISTENER_PREFIX, buildRule.getFullLog());
}
+ @Test
public void testFullLogOutputMagicProperty() {
- getProject().setProperty(JUnitTask.ENABLE_TESTLISTENER_EVENTS, "true");
- executeTarget(PASS_TEST_TARGET);
- assertTrue("expecting full log to have BuildListener events",
- hasBuildListenerEvents(getFullLog()));
+ buildRule.getProject().setProperty(JUnitTask.ENABLE_TESTLISTENER_EVENTS, "true");
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertContains("expecting full log to have BuildListener events",
+ JUnitTask.TESTLISTENER_PREFIX, buildRule.getFullLog());
}
+ @Test
public void testNoFullLogOutputMagicPropertyWins() {
- getProject().setProperty(JUnitTask.ENABLE_TESTLISTENER_EVENTS, "false");
- getProject().setProperty("enableEvents", "true");
- executeTarget(PASS_TEST_TARGET);
- assertFalse("expecting full log to not have BuildListener events",
- hasBuildListenerEvents(getFullLog()));
+ buildRule.getProject().setProperty(JUnitTask.ENABLE_TESTLISTENER_EVENTS, "false");
+ buildRule.getProject().setProperty("enableEvents", "true");
+ buildRule.executeTarget(PASS_TEST_TARGET);
+ assertNotContains("expecting full log to not have BuildListener events",
+ JUnitTask.TESTLISTENER_PREFIX, buildRule.getFullLog());
}
- private boolean hasBuildListenerEvents(String log) {
- return log.indexOf(JUnitTask.TESTLISTENER_PREFIX) >= 0;
- }
-
- private boolean hasEventMessage(String eventPrefix) {
- return getFullLog().indexOf(eventPrefix) >= 0;
- }
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java
index 2b685b7e1..a75c5cbe5 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitTestRunnerTest.java
@@ -17,23 +17,31 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
-import java.io.*;
-import junit.framework.*;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import junit.framework.AssertionFailedError;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
import org.apache.tools.ant.BuildException;
+import org.junit.Test;
/**
* Small testcase for the runner, tests are very very very basics.
* They must be enhanced with time.
*
*/
-public class JUnitTestRunnerTest extends TestCase {
+public class JUnitTestRunnerTest{
- // mandatory constructor
- public JUnitTestRunnerTest(String name){
- super(name);
- }
+
// check that a valid method name generates no errors
+ @Test
public void testValidMethod(){
TestRunner runner = createRunnerForTestMethod(ValidMethodTestCase.class,"testA");
runner.run();
@@ -41,6 +49,7 @@ public class JUnitTestRunnerTest extends TestCase {
}
// check that having an invalid method name generates an error
+ @Test
public void testInvalidMethod(){
TestRunner runner = createRunnerForTestMethod(InvalidMethodTestCase.class,"testInvalid");
runner.run();
@@ -50,6 +59,7 @@ public class JUnitTestRunnerTest extends TestCase {
}
// check that having no suite generates no errors
+ @Test
public void testNoSuite(){
TestRunner runner = createRunner(NoSuiteTestCase.class);
runner.run();
@@ -57,6 +67,7 @@ public class JUnitTestRunnerTest extends TestCase {
}
// check that a suite generates no errors
+ @Test
public void testSuite(){
TestRunner runner = createRunner(SuiteTestCase.class);
runner.run();
@@ -64,6 +75,7 @@ public class JUnitTestRunnerTest extends TestCase {
}
// check that an invalid suite generates an error.
+ @Test
public void testInvalidSuite(){
TestRunner runner = createRunner(InvalidSuiteTestCase.class);
runner.run();
@@ -74,6 +86,7 @@ public class JUnitTestRunnerTest extends TestCase {
// check that something which is not a testcase generates no errors
// at first even though this is incorrect.
+ @Test
public void testNoTestCase(){
TestRunner runner = createRunner(NoTestCase.class);
runner.run();
@@ -88,6 +101,7 @@ public class JUnitTestRunnerTest extends TestCase {
}
// check that an exception in the constructor is noticed
+ @Test
public void testInvalidTestCase(){
TestRunner runner = createRunner(InvalidTestCase.class);
runner.run();
@@ -102,12 +116,12 @@ public class JUnitTestRunnerTest extends TestCase {
//assertTrue(error, error.indexOf("thrown on purpose") != -1);
}
- protected TestRunner createRunner(Class clazz){
+ protected TestRunner createRunner(Class> clazz){
return new TestRunner(new JUnitTest(clazz.getName()), null,
true, true, true);
}
- protected TestRunner createRunnerForTestMethod(Class clazz, String method){
+ protected TestRunner createRunnerForTestMethod(Class> clazz, String method){
return new TestRunner(new JUnitTest(clazz.getName()), new String[] {method},
true, true, true);
}
@@ -137,11 +151,10 @@ public class JUnitTestRunnerTest extends TestCase {
public void startTestSuite(JUnitTest suite) throws BuildException{}
public void endTestSuite(JUnitTest suite) throws BuildException{}
public void setOutput(java.io.OutputStream out){}
- public void startTest(Test t) {}
- public void endTest(Test test) {}
- public void addFailure(Test test, Throwable t) { }
- public void addFailure(Test test, AssertionFailedError t) { }
- public void addError(Test test, Throwable t) {
+ public void startTest(junit.framework.Test t) {}
+ public void endTest(junit.framework.Test test) {}
+ public void addFailure(junit.framework.Test test, AssertionFailedError t) { }
+ public void addError(junit.framework.Test test, Throwable t) {
error = t;
}
String getError(){
@@ -189,19 +202,16 @@ public class JUnitTestRunnerTest extends TestCase {
public static class SuiteTestCase extends NoSuiteTestCase {
public SuiteTestCase(String name){ super(name); }
- public static Test suite(){
+ public static junit.framework.Test suite(){
return new TestSuite(SuiteTestCase.class);
}
}
public static class InvalidSuiteTestCase extends NoSuiteTestCase {
public InvalidSuiteTestCase(String name){ super(name); }
- public static Test suite(){
+ public static junit.framework.Test suite(){
throw new NullPointerException("thrown on purpose");
}
}
- public static void main(String[] args){
- junit.textui.TestRunner.run(JUnitTestRunnerTest.class);
- }
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelperTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelperTest.java
index a23b840b7..8af3d23c9 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/JUnitVersionHelperTest.java
@@ -17,53 +17,65 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
-import junit.framework.Test;
+import static org.junit.Assert.assertEquals;
+import junit.framework.JUnit4TestAdapterCache;
import junit.framework.TestCase;
import junit.framework.TestResult;
+import org.junit.Test;
+import org.junit.runner.Description;
+
/**
*/
-public class JUnitVersionHelperTest extends TestCase {
-
- public JUnitVersionHelperTest(String name) {
- super(name);
- }
+public class JUnitVersionHelperTest {
+ @Test
public void testMyOwnName() {
assertEquals("testMyOwnName",
- JUnitVersionHelper.getTestCaseName(this));
+ JUnitVersionHelper.getTestCaseName(
+ JUnit4TestAdapterCache.getDefault().asTest(
+ Description.createTestDescription(JUnitVersionHelperTest.class, "testMyOwnName")
+ )
+ )
+ );
}
+ @Test
public void testNonTestCaseName() {
assertEquals("I'm a foo",
JUnitVersionHelper.getTestCaseName(new Foo1()));
}
+ @Test
public void testNoStringReturn() {
assertEquals("unknown",
JUnitVersionHelper.getTestCaseName(new Foo2()));
}
+ @Test
public void testNoGetName() {
assertEquals("unknown",
JUnitVersionHelper.getTestCaseName(new Foo3()));
}
+ @Test
public void testNameNotGetName() {
assertEquals("I'm a foo, too",
JUnitVersionHelper.getTestCaseName(new Foo4()));
}
+ @Test
public void testNull() {
assertEquals("unknown", JUnitVersionHelper.getTestCaseName(null));
}
+ @Test
public void testTestCaseSubClass() {
assertEquals("overridden getName",
JUnitVersionHelper.getTestCaseName(new Foo5()));
}
- public static class Foo implements Test {
+ public static class Foo implements junit.framework.Test {
public int countTestCases() {return 0;}
public void run(TestResult result) {}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/NoVmCrash.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/NoVmCrash.java
index 601eab2b9..392a92ee4 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/NoVmCrash.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/NoVmCrash.java
@@ -17,16 +17,13 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
-import junit.framework.TestCase;
+import org.junit.Test;
/**
*/
-public class NoVmCrash extends TestCase {
-
- public NoVmCrash(String name) {
- super(name);
- }
+public class NoVmCrash {
+ @Test
public void testNoCrash() {
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Printer.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Printer.java
index c0acc1cf7..0200648db 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Printer.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Printer.java
@@ -17,14 +17,13 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
-import junit.framework.TestCase;
+import org.junit.Test;
/**
*/
-public class Printer extends TestCase {
+public class Printer {
- public Printer(String name) {
- super(name);
+ public Printer() {
System.err.println("constructor print to System.err");
System.out.println("constructor print to System.out");
}
@@ -34,6 +33,7 @@ public class Printer extends TestCase {
System.out.println("static print to System.out");
}
+ @Test
public void testNoCrash() {
System.err.println("method print to System.err");
System.out.println("method print to System.out");
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Sleeper.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Sleeper.java
index cabc76370..150989483 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Sleeper.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/Sleeper.java
@@ -17,21 +17,14 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
-import junit.framework.TestCase;
-/**
- */
-public class Sleeper extends TestCase {
+import org.junit.Test;
- public Sleeper(String name) {
- super(name);
- }
+public class Sleeper {
- public void testSleep() {
- try {
- Thread.sleep(5 * 1000);
- } catch (InterruptedException e) {
- } // end of try-catch
+ @Test
+ public void testSleep() throws InterruptedException {
+ Thread.sleep(5 * 1000);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrashTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrashTest.java
index f6125e754..a85d9fea6 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrashTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/TearDownOnVmCrashTest.java
@@ -18,21 +18,36 @@
package org.apache.tools.ant.taskdefs.optional.junit;
-import org.apache.tools.ant.BuildFileTest;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.apache.tools.ant.AntAssert.assertNotContains;
+import static org.junit.Assert.assertEquals;
-public class TearDownOnVmCrashTest extends BuildFileTest {
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+public class TearDownOnVmCrashTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/junit/teardownlistener.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/junit/teardownlistener.xml");
}
+ @Test
public void testNoTeardown() {
- expectPropertySet("testNoTeardown", "error");
- assertOutputNotContaining(null, "tearDown called on Timeout");
+ buildRule.executeTarget("testNoTeardown");
+ assertEquals("true", buildRule.getProject().getProperty("error"));
+ assertNotContains("tearDown called on Timeout", buildRule.getOutput());
}
+ @Test
public void testTeardown() {
- expectPropertySet("testTeardown", "error");
- assertOutputContaining("tearDown called on Timeout");
+ buildRule.executeTarget("testTeardown");
+ assertEquals("true", buildRule.getProject().getProperty("error"));
+ assertContains("tearDown called on Timeout", buildRule.getOutput());
}
}
\ No newline at end of file
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/VmCrash.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/VmCrash.java
index 8ccf17abe..92d21b681 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/VmCrash.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/VmCrash.java
@@ -17,16 +17,13 @@
*/
package org.apache.tools.ant.taskdefs.optional.junit;
-import junit.framework.TestCase;
+import org.junit.Test;
/**
*/
-public class VmCrash extends TestCase {
-
- public VmCrash(String name) {
- super(name);
- }
+public class VmCrash {
+ @Test
public void testCrash() {
System.exit(0);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLFormatterWithCDATAOnSystemOut.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLFormatterWithCDATAOnSystemOut.java
index f93fb889a..3f464d872 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLFormatterWithCDATAOnSystemOut.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLFormatterWithCDATAOnSystemOut.java
@@ -20,16 +20,21 @@ package org.apache.tools.ant.taskdefs.optional.junit;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-import org.apache.tools.ant.BuildFileTest;
+
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
-public class XMLFormatterWithCDATAOnSystemOut extends BuildFileTest {
+public class XMLFormatterWithCDATAOnSystemOut {
- private static String DIR = "src/etc/testcases/taskdefs/optional/junit";
- private static String REPORT =
+ private static final String DIR = "src/etc/testcases/taskdefs/optional/junit";
+ private static final String REPORT =
"TEST-" + XMLFormatterWithCDATAOnSystemOut.class.getName() + ".xml";
- private static String TESTDATA =
+ private static final String TESTDATA =
"" +
"" +
" " +
@@ -45,20 +50,21 @@ public class XMLFormatterWithCDATAOnSystemOut extends BuildFileTest {
"]]>" +
" ";
- public XMLFormatterWithCDATAOnSystemOut(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Test
public void testOutput() {
System.out.println(TESTDATA);
}
+ @Test
public void testBuildfile() throws IOException {
- configureProject(DIR + "/cdataoutput.xml");
- if (getProject().getProperty("cdata.inner") == null) {
+ buildRule.configureProject(DIR + "/cdataoutput.xml");
+ if (buildRule.getProject().getProperty("cdata.inner") == null) {
// avoid endless loop
- executeTarget("run-junit");
- File f = getProject().resolveFile(REPORT);
+ buildRule.executeTarget("run-junit");
+ File f = buildRule.getProject().resolveFile(REPORT);
FileReader reader = null;
try {
reader = new FileReader(f);
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregatorTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregatorTest.java
index 609d4ad41..faa323ac8 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregatorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/junit/XMLResultAggregatorTest.java
@@ -18,28 +18,29 @@
package org.apache.tools.ant.taskdefs.optional.junit;
+import static org.junit.Assert.assertTrue;
+
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.security.Permission;
-import junit.framework.TestCase;
+
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Delete;
import org.apache.tools.ant.types.FileSet;
+import org.junit.Assume;
+import org.junit.Test;
-public class XMLResultAggregatorTest extends TestCase {
-
- public XMLResultAggregatorTest(String name) {
- super(name);
- }
+public class XMLResultAggregatorTest {
+ @Test
public void testFrames() throws Exception {
// For now, skip this test on JDK 6 (and below); see below for why:
try {
Class.forName("java.nio.file.Files");
} catch (ClassNotFoundException x) {
- return;
+ Assume.assumeNoException("Skip test on JDK 6 and below", x);
}
final File d = new File(System.getProperty("java.io.tmpdir"), "XMLResultAggregatorTest");
if (d.exists()) {
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java
index ffe7228f7..1a22115ed 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java
@@ -17,6 +17,11 @@
*/
package org.apache.tools.ant.taskdefs.optional.net;
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
@@ -28,69 +33,87 @@ import java.util.Vector;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.DirectoryScanner;
+import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.condition.Os;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.util.RetryHandler;
import org.apache.tools.ant.util.Retryable;
import org.apache.tools.ant.util.regexp.RegexpMatcher;
import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;
-
-public class FTPTest extends BuildFileTest{
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+//FIXME these tests are more integration than unit tests and report errors badly
+public class FTPTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
// keep track of what operating systems are supported here.
private boolean supportsSymlinks = Os.isFamily("unix");
private FTPClient ftp;
- private boolean connectionSucceeded = true;
- private boolean loginSuceeded = true;
+
+ private boolean loginSuceeded = false;
+
+ private String loginFailureMessage;
+
private String tmpDir = null;
private String remoteTmpDir = null;
private String ftpFileSep = null;
private myFTP myFTPTask = new myFTP();
- public FTPTest(String name) {
- super(name);
- }
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml");
- getProject().executeTarget("setup");
- tmpDir = getProject().getProperty("tmp.dir");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml");
+ Project project = buildRule.getProject();
+ project.executeTarget("setup");
+ tmpDir = project.getProperty("tmp.dir");
ftp = new FTPClient();
- ftpFileSep = getProject().getProperty("ftp.filesep");
+ ftpFileSep = project.getProperty("ftp.filesep");
myFTPTask.setSeparator(ftpFileSep);
- myFTPTask.setProject(getProject());
+ myFTPTask.setProject(project);
remoteTmpDir = myFTPTask.resolveFile(tmpDir);
- String remoteHost = getProject().getProperty("ftp.host");
- int port = Integer.parseInt(getProject().getProperty("ftp.port"));
- String remoteUser = getProject().getProperty("ftp.user");
- String password = getProject().getProperty("ftp.password");
+ String remoteHost = project.getProperty("ftp.host");
+ int port = Integer.parseInt(project.getProperty("ftp.port"));
+ String remoteUser = project.getProperty("ftp.user");
+ String password = project.getProperty("ftp.password");
+ boolean connectionSucceeded = false;
try {
ftp.connect(remoteHost, port);
+ connectionSucceeded = true;
} catch (Exception ex) {
- connectionSucceeded = false;
- loginSuceeded = false;
- System.out.println("could not connect to host " + remoteHost + " on port " + port);
+ loginFailureMessage = "could not connect to host " + remoteHost + " on port " + port;
}
if (connectionSucceeded) {
try {
ftp.login(remoteUser, password);
+ loginSuceeded = true;
} catch (IOException ioe) {
- loginSuceeded = false;
- System.out.println("could not log on to " + remoteHost + " as user " + remoteUser);
+ loginFailureMessage = "could not log on to " + remoteHost + " as user " + remoteUser;
}
}
}
+ @After
public void tearDown() {
try {
- ftp.disconnect();
+ if (ftp!= null) {
+ ftp.disconnect();
+ }
} catch (IOException ioe) {
// do nothing
}
- getProject().executeTarget("cleanup");
+ buildRule.getProject().executeTarget("cleanup");
}
+
private boolean changeRemoteDir(String remoteDir) {
boolean result = true;
try {
@@ -102,104 +125,102 @@ public class FTPTest extends BuildFileTest{
}
return result;
}
+
+ @Test
public void test1() {
- if (loginSuceeded) {
- if (changeRemoteDir(remoteTmpDir)) {
- FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
- ds.setIncludes(new String[] {"alpha"});
- ds.scan();
- compareFiles(ds, new String[] {} ,new String[] {"alpha"});
- }
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+
+ FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
+ ds.setIncludes(new String[] {"alpha"});
+ ds.scan();
+ compareFiles(ds, new String[] {} ,new String[] {"alpha"});
}
+ @Test
public void test2() {
- if (loginSuceeded) {
- if (changeRemoteDir(remoteTmpDir)) {
- FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
- ds.setIncludes(new String[] {"alpha/"});
- ds.scan();
- compareFiles(ds, new String[] {"alpha/beta/beta.xml",
- "alpha/beta/gamma/gamma.xml"},
- new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
- }
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
+ ds.setBasedir(new File(buildRule.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"});
}
+ @Test
public void test3() {
- if (loginSuceeded) {
- if (changeRemoteDir(remoteTmpDir)) {
- FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
- ds.scan();
- compareFiles(ds, new String[] {"alpha/beta/beta.xml",
- "alpha/beta/gamma/gamma.xml"},
- new String[] {"alpha", "alpha/beta",
- "alpha/beta/gamma"});
- }
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
+ ds.setBasedir(new File(buildRule.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"});
}
+ @Test
public void testFullPathMatchesCaseSensitive() {
- if (loginSuceeded) {
- if (changeRemoteDir(remoteTmpDir)) {
- FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
- ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
- ds.scan();
- compareFiles(ds, new String[] {}, new String[] {});
- }
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
+ ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
+ ds.scan();
+ compareFiles(ds, new String[] {}, new String[] {});
}
+ @Test
public void testFullPathMatchesCaseInsensitive() {
- if (loginSuceeded) {
- if (changeRemoteDir(remoteTmpDir)) {
- FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setCaseSensitive(false);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
- ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
- ds.scan();
- compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
- new String[] {});
- }
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
+ ds.setCaseSensitive(false);
+ ds.setBasedir(new File(buildRule.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[] {});
}
+ @Test
public void test2ButCaseInsensitive() {
- if (loginSuceeded) {
- if (changeRemoteDir(remoteTmpDir)) {
- FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
- ds.setIncludes(new String[] {"ALPHA/"});
- ds.setCaseSensitive(false);
- ds.scan();
- compareFiles(ds, new String[] {"alpha/beta/beta.xml",
- "alpha/beta/gamma/gamma.xml"},
- new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
- }
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
+ ds.setBasedir(new File(buildRule.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"});
}
+
+ @Test
public void test2bisButCaseInsensitive() {
- if (loginSuceeded) {
- if (changeRemoteDir(remoteTmpDir)) {
- FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
- ds.setIncludes(new String[] {"alpha/BETA/gamma/"});
- ds.setCaseSensitive(false);
- ds.scan();
- compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
- new String[] {"alpha/beta/gamma"});
- }
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
+ ds.setIncludes(new String[] {"alpha/BETA/gamma/"});
+ ds.setCaseSensitive(false);
+ ds.scan();
+ compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
+ new String[] {"alpha/beta/gamma"});
}
+
+ @Test
public void testGetWithSelector() {
- expectLogContaining("ftp-get-with-selector",
- "selectors are not supported in remote filesets");
- FileSet fsDestination = (FileSet) getProject().getReference("fileset-destination-without-selector");
- DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(getProject());
+ buildRule.executeTarget("ftp-get-with-selector");
+ assertContains("selectors are not supported in remote filesets", buildRule.getLog());
+ FileSet fsDestination = (FileSet) buildRule.getProject().getReference("fileset-destination-without-selector");
+ DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(buildRule.getProject());
dsDestination.scan();
String [] sortedDestinationDirectories = dsDestination.getIncludedDirectories();
String [] sortedDestinationFiles = dsDestination.getIncludedFiles();
@@ -211,58 +232,46 @@ public class FTPTest extends BuildFileTest{
sortedDestinationFiles[counter] =
sortedDestinationFiles[counter].replace(File.separatorChar, '/');
}
- FileSet fsSource = (FileSet) getProject().getReference("fileset-source-without-selector");
- DirectoryScanner dsSource = fsSource.getDirectoryScanner(getProject());
+ FileSet fsSource = (FileSet) buildRule.getProject().getReference("fileset-source-without-selector");
+ DirectoryScanner dsSource = fsSource.getDirectoryScanner(buildRule.getProject());
dsSource.scan();
compareFiles(dsSource, sortedDestinationFiles, sortedDestinationDirectories);
}
+
+ @Test
public void testGetFollowSymlinksTrue() {
- if (!supportsSymlinks) {
- return;
- }
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
- getProject().executeTarget("ftp-get-directory-symbolic-link");
- FileSet fsDestination = (FileSet) getProject().getReference("fileset-destination-without-selector");
- DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(getProject());
+ Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ buildRule.getProject().executeTarget("ftp-get-directory-symbolic-link");
+ FileSet fsDestination = (FileSet) buildRule.getProject().getReference("fileset-destination-without-selector");
+ DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(buildRule.getProject());
dsDestination.scan();
compareFiles(dsDestination, new String[] {"alpha/beta/gamma/gamma.xml"},
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+
+ @Test
public void testGetFollowSymlinksFalse() {
- if (!supportsSymlinks) {
- return;
- }
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
- getProject().executeTarget("ftp-get-directory-no-symbolic-link");
- FileSet fsDestination = (FileSet) getProject().getReference("fileset-destination-without-selector");
- DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(getProject());
+ Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ buildRule.getProject().executeTarget("ftp-get-directory-no-symbolic-link");
+ FileSet fsDestination = (FileSet) buildRule.getProject().getReference("fileset-destination-without-selector");
+ DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(buildRule.getProject());
dsDestination.scan();
compareFiles(dsDestination, new String[] {},
new String[] {});
}
+
+ @Test
public void testAllowSymlinks() {
- if (!supportsSymlinks) {
- return;
- }
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
- getProject().executeTarget("symlink-setup");
+ Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ buildRule.getProject().executeTarget("symlink-setup");
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/beta/gamma/"});
ds.setFollowSymlinks(true);
ds.scan();
@@ -270,76 +279,62 @@ public class FTPTest extends BuildFileTest{
new String[] {"alpha/beta/gamma"});
}
+ @Test
public void testProhibitSymlinks() {
- if (!supportsSymlinks) {
- return;
- }
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
- getProject().executeTarget("symlink-setup");
+ Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ buildRule.getProject().executeTarget("symlink-setup");
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/beta/gamma/"});
ds.setFollowSymlinks(false);
ds.scan();
compareFiles(ds, new String[] {}, new String[] {});
}
+
+ @Test
public void testFileSymlink() {
- if (!supportsSymlinks) {
- return;
- }
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
- getProject().executeTarget("symlink-file-setup");
+ Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ buildRule.getProject().executeTarget("symlink-file-setup");
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/beta/gamma/"});
ds.setFollowSymlinks(true);
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
new String[] {"alpha/beta/gamma"});
}
+
// father and child pattern test
+ @Test
public void testOrderOfIncludePatternsIrrelevant() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
String [] expectedFiles = {"alpha/beta/beta.xml",
"alpha/beta/gamma/gamma.xml"};
String [] expectedDirectories = {"alpha/beta", "alpha/beta/gamma" };
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/be?a/**", "alpha/beta/gamma/"});
ds.scan();
compareFiles(ds, expectedFiles, expectedDirectories);
// redo the test, but the 2 include patterns are inverted
ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/beta/gamma/", "alpha/be?a/**"});
ds.scan();
compareFiles(ds, expectedFiles, expectedDirectories);
}
+ @Test
public void testPatternsDifferInCaseScanningSensitive() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/beta.xml",
@@ -347,15 +342,12 @@ public class FTPTest extends BuildFileTest{
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testPatternsDifferInCaseScanningInsensitive() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
ds.setCaseSensitive(false);
ds.scan();
@@ -364,15 +356,12 @@ public class FTPTest extends BuildFileTest{
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testFullpathDiffersInCaseScanningSensitive() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {
"alpha/beta/gamma/gamma.xml",
"alpha/beta/gamma/GAMMA.XML"
@@ -382,15 +371,12 @@ public class FTPTest extends BuildFileTest{
new String[] {});
}
+ @Test
public void testFullpathDiffersInCaseScanningInsensitive() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {
"alpha/beta/gamma/gamma.xml",
"alpha/beta/gamma/GAMMA.XML"
@@ -401,15 +387,12 @@ public class FTPTest extends BuildFileTest{
new String[] {});
}
+ @Test
public void testParentDiffersInCaseScanningSensitive() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/beta.xml",
@@ -417,15 +400,12 @@ public class FTPTest extends BuildFileTest{
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testParentDiffersInCaseScanningInsensitive() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
ds.setCaseSensitive(false);
ds.scan();
@@ -434,15 +414,12 @@ public class FTPTest extends BuildFileTest{
new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
}
+ @Test
public void testExcludeOneFile() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {
"**/*.xml"
});
@@ -453,15 +430,13 @@ public class FTPTest extends BuildFileTest{
compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
new String[] {});
}
+
+ @Test
public void testExcludeHasPrecedence() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {
"alpha/**"
});
@@ -473,15 +448,13 @@ public class FTPTest extends BuildFileTest{
new String[] {});
}
+
+ @Test
public void testAlternateIncludeExclude() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setIncludes(new String[] {
"alpha/**",
"alpha/beta/gamma/**"
@@ -494,15 +467,13 @@ public class FTPTest extends BuildFileTest{
new String[] {"alpha"});
}
+
+ @Test
public void testAlternateExcludeInclude() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setExcludes(new String[] {
"alpha/**",
"alpha/beta/gamma/**"
@@ -515,29 +486,25 @@ public class FTPTest extends BuildFileTest{
new String[] {});
}
+
/**
* Test inspired by Bug#1415.
*/
+ @Test
public void testChildrenOfExcludedDirectory() {
- if (!loginSuceeded) {
- return;
- }
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
- getProject().executeTarget("children-of-excluded-dir-setup");
+ Assume.assumeTrue(loginFailureMessage, loginSuceeded);
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ buildRule.getProject().executeTarget("children-of-excluded-dir-setup");
FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setExcludes(new String[] {"alpha/**"});
ds.scan();
compareFiles(ds, new String[] {"delta/delta.xml"},
new String[] {"delta"});
ds = myFTPTask.newScanner(ftp);
- if (!changeRemoteDir(remoteTmpDir)) {
- return;
- }
- ds.setBasedir(new File(getProject().getBaseDir(), "tmp"));
+ Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
+ ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
ds.setExcludes(new String[] {"alpha"});
ds.scan();
compareFiles(ds, new String[] {"alpha/beta/beta.xml",
@@ -636,11 +603,12 @@ public class FTPTest extends BuildFileTest{
* configuration is an ftp server on localhost which formats
* timestamps as GMT.
*/
+ @Test
public void testTimezonePut() {
CountLogListener log = new CountLogListener("(\\d+) files? sent");
- getProject().executeTarget("timed.test.setup");
- getProject().addBuildListener(log);
- getProject().executeTarget("timed.test.put.older");
+ buildRule.getProject().executeTarget("timed.test.setup");
+ buildRule.getProject().addBuildListener(log);
+ buildRule.getProject().executeTarget("timed.test.put.older");
assertEquals(1, log.getCount());
}
@@ -650,11 +618,12 @@ public class FTPTest extends BuildFileTest{
* configuration is an ftp server on localhost which formats
* timestamps as GMT.
*/
+ @Test
public void testTimezoneGet() {
CountLogListener log = new CountLogListener("(\\d+) files? retrieved");
- getProject().executeTarget("timed.test.setup");
- getProject().addBuildListener(log);
- getProject().executeTarget("timed.test.get.older");
+ buildRule.getProject().executeTarget("timed.test.setup");
+ buildRule.getProject().addBuildListener(log);
+ buildRule.getProject().executeTarget("timed.test.get.older");
assertEquals(3, log.getCount());
}
@@ -663,6 +632,7 @@ public class FTPTest extends BuildFileTest{
* Tests that the presence of one of the server config params forces
* the system type to Unix if not specified.
*/
+ @Test
public void testConfiguration1() {
int[] expectedCounts = {
1,1,0,1,0,0,0
@@ -674,6 +644,7 @@ public class FTPTest extends BuildFileTest{
/**
* Tests the systemTypeKey attribute.
*/
+ @Test
public void testConfiguration2() {
int[] expectedCounts = {
1,0,0,1,1,0,0
@@ -685,6 +656,7 @@ public class FTPTest extends BuildFileTest{
/**
* Tests the systemTypeKey attribute with UNIX specified.
*/
+ @Test
public void testConfiguration3() {
int[] expectedCounts = {
1,0,1,0,0,1,0
@@ -693,6 +665,7 @@ public class FTPTest extends BuildFileTest{
}
+ @Test
public void testConfigurationLang() {
int[] expectedCounts = {
1,1,0,0,0,0,1
@@ -709,6 +682,7 @@ public class FTPTest extends BuildFileTest{
/**
* Tests the systemTypeKey attribute.
*/
+ @Test
public void testConfigurationNone() {
int[] expectedCounts = {
0,0,0,0,0,0,0
@@ -722,7 +696,7 @@ public class FTPTest extends BuildFileTest{
"custom configuration",
"custom config: system key = default (UNIX)",
"custom config: system key = UNIX",
- "custom config: server time zone ID = " + getProject().getProperty("ftp.server.timezone"),
+ "custom config: server time zone ID = " + buildRule.getProject().getProperty("ftp.server.timezone"),
"custom config: system key = WINDOWS",
"custom config: default date format = yyyy/MM/dd HH:mm",
"custom config: server language code = de"
@@ -733,8 +707,8 @@ public class FTPTest extends BuildFileTest{
counter.addLogMessageToSearch(messages[i]);
}
- getProject().addBuildListener(counter);
- getProject().executeTarget(target);
+ buildRule.getProject().addBuildListener(counter);
+ buildRule.getProject().executeTarget(target);
for (int i=0; i < messages.length; i++) {
assertEquals("target "+target+":message "+ i, expectedCounts[i], counter.getMatchCount(messages[i]));
}
@@ -745,9 +719,11 @@ public class FTPTest extends BuildFileTest{
/**
* this test is inspired by a user reporting that deletions of directories with the ftp task do not work
*/
+ @Test
public void testFTPDelete() {
- getProject().executeTarget("ftp-delete");
+ buildRule.getProject().executeTarget("ftp-delete");
}
+
private void compareFiles(DirectoryScanner ds, String[] expectedFiles,
String[] expectedDirectories) {
String includedFiles[] = ds.getIncludedFiles();
@@ -832,43 +808,51 @@ public class FTPTest extends BuildFileTest{
}
}
public void testGetWithSelectorRetryable1() {
- getProject().addTaskDefinition("ftp", oneFailureFTP.class);
+ buildRule.getProject().addTaskDefinition("ftp", oneFailureFTP.class);
try {
- getProject().executeTarget("ftp-get-with-selector-retryable");
+ buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
} catch (BuildException bx) {
fail("Two retries expected, failed after one.");
}
}
+
+ @Test
public void testGetWithSelectorRetryable2() {
- getProject().addTaskDefinition("ftp", twoFailureFTP.class);
+ buildRule.getProject().addTaskDefinition("ftp", twoFailureFTP.class);
try {
- getProject().executeTarget("ftp-get-with-selector-retryable");
+ buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
} catch (BuildException bx) {
fail("Two retries expected, failed after two.");
}
}
+ @Test
public void testGetWithSelectorRetryable3() {
- getProject().addTaskDefinition("ftp", threeFailureFTP.class);
+ buildRule.getProject().addTaskDefinition("ftp", threeFailureFTP.class);
try {
- getProject().executeTarget("ftp-get-with-selector-retryable");
+ buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
fail("Two retries expected, continued after two.");
} catch (BuildException bx) {
}
}
+
+ @Test
public void testGetWithSelectorRetryableRandom() {
- getProject().addTaskDefinition("ftp", randomFailureFTP.class);
+ buildRule.getProject().addTaskDefinition("ftp", randomFailureFTP.class);
try {
- getProject().setProperty("ftp.retries", "forever");
- getProject().executeTarget("ftp-get-with-selector-retryable");
+ buildRule.getProject().setProperty("ftp.retries", "forever");
+ buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
} catch (BuildException bx) {
fail("Retry forever specified, but failed.");
}
}
+ @Test
public void testInitialCommand() {
performCommandTest("test-initial-command", new int[] { 1,0 });
}
+
+ @Test
public void testSiteAction() {
performCommandTest("test-site-action", new int[] { 1,0 });
}
@@ -884,8 +868,8 @@ public class FTPTest extends BuildFileTest{
counter.addLogMessageToSearch(messages[i]);
}
- getProject().addBuildListener(counter);
- getProject().executeTarget(target);
+ buildRule.getProject().addBuildListener(counter);
+ buildRule.getProject().executeTarget(target);
for (int i=0; i < messages.length; i++) {
assertEquals("target "+target+":message "+ i, expectedCounts[i], counter.getMatchCount(messages[i]));
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java
index 07cb1eb49..5d4d4cf61 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/script/ScriptDefTest.java
@@ -17,36 +17,44 @@
*/
package org.apache.tools.ant.taskdefs.optional.script;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
import java.io.File;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
/**
* Tests the examples of the <scriptdef> task.
*
* @since Ant 1.6
*/
-public class ScriptDefTest extends BuildFileTest {
+public class ScriptDefTest {
- public ScriptDefTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- /**
- * The JUnit setup method
- */
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/taskdefs/optional/script/scriptdef.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/script/scriptdef.xml");
}
+ @Test
public void testSimple() {
- executeTarget("simple");
+ buildRule.executeTarget("simple");
// get the fileset and its basedir
- Project p = getProject();
+ Project p = buildRule.getProject();
FileSet fileset = (FileSet) p.getReference("testfileset");
File baseDir = fileset.getDir(p);
- String log = getLog();
+ String log = buildRule.getLog();
assertTrue("Expecting attribute value printed",
log.indexOf("Attribute attr1 = test") != -1);
@@ -54,25 +62,34 @@ public class ScriptDefTest extends BuildFileTest {
log.indexOf("Fileset basedir = " + baseDir.getAbsolutePath()) != -1);
}
+ @Test
public void testNoLang() {
- expectBuildExceptionContaining("nolang",
- "Absence of language attribute not detected",
- "requires a language attribute");
+ try {
+ buildRule.executeTarget("nolang");
+ fail("Absence of language attribute not detected");
+ } catch(BuildException ex) {
+ AntAssert.assertContains("requires a language attribute", ex.getMessage());
+ }
}
+ @Test
public void testNoName() {
- expectBuildExceptionContaining("noname",
- "Absence of name attribute not detected",
- "scriptdef requires a name attribute");
+ try {
+ buildRule.executeTarget("noname");
+ fail("Absence of name attribute not detected");
+ } catch(BuildException ex) {
+ AntAssert.assertContains("scriptdef requires a name attribute", ex.getMessage());
+ }
}
+ @Test
public void testNestedByClassName() {
- executeTarget("nestedbyclassname");
+ buildRule.executeTarget("nestedbyclassname");
// get the fileset and its basedir
- Project p = getProject();
+ Project p = buildRule.getProject();
FileSet fileset = (FileSet) p.getReference("testfileset");
File baseDir = fileset.getDir(p);
- String log = getLog();
+ String log = buildRule.getLog();
assertTrue("Expecting attribute value to be printed",
log.indexOf("Attribute attr1 = test") != -1);
@@ -80,35 +97,47 @@ public class ScriptDefTest extends BuildFileTest {
log.indexOf("Fileset basedir = " + baseDir.getAbsolutePath()) != -1);
}
+ @Test
public void testNoElement() {
- expectOutput("noelement", "Attribute attr1 = test");
+ buildRule.executeTarget("noelement");
+ assertEquals("Attribute attr1 = test", buildRule.getOutput().trim());
}
+ @Test
public void testException() {
- expectBuildExceptionContaining("exception",
- "Should have thrown an exception in the script",
- "TypeError");
+ try {
+ buildRule.executeTarget("exception");
+ fail("Should have thrown an exception in the script");
+ } catch(BuildException ex) {
+ AntAssert.assertContains("TypeError", ex.getMessage());
+ }
}
+ @Test
public void testDoubleDef() {
- executeTarget("doubledef");
- String log = getLog();
+ buildRule.executeTarget("doubledef");
+ String log = buildRule.getLog();
assertTrue("Task1 did not execute",
log.indexOf("Task1") != -1);
assertTrue("Task2 did not execute",
log.indexOf("Task2") != -1);
}
+ @Test
public void testDoubleAttribute() {
- expectBuildExceptionContaining("doubleAttributeDef",
- "Should have detected duplicate attribute definition",
- "attr1 attribute more than once");
+ try {
+ buildRule.executeTarget("doubleAttributeDef");
+ fail("Should have detected duplicate attirbute definition");
+ } catch(BuildException ex) {
+ AntAssert.assertContains("attr1 attribute more than once", ex.getMessage());
+ }
}
+ @Test
public void testProperty() {
- executeTarget("property");
+ buildRule.executeTarget("property");
// get the fileset and its basedir
- String log = getLog();
+ String log = buildRule.getLog();
assertTrue("Expecting property in attribute value replaced",
log.indexOf("Attribute value = test") != -1);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/sos/SOSTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/sos/SOSTest.java
index d36de008c..c45ec17e8 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/sos/SOSTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/sos/SOSTest.java
@@ -19,17 +19,25 @@ package org.apache.tools.ant.taskdefs.optional.sos;
import java.io.File;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.Path;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Testcase to ensure that command line generation and required attributes are
* correct.
*
*/
-public class SOSTest extends BuildFileTest {
+public class SOSTest {
private Commandline commandline;
@@ -46,33 +54,19 @@ public class SOSTest extends BuildFileTest {
private static final String SOS_HOME = "/home/user/.sos";
private static final String VERSION = "007";
- /**
- * Constructor for the SOSTest object
- *
- * @param s Test name
- */
- public SOSTest(String s) {
- super(s);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ private Project project;
- /**
- * The JUnit setup method
- *
- * @throws Exception
- */
- protected void setUp()
- throws Exception {
+ @Before
+ public void setUp() {
project = new Project();
+ project.init();
project.setBasedir(".");
}
- /**
- * The teardown method for JUnit
- *
- * @throws Exception
- */
- protected void tearDown()
- throws Exception {
+ @After
+ public void tearDown() {
File file = new File(project.getBaseDir(), LOCAL_PATH);
if (file.exists()) {
file.delete();
@@ -80,6 +74,7 @@ public class SOSTest extends BuildFileTest {
}
/** Test SOSGetFile flags & commandline generation */
+ @Test
public void testGetFileFlags() {
String[] sTestCmdLine = {"soscmd", "-command", "GetFile", "-file",
SRC_FILE, "-revision", "007", "-server", SOS_SERVER_PATH, "-name",
@@ -110,6 +105,7 @@ public class SOSTest extends BuildFileTest {
}
/** Test SOSGetProject flags & commandline generation */
+ @Test
public void testGetProjectFlags() {
String[] sTestCmdLine = {"soscmd", "-command", "GetProject", "-recursive",
"-label", SRC_LABEL, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
@@ -137,8 +133,9 @@ public class SOSTest extends BuildFileTest {
}
/** Tests SOSGet required attributes. */
+ @Test
public void testGetExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
expectSpecificBuildException("sosget.1", "some cause", "sosserverpath attribute must be set!");
expectSpecificBuildException("sosget.2", "some cause", "username attribute must be set!");
expectSpecificBuildException("sosget.3", "some cause", "vssserverpath attribute must be set!");
@@ -146,6 +143,7 @@ public class SOSTest extends BuildFileTest {
}
/** Test CheckInFile option flags */
+ @Test
public void testCheckinFileFlags() {
String[] sTestCmdLine = {"soscmd", "-command", "CheckInFile", "-file",
SRC_FILE, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
@@ -176,6 +174,7 @@ public class SOSTest extends BuildFileTest {
}
/** Test CheckInProject option flags */
+ @Test
public void testCheckinProjectFlags() {
String[] sTestCmdLine = {"soscmd", "-command", "CheckInProject",
"-recursive", "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
@@ -203,8 +202,9 @@ public class SOSTest extends BuildFileTest {
}
/** Test SOSCheckIn required attributes. */
+ @Test
public void testCheckinExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
expectSpecificBuildException("soscheckin.1", "some cause", "sosserverpath attribute must be set!");
expectSpecificBuildException("soscheckin.2", "some cause", "username attribute must be set!");
expectSpecificBuildException("soscheckin.3", "some cause", "vssserverpath attribute must be set!");
@@ -212,6 +212,7 @@ public class SOSTest extends BuildFileTest {
}
/** Test CheckOutFile option flags */
+ @Test
public void testCheckoutFileFlags() {
String[] sTestCmdLine = {"soscmd", "-command", "CheckOutFile", "-file",
SRC_FILE, "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
@@ -241,6 +242,7 @@ public class SOSTest extends BuildFileTest {
}
/** Test CheckOutProject option flags */
+ @Test
public void testCheckoutProjectFlags() {
String[] sTestCmdLine = {"soscmd", "-command", "CheckOutProject",
"-recursive", "-server", SOS_SERVER_PATH, "-name", SOS_USERNAME,
@@ -267,8 +269,9 @@ public class SOSTest extends BuildFileTest {
}
/** Test SOSCheckout required attributes. */
+ @Test
public void testCheckoutExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
expectSpecificBuildException("soscheckout.1", "some cause", "sosserverpath attribute must be set!");
expectSpecificBuildException("soscheckout.2", "some cause", "username attribute must be set!");
expectSpecificBuildException("soscheckout.3", "some cause", "vssserverpath attribute must be set!");
@@ -276,6 +279,7 @@ public class SOSTest extends BuildFileTest {
}
/** Test Label option flags */
+ @Test
public void testLabelFlags() {
String[] sTestCmdLine = {"soscmd", "-command", "AddLabel", "-server",
SOS_SERVER_PATH, "-name", SOS_USERNAME, "-password", "", "-database",
@@ -301,8 +305,9 @@ public class SOSTest extends BuildFileTest {
}
/** Test SOSLabel required attributes. */
+ @Test
public void testLabelExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/sos/sos.xml");
expectSpecificBuildException("soslabel.1", "some cause", "sosserverpath attribute must be set!");
expectSpecificBuildException("soslabel.2", "some cause", "username attribute must be set!");
expectSpecificBuildException("soslabel.3", "some cause", "vssserverpath attribute must be set!");
@@ -310,6 +315,16 @@ public class SOSTest extends BuildFileTest {
expectSpecificBuildException("soslabel.5", "some cause", "label attribute must be set!");
}
+ private void expectSpecificBuildException(String target, String errorMessage,
+ String exceptionMessage) {
+ try {
+ buildRule.executeTarget(target);
+ fail(errorMessage);
+ } catch(BuildException ex) {
+ assertEquals(exceptionMessage, ex.getMessage());
+ }
+ }
+
/**
* Iterate through the generated command line comparing it to reference
* one.
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/splash/SplashScreenTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/splash/SplashScreenTest.java
index fb75301f4..fb0b3eaf4 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/splash/SplashScreenTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/splash/SplashScreenTest.java
@@ -30,25 +30,19 @@ import org.apache.tools.ant.Project;
*/
public class SplashScreenTest {
- public static void main(String[] args) {
+ public static void main(String[] args) throws InterruptedException {
Project p = new Project();
SplashTask t = new SplashTask();
t.setProject(p);
t.execute();
// give it some time to display
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- } // end of try-catch
+ Thread.sleep(2000);
p.fireBuildFinished(null);
System.err.println("finished");
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- } // end of try-catch
+ Thread.sleep(2000);
System.err.println("exiting");
System.exit(0);
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java
index f970e0ed7..dff5b25a9 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/ssh/ScpTest.java
@@ -18,18 +18,26 @@
package org.apache.tools.ant.taskdefs.optional.ssh;
-import junit.framework.TestCase;
-
-import java.io.*;
-import java.util.List;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
+import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.condition.FilesMatch;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.selectors.FilenameSelector;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* This is a unit test for the Scp task in Ant. It must be
@@ -47,7 +55,7 @@ import org.apache.tools.ant.types.selectors.FilenameSelector;
* supports RSA and DSA keys. If it is not present
* this task setTrust() to true. (optional)
*/
-public class ScpTest extends TestCase {
+public class ScpTest {
private File tempDir;
private String sshHostUri = System.getProperty("scp.host");
@@ -56,24 +64,26 @@ public class ScpTest extends TestCase {
private List cleanUpList = new ArrayList();
- public ScpTest(String testname) {
- super(testname);
+ public ScpTest() {
if (System.getProperty("scp.tmp") != null) {
tempDir = new File(System.getProperty("scp.tmp"));
}
}
- protected void setUp() {
+ @Before
+ public void setUp() {
cleanUpList.clear();
}
- protected void tearDown() {
+ @After
+ public void tearDown() {
for( Iterator i = cleanUpList.iterator(); i.hasNext(); ) {
File file = (File) i.next();
file.delete();
}
}
+ @Test
public void testSingleFileUploadAndDownload() throws IOException {
assertNotNull("system property scp.tmp must be set", tempDir);
File uploadFile = createTemporaryFile();
@@ -86,9 +96,8 @@ public class ScpTest extends TestCase {
File testFile = new File( tempDir.getPath() + File.separator +
"download-testSingleFileUploadAndDownload.test" );
- addCleanup( testFile );
- assertTrue( "Assert that the testFile does not exist.",
- !testFile.exists() );
+ addCleanup(testFile );
+ assertFalse("Assert that the testFile does not exist.", testFile.exists());
// download
scpTask = createTask();
@@ -100,6 +109,7 @@ public class ScpTest extends TestCase {
compareFiles( uploadFile, testFile );
}
+ @Test
public void testMultiUploadAndDownload() throws IOException {
assertNotNull("system property scp.tmp must be set", tempDir);
List uploadList = new ArrayList();
@@ -137,6 +147,7 @@ public class ScpTest extends TestCase {
}
}
+ @Test
public void testRemoteToDir() throws IOException {
Scp scpTask = createTask();
@@ -149,6 +160,7 @@ public class ScpTest extends TestCase {
catch (BuildException e)
{
// expected
+ //TODO we should be asserting a value in here
}
// And this one should work
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/unix/SymlinkTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/unix/SymlinkTest.java
index 8a108d343..9bd910174 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/unix/SymlinkTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/unix/SymlinkTest.java
@@ -29,11 +29,21 @@
package org.apache.tools.ant.taskdefs.optional.unix;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.taskdefs.condition.Os;
-import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.util.SymbolicLinkUtils;
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
@@ -46,249 +56,240 @@ import java.io.File;
*
*/
-public class SymlinkTest extends BuildFileTest {
+public class SymlinkTest {
- private Project p;
- private boolean supportsSymlinks = Os.isFamily("unix");
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- public SymlinkTest(String name) {
- super(name);
- }
+ private boolean supportsSymlinks = Os.isFamily("unix");
+ @Before
public void setUp() {
- if (supportsSymlinks) {
- configureProject("src/etc/testcases/taskdefs/optional/unix/symlink.xml");
- executeTarget("setUp");
- }
+ Assume.assumeTrue("Symlinks not supported on current operating system", supportsSymlinks);
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/unix/symlink.xml");
+ buildRule.executeTarget("setUp");
}
-
+ @Test
public void testSingle() {
- if (supportsSymlinks) {
- executeTarget("test-single");
- p = getProject();
- assertNotNull("Failed to create file",
+ buildRule.executeTarget("test-single");
+ Project p = buildRule.getProject();
+ assertNotNull("Failed to create file",
p.getProperty("test.single.file.created"));
- assertNotNull("Failed to create link",
+ assertNotNull("Failed to create link",
p.getProperty("test.single.link.created"));
- }
}
+ @Test
public void testDelete() {
- if (supportsSymlinks) {
- executeTarget("test-delete");
- p = getProject();
- String linkDeleted = p.getProperty("test.delete.link.still.there");
- assertNotNull("Actual file deleted by symlink",
- p.getProperty("test.delete.file.still.there"));
- if (linkDeleted != null) {
- fail(linkDeleted);
- }
+ buildRule.executeTarget("test-delete");
+ Project p = buildRule.getProject();
+ String linkDeleted = p.getProperty("test.delete.link.still.there");
+ assertNotNull("Actual file deleted by symlink",
+ p.getProperty("test.delete.file.still.there"));
+ if (linkDeleted != null) {
+ fail(linkDeleted);
}
}
+ @Test
public void testRecord() {
- if (supportsSymlinks) {
- executeTarget("test-record");
- p = getProject();
+ buildRule.executeTarget("test-record");
+ Project p = buildRule.getProject();
- assertNotNull("Failed to create dir1",
- p.getProperty("test.record.dir1.created"));
+ assertNotNull("Failed to create dir1",
+ p.getProperty("test.record.dir1.created"));
- assertNotNull("Failed to create dir2",
- p.getProperty("test.record.dir2.created"));
+ assertNotNull("Failed to create dir2",
+ p.getProperty("test.record.dir2.created"));
- assertNotNull("Failed to create file1",
- p.getProperty("test.record.file1.created"));
+ assertNotNull("Failed to create file1",
+ p.getProperty("test.record.file1.created"));
- assertNotNull("Failed to create file2",
- p.getProperty("test.record.file2.created"));
+ assertNotNull("Failed to create file2",
+ p.getProperty("test.record.file2.created"));
- assertNotNull("Failed to create fileA",
- p.getProperty("test.record.fileA.created"));
+ assertNotNull("Failed to create fileA",
+ p.getProperty("test.record.fileA.created"));
- assertNotNull("Failed to create fileB",
- p.getProperty("test.record.fileB.created"));
+ assertNotNull("Failed to create fileB",
+ p.getProperty("test.record.fileB.created"));
- assertNotNull("Failed to create fileC",
- p.getProperty("test.record.fileC.created"));
+ assertNotNull("Failed to create fileC",
+ p.getProperty("test.record.fileC.created"));
- assertNotNull("Failed to create link1",
- p.getProperty("test.record.link1.created"));
+ assertNotNull("Failed to create link1",
+ p.getProperty("test.record.link1.created"));
- assertNotNull("Failed to create link2",
- p.getProperty("test.record.link2.created"));
+ assertNotNull("Failed to create link2",
+ p.getProperty("test.record.link2.created"));
- assertNotNull("Failed to create link3",
- p.getProperty("test.record.link3.created"));
+ assertNotNull("Failed to create link3",
+ p.getProperty("test.record.link3.created"));
- assertNotNull("Failed to create dirlink",
- p.getProperty("test.record.dirlink.created"));
+ assertNotNull("Failed to create dirlink",
+ p.getProperty("test.record.dirlink.created"));
- assertNotNull("Failed to create dirlink2",
- p.getProperty("test.record.dirlink2.created"));
+ assertNotNull("Failed to create dirlink2",
+ p.getProperty("test.record.dirlink2.created"));
- assertNotNull("Couldn't record links in dir1",
- p.getProperty("test.record.dir1.recorded"));
+ assertNotNull("Couldn't record links in dir1",
+ p.getProperty("test.record.dir1.recorded"));
- assertNotNull("Couldn't record links in dir2",
- p.getProperty("test.record.dir2.recorded"));
+ assertNotNull("Couldn't record links in dir2",
+ p.getProperty("test.record.dir2.recorded"));
- String dir3rec = p.getProperty("test.record.dir3.recorded");
-
- if (dir3rec != null) {
- fail(dir3rec);
- }
+ String dir3rec = p.getProperty("test.record.dir3.recorded");
+ if (dir3rec != null) {
+ fail(dir3rec);
}
+
}
+ @Test
public void testRecreate() {
- if (supportsSymlinks) {
- executeTarget("test-recreate");
- p = getProject();
- String link1Rem = p.getProperty("test.recreate.link1.not.removed");
- String link2Rem = p.getProperty("test.recreate.link2.not.removed");
- String link3Rem = p.getProperty("test.recreate.link3.not.removed");
- String dirlinkRem = p.getProperty("test.recreate.dirlink.not.removed");
- if (link1Rem != null) {
- fail(link1Rem);
- }
- if (link2Rem != null) {
- fail(link2Rem);
- }
- if (link3Rem != null) {
- fail(link3Rem);
- }
- if (dirlinkRem != null) {
- fail(dirlinkRem);
- }
- assertNotNull("Failed to recreate link1",
- p.getProperty("test.recreate.link1.recreated"));
- assertNotNull("Failed to recreate link2",
- p.getProperty("test.recreate.link2.recreated"));
- assertNotNull("Failed to recreate link3",
- p.getProperty("test.recreate.link3.recreated"));
- assertNotNull("Failed to recreate dirlink",
- p.getProperty("test.recreate.dirlink.recreated"));
-
- String doubleRecreate = p.getProperty("test.recreate.dirlink2.recreated.twice");
-
- if (doubleRecreate != null) {
- fail(doubleRecreate);
- }
-
- assertNotNull("Failed to alter dirlink3",
- p.getProperty("test.recreate.dirlink3.was.altered"));
-
+ buildRule.executeTarget("test-recreate");
+ Project p = buildRule.getProject();
+ String link1Rem = p.getProperty("test.recreate.link1.not.removed");
+ String link2Rem = p.getProperty("test.recreate.link2.not.removed");
+ String link3Rem = p.getProperty("test.recreate.link3.not.removed");
+ String dirlinkRem = p.getProperty("test.recreate.dirlink.not.removed");
+ if (link1Rem != null) {
+ fail(link1Rem);
+ }
+ if (link2Rem != null) {
+ fail(link2Rem);
+ }
+ if (link3Rem != null) {
+ fail(link3Rem);
+ }
+ if (dirlinkRem != null) {
+ fail(dirlinkRem);
+ }
+ assertNotNull("Failed to recreate link1",
+ p.getProperty("test.recreate.link1.recreated"));
+ assertNotNull("Failed to recreate link2",
+ p.getProperty("test.recreate.link2.recreated"));
+ assertNotNull("Failed to recreate link3",
+ p.getProperty("test.recreate.link3.recreated"));
+ assertNotNull("Failed to recreate dirlink",
+ p.getProperty("test.recreate.dirlink.recreated"));
+
+ String doubleRecreate = p.getProperty("test.recreate.dirlink2.recreated.twice");
+
+ if (doubleRecreate != null) {
+ fail(doubleRecreate);
}
+
+ assertNotNull("Failed to alter dirlink3",
+ p.getProperty("test.recreate.dirlink3.was.altered"));
}
+ @Test
public void testSymbolicLinkUtilsMethods() throws Exception {
- if (supportsSymlinks) {
- executeTarget("test-fileutils");
- SymbolicLinkUtils su = SymbolicLinkUtils.getSymbolicLinkUtils();
-
- java.io.File f = new File(getOutputDir(), "file1");
- assertTrue(f.exists());
- assertFalse(f.isDirectory());
- assertTrue(f.isFile());
- assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isSymbolicLink(f.getParentFile(),
- f.getName()));
- assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
-
- f = new File(getOutputDir(), "dir1");
- assertTrue(f.exists());
- assertTrue(f.isDirectory());
- assertFalse(f.isFile());
- assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isSymbolicLink(f.getParentFile(),
- f.getName()));
- assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
-
- f = new File(getOutputDir(), "file2");
- assertFalse(f.exists());
- assertFalse(f.isDirectory());
- assertFalse(f.isFile());
- assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isSymbolicLink(f.getParentFile(),
- f.getName()));
- assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
-
- f = new File(getOutputDir(), "dir2");
- assertFalse(f.exists());
- assertFalse(f.isDirectory());
- assertFalse(f.isFile());
- assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isSymbolicLink(f.getParentFile(),
- f.getName()));
- assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
-
-
- f = new File(getOutputDir(), "file.there");
- assertTrue(f.exists());
- assertFalse(f.isDirectory());
- assertTrue(f.isFile());
- assertTrue(su.isSymbolicLink(f.getAbsolutePath()));
- assertTrue(su.isSymbolicLink(f.getParentFile(),
- f.getName()));
- assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
-
- f = new File(getOutputDir(), "dir.there");
- assertTrue(f.exists());
- assertTrue(f.isDirectory());
- assertFalse(f.isFile());
- assertTrue(su.isSymbolicLink(f.getAbsolutePath()));
- assertTrue(su.isSymbolicLink(f.getParentFile(),
- f.getName()));
- assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
-
- // it is not possible to find out that symbolic links pointing
- // to inexistent files or directories are symbolic links
- // it used to be possible to detect this on Mac
- // this is not true under Snow Leopard and JDK 1.5
- // Removing special handling of MacOS until someone shouts
- // Antoine
- f = new File(getOutputDir(), "file.notthere");
- assertFalse(f.exists());
- assertFalse(f.isDirectory());
- assertFalse(f.isFile());
- assertTrue(su.isSymbolicLink(f.getAbsolutePath()) == false);
- assertTrue(su.isSymbolicLink(f.getParentFile(), f.getName()) == false);
- assertTrue(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertTrue(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
-
- f = new File(getOutputDir(), "dir.notthere");
- assertFalse(f.exists());
- assertFalse(f.isDirectory());
- assertFalse(f.isFile());
- assertTrue(su.isSymbolicLink(f.getAbsolutePath()) == false);
- assertTrue(su.isSymbolicLink(f.getParentFile(), f.getName()) == false);
- assertTrue(su.isDanglingSymbolicLink(f.getAbsolutePath()));
- assertTrue(su.isDanglingSymbolicLink(f.getParentFile(),
- f.getName()));
- }
+ buildRule.executeTarget("test-fileutils");
+ SymbolicLinkUtils su = SymbolicLinkUtils.getSymbolicLinkUtils();
+
+ java.io.File f = new File(buildRule.getOutputDir(), "file1");
+ assertTrue(f.exists());
+ assertFalse(f.isDirectory());
+ assertTrue(f.isFile());
+ assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isSymbolicLink(f.getParentFile(),
+ f.getName()));
+ assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
+ f = new File(buildRule.getOutputDir(), "dir1");
+ assertTrue(f.exists());
+ assertTrue(f.isDirectory());
+ assertFalse(f.isFile());
+ assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isSymbolicLink(f.getParentFile(),
+ f.getName()));
+ assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
+ f = new File(buildRule.getOutputDir(), "file2");
+ assertFalse(f.exists());
+ assertFalse(f.isDirectory());
+ assertFalse(f.isFile());
+ assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isSymbolicLink(f.getParentFile(),
+ f.getName()));
+ assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
+ f = new File(buildRule.getOutputDir(), "dir2");
+ assertFalse(f.exists());
+ assertFalse(f.isDirectory());
+ assertFalse(f.isFile());
+ assertFalse(su.isSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isSymbolicLink(f.getParentFile(),
+ f.getName()));
+ assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
+
+ f = new File(buildRule.getOutputDir(), "file.there");
+ assertTrue(f.exists());
+ assertFalse(f.isDirectory());
+ assertTrue(f.isFile());
+ assertTrue(su.isSymbolicLink(f.getAbsolutePath()));
+ assertTrue(su.isSymbolicLink(f.getParentFile(),
+ f.getName()));
+ assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
+ f = new File(buildRule.getOutputDir(), "dir.there");
+ assertTrue(f.exists());
+ assertTrue(f.isDirectory());
+ assertFalse(f.isFile());
+ assertTrue(su.isSymbolicLink(f.getAbsolutePath()));
+ assertTrue(su.isSymbolicLink(f.getParentFile(),
+ f.getName()));
+ assertFalse(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertFalse(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
+ // it is not possible to find out that symbolic links pointing
+ // to inexistent files or directories are symbolic links
+ // it used to be possible to detect this on Mac
+ // this is not true under Snow Leopard and JDK 1.5
+ // Removing special handling of MacOS until someone shouts
+ // Antoine
+ f = new File(buildRule.getOutputDir(), "file.notthere");
+ assertFalse(f.exists());
+ assertFalse(f.isDirectory());
+ assertFalse(f.isFile());
+ assertTrue(su.isSymbolicLink(f.getAbsolutePath()) == false);
+ assertTrue(su.isSymbolicLink(f.getParentFile(), f.getName()) == false);
+ assertTrue(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertTrue(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
+ f = new File(buildRule.getOutputDir(), "dir.notthere");
+ assertFalse(f.exists());
+ assertFalse(f.isDirectory());
+ assertFalse(f.isFile());
+ assertTrue(su.isSymbolicLink(f.getAbsolutePath()) == false);
+ assertTrue(su.isSymbolicLink(f.getParentFile(), f.getName()) == false);
+ assertTrue(su.isDanglingSymbolicLink(f.getAbsolutePath()));
+ assertTrue(su.isDanglingSymbolicLink(f.getParentFile(),
+ f.getName()));
+
}
+ @After
public void tearDown() {
- if (supportsSymlinks) {
- executeTarget("tearDown");
- }
+ buildRule.executeTarget("tearDown");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java
index cd6c2f9bd..aa96d8d51 100644
--- a/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java
+++ b/src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java
@@ -23,18 +23,26 @@ import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Location;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Tstamp;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.Path;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Testcase to ensure that command line generation and required attributes are correct.
*
*/
-public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
+public class MSVSSTest implements MSVSSConstants {
private Commandline commandline;
@@ -52,43 +60,30 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
private static final String OUTPUT = "output.log";
private static final String SS_DIR = "c:/winnt".replace('/', File.separatorChar);
- /**
- * Constructor for the MSVSSTest object
- *
- * @param s Test name
- */
- public MSVSSTest(String s) {
- super(s);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ private Project project;
- /**
- * The JUnit setup method
- *
- * @throws Exception
- */
- protected void setUp()
- throws Exception {
+ @Before
+ public void setUp(){
project = new Project();
project.setBasedir(".");
+ project.init();
}
- /**
- * The teardown method for JUnit
- *
- * @throws Exception
- */
- protected void tearDown()
- throws Exception {
+ @After
+ public void tearDown() {
File file = new File(project.getBaseDir(), LOCAL_PATH);
if (file.exists()) {
file.delete();
}
}
- /** Tests VSSGet commandline generation. */
+ @Test
public void testGetCommandLine() {
String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_GET, DS_VSS_PROJECT_PATH,
- MSVSS.FLAG_OVERRIDE_WORKING_DIR + project.getBaseDir().getAbsolutePath()
+ MSVSS.FLAG_OVERRIDE_WORKING_DIR + project.getBaseDir()
+ .getAbsolutePath()
+ File.separator + LOCAL_PATH, MSVSS.FLAG_AUTORESPONSE_DEF,
MSVSS.FLAG_RECURSION, MSVSS.FLAG_VERSION + VERSION, MSVSS.FLAG_LOGIN
+ VSS_USERNAME + "," + VSS_PASSWORD, FLAG_FILETIME_UPDATED, FLAG_SKIP_WRITABLE};
@@ -117,12 +112,14 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
}
/** Tests VSSGet required attributes. */
+ @Test
public void testGetExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vssget.1", "some cause", "vsspath attribute must be set!");
}
/** Tests Label commandline generation. */
+ @Test
public void testLabelCommandLine1() {
String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_LABEL, DS_VSS_PROJECT_PATH,
MSVSS.FLAG_COMMENT + SRC_COMMENT, MSVSS.FLAG_AUTORESPONSE_YES,
@@ -145,6 +142,7 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
}
/** Tests Label commandline generation with a label of more than 31 chars. */
+ @Test
public void testLabelCommandLine2() {
String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_LABEL, DS_VSS_PROJECT_PATH,
MSVSS.FLAG_COMMENT + SRC_COMMENT, MSVSS.FLAG_AUTORESPONSE_DEF,
@@ -167,18 +165,21 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
/**
* Test VSSLabel required attributes.
*/
+ @Test
public void testLabelExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vsslabel.1", "some cause", "vsspath attribute must be set!");
expectSpecificBuildException("vsslabel.2", "some cause", "label attribute must be set!");
}
/** Tests VSSHistory commandline generation with from label. */
+ @Test
public void testHistoryCommandLine1() {
String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_HISTORY, DS_VSS_PROJECT_PATH,
MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_VERSION_LABEL + LONG_LABEL
+ MSVSS.VALUE_FROMLABEL + SRC_LABEL, MSVSS.FLAG_LOGIN + VSS_USERNAME
- + "," + VSS_PASSWORD, MSVSS.FLAG_OUTPUT + project.getBaseDir().getAbsolutePath()
+ + "," + VSS_PASSWORD, MSVSS.FLAG_OUTPUT + project.getBaseDir()
+ .getAbsolutePath()
+ File.separator + OUTPUT};
// Set up a VSSHistory task
@@ -199,6 +200,7 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
}
/** Tests VSSHistory commandline generation with from date. */
+ @Test
public void testHistoryCommandLine2() {
String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_HISTORY, DS_VSS_PROJECT_PATH,
MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_VERSION_DATE + DATE + MSVSS.VALUE_FROMDATE
@@ -219,6 +221,7 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
}
/** Tests VSSHistory commandline generation with date calculation. */
+ @Test
public void testHistoryCommandLine3() {
// Set up a Timestamp
Tstamp tstamp = new Tstamp();
@@ -256,12 +259,24 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
/**
* Tests VSSHistory required attributes.
*/
+ @Test
public void testHistoryExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vsshistory.1", "some cause", "vsspath attribute must be set!");
}
+ private void expectSpecificBuildException(String target, String failMessage,
+ String exceptionMessage) {
+ try {
+ buildRule.executeTarget(target);
+ fail(failMessage);
+ } catch(BuildException ex) {
+ assertEquals(exceptionMessage, ex.getMessage());
+ }
+ }
+
/** Tests CheckIn commandline generation. */
+ @Test
public void testCheckinCommandLine() {
String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_CHECKIN, DS_VSS_PROJECT_PATH,
MSVSS.FLAG_AUTORESPONSE_NO, MSVSS.FLAG_WRITABLE, MSVSS.FLAG_LOGIN + VSS_USERNAME,
@@ -284,12 +299,14 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
/**
* Test VSSCheckIn required attributes.
*/
+ @Test
public void testCheckinExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vsscheckin.1", "some cause", "vsspath attribute must be set!");
}
/** Tests CheckOut commandline generation. */
+ @Test
public void testCheckoutCommandLine() {
String[] sTestCmdLine = {SS_DIR + File.separator + MSVSS.SS_EXE, MSVSS.COMMAND_CHECKOUT,
DS_VSS_PROJECT_PATH, MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_RECURSION,
@@ -318,13 +335,15 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
/**
* Test VSSCheckout required attributes.
*/
+ @Test
public void testCheckoutExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vsscheckout.1", "some cause", "vsspath attribute must be set!");
expectSpecificBuildException("vsscheckout.2", "some cause", "blah is not a legal value for this attribute");
}
/** Tests Add commandline generation. */
+ @Test
public void testAddCommandLine() {
String[] sTestCmdLine = {SS_DIR + File.separator + MSVSS.SS_EXE, MSVSS.COMMAND_ADD,
project.getBaseDir().getAbsolutePath() + File.separator + LOCAL_PATH,
@@ -349,12 +368,14 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
/**
* Test VSSAdd required attributes.
*/
+ @Test
public void testAddExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vssadd.1", "some cause", "localPath attribute must be set!");
}
/** Tests CP commandline generation. */
+ @Test
public void testCpCommandLine() {
String[] sTestCmdLine = {MSVSS.SS_EXE, MSVSS.COMMAND_CP,
DS_VSS_PROJECT_PATH, MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_LOGIN +
@@ -374,12 +395,14 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
/**
* Test VSSCP required attributes.
*/
+ @Test
public void testCpExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vsscp.1", "some cause", "vsspath attribute must be set!");
}
/** Tests Create commandline generation. */
+ @Test
public void testCreateCommandLine() {
String[] sTestCmdLine = { MSVSS.SS_EXE, MSVSS.COMMAND_CREATE,
DS_VSS_PROJECT_PATH, MSVSS.FLAG_COMMENT + SRC_COMMENT, MSVSS.FLAG_AUTORESPONSE_NO,
@@ -403,8 +426,9 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
/**
* Test VSSCreate required attributes.
*/
+ @Test
public void testCreateExceptions() {
- configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/vss/vss.xml");
expectSpecificBuildException("vsscreate.1", "some cause", "vsspath attribute must be set!");
}
@@ -422,7 +446,7 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
while (testIndex < testLength) {
try {
- if (sGeneratedCmdLine[genIndex] == "") {
+ if (sGeneratedCmdLine[genIndex].equals("")) {
genIndex++;
continue;
}
@@ -439,7 +463,7 @@ public class MSVSSTest extends BuildFileTest implements MSVSSConstants {
// Count the number of empty strings
int cnt = 0;
for (int i = 0; i < genLength; i++) {
- if (sGeneratedCmdLine[i] == "") {
+ if (sGeneratedCmdLine[i].equals("")) {
cnt++;
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/AbstractFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/AbstractFileSetTest.java
index a2aae129d..aa4fd39c3 100644
--- a/src/tests/junit/org/apache/tools/ant/types/AbstractFileSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/AbstractFileSetTest.java
@@ -20,10 +20,13 @@ package org.apache.tools.ant.types;
import java.io.File;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Base class for FileSetTest and DirSetTest.
@@ -32,14 +35,12 @@ import org.apache.tools.ant.Project;
*
*/
-public abstract class AbstractFileSetTest extends TestCase {
+public abstract class AbstractFileSetTest {
private Project project;
- public AbstractFileSetTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
project = new Project();
project.setBasedir(".");
@@ -51,6 +52,7 @@ public abstract class AbstractFileSetTest extends TestCase {
return project;
}
+ @Test
public final void testEmptyElementIfIsReference() {
AbstractFileSet f = getInstance();
f.setIncludes("**/*.java");
@@ -182,6 +184,7 @@ public abstract class AbstractFileSetTest extends TestCase {
}
}
+ @Test
public void testCircularReferenceCheck() {
AbstractFileSet f = getInstance();
project.addReference("dummy", f);
diff --git a/src/tests/junit/org/apache/tools/ant/types/AddTypeTest.java b/src/tests/junit/org/apache/tools/ant/types/AddTypeTest.java
index 715cbc1be..6c91a9afa 100644
--- a/src/tests/junit/org/apache/tools/ant/types/AddTypeTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/AddTypeTest.java
@@ -18,84 +18,121 @@
package org.apache.tools.ant.types;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.condition.Condition;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class AddTypeTest extends BuildFileTest {
+import static org.junit.Assert.fail;
- public AddTypeTest(String name) {
- super(name);
- }
+public class AddTypeTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/addtype.xml");
+ buildRule.configureProject("src/etc/testcases/types/addtype.xml");
}
+ @Test
public void testAddPath() {
- executeTarget("addpath");
+ buildRule.executeTarget("addpath");
}
+ @Test
public void testAddCondition() {
- executeTarget("addcondition");
+ buildRule.executeTarget("addcondition");
}
+ @Test
public void testAddFilter() {
- executeTarget("addfilter");
+ buildRule.executeTarget("addfilter");
}
+ @Test
public void testAddSelector() {
- executeTarget("addselector");
+ buildRule.executeTarget("addselector");
}
+ @Test
public void testNestedA() {
- expectLogContaining("nested.a", "add A called");
+ buildRule.executeTarget("nested.a");
+ AntAssert.assertContains("add A called", buildRule.getLog());
}
+ @Test
public void testNestedB() {
- expectLogContaining("nested.b", "add B called");
+ buildRule.executeTarget("nested.b");
+ AntAssert.assertContains( "add B called", buildRule.getLog());
}
+ @Test
public void testNestedC() {
- expectLogContaining("nested.c", "add C called");
+ buildRule.executeTarget("nested.c");
+ AntAssert.assertContains( "add C called", buildRule.getLog());
}
+ @Test
public void testNestedAB() {
- expectBuildExceptionContaining(
- "nested.ab", "Should have got ambiguous", "ambiguous");
+ try {
+ buildRule.executeTarget("nested.ab");
+ fail("Build exception expected: Should have got ambiguous");
+ } catch (BuildException ex) {
+ AntAssert.assertContains("ambiguous", ex.getMessage());
+ }
}
+ @Test
public void testConditionType() {
- expectLogContaining("condition.type", "beforeafter");
+ buildRule.executeTarget("condition.type");
+ AntAssert.assertContains( "beforeafter", buildRule.getLog());
}
+ @Test
public void testConditionTask() {
- expectLogContaining("condition.task", "My Condition execution");
+ buildRule.executeTarget("condition.task");
+ AntAssert.assertContains( "My Condition execution", buildRule.getLog());
}
+
+ @Test
public void testConditionConditionType() {
- expectLogContaining("condition.condition.type", "My Condition eval");
+ buildRule.executeTarget("condition.condition.type");
+ AntAssert.assertContains( "My Condition eval", buildRule.getLog());
}
+
+ @Test
public void testConditionConditionTask() {
- expectBuildExceptionContaining(
- "condition.condition.task", "task masking condition",
- "doesn't support the nested");
+ try {
+ buildRule.executeTarget("condition.condition.task");
+ fail("Build exception expected: Task masking condition");
+ } catch (BuildException ex) {
+ AntAssert.assertContains("doesn't support the nested", ex.getMessage());
+ }
}
+ @Test
public void testAddConfigured() {
- expectLogContaining(
- "myaddconfigured", "value is Value Setexecute: value is Value Set");
+ buildRule.executeTarget("myaddconfigured");
+ AntAssert.assertContains("value is Value Setexecute: value is Value Set",
+ buildRule.getLog());
}
+ @Test
public void testAddConfiguredValue() {
- expectLogContaining(
- "myaddconfiguredvalue",
- "value is Value Setexecute: value is Value Set");
+ buildRule.executeTarget("myaddconfiguredvalue");
+ AntAssert.assertContains("value is Value Setexecute: value is Value Set",
+ buildRule.getLog());
}
+ @Test
public void testNamespace() {
- executeTarget("namespacetest");
+ buildRule.executeTarget("namespacetest");
}
// The following will be used as types and tasks
diff --git a/src/tests/junit/org/apache/tools/ant/types/AssertionsTest.java b/src/tests/junit/org/apache/tools/ant/types/AssertionsTest.java
index 37b590c8d..4210fc1a6 100644
--- a/src/tests/junit/org/apache/tools/ant/types/AssertionsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/AssertionsTest.java
@@ -17,81 +17,108 @@
*/
package org.apache.tools.ant.types;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
/**
* test assertion handling
*/
-public class AssertionsTest extends BuildFileTest {
+public class AssertionsTest {
- public AssertionsTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- protected void setUp() throws Exception {
- configureProject("src/etc/testcases/types/assertions.xml");
+ @Before
+ public void setUp() {
+ buildRule.configureProject("src/etc/testcases/types/assertions.xml");
}
+
/**
* runs a test and expects an assertion thrown in forked code
* @param target
*/
- protected void expectAssertion(String target) {
- expectBuildExceptionContaining(target,
- "assertion not thrown in "+target,
- "Java returned: 1");
+ private void expectAssertion(String target) {
+ try {
+ buildRule.executeTarget(target);
+ fail("BuildException should have been thrown by assertion fail in task");
+ } catch (BuildException ex) {
+ assertContains("assertion not thrown in "+target, "Java returned: 1", ex.getMessage());
+ }
}
+ @Test
public void testClassname() {
expectAssertion("test-classname");
}
+ @Test
public void testPackage() {
expectAssertion("test-package");
}
+ @Test
public void testEmptyAssertions() {
- executeTarget("test-empty-assertions");
+ buildRule.executeTarget("test-empty-assertions");
}
+ @Test
public void testDisable() {
- executeTarget("test-disable");
+ buildRule.executeTarget("test-disable");
}
+ @Test
public void testOverride() {
expectAssertion("test-override");
}
+ @Test
public void testOverride2() {
- executeTarget("test-override2");
+ buildRule.executeTarget("test-override2");
}
+
+ @Test
public void testReferences() {
expectAssertion("test-references");
}
+ @Test
public void testMultipleAssertions() {
- expectBuildExceptionContaining("test-multiple-assertions",
- "multiple assertions rejected",
- "Only one assertion declaration is allowed");
+ try {
+ buildRule.executeTarget("test-multiple-assertions");
+ fail("BuildException should have been thrown by assertion fail in task");
+ } catch (BuildException ex) {
+ assertContains("multiple assertions rejected", "Only one assertion declaration is allowed", ex.getMessage());
+ }
}
+ @Test
public void testReferenceAbuse() {
- expectBuildExceptionContaining("test-reference-abuse",
- "reference abuse rejected",
- "You must not specify");
+ try {
+ buildRule.executeTarget("test-reference-abuse");
+ fail("BuildException should have been thrown by reference abuse");
+ } catch (BuildException ex) {
+ assertContains("reference abuse rejected", "You must not specify", ex.getMessage());
+ }
}
+ @Test
public void testNofork() {
- if (AssertionsTest.class.desiredAssertionStatus()) {
- return; // ran Ant tests with -ea and this would fail spuriously
- }
- expectLogContaining("test-nofork",
- "Assertion statements are currently ignored in non-forked mode");
+ Assume.assumeFalse("ran Ant tests with -ea and this would fail spuriously", AssertionsTest.class.desiredAssertionStatus());
+ buildRule.executeTarget("test-nofork");
+ assertContains("Assertion statements are currently ignored in non-forked mode", buildRule.getLog());
}
-
+ @Test
public void testJUnit() {
- executeTarget("test-junit");
+ buildRule.executeTarget("test-junit");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java b/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java
index bb9e68cb0..c18ff5eee 100644
--- a/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/CommandlineJavaTest.java
@@ -18,25 +18,31 @@
package org.apache.tools.ant.types;
-import junit.framework.TestCase;
import org.apache.tools.ant.MagicNames;
import org.apache.tools.ant.Project;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
/**
- * JUnit 3 testcases for org.apache.tools.ant.CommandlineJava
+ * JUnit testcases for org.apache.tools.ant.CommandlineJava
*
*/
-public class CommandlineJavaTest extends TestCase {
+public class CommandlineJavaTest {
private String cloneVm;
- public CommandlineJavaTest(String name) {
- super(name);
- }
private Project project;
+ @Before
public void setUp() {
project = new Project();
project.setBasedir(System.getProperty("root"));
@@ -47,12 +53,14 @@ public class CommandlineJavaTest extends TestCase {
}
}
+ @After
public void tearDown() {
if (cloneVm != null) {
System.setProperty("ant.build.clonevm", cloneVm);
}
}
+ @Test
public void testGetCommandline() throws Exception {
CommandlineJava c = new CommandlineJava();
c.createArgument().setValue("org.apache.tools.ant.CommandlineJavaTest");
@@ -73,7 +81,7 @@ public class CommandlineJavaTest extends TestCase {
assertEquals("no classpath",
"org.apache.tools.ant.CommandlineJavaTest", s[3]);
try {
- CommandlineJava c2 = (CommandlineJava) c.clone();
+ c.clone();
} catch (NullPointerException ex) {
fail("cloning should work without classpath specified");
}
@@ -94,6 +102,7 @@ public class CommandlineJavaTest extends TestCase {
"org.apache.tools.ant.CommandlineJavaTest", s[5]);
}
+ @Test
public void testJarOption() throws Exception {
CommandlineJava c = new CommandlineJava();
c.createArgument().setValue("arg1");
@@ -108,6 +117,7 @@ public class CommandlineJavaTest extends TestCase {
assertEquals("arg1", s[5]);
}
+ @Test
public void testSysproperties() {
String currentClasspath = System.getProperty("java.class.path");
assertNotNull(currentClasspath);
@@ -141,6 +151,7 @@ public class CommandlineJavaTest extends TestCase {
assertNull(System.getProperty("key2"));
}
+ @Test
public void testAssertions() throws Exception {
CommandlineJava c = new CommandlineJava();
c.createArgument().setValue("org.apache.tools.ant.CommandlineJavaTest");
diff --git a/src/tests/junit/org/apache/tools/ant/types/CommandlineTest.java b/src/tests/junit/org/apache/tools/ant/types/CommandlineTest.java
index 2f1723792..e8e444292 100644
--- a/src/tests/junit/org/apache/tools/ant/types/CommandlineTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/CommandlineTest.java
@@ -18,20 +18,20 @@
package org.apache.tools.ant.types;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNotNull;
/**
* JUnit 3 testcases for org.apache.tools.ant.CommandLine
*
*/
-public class CommandlineTest extends TestCase {
-
- public CommandlineTest(String name) {
- super(name);
- }
+public class CommandlineTest {
+ @Test
public void testTokenizer() {
String[] s = Commandline.translateCommandline("1 2 3");
assertEquals("Simple case", 3, s.length);
@@ -107,20 +107,21 @@ public class CommandlineTest extends TestCase {
// now to the expected failures
try {
- s = Commandline.translateCommandline("a \'b c");
+ Commandline.translateCommandline("a \'b c");
fail("unbalanced single quotes undetected");
} catch (BuildException be) {
assertEquals("unbalanced quotes in a \'b c", be.getMessage());
}
try {
- s = Commandline.translateCommandline("a \"b c");
+ Commandline.translateCommandline("a \"b c");
fail("unbalanced double quotes undetected");
} catch (BuildException be) {
assertEquals("unbalanced quotes in a \"b c", be.getMessage());
}
}
+ @Test
public void testToString() {
assertEquals("", Commandline.toString(new String[0]));
assertEquals("", Commandline.toString(null));
@@ -130,6 +131,7 @@ public class CommandlineTest extends TestCase {
assertEquals("1 \'2\"3\'", Commandline.toString(new String[] {"1", "2\"3"}));
}
+ @Test
public void testAwkCommand() {
Commandline c = new Commandline();
c.setExecutable("awk");
@@ -141,6 +143,7 @@ public class CommandlineTest extends TestCase {
assertEquals("'NR == 2 { print $NF }'", s[1]);
}
+ @Test
public void testPrefix() {
Commandline c = new Commandline();
Commandline.Argument a = c.createArgument();
@@ -151,6 +154,7 @@ public class CommandlineTest extends TestCase {
assertEquals("-f=foo", s[0]);
}
+ @Test
public void testSuffix() {
Commandline c = new Commandline();
Commandline.Argument a = c.createArgument();
@@ -161,6 +165,7 @@ public class CommandlineTest extends TestCase {
assertEquals("foo,1", s[0]);
}
+ @Test
public void testPrefixSuffixLine() {
Commandline c = new Commandline();
Commandline.Argument a = c.createArgument();
diff --git a/src/tests/junit/org/apache/tools/ant/types/DescriptionTest.java b/src/tests/junit/org/apache/tools/ant/types/DescriptionTest.java
index 966465dc0..90dbce7fe 100644
--- a/src/tests/junit/org/apache/tools/ant/types/DescriptionTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/DescriptionTest.java
@@ -18,41 +18,42 @@
package org.apache.tools.ant.types;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* FilterSet testing
*
*/
-public class DescriptionTest extends BuildFileTest {
-
- public DescriptionTest(String name) {
- super(name);
- }
-
- public void setUp() {
- }
-
- public void tearDown() {
- }
+public class DescriptionTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Test
public void test1() {
- configureProject("src/etc/testcases/types/description1.xml");
- assertEquals("Single description failed", "Test Project Description", project.getDescription());
+ buildRule.configureProject("src/etc/testcases/types/description1.xml");
+ assertEquals("Single description failed", "Test Project Description", buildRule.getProject().getDescription());
}
+ @Test
public void test2() {
- configureProject("src/etc/testcases/types/description2.xml");
- assertEquals("Multi line description failed", "Multi Line\nProject Description", project.getDescription());
+ buildRule.configureProject("src/etc/testcases/types/description2.xml");
+ assertEquals("Multi line description failed", "Multi Line\nProject Description", buildRule.getProject().getDescription());
}
+ @Test
public void test3() {
- configureProject("src/etc/testcases/types/description3.xml");
- assertEquals("Multi instance description failed", "Multi Instance Project Description", project.getDescription());
+ buildRule.configureProject("src/etc/testcases/types/description3.xml");
+ assertEquals("Multi instance description failed", "Multi Instance Project Description", buildRule.getProject().getDescription());
}
+ @Test
public void test4() {
- configureProject("src/etc/testcases/types/description4.xml");
- assertEquals("Multi instance nested description failed", "Multi Instance Nested Project Description", project.getDescription());
+ buildRule.configureProject("src/etc/testcases/types/description4.xml");
+ assertEquals("Multi instance nested description failed", "Multi Instance Nested Project Description", buildRule.getProject().getDescription());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/DirSetTest.java b/src/tests/junit/org/apache/tools/ant/types/DirSetTest.java
index 1aa5e99a3..8c659ba79 100644
--- a/src/tests/junit/org/apache/tools/ant/types/DirSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/DirSetTest.java
@@ -21,6 +21,10 @@ package org.apache.tools.ant.types;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.tools.ant.BuildException;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* JUnit 3 testcases for org.apache.tools.ant.types.DirSet.
@@ -28,14 +32,11 @@ import org.apache.tools.ant.BuildException;
*/
public class DirSetTest extends AbstractFileSetTest {
- public DirSetTest(String name) {
- super(name);
- }
-
protected AbstractFileSet getInstance() {
return new DirSet();
}
+ @Test
public void testFileSetIsNoDirSet() {
DirSet ds = (DirSet) getInstance();
ds.setProject(getProject());
diff --git a/src/tests/junit/org/apache/tools/ant/types/EnumeratedAttributeTest.java b/src/tests/junit/org/apache/tools/ant/types/EnumeratedAttributeTest.java
index e0751b45b..0e2e241e2 100644
--- a/src/tests/junit/org/apache/tools/ant/types/EnumeratedAttributeTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/EnumeratedAttributeTest.java
@@ -18,21 +18,22 @@
package org.apache.tools.ant.types;
-import junit.framework.TestCase;
import org.apache.tools.ant.BuildException;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
- * JUnit 3 testcases for org.apache.tools.ant.EnumeratedAttribute.
+ * JUnit testcases for org.apache.tools.ant.EnumeratedAttribute.
*/
-public class EnumeratedAttributeTest extends TestCase {
+public class EnumeratedAttributeTest {
private static String[] expected = {"a", "b", "c"};
- public EnumeratedAttributeTest(String name) {
- super(name);
- }
-
+ @Test
public void testContains() {
EnumeratedAttribute t1 = new TestNormal();
for (int i=0; i dummy2 --> dummy3 --> dummy1
FileList f1 = new FileList();
- project.addReference("dummy1", f1);
- f1.setRefid(new Reference(getProject(), "dummy2"));
+ buildRule.getProject().addReference("dummy1", f1);
+ f1.setRefid(new Reference(buildRule.getProject(), "dummy2"));
FileList f2 = new FileList();
- project.addReference("dummy2", f2);
- f2.setRefid(new Reference(getProject(), "dummy3"));
+ buildRule.getProject().addReference("dummy2", f2);
+ f2.setRefid(new Reference(buildRule.getProject(), "dummy3"));
FileList f3 = new FileList();
- project.addReference("dummy3", f3);
- f3.setRefid(new Reference(getProject(), "dummy1"));
+ buildRule.getProject().addReference("dummy3", f3);
+ f3.setRefid(new Reference(buildRule.getProject(), "dummy1"));
try {
- f1.getDir(project);
+ f1.getDir(buildRule.getProject());
fail("Can make circular reference.");
} catch (BuildException be) {
assertEquals("This data type contains a circular reference.",
be.getMessage());
}
try {
- f1.getFiles(project);
+ f1.getFiles(buildRule.getProject());
fail("Can make circular reference.");
} catch (BuildException be) {
assertEquals("This data type contains a circular reference.",
@@ -123,27 +131,33 @@ public class FileListTest extends BuildFileTest {
// dummy1 --> dummy2 --> dummy3
// (which has the Project's basedir as root).
f1 = new FileList();
- project.addReference("dummy1", f1);
- f1.setRefid(new Reference(getProject(), "dummy2"));
+ buildRule.getProject().addReference("dummy1", f1);
+ f1.setRefid(new Reference(buildRule.getProject(), "dummy2"));
f2 = new FileList();
- project.addReference("dummy2", f2);
- f2.setRefid(new Reference(getProject(), "dummy3"));
+ buildRule.getProject().addReference("dummy2", f2);
+ f2.setRefid(new Reference(buildRule.getProject(), "dummy3"));
f3 = new FileList();
- project.addReference("dummy3", f3);
- f3.setDir(project.resolveFile("."));
- File dir = f1.getDir(project);
- assertEquals("Dir is basedir", dir, project.getBaseDir());
+ buildRule.getProject().addReference("dummy3", f3);
+ f3.setDir(buildRule.getProject().resolveFile("."));
+ File dir = f1.getDir(buildRule.getProject());
+ assertEquals("Dir is basedir", dir, buildRule.getProject().getBaseDir());
}
-
+
+ @Test
public void testSimple() {
- expectLog("simple", "/abc/a");
+ buildRule.executeTarget("simple");
+ assertEquals("/abc/a", buildRule.getLog());
}
+ @Test
public void testDouble() {
- expectLog("double", "/abc/a:/abc/b");
+ buildRule.executeTarget("double");
+ assertEquals("/abc/a:/abc/b", buildRule.getLog());
}
+ @Test
public void testNested() {
- expectLog("nested", "/abc/a:/abc/b");
+ buildRule.executeTarget("nested");
+ assertEquals("/abc/a:/abc/b", buildRule.getLog());
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/FileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/FileSetTest.java
index 359598690..8a1c35ac0 100644
--- a/src/tests/junit/org/apache/tools/ant/types/FileSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/FileSetTest.java
@@ -28,9 +28,6 @@ package org.apache.tools.ant.types;
public class FileSetTest extends AbstractFileSetTest {
- public FileSetTest(String name) {
- super(name);
- }
protected AbstractFileSet getInstance() {
return new FileSet();
diff --git a/src/tests/junit/org/apache/tools/ant/types/FilterSetTest.java b/src/tests/junit/org/apache/tools/ant/types/FilterSetTest.java
index 4f014285f..f4df4a383 100644
--- a/src/tests/junit/org/apache/tools/ant/types/FilterSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/FilterSetTest.java
@@ -18,47 +18,60 @@
package org.apache.tools.ant.types;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
-import org.apache.tools.ant.BuildFileTest;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* FilterSet testing
*
*/
-public class FilterSetTest extends BuildFileTest {
+public class FilterSetTest {
static private final int BUF_SIZE = 32768;
- public FilterSetTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/filterset.xml");
+ buildRule.configureProject("src/etc/testcases/types/filterset.xml");
}
+ @After
public void tearDown() {
- executeTarget("cleanup");
+ buildRule.executeTarget("cleanup");
}
- public void test1() {
- executeTarget("test1");
+ @Test
+ public void test1() throws IOException {
+ buildRule.executeTarget("test1");
assertTrue("Filterset 1 failed", compareFiles("src/etc/testcases/types/gold/filterset1.txt",
"src/etc/testcases/types/dest1.txt"));
}
- public void test2() {
- executeTarget("test2");
+ @Test
+ public void test2() throws IOException {
+ buildRule.executeTarget("test2");
assertTrue("Filterset 2 failed", compareFiles("src/etc/testcases/types/gold/filterset2.txt",
"src/etc/testcases/types/dest2.txt"));
}
- public void test3() {
- executeTarget("test3");
+ @Test
+ public void test3() throws IOException {
+ buildRule.executeTarget("test3");
assertTrue("Filterset 3 failed", compareFiles("src/etc/testcases/types/gold/filterset3.txt",
"src/etc/testcases/types/dest3.txt"));
}
@@ -68,6 +81,7 @@ public class FilterSetTest extends BuildFileTest {
* the filter value @test@ contains another filter value, it will
* actually resolve.
*/
+ @Test
public void testRecursive() {
String result = "it works line";
String line="@test@ line";
@@ -84,6 +98,7 @@ public class FilterSetTest extends BuildFileTest {
* Test to see what happens when the resolving occurs in an
* infinite loop.
*/
+ @Test
public void testInfinite() {
String result = "@test@ line testvalue";
String line = "@test@ line @test3@";
@@ -101,6 +116,7 @@ public class FilterSetTest extends BuildFileTest {
* Test to see what happens when the resolving occurs in
* what would be an infinite loop, but with recursion disabled.
*/
+ @Test
public void testRecursionDisabled() {
String result = "@test1@ line testvalue";
String line = "@test@ line @test2@";
@@ -114,6 +130,7 @@ public class FilterSetTest extends BuildFileTest {
assertEquals(result, fs.replaceTokens(line));
}
+ @Test
public void testNonInfiniteRecursiveMultipleOnSingleLine() {
FilterSet filters = new FilterSet();
@@ -131,91 +148,92 @@ public class FilterSetTest extends BuildFileTest {
assertEquals(result, filters.replaceTokens(line));
}
+ @Test
public void testNestedFilterSets() {
- executeTarget("test-nested-filtersets");
+ buildRule.executeTarget("test-nested-filtersets");
- FilterSet fs = (FilterSet) getProject().getReference("1");
+ FilterSet fs = (FilterSet) buildRule.getProject().getReference("1");
Hashtable filters = fs.getFilterHash();
assertEquals(1, filters.size());
assertEquals("value1", filters.get("token1"));
- fs = (FilterSet) getProject().getReference("2");
+ fs = (FilterSet) buildRule.getProject().getReference("2");
filters = fs.getFilterHash();
assertEquals(2, filters.size());
assertEquals("1111", filters.get("aaaa"));
assertEquals("2222", filters.get("bbbb"));
- fs = (FilterSet) getProject().getReference("3");
+ fs = (FilterSet) buildRule.getProject().getReference("3");
filters = fs.getFilterHash();
assertEquals(1, filters.size());
assertEquals("value4", filters.get("token4"));
- fs = (FilterSet) getProject().getReference("5");
+ fs = (FilterSet) buildRule.getProject().getReference("5");
filters = fs.getFilterHash();
assertEquals(1, filters.size());
assertEquals("value1", filters.get("token1"));
}
+ @Test
public void testFiltersFileElement() {
- executeTarget("testFiltersFileElement");
+ buildRule.executeTarget("testFiltersFileElement");
}
+ @Test
public void testFiltersFileAttribute() {
- executeTarget("testFiltersFileAttribute");
+ buildRule.executeTarget("testFiltersFileAttribute");
}
+ @Test
public void testMultipleFiltersFiles() {
- executeTarget("testMultipleFiltersFiles");
+ buildRule.executeTarget("testMultipleFiltersFiles");
}
+ @Test
public void testMissingFiltersFile() {
- expectBuildException("testMissingFiltersFile",
- "should fail due to missing filtersfile");
+ try {
+ buildRule.executeTarget("testMissingFiltersFile");
+ fail("should fail due to missing filtersfile");
+ } catch (BuildException ex) {
+ //TODO assert exception text
+ }
}
+ @Test
public void testAllowMissingFiltersFile() {
- executeTarget("testAllowMissingFiltersFile");
+ buildRule.executeTarget("testAllowMissingFiltersFile");
}
- private boolean compareFiles(String name1, String name2) {
+ private boolean compareFiles(String name1, String name2) throws IOException {
File file1 = new File(System.getProperty("root"), name1);
File file2 = new File(System.getProperty("root"), name2);
- try {
- if (!file1.exists() || !file2.exists()) {
- System.out.println("One or both files do not exist:" + name1 + ", " + name2);
- return false;
- }
- if (file1.length() != file2.length()) {
- System.out.println("File size mismatch:" + name1 + "(" + file1.length() + "), " +
- name2 + "(" + file2.length() + ")");
- return false;
- }
+ if (!file1.exists() || !file2.exists()) {
+ return false;
+ }
+
+ if (file1.length() != file2.length()) {
+ return false;
+ }
- // byte - byte compare
- byte[] buffer1 = new byte[BUF_SIZE];
- byte[] buffer2 = new byte[BUF_SIZE];
-
- FileInputStream fis1 = new FileInputStream(file1);
- FileInputStream fis2 = new FileInputStream(file2);
- int index = 0;
- int read = 0;
- while ((read = fis1.read(buffer1)) != -1) {
- fis2.read(buffer2);
- for (int i = 0; i < read; ++i, ++index) {
- if (buffer1[i] != buffer2[i]) {
- System.out.println("Bytes mismatch:" + name1 + ", " + name2 +
- " at byte " + index);
- return false;
- }
+ // byte - byte compare
+ byte[] buffer1 = new byte[BUF_SIZE];
+ byte[] buffer2 = new byte[BUF_SIZE];
+
+ FileInputStream fis1 = new FileInputStream(file1);
+ FileInputStream fis2 = new FileInputStream(file2);
+ int index = 0;
+ int read = 0;
+ while ((read = fis1.read(buffer1)) != -1) {
+ fis2.read(buffer2);
+ for (int i = 0; i < read; ++i, ++index) {
+ if (buffer1[i] != buffer2[i]) {
+ return false;
}
}
- return true;
- }
- catch (IOException e) {
- System.out.println("IOException comparing files: " + name1 + ", " + name2);
- return false;
}
+ return true;
+
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java b/src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java
index d618b7692..3e08b2cbb 100644
--- a/src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java
@@ -18,24 +18,30 @@
package org.apache.tools.ant.types;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.BuildException;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class FlexIntegerTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
- public FlexIntegerTest(String name) {
- super(name);
- }
+public class FlexIntegerTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/flexinteger.xml");
+ buildRule.configureProject("src/etc/testcases/types/flexinteger.xml");
}
+ @Test
public void testFlexInteger() {
- executeTarget("test");
- assertEquals(project.getProperty("flexint.value1"), "10");
- assertEquals(project.getProperty("flexint.value2"), "8");
+ buildRule.executeTarget("test");
+ assertEquals(buildRule.getProject().getProperty("flexint.value1"), "10");
+ assertEquals(buildRule.getProject().getProperty("flexint.value2"), "8");
}
// This class acts as a custom Ant task also
@@ -44,12 +50,7 @@ public class FlexIntegerTest extends BuildFileTest {
String propName;
private FlexInteger value;
- /**
- * To make taskdef happy
- */
- public FlexIntegerTest() {
- super("FlexIntegerTest");
- }
+
public void setPropName(String propName) {
this.propName = propName;
diff --git a/src/tests/junit/org/apache/tools/ant/types/MapperTest.java b/src/tests/junit/org/apache/tools/ant/types/MapperTest.java
index 7a756f04c..980f5cc27 100644
--- a/src/tests/junit/org/apache/tools/ant/types/MapperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/MapperTest.java
@@ -18,39 +18,45 @@
package org.apache.tools.ant.types;
-import java.io.File;
-import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.List;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.util.ChainedMapper;
import org.apache.tools.ant.util.FileNameMapper;
import org.apache.tools.ant.util.FlatFileNameMapper;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.ant.util.MergingMapper;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
- * JUnit 3 testcases for org.apache.tools.ant.types.Mapper.
+ * JUnit testcases for org.apache.tools.ant.types.Mapper.
+ *
*/
-public class MapperTest extends TestCase {
+public class MapperTest {
- private Project project;
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- public MapperTest(String name) {
- super(name);
- }
+ private Project project;
+ @Before
public void setUp() {
project = new Project();
project.setBasedir(".");
}
+ @Test
public void testEmptyElementIfIsReference() {
Mapper m = new Mapper(project);
m.setFrom("*.java");
@@ -92,6 +98,7 @@ public class MapperTest extends TestCase {
}
}
+ @Test
public void testCircularReferenceCheck() {
Mapper m = new Mapper(project);
project.addReference("dummy", m);
@@ -144,6 +151,7 @@ public class MapperTest extends TestCase {
assertEquals("a.class", result[0]);
}
+ @Test
public void testNested() {
Mapper mapper1 = new Mapper(project);
Mapper.MapperType mt = new Mapper.MapperType();
@@ -175,6 +183,7 @@ public class MapperTest extends TestCase {
list.contains("mergefile"));
}
+ @Test
public void testChained() {
// a --> b --> c --- def
@@ -217,35 +226,10 @@ public class MapperTest extends TestCase {
assertTrue("cannot find expected target \"ghi\"", list.contains("ghi"));
}
+ @Test
public void testCopyTaskWithTwoFilesets() {
- TaskdefForCopyTest t = new TaskdefForCopyTest("test1");
- try {
- t.setUp();
- t.test1();
- } finally {
- t.tearDown();
- }
+ buildRule.configureProject("src/etc/testcases/types/mapper.xml");
+ buildRule.executeTarget("test1");
}
- private class TaskdefForCopyTest extends BuildFileTest {
- TaskdefForCopyTest(String name) {
- super(name);
- }
-
- public void setUp() {
- configureProject("src/etc/testcases/types/mapper.xml");
- }
-
- public void tearDown() {
- try {
- super.tearDown();
- } catch (Exception exc) {
- // ignore
- }
- }
-
- public void test1() {
- executeTarget("test1");
- }
- }
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/PathTest.java b/src/tests/junit/org/apache/tools/ant/types/PathTest.java
index ca944a911..2ad1819cf 100644
--- a/src/tests/junit/org/apache/tools/ant/types/PathTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/PathTest.java
@@ -21,34 +21,36 @@ package org.apache.tools.ant.types;
import java.io.File;
import java.util.Locale;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.condition.Os;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
- * JUnit 3 testcases for org.apache.tools.ant.types.Path
+ * JUnit testcases for org.apache.tools.ant.types.Path
*
*/
-public class PathTest extends TestCase {
+public class PathTest {
public static boolean isUnixStyle = File.pathSeparatorChar == ':';
public static boolean isNetWare = Os.isFamily("netware");
private Project project;
- public PathTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
project = new Project();
project.setBasedir(System.getProperty("root"));
}
// actually tests constructor as well as setPath
+ @Test
public void testConstructorUnixStyle() {
Path p = new Path(project, "/a:/b");
String[] l = p.list();
@@ -66,6 +68,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testRelativePathUnixStyle() {
project.setBasedir(new File(System.getProperty("root"), "src/etc").getAbsolutePath());
Path p = new Path(project, "..:testcases");
@@ -89,6 +92,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testConstructorWindowsStyle() {
Path p = new Path(project, "\\a;\\b");
String[] l = p.list();
@@ -176,6 +180,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testConstructorNetWareStyle() {
// try a netware-volume length path, see how it is handled
Path p = new Path(project, "sys:\\test");
@@ -296,6 +301,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testConstructorMixedStyle() {
Path p = new Path(project, "\\a;\\b:/c");
String[] l = p.list();
@@ -316,6 +322,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testSetLocation() {
Path p = new Path(project);
p.setLocation(new File(File.separatorChar+"a"));
@@ -332,6 +339,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testAppending() {
Path p = new Path(project, "/a:/b");
String[] l = p.list();
@@ -350,6 +358,7 @@ public class PathTest extends TestCase {
assertEquals("7 after append", 7, l.length);
}
+ @Test
public void testEmpyPath() {
Path p = new Path(project, "");
String[] l = p.list();
@@ -365,6 +374,7 @@ public class PathTest extends TestCase {
assertEquals("0 after append", 0, l.length);
}
+ @Test
public void testUnique() {
Path p = new Path(project, "/a:/a");
String[] l = p.list();
@@ -384,6 +394,7 @@ public class PathTest extends TestCase {
assertEquals("1 after append", 1, l.length);
}
+ @Test
public void testEmptyElementIfIsReference() {
Path p = new Path(project, "/a:/a");
try {
@@ -465,6 +476,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testCircularReferenceCheck() {
Path p = new Path(project);
project.addReference("dummy", p);
@@ -513,6 +525,7 @@ public class PathTest extends TestCase {
}
}
+ @Test
public void testFileList() {
Path p = new Path(project);
FileList f = new FileList();
@@ -525,6 +538,7 @@ public class PathTest extends TestCase {
assertEquals(project.resolveFile("build.xml").getAbsolutePath(), l[0]);
}
+ @Test
public void testFileSet() {
Path p = new Path(project);
FileSet f = new FileSet();
@@ -537,6 +551,7 @@ public class PathTest extends TestCase {
assertEquals(project.resolveFile("build.xml").getAbsolutePath(), l[0]);
}
+ @Test
public void testDirSet() {
Path p = new Path(project);
DirSet d = new DirSet();
@@ -549,6 +564,7 @@ public class PathTest extends TestCase {
assertEquals(project.resolveFile("build").getAbsolutePath(), l[0]);
}
+ @Test
public void testRecursion() {
Path p = new Path(project);
try {
diff --git a/src/tests/junit/org/apache/tools/ant/types/PatternSetTest.java b/src/tests/junit/org/apache/tools/ant/types/PatternSetTest.java
index 5f30ed733..065d757db 100644
--- a/src/tests/junit/org/apache/tools/ant/types/PatternSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/PatternSetTest.java
@@ -18,12 +18,15 @@
package org.apache.tools.ant.types;
-import java.io.File;
-
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* JUnit 3 testcases for org.apache.tools.ant.types.PatternSet.
@@ -32,19 +35,17 @@ import org.apache.tools.ant.Project;
*
*/
-public class PatternSetTest extends TestCase {
+public class PatternSetTest {
private Project project;
- public PatternSetTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
project = new Project();
project.setBasedir(".");
}
+ @Test
public void testEmptyElementIfIsReference() {
PatternSet p = new PatternSet();
p.setIncludes("**/*.java");
@@ -119,6 +120,7 @@ public class PatternSetTest extends TestCase {
}
}
+ @Test
public void testCircularReferenceCheck() {
PatternSet p = new PatternSet();
project.addReference("dummy", p);
@@ -185,6 +187,7 @@ public class PatternSetTest extends TestCase {
assertEquals("exclude", i[0]);
}
+ @Test
public void testNestedPatternset() {
PatternSet p = new PatternSet();
p.setIncludes("**/*.java");
diff --git a/src/tests/junit/org/apache/tools/ant/types/PermissionsTest.java b/src/tests/junit/org/apache/tools/ant/types/PermissionsTest.java
index 7c6e062c6..1e43fe1a1 100644
--- a/src/tests/junit/org/apache/tools/ant/types/PermissionsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/PermissionsTest.java
@@ -18,22 +18,21 @@
package org.apache.tools.ant.types;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.ExitException;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.fail;
/**
* JUnit 3 testcases for org.apache.tools.ant.types.Permissions.
*
*/
-public class PermissionsTest extends TestCase {
+public class PermissionsTest {
Permissions perms;
- public PermissionsTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
perms = new Permissions();
Permissions.Permission perm = new Permissions.Permission();
@@ -72,16 +71,18 @@ public class PermissionsTest extends TestCase {
}
/** Tests a permission that is granted per default. */
+ @Test
public void testDefaultGranted() {
perms.setSecurityManager();
try {
- String s = System.getProperty("line.separator");
+ System.getProperty("line.separator");
} finally {
perms.restoreSecurityManager();
}
}
/** Tests a permission that has been granted later via wildcard. */
+ @Test
public void testGranted() {
perms.setSecurityManager();
try {
@@ -93,6 +94,7 @@ public class PermissionsTest extends TestCase {
}
/** Tests a permission that has been granted and revoked later. */
+ @Test
public void testGrantedAndRevoked() {
perms.setSecurityManager();
try {
@@ -107,6 +109,7 @@ public class PermissionsTest extends TestCase {
}
/** Tests a permission that is granted as per default but revoked later via wildcard. */
+ @Test
public void testDefaultRevoked() {
perms.setSecurityManager();
try {
@@ -119,13 +122,15 @@ public class PermissionsTest extends TestCase {
}
}
/** Tests a permission that has not been granted or revoked. */
+ @Test
public void testOther() {
String ls = System.getProperty("line.separator");
perms.setSecurityManager();
try {
- String s = System.setProperty("line.separator",ls);
+ System.setProperty("line.separator",ls);
fail("Could perform an action that should have been forbidden.");
} catch (SecurityException e){
+ //TODO assert exception message
// Was expected, test passes
} finally {
perms.restoreSecurityManager();
@@ -133,6 +138,7 @@ public class PermissionsTest extends TestCase {
}
/** Tests an exit condition. */
+ @Test
public void testExit() {
perms.setSecurityManager();
try {
@@ -149,8 +155,4 @@ public class PermissionsTest extends TestCase {
}
}
-
- public void tearDown() {
- }
-
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/PolyTest.java b/src/tests/junit/org/apache/tools/ant/types/PolyTest.java
index fe6d28616..0d5e2ceb4 100644
--- a/src/tests/junit/org/apache/tools/ant/types/PolyTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/PolyTest.java
@@ -18,34 +18,46 @@
package org.apache.tools.ant.types;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class PolyTest extends BuildFileTest {
-
- public PolyTest(String name) {
- super(name);
- }
+public class PolyTest {
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/poly.xml");
+ buildRule.configureProject("src/etc/testcases/types/poly.xml");
}
+ @Test
public void testFileSet() {
- expectLogContaining("fileset", "types.FileSet");
+ buildRule.executeTarget("fileset");
+ AntAssert.assertContains( "types.FileSet", buildRule.getLog());
}
+ @Test
public void testFileSetAntType() {
- expectLogContaining("fileset-ant-type", "types.PolyTest$MyFileSet");
+ buildRule.executeTarget("fileset-ant-type");
+ AntAssert.assertContains("types.PolyTest$MyFileSet", buildRule.getLog());
}
+ @Test
public void testPath() {
- expectLogContaining("path", "types.Path");
+ buildRule.executeTarget("path");
+ AntAssert.assertContains( "types.Path", buildRule.getLog());
}
+ @Test
public void testPathAntType() {
- expectLogContaining("path-ant-type", "types.PolyTest$MyPath");
+ buildRule.executeTarget("path-ant-type");
+ AntAssert.assertContains( "types.PolyTest$MyPath", buildRule.getLog());
}
public static class MyFileSet extends FileSet {}
diff --git a/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java b/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java
index 459f0545a..f4c2abe0c 100644
--- a/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/RedirectorElementTest.java
@@ -17,48 +17,70 @@
*/
package org.apache.tools.ant.types;
+import org.apache.tools.ant.AntAssert;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
-import org.apache.tools.ant.BuildFileTest;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class RedirectorElementTest extends BuildFileTest {
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
- public RedirectorElementTest(String name) {
- super(name);
- }
+public class RedirectorElementTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/redirector.xml", Project.MSG_VERBOSE);
+ buildRule.configureProject("src/etc/testcases/types/redirector.xml", Project.MSG_VERBOSE);
}
+ @Test
public void test1() {
- executeTarget("test1");
- assertTrue((getProject(). getReference("test1")
+ buildRule.executeTarget("test1");
+ assertTrue((buildRule.getProject(). getReference("test1")
instanceof RedirectorElement));
}
+ @Test
public void test2() {
- expectBuildException("test2", "You must not specify more than one "
- + "attribute when using refid");
+ try {
+ buildRule.executeTarget("test2");
+ fail("You must not specify more than one attribute when using refid");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test3() {
- expectBuildException("test3", "You must not specify nested elements "
- + "when using refid");
+ try {
+ buildRule.executeTarget("test3");
+ fail("You must not specify nested elements when using refid");
+ } catch (BuildException ex) {
+ //TODO assert exception message
+ }
}
+ @Test
public void test4() {
- executeTarget("test4");
+ buildRule.executeTarget("test4");
}
+ @Test
public void testLogInputString() {
- executeTarget("testLogInputString");
- if (super.getLog().indexOf("testLogInputString can-cat") >=0 ) {
- assertDebuglogContaining("Using input string");
+ buildRule.executeTarget("testLogInputString");
+ if (buildRule.getLog().indexOf("testLogInputString can-cat") >=0 ) {
+ AntAssert.assertContains("Using input string", buildRule.getFullLog());
}
}
+ @Test
public void testRefid() {
- executeTarget("testRefid");
+ buildRule.executeTarget("testRefid");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/ResourceOutputTest.java b/src/tests/junit/org/apache/tools/ant/types/ResourceOutputTest.java
index f0ec5e428..b66335a3b 100644
--- a/src/tests/junit/org/apache/tools/ant/types/ResourceOutputTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/ResourceOutputTest.java
@@ -23,7 +23,6 @@ import java.io.IOException;
import java.net.UnknownServiceException;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.resources.ImmutableResourceException;
@@ -33,78 +32,85 @@ import org.apache.tools.ant.types.resources.URLResource;
import org.apache.tools.ant.types.resources.ZipResource;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.ResourceUtils;
+import org.junit.Before;
+import org.junit.Test;
-public class ResourceOutputTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
+public class ResourceOutputTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
private static final File basedir = new File(System.getProperty("root"),
"src/etc/testcases/types/resources");
- public ResourceOutputTest(String name) {
- super(name);
- }
+ private Project project;
+ @Before
public void setUp() {
project = new Project();
project.init();
project.setUserProperty("basedir" , basedir.getAbsolutePath());
}
+ @Test
public void testresourceoutput() {
try {
testoutputbe(new Resource("foo"));
fail("should have caught UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
+ //TODO assert exception message
}
}
+ @Test
public void teststringoutput1() {
StringResource r = new StringResource();
testoutputbe(r);
assertEquals("foo", r.getValue());
}
- public void teststringoutput2() {
+ @Test
+ public void teststringoutput2() throws IOException {
StringResource r = new StringResource("bar");
try {
testoutput(r);
fail("should have caught ImmutableResourceException");
} catch (ImmutableResourceException e) {
- } catch (IOException e) {
- fail("caught some other IOException: " + e);
+ //TODO assert exception message
}
assertEquals("bar", r.getValue());
}
+ @Test
public void testpropertyoutput1() {
- PropertyResource r = new PropertyResource(getProject(), "bar");
+ PropertyResource r = new PropertyResource(project, "bar");
testoutputbe(r);
- assertPropertyEquals("bar", "foo");
+ assertEquals("foo", project.getProperty("bar"));
}
- public void testpropertyoutput2() {
- getProject().setNewProperty("bar", "bar");
- PropertyResource r = new PropertyResource(getProject(), "bar");
+ @Test
+ public void testpropertyoutput2() throws IOException {
+ project.setNewProperty("bar", "bar");
+ PropertyResource r = new PropertyResource(project, "bar");
try {
testoutput(r);
fail("should have caught ImmutableResourceException");
} catch (ImmutableResourceException e) {
- } catch (IOException e) {
- fail("caught some other IOException: " + e);
+ //TODO assert exception message
}
- assertPropertyEquals("bar", "bar");
+ assertEquals("bar", project.getProperty("bar"));
}
- public void testurloutput() {
- File f = getProject().resolveFile("testurloutput");
+ @Test
+ public void testurloutput() throws IOException {
+ File f = project.resolveFile("testurloutput");
try {
FILE_UTILS.createNewFile(f);
testoutput(new URLResource(f));
fail("should have caught UnknownServiceException");
} catch (UnknownServiceException e) {
- } catch (IOException e) {
- e.printStackTrace(System.err);
- fail("caught some other IOException: " + e);
+ //TODO assert exception message
} finally {
if (!f.delete()) {
f.deleteOnExit();
@@ -112,15 +118,16 @@ public class ResourceOutputTest extends BuildFileTest {
}
}
+ @Test
public void testzipentryoutput() {
Zip z = new Zip();
- z.setProject(getProject());
+ z.setProject(project);
Zip.WhenEmpty create = new Zip.WhenEmpty();
create.setValue("create");
z.setWhenempty(create);
z.setBasedir(basedir);
z.setExcludes("**/*");
- File f = getProject().resolveFile("foo");
+ File f = project.resolveFile("foo");
z.setDestFile(f);
z.execute();
ZipResource r = new ZipResource();
@@ -130,6 +137,7 @@ public class ResourceOutputTest extends BuildFileTest {
testoutputbe(r);
fail("should have caught UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
+ //TODO assert exception message
} finally {
if (!f.delete()) {
f.deleteOnExit();
diff --git a/src/tests/junit/org/apache/tools/ant/types/TarFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/TarFileSetTest.java
index d0d570bde..b30168aa7 100644
--- a/src/tests/junit/org/apache/tools/ant/types/TarFileSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/TarFileSetTest.java
@@ -21,6 +21,11 @@ package org.apache.tools.ant.types;
import java.io.File;
import org.apache.tools.ant.BuildException;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* JUnit 3 testcases for org.apache.tools.ant.types.TarFileSet.
@@ -31,13 +36,12 @@ import org.apache.tools.ant.BuildException;
public class TarFileSetTest extends AbstractFileSetTest {
- public TarFileSetTest(String name) {
- super(name);
- }
protected AbstractFileSet getInstance() {
return new TarFileSet();
}
+
+ @Test
public final void testAttributes() {
TarFileSet f = (TarFileSet)getInstance();
//check that dir and src are incompatible
diff --git a/src/tests/junit/org/apache/tools/ant/types/XMLCatalogBuildFileTest.java b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogBuildFileTest.java
index 6d487affc..96c0c5d25 100644
--- a/src/tests/junit/org/apache/tools/ant/types/XMLCatalogBuildFileTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogBuildFileTest.java
@@ -18,25 +18,24 @@
package org.apache.tools.ant.types;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
- * BuildFileTest testcases for org.apache.tools.ant.types.XMLCatalog
+ * testcases for org.apache.tools.ant.types.XMLCatalog
*
* @see org.apache.tools.ant.types.XMLCatalogTest
*
*/
-public class XMLCatalogBuildFileTest extends BuildFileTest {
+public class XMLCatalogBuildFileTest {
- public XMLCatalogBuildFileTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
- public void setUp() {
- }
- public void tearDown() {
- }
//
// Ensure that an external entity resolves as expected with NO
@@ -45,10 +44,11 @@ public class XMLCatalogBuildFileTest extends BuildFileTest {
// Transform an XML file that refers to the entity into a text
// file, stuff result into property: val1
//
+ @Test
public void testEntityNoCatalog() {
- configureProject("src/etc/testcases/types/xmlcatalog.xml");
- expectPropertySet("testentitynocatalog", "val1",
- "A stitch in time saves nine");
+ buildRule.configureProject("src/etc/testcases/types/xmlcatalog.xml");
+ buildRule.executeTarget("testentitynocatalog");
+ assertEquals("A stitch in time saves nine", buildRule.getProject().getProperty("val1"));
}
//
@@ -59,10 +59,11 @@ public class XMLCatalogBuildFileTest extends BuildFileTest {
// file, entity is listed in the XMLCatalog pointing to a
// different file. Stuff result into property: val2
//
+ @Test
public void testEntityWithCatalog() {
- configureProject("src/etc/testcases/types/xmlcatalog.xml");
- expectPropertySet("testentitywithcatalog", "val2",
- "No news is good news");
+ buildRule.configureProject("src/etc/testcases/types/xmlcatalog.xml");
+ buildRule.executeTarget("testentitywithcatalog");
+ assertEquals("No news is good news", buildRule.getProject().getProperty("val2"));
}
//
@@ -73,10 +74,11 @@ public class XMLCatalogBuildFileTest extends BuildFileTest {
// via the document() function. The _second_ XML file refers to an entity.
// Stuff result into the property: val3
//
+ @Test
public void testDocumentNoCatalog() {
- configureProject("src/etc/testcases/types/xmlcatalog.xml");
- expectPropertySet("testdocumentnocatalog", "val3",
- "A stitch in time saves nine");
+ buildRule.configureProject("src/etc/testcases/types/xmlcatalog.xml");
+ buildRule.executeTarget("testdocumentnocatalog");
+ assertEquals("A stitch in time saves nine", buildRule.getProject().getProperty("val3"));
}
//
@@ -87,10 +89,10 @@ public class XMLCatalogBuildFileTest extends BuildFileTest {
// via the document() function. The _second_ XML file refers to an entity.
// The entity is listed in the XMLCatalog pointing to a different file.
// Stuff result into the property: val4
- //
+ @Test
public void testDocumentWithCatalog() {
- configureProject("src/etc/testcases/types/xmlcatalog.xml");
- expectPropertySet("testdocumentwithcatalog", "val4",
- "No news is good news");
+ buildRule.configureProject("src/etc/testcases/types/xmlcatalog.xml");
+ buildRule.executeTarget("testdocumentwithcatalog");
+ assertEquals("No news is good news", buildRule.getProject().getProperty("val4"));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/XMLCatalogTest.java b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogTest.java
index 1a860af6f..c1adc30db 100644
--- a/src/tests/junit/org/apache/tools/ant/types/XMLCatalogTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/XMLCatalogTest.java
@@ -19,24 +19,33 @@
package org.apache.tools.ant.types;
import java.io.File;
+import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
import javax.xml.transform.sax.SAXSource;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.util.JAXPUtils;
+import org.junit.Before;
+import org.junit.Test;
import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNotNull;
/**
* JUnit testcases for org.apache.tools.ant.types.XMLCatalog
*
*/
-public class XMLCatalogTest extends TestCase {
+public class XMLCatalogTest {
private Project project;
private XMLCatalog catalog;
@@ -47,14 +56,11 @@ public class XMLCatalogTest extends TestCase {
return cat;
}
- private String toURLString(File file) throws MalformedURLException {
+ private static String toURLString(File file) throws MalformedURLException {
return JAXPUtils.getSystemId(file);
}
- public XMLCatalogTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
project = new Project();
project.setBasedir(System.getProperty("root"));
@@ -71,11 +77,7 @@ public class XMLCatalogTest extends TestCase {
catalog = newCatalog();
}
- public void tearDown() {
- project = null;
- catalog = null;
- }
-
+ @Test
public void testEmptyCatalog() {
try {
InputSource result = catalog.resolveEntity("PUBLIC ID ONE",
@@ -116,34 +118,28 @@ public class XMLCatalogTest extends TestCase {
return resultStr;
}
- public void testNonExistentEntry() {
+ @Test
+ public void testNonExistentEntry() throws IOException, SAXException, TransformerException {
ResourceLocation dtd = new ResourceLocation();
dtd.setPublicId("PUBLIC ID ONE");
dtd.setLocation("i/dont/exist.dtd");
- try {
- InputSource result = catalog.resolveEntity("PUBLIC ID ONE",
- "i/dont/exist.dtd");
- assertNull("Nonexistent Catalog entry should not be returned", result);
- } catch (Exception e) {
- fail("resolveEntity() failed!" + e.toString());
- }
+ InputSource isResult = catalog.resolveEntity("PUBLIC ID ONE",
+ "i/dont/exist.dtd");
+ assertNull("Nonexistent Catalog entry should not be returned", isResult);
- try {
- Source result = catalog.resolve("i/dont/exist.dtd", null);
- String expected = toURLString(new File(project.getBaseDir().toURL() +
- "/i/dont/exist.dtd"));
- String resultStr =
- fileURLPartWithoutLeadingSlashes((SAXSource)result);
- assertTrue("Nonexistent Catalog entry return input with a system ID like "
- + expected + " but was " + resultStr,
- expected.endsWith(resultStr));
- } catch (Exception e) {
- fail("resolve() failed!" + e.toString());
- }
+ Source result = catalog.resolve("i/dont/exist.dtd", null);
+ String expected = toURLString(new File(project.getBaseDir().toURL() +
+ "/i/dont/exist.dtd"));
+ String resultStr =
+ fileURLPartWithoutLeadingSlashes((SAXSource)result);
+ assertTrue("Nonexistent Catalog entry return input with a system ID like "
+ + expected + " but was " + resultStr,
+ expected.endsWith(resultStr));
}
+ @Test
public void testEmptyElementIfIsReference() {
ResourceLocation dtd = new ResourceLocation();
dtd.setPublicId("PUBLIC ID ONE");
@@ -171,7 +167,8 @@ public class XMLCatalogTest extends TestCase {
}
}
- public void testCircularReferenceCheck() {
+ @Test
+ public void testCircularReferenceCheck() throws IOException, SAXException {
// catalog <--> catalog
project.addReference("catalog", catalog);
@@ -201,20 +198,19 @@ public class XMLCatalogTest extends TestCase {
catalog1.setRefid(new Reference(project, "catalog2"));
try {
- InputSource result = catalog1.resolveEntity("PUBLIC ID ONE",
+ catalog1.resolveEntity("PUBLIC ID ONE",
"i/dont/exist.dtd");
fail("Can make circular reference");
} catch (BuildException be) {
assertEquals("This data type contains a circular reference.",
- be.getMessage());
- } catch (Exception e) {
- fail("resolveEntity() failed!" + e.toString());
+ be.getMessage());
}
}
// inspired by Bugzilla Report 23913
// a problem used to happen under Windows when the location of the DTD was given as an absolute path
// possibly with a mixture of file separators
- public void testAbsolutePath() {
+ @Test
+ public void testAbsolutePath() throws IOException, SAXException {
ResourceLocation dtd = new ResourceLocation();
dtd.setPublicId("-//stevo//DTD doc 1.0//EN");
@@ -223,19 +219,17 @@ public class XMLCatalogTest extends TestCase {
catalog.addDTD(dtd);
File dtdFile = project.resolveFile(sysid);
- try {
- InputSource result = catalog.resolveEntity("-//stevo//DTD doc 1.0//EN",
- "nap:chemical+brothers");
- assertNotNull(result);
- assertEquals(toURLString(dtdFile),
- result.getSystemId());
- } catch (Exception e) {
- fail("resolveEntity() failed!" + e.toString());
- }
+ InputSource result = catalog.resolveEntity("-//stevo//DTD doc 1.0//EN",
+ "nap:chemical+brothers");
+ assertNotNull(result);
+ assertEquals(toURLString(dtdFile),
+ result.getSystemId());
+
}
- public void testSimpleEntry() {
+ @Test
+ public void testSimpleEntry() throws IOException, SAXException {
ResourceLocation dtd = new ResourceLocation();
dtd.setPublicId("-//stevo//DTD doc 1.0//EN");
@@ -244,18 +238,16 @@ public class XMLCatalogTest extends TestCase {
catalog.addDTD(dtd);
File dtdFile = project.resolveFile(sysid);
- try {
- InputSource result = catalog.resolveEntity("-//stevo//DTD doc 1.0//EN",
- "nap:chemical+brothers");
- assertNotNull(result);
- assertEquals(toURLString(dtdFile),
- result.getSystemId());
- } catch (Exception e) {
- fail("resolveEntity() failed!" + e.toString());
- }
+ InputSource result = catalog.resolveEntity("-//stevo//DTD doc 1.0//EN",
+ "nap:chemical+brothers");
+ assertNotNull(result);
+ assertEquals(toURLString(dtdFile),
+ result.getSystemId());
+
}
- public void testEntryReference() {
+ @Test
+ public void testEntryReference() throws IOException, SAXException, TransformerException {
String publicId = "-//stevo//DTD doc 1.0//EN";
String sysid = "src/etc/testcases/taskdefs/optional/xml/doc.dtd";
@@ -286,28 +278,22 @@ public class XMLCatalogTest extends TestCase {
catalog1.setRefid(new Reference(project, "catalog"));
catalog2.setRefid(new Reference(project, "catalog1"));
- try {
- InputSource result = catalog2.resolveEntity(publicId,
- "nap:chemical+brothers");
+ InputSource isResult = catalog2.resolveEntity(publicId,
+ "nap:chemical+brothers");
+
+ assertNotNull(isResult);
+ assertEquals(toURLString(dtdFile),
+ isResult.getSystemId());
- assertNotNull(result);
- assertEquals(toURLString(dtdFile),
- result.getSystemId());
- } catch (Exception e) {
- fail("resolveEntity() failed!" + e.toString());
- }
- try {
Source result = catalog.resolve(uri, null);
assertNotNull(result);
assertEquals(toURLString(xmlFile),
result.getSystemId());
- } catch (Exception e) {
- fail("resolve() failed!" + e.toString());
- }
}
- public void testNestedCatalog() {
+ @Test
+ public void testNestedCatalog() throws IOException, SAXException, TransformerException {
String publicId = "-//stevo//DTD doc 1.0//EN";
String dtdLoc = "src/etc/testcases/taskdefs/optional/xml/doc.dtd";
@@ -330,37 +316,25 @@ public class XMLCatalogTest extends TestCase {
XMLCatalog catalog1 = newCatalog();
catalog1.addConfiguredXMLCatalog(catalog);
- try {
- InputSource result = catalog1.resolveEntity(publicId,
- "nap:chemical+brothers");
- assertNotNull(result);
- assertEquals(toURLString(dtdFile),
- result.getSystemId());
- } catch (Exception e) {
- fail("resolveEntity() failed!" + e.toString());
- }
+ InputSource isResult = catalog1.resolveEntity(publicId,
+ "nap:chemical+brothers");
+ assertNotNull(isResult);
+ assertEquals(toURLString(dtdFile),
+ isResult.getSystemId());
- try {
- Source result = catalog.resolve(uri, null);
- assertNotNull(result);
- assertEquals(toURLString(xmlFile),
- result.getSystemId());
- } catch (Exception e) {
- fail("resolve() failed!" + e.toString());
- }
+ Source result = catalog.resolve(uri, null);
+ assertNotNull(result);
+ assertEquals(toURLString(xmlFile),
+ result.getSystemId());
}
- public void testResolverBase() {
+ @Test
+ public void testResolverBase() throws MalformedURLException, TransformerException {
String uri = "http://foo.com/bar/blah.xml";
String uriLoc = "etc/testcases/taskdefs/optional/xml/about.xml";
- String base = null;
- try {
- base = toURLString(project.getBaseDir()) + "/src/";
- } catch (MalformedURLException ex) {
- fail (ex.toString());
- }
+ String base = toURLString(project.getBaseDir()) + "/src/";
ResourceLocation entity = new ResourceLocation();
entity.setPublicId(uri);
@@ -368,17 +342,15 @@ public class XMLCatalogTest extends TestCase {
catalog.addEntity(entity);
File xmlFile = project.resolveFile("src/" + uriLoc);
- try {
- Source result = catalog.resolve(uri, base);
- assertNotNull(result);
- assertEquals(toURLString(xmlFile),
- result.getSystemId());
- } catch (Exception e) {
- fail("resolve() failed!" + e.toString());
- }
+ Source result = catalog.resolve(uri, base);
+ assertNotNull(result);
+ assertEquals(toURLString(xmlFile),
+ result.getSystemId());
+
}
- public void testClasspath() {
+ @Test
+ public void testClasspath() throws IOException, TransformerException, SAXException {
String publicId = "-//stevo//DTD doc 1.0//EN";
@@ -405,23 +377,16 @@ public class XMLCatalogTest extends TestCase {
aPath.append(new Path(project, path2));
catalog.setClasspath(aPath);
- try {
- InputSource result = catalog.resolveEntity(publicId,
- "nap:chemical+brothers");
- assertNotNull(result);
- String resultStr = new URL(result.getSystemId()).getFile();
- assertTrue(toURLString(dtdFile).endsWith(resultStr));
- } catch (Exception e) {
- fail("resolveEntity() failed!" + e.toString());
- }
+ InputSource isResult = catalog.resolveEntity(publicId,
+ "nap:chemical+brothers");
+ assertNotNull(isResult);
+ String resultStr1 = new URL(isResult.getSystemId()).getFile();
+ assertTrue(toURLString(dtdFile).endsWith(resultStr1));
+
+ Source result = catalog.resolve(uri, null);
+ assertNotNull(result);
+ String resultStr = new URL(result.getSystemId()).getFile();
+ assertTrue(toURLString(xmlFile).endsWith(resultStr));
- try {
- Source result = catalog.resolve(uri, null);
- assertNotNull(result);
- String resultStr = new URL(result.getSystemId()).getFile();
- assertTrue(toURLString(xmlFile).endsWith(resultStr));
- } catch (Exception e) {
- fail("resolve() failed!" + e.toString());
- }
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/ZipFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/ZipFileSetTest.java
index 19b25827a..e7b14c191 100644
--- a/src/tests/junit/org/apache/tools/ant/types/ZipFileSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/ZipFileSetTest.java
@@ -21,6 +21,11 @@ package org.apache.tools.ant.types;
import java.io.File;
import org.apache.tools.ant.BuildException;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* JUnit 3 testcases for org.apache.tools.ant.types.ZipFileSet.
@@ -31,13 +36,11 @@ import org.apache.tools.ant.BuildException;
public class ZipFileSetTest extends AbstractFileSetTest {
- public ZipFileSetTest(String name) {
- super(name);
- }
-
protected AbstractFileSet getInstance() {
return new ZipFileSet();
}
+
+ @Test
public final void testAttributes() {
ZipFileSet f = (ZipFileSet)getInstance();
//check that dir and src are incompatible
diff --git a/src/tests/junit/org/apache/tools/ant/types/mappers/GlobMapperTest.java b/src/tests/junit/org/apache/tools/ant/types/mappers/GlobMapperTest.java
index 71a79d378..310fb5e50 100644
--- a/src/tests/junit/org/apache/tools/ant/types/mappers/GlobMapperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/mappers/GlobMapperTest.java
@@ -18,25 +18,31 @@
package org.apache.tools.ant.types.mappers;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Testcase for the <globmapper> mapper.
*
*/
-public class GlobMapperTest extends BuildFileTest {
- public GlobMapperTest(String name) {
- super(name);
- }
+public class GlobMapperTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/mappers/globmapper.xml");
+ buildRule.configureProject("src/etc/testcases/types/mappers/globmapper.xml");
}
+ @Test
public void testIgnoreCase() {
- executeTarget("ignore.case");
+ buildRule.executeTarget("ignore.case");
}
public void testHandleDirSep() {
- executeTarget("handle.dirsep");
+ buildRule.executeTarget("handle.dirsep");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/mappers/RegexpPatternMapperTest.java b/src/tests/junit/org/apache/tools/ant/types/mappers/RegexpPatternMapperTest.java
index a3c1c3a09..d01593b4f 100644
--- a/src/tests/junit/org/apache/tools/ant/types/mappers/RegexpPatternMapperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/mappers/RegexpPatternMapperTest.java
@@ -18,25 +18,33 @@
package org.apache.tools.ant.types.mappers;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Testcase for the <regexpmapper> mapper.
*
*/
-public class RegexpPatternMapperTest extends BuildFileTest {
- public RegexpPatternMapperTest(String name) {
- super(name);
- }
+public class RegexpPatternMapperTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/mappers/regexpmapper.xml");
+ buildRule.configureProject("src/etc/testcases/types/mappers/regexpmapper.xml");
}
+ @Test
public void testIgnoreCase() {
- executeTarget("ignore.case");
+ buildRule.executeTarget("ignore.case");
}
+
+ @Test
public void testHandleDirSep() {
- executeTarget("handle.dirsep");
+ buildRule.executeTarget("handle.dirsep");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/ScriptMapperTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptMapperTest.java
index 208e7a1f9..bf727db90 100644
--- a/src/tests/junit/org/apache/tools/ant/types/optional/ScriptMapperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptMapperTest.java
@@ -18,27 +18,36 @@
package org.apache.tools.ant.types.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
/**
* Test our script mapping
*/
-public class ScriptMapperTest extends BuildFileTest {
- public ScriptMapperTest(String name) {
- super(name);
- }
+public class ScriptMapperTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/mappers/scriptmapper.xml");
+ buildRule.configureProject("src/etc/testcases/types/mappers/scriptmapper.xml");
}
+ @Test
public void testClear() {
- executeTarget("testClear");
+ buildRule.executeTarget("testClear");
}
+
+ @Test
public void testSetMultiple() {
- executeTarget("testSetMultiple");
+ buildRule.executeTarget("testSetMultiple");
}
+
+ @Test
public void testPassthrough() {
- executeTarget("testPassthrough");
+ buildRule.executeTarget("testPassthrough");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/ScriptSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptSelectorTest.java
index 1052669e2..304d6d090 100644
--- a/src/tests/junit/org/apache/tools/ant/types/optional/ScriptSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/optional/ScriptSelectorTest.java
@@ -17,45 +17,67 @@
*/
package org.apache.tools.ant.types.optional;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.apache.tools.ant.AntAssert.assertContains;
+import static org.junit.Assert.fail;
/**
* Test that scripting selection works. Needs scripting support to work
*/
-public class ScriptSelectorTest extends BuildFileTest {
-
+public class ScriptSelectorTest {
- public ScriptSelectorTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/selectors/scriptselector.xml");
+ buildRule.configureProject("src/etc/testcases/types/selectors/scriptselector.xml");
}
+ @Test
public void testNolanguage() {
- expectBuildExceptionContaining("testNolanguage",
- "Absence of language attribute not detected",
- "script language must be specified");
+ try {
+ buildRule.executeTarget("testNolanguage");
+ fail("Absence of language attribute not detected");
+ } catch(BuildException ex) {
+ assertContains("script language must be specified", ex.getMessage());
+
+ }
}
+ @Test
public void testSelectionSetByDefault() {
- executeTarget("testSelectionSetByDefault");
+ buildRule.executeTarget("testSelectionSetByDefault");
}
+
+ @Test
public void testSelectionSetWorks() {
- executeTarget("testSelectionSetWorks");
+ buildRule.executeTarget("testSelectionSetWorks");
}
+
+ @Test
public void testSelectionClearWorks() {
- executeTarget("testSelectionClearWorks");
+ buildRule.executeTarget("testSelectionClearWorks");
}
+
+ @Test
public void testFilenameAttribute() {
- executeTarget("testFilenameAttribute");
+ buildRule.executeTarget("testFilenameAttribute");
}
+
+ @Test
public void testFileAttribute() {
- executeTarget("testFileAttribute");
+ buildRule.executeTarget("testFileAttribute");
}
+
+ @Test
public void testBasedirAttribute() {
- executeTarget("testBasedirAttribute");
+ buildRule.executeTarget("testBasedirAttribute");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java
index e79bd6ae3..392667cb7 100644
--- a/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/optional/depend/ClassFileSetTest.java
@@ -21,33 +21,40 @@ package org.apache.tools.ant.types.optional.depend;
import java.io.File;
import java.util.Hashtable;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
/**
* Testcase for the Classfileset optional type.
*
*/
-public class ClassFileSetTest extends BuildFileTest {
+public class ClassFileSetTest {
public static final String RESULT_FILESET = "result";
- public ClassFileSetTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
// share the setup for testing the depend task
- configureProject("src/etc/testcases/taskdefs/optional/depend/depend.xml");
+ buildRule.configureProject("src/etc/testcases/taskdefs/optional/depend/depend.xml");
}
/**
* Test basic classfileset
*/
+ @Test
public void testBasicSet() {
- Project p = getProject();
- executeTarget("testbasicset");
+ Project p = buildRule.getProject();
+ buildRule.executeTarget("testbasicset");
FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET);
DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p);
String[] scannedFiles = scanner.getIncludedFiles();
@@ -70,9 +77,10 @@ public class ClassFileSetTest extends BuildFileTest {
/**
* Test small classfileset
*/
+ @Test
public void testSmallSet() {
- Project p = getProject();
- executeTarget("testsmallset");
+ Project p = buildRule.getProject();
+ buildRule.executeTarget("testsmallset");
FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET);
DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p);
String[] scannedFiles = scanner.getIncludedFiles();
@@ -91,9 +99,10 @@ public class ClassFileSetTest extends BuildFileTest {
/**
* Test combo classfileset
*/
+ @Test
public void testComboSet() {
- Project p = getProject();
- executeTarget("testcomboset");
+ Project p = buildRule.getProject();
+ buildRule.executeTarget("testcomboset");
FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET);
DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p);
String[] scannedFiles = scanner.getIncludedFiles();
@@ -110,16 +119,18 @@ public class ClassFileSetTest extends BuildFileTest {
/**
* Test that you can pass a classfileset by reference to a fileset.
*/
+ @Test
public void testByReference() {
- executeTarget("testbyreference");
+ buildRule.executeTarget("testbyreference");
}
/**
* Test that classes included in a method "System.out.println(MyClass.class)" are included.
*/
+ @Test
public void testMethodParam() {
- Project p = getProject();
- executeTarget("testmethodparam");
+ Project p = buildRule.getProject();
+ buildRule.executeTarget("testmethodparam");
FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET);
DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p);
String[] scannedFiles = scanner.getIncludedFiles();
@@ -144,9 +155,10 @@ public class ClassFileSetTest extends BuildFileTest {
/**
* Test that classes included in a method "System.out.println(Outer.Inner.class)" are included.
*/
+ @Test
public void testMethodParamInner() {
- Project p = getProject();
- executeTarget("testmethodparaminner");
+ Project p = buildRule.getProject();
+ buildRule.executeTarget("testmethodparaminner");
FileSet resultFileSet = (FileSet)p.getReference(RESULT_FILESET);
DirectoryScanner scanner = resultFileSet.getDirectoryScanner(p);
String[] scannedFiles = scanner.getIncludedFiles();
@@ -166,8 +178,9 @@ public class ClassFileSetTest extends BuildFileTest {
files.containsKey("test" + File.separator + "MethodParam.class"));
}
+ @Test
public void testResourceCollection() {
- executeTarget("testresourcecollection");
+ buildRule.executeTarget("testresourcecollection");
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/FileResourceTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/FileResourceTest.java
index 673a8353f..71efc656a 100644
--- a/src/tests/junit/org/apache/tools/ant/types/resources/FileResourceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/resources/FileResourceTest.java
@@ -21,19 +21,24 @@ import java.io.File;
import org.apache.tools.ant.Project;
-import junit.framework.TestCase;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* Test Java API of {@link FileResource}.
*/
-public class FileResourceTest extends TestCase {
+public class FileResourceTest {
private File root;
+ @Before
public void setUp() {
root = new File(System.getProperty("root"));
}
+ @Test
public void testAttributes() {
FileResource f = new FileResource();
f.setBaseDir(root);
@@ -43,6 +48,7 @@ public class FileResourceTest extends TestCase {
assertEquals("foo", f.getName());
}
+ @Test
public void testNonImmediateBasedir() {
FileResource f = new FileResource();
f.setBaseDir(root);
@@ -52,6 +58,7 @@ public class FileResourceTest extends TestCase {
assertEquals("foo/bar", f.getName().replace(File.separatorChar, '/'));
}
+ @Test
public void testFile() {
FileResource f = new FileResource(new File(root, "foo"));
assertEquals(new File(root, "foo"), f.getFile());
@@ -59,6 +66,7 @@ public class FileResourceTest extends TestCase {
assertEquals("foo", f.getName());
}
+ @Test
public void testBasedirAndName() {
FileResource f = new FileResource(root, "foo");
assertEquals(new File(root, "foo"), f.getFile());
@@ -66,6 +74,7 @@ public class FileResourceTest extends TestCase {
assertEquals("foo", f.getName());
}
+ @Test
public void testNonImmediateBasedirAndName() {
FileResource f = new FileResource(root, "foo/bar");
assertEquals(new File(root, "foo/bar"), f.getFile());
@@ -73,6 +82,7 @@ public class FileResourceTest extends TestCase {
assertEquals("foo/bar", f.getName().replace(File.separatorChar, '/'));
}
+ @Test
public void testProjectAndFilename() {
Project p = new Project();
p.setBaseDir(root);
@@ -82,6 +92,7 @@ public class FileResourceTest extends TestCase {
assertEquals("foo", f.getName());
}
+ @Test
public void testRelativeFactoryResource() {
FileResource f = new FileResource(root, "foo");
FileResource relative = f.getResource("bar").as(FileResource.class);
@@ -90,6 +101,7 @@ public class FileResourceTest extends TestCase {
assertEquals(root, relative.getBaseDir());
}
+ @Test
public void testAbsoluteFactoryResource() {
FileResource f = new FileResource(new File(root, "foo/a"));
assertEquals(new File(root, "foo"), f.getBaseDir());
@@ -99,6 +111,7 @@ public class FileResourceTest extends TestCase {
assertEquals(root, fromFactory.getBaseDir());
}
+ @Test
public void testParentSiblingFactoryResource() {
FileResource f = new FileResource(new File(root, "foo/a"));
assertEquals(new File(root, "foo"), f.getBaseDir());
diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/JavaResourceTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/JavaResourceTest.java
index d07a649cd..a67db39bc 100644
--- a/src/tests/junit/org/apache/tools/ant/types/resources/JavaResourceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/resources/JavaResourceTest.java
@@ -17,33 +17,43 @@
*/
package org.apache.tools.ant.types.resources;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class JavaResourceTest extends BuildFileTest {
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
- public JavaResourceTest(String name) {
- super(name);
- }
+public class JavaResourceTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/resources/javaresource.xml");
+ buildRule.configureProject("src/etc/testcases/types/resources/javaresource.xml");
}
+ @Test
public void testLoadManifest() {
- executeTarget("loadManifest");
- assertNotNull(getProject().getProperty("manifest"));
+ buildRule.executeTarget("loadManifest");
+ assertNotNull(buildRule.getProject().getProperty("manifest"));
// this actually relies on the first manifest being found on
// the classpath (probably rt.jar's) being valid
- assertTrue(getProject().getProperty("manifest")
+ assertTrue(buildRule.getProject().getProperty("manifest")
.startsWith("Manifest-Version:"));
}
+ @Test
public void testIsURLProvider() {
JavaResource r = new JavaResource();
assertSame(r, r.as(URLProvider.class));
}
+ @Test
public void testGetURLOfManifest() {
JavaResource r = new JavaResource();
r.setName("META-INF/MANIFEST.MF");
diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/LazyResourceCollectionTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/LazyResourceCollectionTest.java
index b7108fac6..f91077a6e 100644
--- a/src/tests/junit/org/apache/tools/ant/types/resources/LazyResourceCollectionTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/resources/LazyResourceCollectionTest.java
@@ -23,15 +23,19 @@ import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
-import junit.framework.TestCase;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceCollection;
+import org.junit.Test;
-public class LazyResourceCollectionTest extends TestCase {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class LazyResourceCollectionTest {
private class StringResourceCollection implements ResourceCollection {
- List resources = Arrays.asList(new Resource[] {});
+ List resources = Arrays.asList();
List createdIterators = new ArrayList();
@@ -70,6 +74,7 @@ public class LazyResourceCollectionTest extends TestCase {
}
}
+ @Test
public void testLazyLoading() throws Exception {
StringResourceCollection collectionTest = new StringResourceCollection();
LazyResourceCollectionWrapper lazyCollection = new LazyResourceCollectionWrapper();
@@ -102,7 +107,7 @@ public class LazyResourceCollectionTest extends TestCase {
try {
it.next();
- fail("NoSuchElementException shoudl have been raised");
+ fail("NoSuchElementException should have been raised");
} catch (NoSuchElementException e) {
// ok
}
@@ -114,6 +119,7 @@ public class LazyResourceCollectionTest extends TestCase {
testCollection.createdIterators.size());
}
+ @Test
public void testCaching() throws Exception {
StringResourceCollection collectionTest = new StringResourceCollection();
LazyResourceCollectionWrapper lazyCollection = new LazyResourceCollectionWrapper();
diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/MultiRootFileSetTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/MultiRootFileSetTest.java
index a0e2a00d9..6c05963b8 100644
--- a/src/tests/junit/org/apache/tools/ant/types/resources/MultiRootFileSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/resources/MultiRootFileSetTest.java
@@ -25,15 +25,17 @@ import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.AbstractFileSet;
import org.apache.tools.ant.types.AbstractFileSetTest;
import org.apache.tools.ant.types.Reference;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
* This doesn't actually test much, mainly reference handling.
*/
public class MultiRootFileSetTest extends AbstractFileSetTest {
- public MultiRootFileSetTest(String name) {
- super(name);
- }
protected AbstractFileSet getInstance() {
return new MultiRootFileSet() {
@@ -56,6 +58,7 @@ public class MultiRootFileSetTest extends AbstractFileSetTest {
};
}
+ @Test
public void testEmptyElementIfIsReferenceAdditionalAttributes() {
MultiRootFileSet f = new MultiRootFileSet();
f.setProject(getProject());
@@ -115,6 +118,7 @@ public class MultiRootFileSetTest extends AbstractFileSetTest {
}
}
+ @Test
public void testDirCannotBeSet() {
try {
new MultiRootFileSet().setDir(new File("."));
diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/ResourceListTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/ResourceListTest.java
index bd34fbbed..f0201789d 100644
--- a/src/tests/junit/org/apache/tools/ant/types/resources/ResourceListTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/resources/ResourceListTest.java
@@ -18,25 +18,38 @@
package org.apache.tools.ant.types.resources;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.types.FilterChain;
import org.apache.tools.ant.types.Reference;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-public class ResourceListTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
- protected void setUp() throws Exception {
- configureProject("src/etc/testcases/types/resources/resourcelist.xml");
+public class ResourceListTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
+ public void setUp() throws Exception {
+ buildRule.configureProject("src/etc/testcases/types/resources/resourcelist.xml");
}
- protected void tearDown() throws Exception {
- executeTarget("tearDown");
+ @After
+ public void tearDown() throws Exception {
+ buildRule.executeTarget("tearDown");
}
+ @Test
public void testEmptyElementWithReference() {
ResourceList rl = new ResourceList();
rl.setEncoding("foo");
try {
- rl.setRefid(new Reference(getProject(), "dummyref"));
+ rl.setRefid(new Reference(buildRule.getProject(), "dummyref"));
fail("Can add reference to ResourceList with encoding attribute set.");
} catch (BuildException be) {
assertEquals("You must not specify more than one attribute when using refid",
@@ -44,7 +57,7 @@ public class ResourceListTest extends BuildFileTest {
}
rl = new ResourceList();
- rl.setRefid(new Reference(getProject(), "dummyref"));
+ rl.setRefid(new Reference(buildRule.getProject(), "dummyref"));
try {
rl.setEncoding("foo");
fail("Can set encoding in ResourceList that is a reference");
@@ -54,9 +67,9 @@ public class ResourceListTest extends BuildFileTest {
}
rl = new ResourceList();
- rl.add(new FileResource(getProject(), "."));
+ rl.add(new FileResource(buildRule.getProject(), "."));
try {
- rl.setRefid(new Reference(getProject(), "dummyref"));
+ rl.setRefid(new Reference(buildRule.getProject(), "dummyref"));
fail("Can add reference to ResourceList with nested resource collection.");
} catch (BuildException be) {
assertEquals("You must not specify nested elements when using refid",
@@ -64,9 +77,9 @@ public class ResourceListTest extends BuildFileTest {
}
rl = new ResourceList();
- rl.setRefid(new Reference(getProject(), "dummyref"));
+ rl.setRefid(new Reference(buildRule.getProject(), "dummyref"));
try {
- rl.add(new FileResource(getProject(), "."));
+ rl.add(new FileResource(buildRule.getProject(), "."));
fail("Can add reference to ResourceList with nested resource collection.");
} catch (BuildException be) {
assertEquals("You must not specify nested elements when using refid",
@@ -76,7 +89,7 @@ public class ResourceListTest extends BuildFileTest {
rl = new ResourceList();
rl.addFilterChain(new FilterChain());
try {
- rl.setRefid(new Reference(getProject(), "dummyref"));
+ rl.setRefid(new Reference(buildRule.getProject(), "dummyref"));
fail("Can add reference to ResourceList with nested filter chain.");
} catch (BuildException be) {
assertEquals("You must not specify nested elements when using refid",
@@ -84,7 +97,7 @@ public class ResourceListTest extends BuildFileTest {
}
rl = new ResourceList();
- rl.setRefid(new Reference(getProject(), "dummyref"));
+ rl.setRefid(new Reference(buildRule.getProject(), "dummyref"));
try {
rl.addFilterChain(new FilterChain());
fail("Can add reference to ResourceList with nested filter chain.");
@@ -94,18 +107,19 @@ public class ResourceListTest extends BuildFileTest {
}
}
+ @Test
public void testCircularReference() throws Exception {
ResourceList rl1 = new ResourceList();
- rl1.setProject(getProject());
- rl1.setRefid(new Reference(getProject(), "foo"));
+ rl1.setProject(buildRule.getProject());
+ rl1.setRefid(new Reference(buildRule.getProject(), "foo"));
ResourceList rl2 = new ResourceList();
- rl2.setProject(getProject());
- getProject().addReference("foo", rl2);
+ rl2.setProject(buildRule.getProject());
+ buildRule.getProject().addReference("foo", rl2);
Union u = new Union();
u.add(rl1);
- u.setProject(getProject());
+ u.setProject(buildRule.getProject());
rl2.add(u);
diff --git a/src/tests/junit/org/apache/tools/ant/types/resources/TarResourceTest.java b/src/tests/junit/org/apache/tools/ant/types/resources/TarResourceTest.java
index d0483ae66..a9593f090 100644
--- a/src/tests/junit/org/apache/tools/ant/types/resources/TarResourceTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/resources/TarResourceTest.java
@@ -17,26 +17,38 @@
*/
package org.apache.tools.ant.types.resources;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.util.FileUtils;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
-public class TarResourceTest extends BuildFileTest {
+import static org.apache.tools.ant.FileUtilities.getFileContents;
+import static org.junit.Assert.assertEquals;
- private static final FileUtils FU = FileUtils.getFileUtils();
- public TarResourceTest(String name) {
- super(name);
+public class TarResourceTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+
+ @Before
+ public void setUp() throws Exception {
+ buildRule.configureProject("src/etc/testcases/types/resources/tarentry.xml");
}
- protected void setUp() throws Exception {
- configureProject("src/etc/testcases/types/resources/tarentry.xml");
+
+ @After
+ public void tearDown() throws Exception {
+ buildRule.executeTarget("tearDown");
}
+ @Test
public void testUncompressSource() throws java.io.IOException {
- executeTarget("uncompressSource");
- assertTrue(FU.contentEquals(project.resolveFile("../../asf-logo.gif"),
- new File(getProject().getProperty("output"), "asf-logo.gif")));
+ buildRule.executeTarget("uncompressSource");
+ assertEquals(getFileContents(buildRule.getProject().resolveFile("../../asf-logo.gif")),
+ getFileContents(new File(buildRule.getProject().getProperty("output"), "asf-logo.gif")));
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorRule.java b/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorRule.java
new file mode 100644
index 000000000..d5613b266
--- /dev/null
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorRule.java
@@ -0,0 +1,125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.tools.ant.types.selectors;
+
+import java.io.File;
+
+
+import org.apache.tools.ant.BuildFileRule;
+
+
+/**
+ * Base test case for Selectors. Provides a shared test as well as
+ * a test bed for selecting on, and a helper method for determining
+ * whether selections are correct.
+ *
+ */
+public class BaseSelectorRule extends BuildFileRule {
+
+ private File beddir;
+ private File mirrordir;
+ private final String[] filenames = {".","asf-logo.gif.md5","asf-logo.gif.bz2",
+ "asf-logo.gif.gz","copy.filterset.filtered","zip/asf-logo.gif.zip",
+ "tar/asf-logo.gif.tar","tar/asf-logo-huge.tar.gz",
+ "tar/gz/asf-logo.gif.tar.gz","tar/bz2/asf-logo.gif.tar.bz2",
+ "tar/bz2/asf-logo-huge.tar.bz2","tar/bz2"};
+ private File[] files = new File[filenames.length];
+ private File[] mirrorfiles = new File[filenames.length];
+
+ @Override
+ public void before() throws Throwable {
+ super.before();
+ configureProject("src/etc/testcases/types/selectors.xml");
+ executeTarget("setUp");
+
+ executeTarget("setupfiles");
+ executeTarget("mirrorfiles");
+
+ beddir = new File(super.getProject().getProperty("test.dir"));
+ mirrordir = new File(super.getProject().getProperty("mirror.dir"));
+
+ for (int x = 0; x < files.length; x++) {
+ files[x] = new File(beddir,filenames[x]);
+ mirrorfiles[x] = new File(mirrordir,filenames[x]);
+ }
+ }
+
+ @Override
+ public void after() {
+ super.after();
+ executeTarget("tearDown");
+ }
+
+ public File getBeddir() {
+ return beddir;
+ }
+
+ public File[] getMirrorFiles() {
+ return mirrorfiles;
+ }
+
+ public File[] getFiles() {
+ return files;
+ }
+
+ public String[] getFilenames() {
+ return filenames;
+ }
+
+
+ /**
+ * This is a helper method that takes a selector and calls its
+ * isSelected() method on each file in the testbed. It returns
+ * a string of "T"s amd "F"s
+ */
+ public String selectionString(FileSelector selector) {
+ return selectionString(beddir,files,selector);
+ }
+
+ /**
+ * This is a helper method that takes a selector and calls its
+ * isSelected() method on each file in the mirror testbed. This
+ * variation is used for dependency checks and to get around the
+ * limitations in the touch task when running JDK 1.1. It returns
+ * a string of "T"s amd "F"s.
+ */
+ public String mirrorSelectionString(FileSelector selector) {
+ return selectionString(mirrordir,mirrorfiles,selector);
+ }
+
+ /**
+ * Worker method for the two convenience methods above. Applies a
+ * selector on a set of files passed in and returns a string of
+ * "T"s amd "F"s from applying the selector to each file.
+ */
+ public String selectionString(File basedir, File[] files, FileSelector selector) {
+ StringBuilder buf = new StringBuilder();
+ for (int x = 0; x < files.length; x++) {
+ if (selector.isSelected(basedir,filenames[x],files[x])) {
+ buf.append('T');
+ }
+ else {
+ buf.append('F');
+ }
+ }
+ return buf.toString();
+ }
+
+
+}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorTest.java
index 4fec08822..2332778e6 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/BaseSelectorTest.java
@@ -20,8 +20,6 @@ package org.apache.tools.ant.types.selectors;
import java.io.File;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileTest;
import org.apache.tools.ant.Project;
@@ -31,7 +29,9 @@ import org.apache.tools.ant.Project;
* a test bed for selecting on, and a helper method for determining
* whether selections are correct.
*
+ * @deprecated as of 1.9.4. Use {@link org.apache.tools.ant.types.selectors.BaseSelectorRule} instead.
*/
+@Deprecated
public abstract class BaseSelectorTest extends BuildFileTest {
private Project project;
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsRegexpTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsRegexpTest.java
index fdc60806a..41e9c8309 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsRegexpTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsRegexpTest.java
@@ -20,69 +20,37 @@ package org.apache.tools.ant.types.selectors;
import java.io.File;
-import junit.framework.TestCase;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
-import org.apache.tools.ant.BuildFileTest;
-import org.apache.tools.ant.Project;
+import static org.junit.Assert.assertEquals;
-public class ContainsRegexpTest extends TestCase {
+public class ContainsRegexpTest {
- private Project project;
-
- public ContainsRegexpTest(String name) {
- super(name);
- }
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- project = new Project();
- project.setBasedir(".");
+ buildRule.configureProject("src/etc/testcases/types/selectors.xml");
}
+ @Test
public void testContainsRegexp() {
- TaskdefForRegexpTest MyTask =
- new TaskdefForRegexpTest("containsregexp");
- try {
- MyTask.setUp();
- MyTask.test();
- } finally {
- MyTask.tearDown();
- }
- }
+ buildRule.executeTarget("containsregexp");
+ File dir = new File(buildRule.getOutputDir(), "regexpseltestdest");
+ File[] files = dir.listFiles();
+ int filecount = files.length;
- private class TaskdefForRegexpTest extends BuildFileTest {
- TaskdefForRegexpTest(String name) {
- super(name);
- }
+ if (filecount != 1) {
+ assertEquals("ContainsRegexp test should have copied 1 file",
+ 1, files.length);
- public void setUp() {
- configureProject("src/etc/testcases/types/selectors.xml");
- }
-
- public void tearDown() {
- try {
- super.tearDown();
- } catch (Exception exc) {
- // ignore
- }
- }
-
- public void test() {
- File dir = null;
- File[] files = null;
- int filecount;
-
- executeTarget("containsregexp");
-
- dir = new File(getOutputDir(), "regexpseltestdest");
- files = dir.listFiles();
- filecount = files.length;
-
- if (filecount != 1)
- assertEquals("ContainsRegexp test should have copied 1 file",
- 1, files.length);
-
}
}
+
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsSelectorTest.java
index bde5ecef8..9a5a83fe1 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/ContainsSelectorTest.java
@@ -19,49 +19,44 @@
package org.apache.tools.ant.types.selectors;
import org.apache.tools.ant.BuildException;
-import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Parameter;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Tests Contains Selectors.
*
*/
-public class ContainsSelectorTest extends BaseSelectorTest {
+public class ContainsSelectorTest {
- private Project project;
+ @Rule
+ public final BaseSelectorRule selectorRule = new BaseSelectorRule();
- public ContainsSelectorTest(String name) {
- super(name);
- }
-
- /**
- * Factory method from base class. This is overriden in child
- * classes to return a specific Selector class.
- */
- public BaseSelector getInstance() {
- return new ContainsSelector();
- }
/**
* Test the code that validates the selector.
*/
+ @Test
public void testValidate() {
- ContainsSelector s = (ContainsSelector)getInstance();
+ ContainsSelector s = new ContainsSelector();
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("ContainsSelector did not check for required field 'text'");
} catch (BuildException be1) {
assertEquals("The text attribute is required", be1.getMessage());
}
- s = (ContainsSelector)getInstance();
+ s = new ContainsSelector();
Parameter param = new Parameter();
param.setName("garbage in");
param.setValue("garbage out");
Parameter[] params = {param};
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("ContainsSelector did not check for valid parameter element");
} catch (BuildException be2) {
assertEquals("Invalid parameter garbage in", be2.getMessage());
@@ -72,51 +67,47 @@ public class ContainsSelectorTest extends BaseSelectorTest {
/**
* Tests to make sure that the selector is selecting files correctly.
*/
+ @Test
public void testSelectionBehaviour() {
ContainsSelector s;
String results;
- try {
- makeBed();
-
- s = (ContainsSelector)getInstance();
- s.setText("no such string in test files");
- results = selectionString(s);
- assertEquals("TFFFFFFFFFFT", results);
-
- s = (ContainsSelector)getInstance();
- s.setText("Apache Ant");
- results = selectionString(s);
- assertEquals("TFFFTFFFFFFT", results);
-
- s = (ContainsSelector)getInstance();
- s.setText("apache ant");
- s.setCasesensitive(true);
- results = selectionString(s);
- assertEquals("TFFFFFFFFFFT", results);
-
- s = (ContainsSelector)getInstance();
- s.setText("apache ant");
- s.setCasesensitive(false);
- results = selectionString(s);
- assertEquals("TFFFTFFFFFFT", results);
-
- s = (ContainsSelector)getInstance();
- s.setText("ApacheAnt");
- s.setIgnorewhitespace(true);
- results = selectionString(s);
- assertEquals("TFFFTFFFFFFT", results);
-
- s = (ContainsSelector)getInstance();
- s.setText("A p a c h e A n t");
- s.setIgnorewhitespace(true);
- results = selectionString(s);
- assertEquals("TFFFTFFFFFFT", results);
- }
- finally {
- cleanupBed();
- }
+ s = new ContainsSelector();
+ s.setText("no such string in test files");
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFFFFFFFFFT", results);
+
+ s = new ContainsSelector();
+ s.setText("Apache Ant");
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFFTFFFFFFT", results);
+
+ s = new ContainsSelector();
+ s.setText("apache ant");
+ s.setCasesensitive(true);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFFFFFFFFFT", results);
+
+ s = new ContainsSelector();
+ s.setText("apache ant");
+ s.setCasesensitive(false);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFFTFFFFFFT", results);
+
+ s = new ContainsSelector();
+ s.setText("ApacheAnt");
+ s.setIgnorewhitespace(true);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFFTFFFFFFT", results);
+
+ s = new ContainsSelector();
+ s.setText("A p a c h e A n t");
+ s.setIgnorewhitespace(true);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFFTFFFFFFT", results);
+
+
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/DateSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/DateSelectorTest.java
index 38e069107..6e461bab4 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/DateSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/DateSelectorTest.java
@@ -20,43 +20,42 @@ package org.apache.tools.ant.types.selectors;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Parameter;
+import org.junit.Assume;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Tests Date Selectors.
*
*/
-public class DateSelectorTest extends BaseSelectorTest {
+public class DateSelectorTest {
- public DateSelectorTest(String name) {
- super(name);
- }
+ @Rule
+ public final BaseSelectorRule selectorRule = new BaseSelectorRule();
- /**
- * Factory method from base class. This is overriden in child
- * classes to return a specific Selector class.
- */
- public BaseSelector getInstance() {
- return new DateSelector();
- }
/**
* Test the code that validates the selector.
*/
+ @Test
public void testValidate() {
- DateSelector s = (DateSelector)getInstance();
+ DateSelector s = new DateSelector();
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DateSelector did not check for required fields");
} catch (BuildException be1) {
assertEquals("You must provide a datetime or the number of "
+ "milliseconds.", be1.getMessage());
}
- s = (DateSelector)getInstance();
+ s = new DateSelector();
s.setDatetime("01/01/1969 01:01 AM");
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DateSelector did not check for Datetime being in the "
+ "allowable range");
} catch (BuildException be2) {
@@ -65,10 +64,10 @@ public class DateSelectorTest extends BaseSelectorTest {
+ "1970, 00:00:00 GMT).", be2.getMessage());
}
- s = (DateSelector)getInstance();
+ s = new DateSelector();
s.setDatetime("this is not a date");
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DateSelector did not check for Datetime being in a "
+ "valid format");
} catch (BuildException be3) {
@@ -77,7 +76,7 @@ public class DateSelectorTest extends BaseSelectorTest {
+ " MM/DD/YYYY HH:MM AM_PM format.", be3.getMessage());
}
- s = (DateSelector)getInstance();
+ s = new DateSelector();
Parameter param = new Parameter();
param.setName("garbage in");
param.setValue("garbage out");
@@ -85,34 +84,34 @@ public class DateSelectorTest extends BaseSelectorTest {
params[0] = param;
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DateSelector did not check for valid parameter element");
} catch (BuildException be4) {
assertEquals("Invalid parameter garbage in", be4.getMessage());
}
- s = (DateSelector)getInstance();
+ s = new DateSelector();
param = new Parameter();
param.setName("millis");
param.setValue("garbage out");
params[0] = param;
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DateSelector did not check for valid millis parameter");
} catch (BuildException be5) {
assertEquals("Invalid millisecond setting garbage out",
be5.getMessage());
}
- s = (DateSelector)getInstance();
+ s = new DateSelector();
param = new Parameter();
param.setName("granularity");
param.setValue("garbage out");
params[0] = param;
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DateSelector did not check for valid granularity parameter");
} catch (BuildException be6) {
assertEquals("Invalid granularity setting garbage out",
@@ -124,6 +123,7 @@ public class DateSelectorTest extends BaseSelectorTest {
/**
* Tests to make sure that the selector is selecting files correctly.
*/
+ @Test
public void testSelectionBehaviour() {
DateSelector s;
String results;
@@ -138,93 +138,92 @@ public class DateSelectorTest extends BaseSelectorTest {
DateSelector.TimeComparisons();
after.setValue("after");
- try {
- makeBed();
-
- s = (DateSelector)getInstance();
- s.setDatetime("10/10/1999 1:45 PM");
- s.setWhen(before);
- results = selectionString(s);
- assertEquals("TFFFFFFFFFFT", results);
-
- s = (DateSelector)getInstance();
- s.setDatetime("10/10/1999 1:45 PM");
- s.setWhen(before);
- s.setCheckdirs(true);
- results = selectionString(s);
- assertEquals("FFFFFFFFFFFF", results);
-
- s = (DateSelector)getInstance();
- s.setDatetime("10/10/1999 1:45 PM");
- s.setWhen(after);
- results = selectionString(s);
- assertEquals("TTTTTTTTTTTT", results);
-
- s = (DateSelector)getInstance();
- s.setDatetime("11/21/2001 4:54 AM");
- s.setWhen(before);
- results = selectionString(s);
- assertEquals("TFTFFFFFFFFT", results);
-
- s = (DateSelector)getInstance();
- s.setDatetime("11/21/2001 4:55 AM");
-
- long milliseconds = s.getMillis();
- s.setWhen(equal);
- results = selectionString(s);
- assertEquals("TTFFTFFFTTTT", results);
-
- s = (DateSelector)getInstance();
- s.setMillis(milliseconds);
- s.setWhen(equal);
- results = selectionString(s);
- assertEquals("TTFFTFFFTTTT", results);
-
- s = (DateSelector)getInstance();
- s.setDatetime("11/21/2001 4:56 AM");
- s.setWhen(after);
- results = selectionString(s);
- assertEquals("TFFTFTTTFFFT", results);
-
- s = (DateSelector)getInstance();
- Parameter param1 = new Parameter();
- Parameter param2 = new Parameter();
- param1.setName("datetime");
- param1.setValue("11/21/2001 4:56 AM");
- param2.setName("when");
- param2.setValue("after");
- Parameter[] params = {param1,param2};
- s.setParameters(params);
- results = selectionString(s);
- assertEquals("TFFTFTTTFFFT", results);
- try {
- makeMirror();
-
- s = (DateSelector)getInstance();
- long testtime = mirrorfiles[5].lastModified();
- s.setMillis(testtime);
- s.setWhen(after);
- s.setGranularity(2);
- results = mirrorSelectionString(s);
- assertEquals("TFFFFTTTTTTT", results);
-
- s = (DateSelector)getInstance();
- testtime = mirrorfiles[6].lastModified();
- s.setMillis(testtime);
- s.setWhen(before);
- s.setGranularity(2);
- results = mirrorSelectionString(s);
- assertEquals("TTTTTTTFFFFT", results);
- }
- finally {
- cleanupMirror();
- }
+ s = new DateSelector();
+ s.setDatetime("10/10/1999 1:45 PM");
+ s.setWhen(before);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFFFFFFFFFT", results);
+
+ s = new DateSelector();
+ s.setDatetime("10/10/1999 1:45 PM");
+ s.setWhen(before);
+ s.setCheckdirs(true);
+ results = selectorRule.selectionString(s);
+ assertEquals("FFFFFFFFFFFF", results);
+
+ s = new DateSelector();
+ s.setDatetime("10/10/1999 1:45 PM");
+ s.setWhen(after);
+ results = selectorRule.selectionString(s);
+ assertEquals("TTTTTTTTTTTT", results);
+
+ s = new DateSelector();
+ s.setDatetime("11/21/2001 4:54 AM");
+ s.setWhen(before);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFTFFFFFFFFT", results);
+
+ s = new DateSelector();
+ s.setDatetime("11/21/2001 4:55 AM");
+
+ long milliseconds = s.getMillis();
+ s.setWhen(equal);
+ results = selectorRule.selectionString(s);
+ assertEquals("TTFFTFFFTTTT", results);
+
+ s = new DateSelector();
+ s.setMillis(milliseconds);
+ s.setWhen(equal);
+ results = selectorRule.selectionString(s);
+ assertEquals("TTFFTFFFTTTT", results);
+
+ s = new DateSelector();
+ s.setDatetime("11/21/2001 4:56 AM");
+ s.setWhen(after);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFTFTTTFFFT", results);
+
+ s = new DateSelector();
+ Parameter param1 = new Parameter();
+ Parameter param2 = new Parameter();
+ param1.setName("datetime");
+ param1.setValue("11/21/2001 4:56 AM");
+ param2.setName("when");
+ param2.setValue("after");
+ Parameter[] params = {param1,param2};
+ s.setParameters(params);
+ results = selectorRule.selectionString(s);
+ assertEquals("TFFTFTTTFFFT", results);
+
+ s = new DateSelector();
+ long testtime = selectorRule.getMirrorFiles()[5].lastModified();
+ s.setMillis(testtime);
+ s.setWhen(after);
+ s.setGranularity(2);
+
+ // setup the modified timestamp to match what the test needs, although be aware that the 3rd and 4th
+ // files don't exist so can't be changed, so don't try and loop over them
+ for (int i = 1; i <=2; i++) {
+ Assume.assumeTrue("Cannot setup file times for test", selectorRule.getMirrorFiles()[i].setLastModified(testtime - (3*60*60*100)));
}
- finally {
- cleanupBed();
+
+
+ results = selectorRule.mirrorSelectionString(s);
+ assertEquals("TFFFFTTTTTTT", results);
+
+ s = new DateSelector();
+ testtime = selectorRule.getMirrorFiles()[6].lastModified();
+ s.setMillis(testtime);
+ s.setWhen(before);
+ s.setGranularity(2);
+ for (int i = 7; i <= 10; i++) {
+ Assume.assumeTrue("Cannot setup file times for test", selectorRule.getMirrorFiles()[i].setLastModified(testtime + (3*60*60*100)));
}
+ results = selectorRule.mirrorSelectionString(s);
+ assertEquals("TTTTTTTFFFFT", results);
+
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/DependSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/DependSelectorTest.java
index f70f142b2..ec95878a8 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/DependSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/DependSelectorTest.java
@@ -20,34 +20,28 @@ package org.apache.tools.ant.types.selectors;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Mapper;
+import org.junit.Rule;
+import org.junit.Test;
import java.io.File;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
/**
* Tests Depend Selectors
*
*/
-public class DependSelectorTest extends BaseSelectorTest {
-
- public DependSelectorTest(String name) {
- super(name);
- }
+public class DependSelectorTest {
- /**
- * Factory method from base class. This is overriden in child
- * classes to return a specific Selector class.
- */
- public BaseSelector getInstance() {
- return new DependSelector();
- }
+ @Rule
+ public final BaseSelectorRule selectorRule = new BaseSelectorRule();
- /**
- * Test the code that validates the selector.
- */
- public void testValidate() {
- DependSelector s = (DependSelector)getInstance();
+ @Test
+ public void testValidateSingleMapper() {
try {
+ DependSelector s = new DependSelector();
s.createMapper();
s.createMapper();
fail("DependSelector allowed more than one nested mapper.");
@@ -55,10 +49,14 @@ public class DependSelectorTest extends BaseSelectorTest {
assertEquals("Cannot define more than one mapper",
be1.getMessage());
}
+ }
+
- s = (DependSelector)getInstance();
+ @Test
+ public void testValidateRequiredFields() {
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ DependSelector s = new DependSelector();
+ s.isSelected(selectorRule.getProject().getBaseDir(), selectorRule.getFilenames()[0], selectorRule.getFiles()[0]);
fail("DependSelector did not check for required fields");
} catch (BuildException be2) {
assertEquals("The targetdir attribute is required.",
@@ -67,103 +65,121 @@ public class DependSelectorTest extends BaseSelectorTest {
}
- /**
- * Tests to make sure that the selector is selecting files correctly.
- */
- public void testSelectionBehaviour() {
- DependSelector s;
- String results;
- File subdir;
- Mapper m;
+ @Test
+ public void testNoMapper() {
+ DependSelector s = new DependSelector();
+ s.setTargetdir(selectorRule.getBeddir());
+
+ String results = selectorRule.selectionString(s);
+ assertEquals("FFFFFFFFFFFF", results);
+ }
+
+ @Test
+ public void testIdentityMapper() {
+ DependSelector s = new DependSelector();
+ s.setTargetdir(selectorRule.getBeddir());
+
Mapper.MapperType identity = new Mapper.MapperType();
identity.setValue("identity");
- Mapper.MapperType glob = new Mapper.MapperType();
- glob.setValue("glob");
+
+ Mapper m = s.createMapper();
+ m.setType(identity);
+
+ String results = selectorRule.selectionString(s);
+ assertEquals("FFFFFFFFFFFF", results);
+ }
+
+ @Test
+ public void testMergeMapper() {
+ DependSelector s = new DependSelector();
+ s.setTargetdir(selectorRule.getBeddir());
+
Mapper.MapperType merge = new Mapper.MapperType();
merge.setValue("merge");
- try {
- makeBed();
-
- s = (DependSelector)getInstance();
- s.setTargetdir(beddir);
- results = selectionString(s);
- assertEquals("FFFFFFFFFFFF", results);
-
- s = (DependSelector)getInstance();
- s.setTargetdir(beddir);
- m = s.createMapper();
- m.setType(identity);
- results = selectionString(s);
- assertEquals("FFFFFFFFFFFF", results);
-
- s = (DependSelector)getInstance();
- s.setTargetdir(beddir);
- m = s.createMapper();
- m.setType(merge);
- m.setTo("asf-logo.gif.gz");
- results = selectionString(s);
- assertEquals("TFFFFTTTFFF", results.substring(0,11));
-
- s = (DependSelector)getInstance();
- s.setTargetdir(beddir);
- m = s.createMapper();
- m.setType(merge);
- m.setTo("asf-logo.gif.bz2");
- results = selectionString(s);
- assertEquals("TTFTTTTTTTTT", results);
-
- // Test for path relative to project base directory
- s = (DependSelector)getInstance();
- subdir = new File("selectortest/tar/bz2");
- s.setTargetdir(subdir);
- m = s.createMapper();
- m.setType(glob);
- m.setFrom("*.bz2");
- m.setTo("*.tar.bz2");
- results = selectionString(s);
- assertEquals("FFTFFFFFFTTF", results);
-
- s = (DependSelector)getInstance();
- subdir = new File(beddir,"tar/bz2");
- s.setTargetdir(subdir);
- m = s.createMapper();
- m.setType(glob);
- m.setFrom("*.bz2");
- m.setTo("*.tar.bz2");
- results = selectionString(s);
- assertEquals("FFFFFFFFFTTF", results);
-
- try {
- makeMirror();
-
- s = (DependSelector)getInstance();
- File testdir = new File(getOutputDir(), "selectortest2");
- s.setTargetdir(testdir);
- results = selectionString(s);
- assertEquals("FFFTTFFFFFFF", results);
-
- s = (DependSelector)getInstance();
- testdir = new File(getOutputDir(), "selectortest2/tar/bz2");
- s.setTargetdir(testdir);
- m = s.createMapper();
- m.setType(glob);
- m.setFrom("*.bz2");
- m.setTo("*.tar.bz2");
- results = mirrorSelectionString(s);
- assertEquals("FFFFFFFFFTTF", results);
- results = selectionString(s);
- assertEquals("FFFFFFFFFTTF", results);
- }
- finally {
- cleanupMirror();
- }
+ Mapper m = s.createMapper();
+ m.setType(merge);
+ m.setTo("asf-logo.gif.gz");
- }
- finally {
- cleanupBed();
- }
+ String results = selectorRule.selectionString(s);
+ assertEquals("TFFFFTTTFFF", results.substring(0,11));
+ }
+
+ @Test
+ public void testMergeMapper2() {
+ DependSelector s = new DependSelector();
+ s.setTargetdir(selectorRule.getBeddir());
+
+ Mapper.MapperType merge = new Mapper.MapperType();
+ merge.setValue("merge");
+
+ Mapper m = s.createMapper();
+ m.setType(merge);
+ m.setTo("asf-logo.gif.bz2");
+ String results = selectorRule.selectionString(s);
+ assertEquals("TTFTTTTTTTTT", results);
+ }
+
+ @Test
+ public void testGlobMapperRelativePath() {
+ DependSelector s = new DependSelector();
+ File subdir = new File("selectortest/tar/bz2");
+ s.setTargetdir(subdir);
+
+ Mapper.MapperType glob = new Mapper.MapperType();
+ glob.setValue("glob");
+
+ Mapper m = s.createMapper();
+ m.setType(glob);
+ m.setFrom("*.bz2");
+ m.setTo("*.tar.bz2");
+
+ String results = selectorRule.selectionString(s);
+ assertEquals("FFTFFFFFFTTF", results);
+ }
+
+ @Test
+ public void testRestrictedGlobMapper() {
+ DependSelector s = new DependSelector();
+ File subdir = new File(selectorRule.getBeddir(), "tar/bz2");
+ s.setTargetdir(subdir);
+
+ Mapper.MapperType glob = new Mapper.MapperType();
+ glob.setValue("glob");
+
+ Mapper m = s.createMapper();
+ m.setType(glob);
+ m.setFrom("*.bz2");
+ m.setTo("*.tar.bz2");
+ String results = selectorRule.selectionString(s);
+ assertEquals("FFFFFFFFFTTF", results);
+ }
+
+ @Test
+ public void testSelectionNoMapper() {
+ DependSelector s = new DependSelector();
+ s.setTargetdir(new File(selectorRule.getOutputDir(), "selectortest2"));
+ String results = selectorRule.selectionString(s);
+ assertEquals("FFFTTFFFFFFF", results);
+ }
+
+
+ @Test
+ public void testMirroredSelection() {
+ DependSelector s = new DependSelector();
+ s.setTargetdir(new File(selectorRule.getOutputDir(), "selectortest2/tar/bz2"));
+
+ Mapper.MapperType glob = new Mapper.MapperType();
+ glob.setValue("glob");
+ Mapper m = s.createMapper();
+ m.setType(glob);
+ m.setFrom("*.bz2");
+ m.setTo("*.tar.bz2");
+ String results = selectorRule.mirrorSelectionString(s);
+ assertEquals("FFFFFFFFFTTF", results);
+ results = selectorRule.selectionString(s);
+ assertEquals("FFFFFFFFFTTF", results);
}
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/DepthSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/DepthSelectorTest.java
index e180f3c2a..391fb27dd 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/DepthSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/DepthSelectorTest.java
@@ -20,43 +20,41 @@ package org.apache.tools.ant.types.selectors;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Parameter;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Tests Depth Selectors
*
*/
-public class DepthSelectorTest extends BaseSelectorTest {
+public class DepthSelectorTest {
+
+ @Rule
+ public final BaseSelectorRule selectorRule = new BaseSelectorRule();
- public DepthSelectorTest(String name) {
- super(name);
- }
-
- /**
- * Factory method from base class. This is overriden in child
- * classes to return a specific Selector class.
- */
- public BaseSelector getInstance() {
- return new DepthSelector();
- }
/**
* Test the code that validates the selector.
*/
+ @Test
public void testValidate() {
- DepthSelector s = (DepthSelector)getInstance();
+ DepthSelector s = new DepthSelector();
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DepthSelector did not check for required fields");
} catch (BuildException be1) {
assertEquals("You must set at least one of the min or the " +
"max levels.", be1.getMessage());
}
- s = (DepthSelector)getInstance();
+ s = new DepthSelector();
s.setMin(5);
s.setMax(2);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DepthSelector did not check for maximum being higher "
+ "than minimum");
} catch (BuildException be2) {
@@ -64,7 +62,7 @@ public class DepthSelectorTest extends BaseSelectorTest {
be2.getMessage());
}
- s = (DepthSelector)getInstance();
+ s = new DepthSelector();
Parameter param = new Parameter();
param.setName("garbage in");
param.setValue("garbage out");
@@ -72,34 +70,34 @@ public class DepthSelectorTest extends BaseSelectorTest {
params[0] = param;
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DepthSelector did not check for valid parameter element");
} catch (BuildException be3) {
assertEquals("Invalid parameter garbage in", be3.getMessage());
}
- s = (DepthSelector)getInstance();
+ s = new DepthSelector();
param = new Parameter();
param.setName("min");
param.setValue("garbage out");
params[0] = param;
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DepthSelector accepted bad minimum as parameter");
} catch (BuildException be4) {
assertEquals("Invalid minimum value garbage out",
be4.getMessage());
}
- s = (DepthSelector)getInstance();
+ s = new DepthSelector();
param = new Parameter();
param.setName("max");
param.setValue("garbage out");
params[0] = param;
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("DepthSelector accepted bad maximum as parameter");
} catch (BuildException be5) {
assertEquals("Invalid maximum value garbage out",
@@ -111,44 +109,38 @@ public class DepthSelectorTest extends BaseSelectorTest {
/**
* Tests to make sure that the selector is selecting files correctly.
*/
+ @Test
public void testSelectionBehaviour() {
DepthSelector s;
String results;
- try {
- makeBed();
-
- s = (DepthSelector)getInstance();
- s.setMin(20);
- s.setMax(25);
- results = selectionString(s);
- assertEquals("FFFFFFFFFFFF", results);
-
- s = (DepthSelector)getInstance();
- s.setMin(0);
- results = selectionString(s);
- assertEquals("TTTTTTTTTTTT", results);
-
- s = (DepthSelector)getInstance();
- s.setMin(1);
- results = selectionString(s);
- assertEquals("FFFFFTTTTTTT", results);
-
- s = (DepthSelector)getInstance();
- s.setMax(0);
- results = selectionString(s);
- assertEquals("TTTTTFFFFFFF", results);
-
- s = (DepthSelector)getInstance();
- s.setMin(1);
- s.setMax(1);
- results = selectionString(s);
- assertEquals("FFFFFTTTFFFT", results);
+ s = new DepthSelector();
+ s.setMin(20);
+ s.setMax(25);
+ results = selectorRule.selectionString(s);
+ assertEquals("FFFFFFFFFFFF", results);
+
+ s = new DepthSelector();
+ s.setMin(0);
+ results = selectorRule.selectionString(s);
+ assertEquals("TTTTTTTTTTTT", results);
+
+ s = new DepthSelector();
+ s.setMin(1);
+ results = selectorRule.selectionString(s);
+ assertEquals("FFFFFTTTTTTT", results);
+
+ s = new DepthSelector();
+ s.setMax(0);
+ results = selectorRule.selectionString(s);
+ assertEquals("TTTTTFFFFFFF", results);
+
+ s = new DepthSelector();
+ s.setMin(1);
+ s.setMax(1);
+ results = selectorRule.selectionString(s);
+ assertEquals("FFFFFTTTFFFT", results);
- }
- finally {
- cleanupBed();
- }
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/FilenameSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/FilenameSelectorTest.java
index 8046ce689..ce7729a87 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/FilenameSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/FilenameSelectorTest.java
@@ -20,45 +20,42 @@ package org.apache.tools.ant.types.selectors;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Parameter;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Tests Filename Selectors
*
*/
-public class FilenameSelectorTest extends BaseSelectorTest {
+public class FilenameSelectorTest {
- public FilenameSelectorTest(String name) {
- super(name);
- }
-
- /**
- * Factory method from base class. This is overriden in child
- * classes to return a specific Selector class.
- */
- public BaseSelector getInstance() {
- return new FilenameSelector();
- }
+ @Rule
+ public final BaseSelectorRule selectorRule = new BaseSelectorRule();
/**
* Test the code that validates the selector.
*/
+ @Test
public void testValidate() {
- FilenameSelector s = (FilenameSelector)getInstance();
+ FilenameSelector s = new FilenameSelector();
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("FilenameSelector did not check for required fields");
} catch (BuildException be1) {
assertEquals("The name or regex attribute is required", be1.getMessage());
}
- s = (FilenameSelector)getInstance();
+ s = new FilenameSelector();
Parameter param = new Parameter();
param.setName("garbage in");
param.setValue("garbage out");
Parameter[] params = {param};
s.setParameters(params);
try {
- s.isSelected(basedir,filenames[0],files[0]);
+ s.isSelected(selectorRule.getProject().getBaseDir(),selectorRule.getFilenames()[0],selectorRule.getFiles()[0]);
fail("FilenameSelector did not check for valid parameter element");
} catch (BuildException be2) {
assertEquals("Invalid parameter garbage in", be2.getMessage());
@@ -69,21 +66,20 @@ public class FilenameSelectorTest extends BaseSelectorTest {
/**
* Tests to make sure that the selector is selecting files correctly.
*/
+ @Test
public void testSelectionBehaviour() {
FilenameSelector s;
String results;
- try {
- makeBed();
- s = (FilenameSelector)getInstance();
+ s = new FilenameSelector();
s.setName("no match possible");
- results = selectionString(s);
+ results = selectorRule.selectionString(s);
assertEquals("FFFFFFFFFFFF", results);
- s = (FilenameSelector)getInstance();
+ s = new FilenameSelector();
s.setName("*.gz");
- results = selectionString(s);
+ results = selectorRule.selectionString(s);
// This is turned off temporarily. There appears to be a bug
// in SelectorUtils.matchPattern() where it is recursive on
// Windows even if no ** is in pattern.
@@ -91,31 +87,28 @@ public class FilenameSelectorTest extends BaseSelectorTest {
// vs
//assertEquals("FFFTFFFFTFFF", results); // Windows
- s = (FilenameSelector)getInstance();
+ s = new FilenameSelector();
s.setName("**/*.gz");
s.setNegate(true);
- results = selectionString(s);
+ results = selectorRule.selectionString(s);
assertEquals("TTTFTTTFFTTT", results);
- s = (FilenameSelector)getInstance();
+ s = new FilenameSelector();
s.setName("**/*.GZ");
s.setCasesensitive(false);
- results = selectionString(s);
+ results = selectorRule.selectionString(s);
assertEquals("FFFTFFFTTFFF", results);
- s = (FilenameSelector)getInstance();
+ s = new FilenameSelector();
Parameter param1 = new Parameter();
param1.setName("name");
param1.setValue("**/*.bz2");
Parameter[] params = {param1};
s.setParameters(params);
- results = selectionString(s);
+ results = selectorRule.selectionString(s);
assertEquals("FFTFFFFFFTTF", results);
- }
- finally {
- cleanupBed();
- }
+
}
diff --git a/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java b/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java
index 0ea3b06ed..80dd6dfa8 100644
--- a/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java
+++ b/src/tests/junit/org/apache/tools/ant/types/selectors/ModifiedSelectorTest.java
@@ -25,7 +25,9 @@ import java.text.RuleBasedCollator;
import java.util.Comparator;
import java.util.Iterator;
+import org.apache.tools.ant.AntAssert;
import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.Task;
@@ -40,6 +42,17 @@ import org.apache.tools.ant.types.selectors.modifiedselector.HashvalueAlgorithm;
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector;
import org.apache.tools.ant.types.selectors.modifiedselector.PropertiesfileCache;
import org.apache.tools.ant.util.FileUtils;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
/**
@@ -47,7 +60,10 @@ import org.apache.tools.ant.util.FileUtils;
*
* @since Ant 1.6
*/
-public class ModifiedSelectorTest extends BaseSelectorTest {
+public class ModifiedSelectorTest {
+
+ @Rule
+ public final BaseSelectorRule selectorRule = new BaseSelectorRule();
/** Utilities used for file operations */
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
@@ -59,51 +75,24 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
private Path testclasses = null;
- // ===================== constructors, factories =====================
-
-
- public ModifiedSelectorTest(String name) {
- super(name);
- }
-
-
- /**
- * Factory method from base class. This should be overriden in child
- * classes to return a specific Selector class (like here).
- */
- public BaseSelector getInstance() {
- return new ModifiedSelector();
- }
// ===================== JUnit stuff =====================
+ @Before
public void setUp() {
- // project reference is set in super.setUp()
- super.setUp();
// init the testclasses path object
- Project prj = getProject();
- if (prj != null) {
- testclasses = new Path(prj, prj.getProperty("build.tests.value"));
- }
- }
-
-
- /* * /
- // for test only - ignore tests where we arent work at the moment
- public static junit.framework.Test suite() {
- junit.framework.TestSuite suite= new junit.framework.TestSuite();
- suite.addTest(new ModifiedSelectorTest("testValidateWrongCache"));
- return suite;
+ Project prj = selectorRule.getProject();
+ testclasses = new Path(prj, prj.getProperty("build.tests.value"));
}
- /* */
// ======= testcases for the attributes and nested elements of the selector =====
/** Test right use of cache names. */
+ @Test
public void testValidateWrongCache() {
String name = "this-is-not-a-valid-cache-name";
try {
@@ -118,6 +107,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
/** Test right use of cache names. */
+ @Test
public void testValidateWrongAlgorithm() {
String name = "this-is-not-a-valid-algorithm-name";
try {
@@ -133,6 +123,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
/** Test right use of comparator names. */
+ @Test
public void testValidateWrongComparator() {
String name = "this-is-not-a-valid-comparator-name";
try {
@@ -147,12 +138,12 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
+ @Test
public void testIllegalCustomAlgorithm() {
try {
getAlgoName("java.lang.Object");
fail("Illegal classname used.");
- } catch (Exception e) {
- assertTrue("Wrong exception type: " + e.getClass().getName(), e instanceof BuildException);
+ } catch (BuildException e) {
assertEquals("Wrong exception message.",
"Specified class (java.lang.Object) is not an Algorithm.",
e.getMessage());
@@ -161,16 +152,12 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
+ @Test
public void testNonExistentCustomAlgorithm() {
- boolean noExcThrown = false;
- try {
+ try {
getAlgoName("non.existent.custom.Algorithm");
- noExcThrown = true;
- } catch (Exception e) {
- if (noExcThrown) {
- fail("does 'non.existent.custom.Algorithm' really exist?");
- }
- assertTrue("Wrong exception type: " + e.getClass().getName(), e instanceof BuildException);
+ fail("does 'non.existent.custom.Algorithm' really exist?");
+ } catch (BuildException e) {
assertEquals("Wrong exception message.",
"Specified class (non.existent.custom.Algorithm) not found.",
e.getMessage());
@@ -178,23 +165,22 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
}
-
+ @Test
public void testCustomAlgorithm() {
String algo = getAlgoName("org.apache.tools.ant.types.selectors.modifiedselector.HashvalueAlgorithm");
assertTrue("Wrong algorithm used: "+algo, algo.startsWith("HashvalueAlgorithm"));
}
-
+ @Test
public void testCustomAlgorithm2() {
String algo = getAlgoName("org.apache.tools.ant.types.selectors.MockAlgorithm");
assertTrue("Wrong algorithm used: "+algo, algo.startsWith("MockAlgorithm"));
}
+ @Test
public void testCustomClasses() {
- if (getProject().getProperty("ant.home") == null) {
- return;
- }
+ Assume.assumeNotNull("Ant home not set", selectorRule.getProject().getProperty("ant.home") );
BFT bft = new BFT();
bft.setUp();
try {
@@ -220,16 +206,19 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
+ @Test
public void testDelayUpdateTaskFinished() {
doDelayUpdateTest(1);
}
+ @Test
public void testDelayUpdateTargetFinished() {
doDelayUpdateTest(2);
}
+ @Test
public void testDelayUpdateBuildFinished() {
doDelayUpdateTest(3);
}
@@ -290,7 +279,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
*/
private String getAlgoName(String classname) {
ModifiedSelector sel = new ModifiedSelector();
- sel.setProject(getProject());
+ sel.setProject(selectorRule.getProject());
// add the test classes to its classpath
sel.addClasspath(testclasses);
sel.setAlgorithmClass(classname);
@@ -316,6 +305,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
* Propertycache must have a set 'cachefile' attribute.
* The default in ModifiedSelector "cache.properties" is set by the selector.
*/
+ @Test
public void testPropcacheInvalid() {
Cache cache = new PropertiesfileCache();
if (cache.isValid())
@@ -323,6 +313,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
+ @Test
public void testPropertyfileCache() {
PropertiesfileCache cache = new PropertiesfileCache();
File cachefile = new File("cache.properties");
@@ -333,8 +324,9 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
/** Checks whether a cache file is created. */
+ @Test
public void testCreatePropertiesCacheDirect() {
- File cachefile = new File(basedir, "cachefile.properties");
+ File cachefile = new File(selectorRule.getProject().getBaseDir(), "cachefile.properties");
PropertiesfileCache cache = new PropertiesfileCache();
cache.setCachefile(cachefile);
@@ -350,32 +342,27 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
/** Checks whether a cache file is created. */
+ @Test
public void testCreatePropertiesCacheViaModifiedSelector() {
- File cachefile = new File(basedir, "cachefile.properties");
- try {
-
- // initialize test environment (called "bed")
- makeBed();
+ File cachefile = new File(selectorRule.getProject().getBaseDir(), "cachefile.properties");
+
+ // Configure the selector
+ ModifiedSelector s = new ModifiedSelector();
+ s.setDelayUpdate(false);
+ s.addParam("cache.cachefile", cachefile);
- // Configure the selector
- ModifiedSelector s = (ModifiedSelector)getSelector();
- s.setDelayUpdate(false);
- s.addParam("cache.cachefile", cachefile);
-
- ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName();
- cacheName.setValue("propertyfile");
- s.setCache(cacheName);
+ ModifiedSelector.CacheName cacheName = new ModifiedSelector.CacheName();
+ cacheName.setValue("propertyfile");
+ s.setCache(cacheName);
- s.setUpdate(true);
+ s.setUpdate(true);
- selectionString(s);
+ selectorRule.selectionString(s);
- // evaluate correctness
- assertTrue("Cache file is not created.", cachefile.exists());
- } finally {
- cleanupBed();
- if (cachefile!=null) cachefile.delete();
- }
+ // evaluate correctness
+ assertTrue("Cache file is not created.", cachefile.exists());
+ cachefile.delete();
+
}
@@ -390,32 +377,30 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
* the cache's configuration parameters. That results in the reorganized
* configure() method of ModifiedSelector. This testcase tests that.
*/
+ @Test
public void testCreatePropertiesCacheViaCustomSelector() {
File cachefile = FILE_UTILS.createTempFile("tmp-cache-", ".properties", null, false, false);
- try {
- // initialize test environment (called "bed")
- makeBed();
- // Configure the selector
+ // Configure the selector
- ExtendSelector s = new ExtendSelector();
- s.setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector");
- s.addParam(createParam("update", "true"));
- s.addParam(createParam("cache.cachefile", cachefile.getAbsolutePath()));
- s.addParam(createParam("cache", "propertyfile"));
+ ExtendSelector s = new ExtendSelector();
+ s.setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector");
+ s.addParam(createParam("update", "true"));
+ s.addParam(createParam("cache.cachefile", cachefile.getAbsolutePath()));
+ s.addParam(createParam("cache", "propertyfile"));
- selectionString(s);
+ selectorRule.selectionString(s);
+
+ // evaluate correctness
+ assertTrue("Cache file is not created.", cachefile.exists());
+ cachefile.delete();
- // evaluate correctness
- assertTrue("Cache file is not created.", cachefile.exists());
- } finally {
- cleanupBed();
- if (cachefile!=null) cachefile.delete();
- }
}
- public void _testCustomCache() {
+ @Test
+ @Ignore("same logic as on algorithm, no testcases created")
+ public void testCustomCache() {
// same logic as on algorithm, no testcases created
}
@@ -467,12 +452,14 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
// ============== testcases for the algorithm implementations ==============
+ @Test
public void testHashvalueAlgorithm() {
HashvalueAlgorithm algo = new HashvalueAlgorithm();
doTest(algo);
}
+ @Test
public void testDigestAlgorithmMD5() {
DigestAlgorithm algo = new DigestAlgorithm();
algo.setAlgorithm("MD5");
@@ -480,6 +467,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
+ @Test
public void testDigestAlgorithmSHA() {
DigestAlgorithm algo = new DigestAlgorithm();
algo.setAlgorithm("SHA");
@@ -487,12 +475,14 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
+ @Test
public void testChecksumAlgorithm() {
ChecksumAlgorithm algo = new ChecksumAlgorithm();
doTest(algo);
}
+ @Test
public void testChecksumAlgorithmCRC() {
ChecksumAlgorithm algo = new ChecksumAlgorithm();
algo.setAlgorithm("CRC");
@@ -500,6 +490,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
}
+ @Test
public void testChecksumAlgorithmAdler() {
ChecksumAlgorithm algo = new ChecksumAlgorithm();
algo.setAlgorithm("Adler");
@@ -516,35 +507,30 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
* @param algo configured test object
*/
protected void doTest(Algorithm algo) {
- assertTrue("Algorithm not proper configured.", algo.isValid());
- try {
- makeBed();
-
- for (int i=0; i try third time --> should select only the file with modified
* content
*/
+ @Test
public void testScenario1() {
BFT bft = null;
ModifiedSelector s = null;
try {
- //
- // ***** initialize test environment (called "bed") *****
- //
- makeBed();
- String results = null;
+
+ String results;
// Configure the selector - only defaults are used
- s = (ModifiedSelector)getSelector();
+ s = new ModifiedSelector();
//
// ***** First Run *****
@@ -735,7 +728,7 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
// ***** Third Run *****
// third call should get only those files, which CONTENT changed
// (no timestamp changes required!)
- results = selectionString(s);
+ results = selectorRule.selectionString(s);
//
// ***** Check the result *****
@@ -745,12 +738,12 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
// as (F)alse. Directories are always selected so they always are
// (T)rue.
StringBuffer expected = new StringBuffer();
- for (int i=0; iComparator: java.text.RuleBasedCollator
* Update: true
*/
- public void _testScenario2() { // RuleBasedCollator not yet supported - see Selector:375 note
+ @Test
+ @Ignore("RuleBasedCollator not yet supported - see Selector:375 note")
+ public void testScenario2() {
ExtendSelector s = new ExtendSelector();
BFT bft = new BFT();
String cachefile = System.getProperty("java.io.tmpdir")+"/mycache.txt";
try {
- makeBed();
s.setClassname("org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector");
@@ -809,13 +802,13 @@ public class ModifiedSelectorTest extends BaseSelectorTest {
bft.writeProperties("f4name="+f4name);
bft.doTarget("modifiedselectortest-makeDirty");
// third run
- String results = selectionString(s);
+ String results = selectorRule.selectionString(s);
StringBuffer expected = new StringBuffer();
- for (int i=0; i length2) ? length2 : length1;
+ StringBuffer sb = new StringBuffer();
+ for (int i=0; i filelist.length())
+ ? filelist.length()
+ : selectorRule.getFilenames().length;
+ for (int i=0; i", w.encodedata("]>"));
assertEquals("]]", w.encodedata("]]"));
@@ -132,6 +137,7 @@ public class DOMElementWriterTest extends TestCase {
w.encodedata("A]]>B]]>C"));
}
+ @Test
public void testNoAdditionalWhiteSpaceForText() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElement("root");
@@ -147,6 +153,7 @@ public class DOMElementWriterTest extends TestCase {
sw.toString());
}
+ @Test
public void testNoAdditionalWhiteSpaceForCDATA() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElement("root");
@@ -162,6 +169,7 @@ public class DOMElementWriterTest extends TestCase {
sw.toString());
}
+ @Test
public void testNoAdditionalWhiteSpaceForEmptyElement() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElement("root");
@@ -178,6 +186,7 @@ public class DOMElementWriterTest extends TestCase {
sw.toString());
}
+ @Test
public void testNoNSPrefixByDefault() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElementNS("urn:foo", "root");
@@ -190,6 +199,7 @@ public class DOMElementWriterTest extends TestCase {
+ StringUtils.LINE_SEP, sw.toString());
}
+ @Test
public void testNSOnElement() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElementNS("urn:foo", "root");
@@ -205,6 +215,7 @@ public class DOMElementWriterTest extends TestCase {
+ StringUtils.LINE_SEP, sw.toString());
}
+ @Test
public void testNSPrefixOnAttribute() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElementNS("urn:foo", "root");
@@ -221,6 +232,7 @@ public class DOMElementWriterTest extends TestCase {
+ StringUtils.LINE_SEP, sw.toString());
}
+ @Test
public void testNSPrefixOnAttributeEvenWithoutElement() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElementNS("urn:foo", "root");
@@ -237,6 +249,7 @@ public class DOMElementWriterTest extends TestCase {
+ StringUtils.LINE_SEP, sw.toString());
}
+ @Test
public void testNSGetsReused() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElementNS("urn:foo", "root");
@@ -256,6 +269,7 @@ public class DOMElementWriterTest extends TestCase {
+ StringUtils.LINE_SEP, sw.toString());
}
+ @Test
public void testNSGoesOutOfScope() throws IOException {
Document d = DOMUtils.newDocument();
Element root = d.createElementNS("urn:foo", "root");
diff --git a/src/tests/junit/org/apache/tools/ant/util/DateUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/DateUtilsTest.java
index 95c7a474f..4f5aa844d 100644
--- a/src/tests/junit/org/apache/tools/ant/util/DateUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/DateUtilsTest.java
@@ -20,17 +20,18 @@ package org.apache.tools.ant.util;
import java.util.Calendar;
import java.util.TimeZone;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* TestCase for DateUtils.
*
*/
-public class DateUtilsTest extends TestCase {
- public DateUtilsTest(String s) {
- super(s);
- }
+public class DateUtilsTest {
+
+ @Test
public void testElapsedTime(){
String text = DateUtils.formatElapsedTime(50*1000);
assertEquals("50 seconds", text);
@@ -43,6 +44,7 @@ public class DateUtilsTest extends TestCase {
}
// https://issues.apache.org/bugzilla/show_bug.cgi?id=44659
+ @Test
public void testLongElapsedTime(){
assertEquals("2926 minutes 13 seconds",
DateUtils.formatElapsedTime(1000 * 175573));
@@ -50,6 +52,7 @@ public class DateUtilsTest extends TestCase {
DateUtils.formatElapsedTime(Long.MAX_VALUE));
}
+ @Test
public void testDateTimeISO(){
TimeZone timeZone = TimeZone.getTimeZone("GMT+1");
Calendar cal = Calendar.getInstance(timeZone);
@@ -59,6 +62,7 @@ public class DateUtilsTest extends TestCase {
assertEquals("2002-02-23T09:11:12", text);
}
+ @Test
public void testDateISO(){
TimeZone timeZone = TimeZone.getTimeZone("GMT");
Calendar cal = Calendar.getInstance(timeZone);
@@ -68,6 +72,7 @@ public class DateUtilsTest extends TestCase {
assertEquals("2002-02-23", text);
}
+ @Test
public void testTimeISODate(){
// make sure that elapsed time in set via date works
TimeZone timeZone = TimeZone.getTimeZone("GMT+1");
@@ -78,6 +83,7 @@ public class DateUtilsTest extends TestCase {
assertEquals("20:11:12", text);
}
+ @Test
public void testTimeISO(){
// make sure that elapsed time in ms works
long ms = (20*3600 + 11*60 + 12)*1000;
@@ -86,6 +92,7 @@ public class DateUtilsTest extends TestCase {
assertEquals("20:11:12", text);
}
+ @Test
public void testPhaseOfMoon() {
TimeZone timeZone = TimeZone.getTimeZone("GMT");
Calendar cal = Calendar.getInstance(timeZone);
diff --git a/src/tests/junit/org/apache/tools/ant/util/DeweyDecimalTest.java b/src/tests/junit/org/apache/tools/ant/util/DeweyDecimalTest.java
index 56ca1ac9f..bcda609bd 100644
--- a/src/tests/junit/org/apache/tools/ant/util/DeweyDecimalTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/DeweyDecimalTest.java
@@ -18,7 +18,9 @@
package org.apache.tools.ant.util;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import org.junit.Test;
@SuppressWarnings("ResultOfObjectAllocationIgnored")
diff --git a/src/tests/junit/org/apache/tools/ant/util/FileUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/FileUtilsTest.java
index 153081ff4..d0361cc57 100644
--- a/src/tests/junit/org/apache/tools/ant/util/FileUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/FileUtilsTest.java
@@ -22,30 +22,36 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.condition.Os;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
/**
* Tests for org.apache.tools.ant.util.FileUtils.
*
*/
-public class FileUtilsTest extends TestCase {
+public class FileUtilsTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
private File removeThis;
private String root;
- public FileUtilsTest(String name) {
- super(name);
- }
+ @Before
public void setUp() {
// Windows adds the drive letter in uppercase, unless you run Cygwin
root = new File(File.separator).getAbsolutePath().toUpperCase();
}
+ @After
public void tearDown() {
if (removeThis != null && removeThis.exists()) {
if (!removeThis.delete())
@@ -65,24 +71,16 @@ public class FileUtilsTest extends TestCase {
* @see FileUtils#setFileLastModified(java.io.File, long)
* @throws IOException
*/
+ @Test
public void testSetLastModified() throws IOException {
removeThis = new File("dummy");
FileOutputStream fos = new FileOutputStream(removeThis);
fos.write(new byte[0]);
fos.close();
+ assumeTrue("Could not change file modified time", removeThis.setLastModified(removeThis.lastModified() - 2000));
long modTime = removeThis.lastModified();
assertTrue(modTime != 0);
- /*
- * Sleep for some time to make sure a touched file would get a
- * more recent timestamp according to the file system's
- * granularity (should be > 2s to account for Windows FAT).
- */
- try {
- Thread.sleep(5000);
- } catch (InterruptedException ie) {
- fail(ie.getMessage());
- }
FILE_UTILS.setFileLastModified(removeThis, -1);
long secondModTime = removeThis.lastModified();
@@ -104,6 +102,7 @@ public class FileUtilsTest extends TestCase {
assertTrue(thirdModTime != secondModTime);
}
+ @Test
public void testResolveFile() {
if (!(Os.isFamily("dos") || Os.isFamily("netware"))) {
/*
@@ -203,6 +202,7 @@ public class FileUtilsTest extends TestCase {
}
+ @Test
public void testNormalize() {
if (!(Os.isFamily("dos") || Os.isFamily("netware"))) {
/*
@@ -324,6 +324,7 @@ public class FileUtilsTest extends TestCase {
/**
* Test handling of null arguments.
*/
+ @Test
public void testNullArgs() {
try {
FILE_UTILS.normalize(null);
@@ -340,6 +341,7 @@ public class FileUtilsTest extends TestCase {
/**
* Test createTempFile
*/
+ @Test
public void testCreateTempFile()
{
// null parent dir
@@ -391,6 +393,7 @@ public class FileUtilsTest extends TestCase {
/**
* Test contentEquals
*/
+ @Test
public void testContentEquals() throws IOException {
assertTrue("Non existing files", FILE_UTILS.contentEquals(new File(System.getProperty("root"), "foo"),
new File(System.getProperty("root"), "bar")));
@@ -409,6 +412,7 @@ public class FileUtilsTest extends TestCase {
/**
* Test createNewFile
*/
+ @Test
public void testCreateNewFile() throws IOException {
removeThis = new File("dummy");
assertTrue(!removeThis.exists());
@@ -419,6 +423,7 @@ public class FileUtilsTest extends TestCase {
/**
* Test removeLeadingPath.
*/
+ @Test
public void testRemoveLeadingPath() {
assertEquals("bar", FILE_UTILS.removeLeadingPath(new File("/foo"),
new File("/foo/bar")));
@@ -465,8 +470,9 @@ public class FileUtilsTest extends TestCase {
/**
* test toUri
*/
+ @Test
public void testToURI() {
- String dosRoot = null;
+ String dosRoot;
if (Os.isFamily("dos") || Os.isFamily("netware")) {
dosRoot = System.getProperty("user.dir")
.substring(0, 3).replace(File.separatorChar, '/');
@@ -513,17 +519,19 @@ public class FileUtilsTest extends TestCase {
}
}
+ @Test
public void testIsContextRelativePath() {
- if (Os.isFamily("dos")) {
- assertTrue(FileUtils.isContextRelativePath("/\u00E4nt"));
- assertTrue(FileUtils.isContextRelativePath("\\foo"));
- }
+ assumeTrue("Test only runs on DOS", Os.isFamily("dos"));
+ assertTrue(FileUtils.isContextRelativePath("/\u00E4nt"));
+ assertTrue(FileUtils.isContextRelativePath("\\foo"));
}
+
/**
* test fromUri
*/
+ @Test
public void testFromURI() {
- String dosRoot = null;
+ String dosRoot;
if (Os.isFamily("dos") || Os.isFamily("netware")) {
dosRoot = System.getProperty("user.dir").substring(0, 2);
} else {
@@ -542,6 +550,7 @@ public class FileUtilsTest extends TestCase {
assertEquals(dosRoot + File.separator + "foo#bar", FILE_UTILS.fromURI("file:///foo%23bar"));
}
+ @Test
public void testModificationTests() {
//get a time
@@ -564,6 +573,7 @@ public class FileUtilsTest extends TestCase {
!FILE_UTILS.isUpToDate(firstTime,-1L));
}
+ @Test
public void testHasErrorInCase() {
File tempFolder = new File(System.getProperty("java.io.tmpdir"));
File wellcased = FILE_UTILS.createTempFile("alpha", "beta", tempFolder,
@@ -603,8 +613,8 @@ public class FileUtilsTest extends TestCase {
private void assertEqualsIgnoreDriveCase(String s1, String s2) {
if ((Os.isFamily("dos") || Os.isFamily("netware"))
&& s1.length() > 0 && s2.length() > 0) {
- StringBuffer sb1 = new StringBuffer(s1);
- StringBuffer sb2 = new StringBuffer(s2);
+ StringBuilder sb1 = new StringBuilder(s1);
+ StringBuilder sb2 = new StringBuilder(s2);
sb1.setCharAt(0, Character.toUpperCase(s1.charAt(0)));
sb2.setCharAt(0, Character.toUpperCase(s2.charAt(0)));
assertEquals(sb1.toString(), sb2.toString());
diff --git a/src/tests/junit/org/apache/tools/ant/util/GlobPatternMapperTest.java b/src/tests/junit/org/apache/tools/ant/util/GlobPatternMapperTest.java
index bca05b2e3..5bd7db606 100644
--- a/src/tests/junit/org/apache/tools/ant/util/GlobPatternMapperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/GlobPatternMapperTest.java
@@ -18,18 +18,19 @@
package org.apache.tools.ant.util;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
/**
* Tests for org.apache.tools.ant.util;GlobPatternMapper.
*
*/
-public class GlobPatternMapperTest extends TestCase {
-
- public GlobPatternMapperTest(String name) {
- super(name);
- }
+public class GlobPatternMapperTest {
+ @Test
public void testNoPatternAtAll() {
GlobPatternMapper m = new GlobPatternMapper();
m.setFrom("foobar");
@@ -41,6 +42,7 @@ public class GlobPatternMapperTest extends TestCase {
assertEquals("baz", result[0]);
}
+ @Test
public void testPostfixOnly() {
GlobPatternMapper m = new GlobPatternMapper();
m.setFrom("*foo");
@@ -57,6 +59,7 @@ public class GlobPatternMapperTest extends TestCase {
assertEquals("foobar.", result[0]);
}
+ @Test
public void testPrefixOnly() {
GlobPatternMapper m = new GlobPatternMapper();
m.setFrom("foo*");
@@ -73,6 +76,7 @@ public class GlobPatternMapperTest extends TestCase {
assertEquals(".barfoo", result[0]);
}
+ @Test
public void testPreAndPostfix() {
GlobPatternMapper m = new GlobPatternMapper();
m.setFrom("foo*bar");
diff --git a/src/tests/junit/org/apache/tools/ant/util/JAXPUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/JAXPUtilsTest.java
index e5a3b7f57..105c33d1d 100644
--- a/src/tests/junit/org/apache/tools/ant/util/JAXPUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/JAXPUtilsTest.java
@@ -17,18 +17,18 @@
*/
package org.apache.tools.ant.util;
-import junit.framework.TestCase;
+import org.junit.Test;
import java.io.File;
+import static org.junit.Assert.assertTrue;
+
/**
* JAXPUtils test case
*/
-public class JAXPUtilsTest extends TestCase {
- public JAXPUtilsTest(String name){
- super(name);
- }
+public class JAXPUtilsTest {
+ @Test
public void testGetSystemId(){
File file = null;
if ( File.separatorChar == '\\' ){
diff --git a/src/tests/junit/org/apache/tools/ant/util/JavaEnvUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/JavaEnvUtilsTest.java
index 9dd64e14b..21017cccb 100644
--- a/src/tests/junit/org/apache/tools/ant/util/JavaEnvUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/JavaEnvUtilsTest.java
@@ -20,113 +20,116 @@ package org.apache.tools.ant.util;
import java.io.File;
import junit.framework.AssertionFailedError;
-import junit.framework.TestCase;
import org.apache.tools.ant.taskdefs.condition.Os;
+import org.junit.Assume;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/**
* TestCase for JavaEnvUtils.
*
*/
-public class JavaEnvUtilsTest extends TestCase {
+public class JavaEnvUtilsTest {
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
- public JavaEnvUtilsTest(String s) {
- super(s);
- }
+ @Test
public void testGetExecutableNetware() {
- if (Os.isName("netware")) {
- assertEquals("java", JavaEnvUtils.getJreExecutable("java"));
- assertEquals("javac", JavaEnvUtils.getJdkExecutable("javac"));
- assertEquals("foo", JavaEnvUtils.getJreExecutable("foo"));
- assertEquals("foo", JavaEnvUtils.getJdkExecutable("foo"));
- }
+ Assume.assumeTrue("Test only runs on netware", Os.isName("netware"));
+ assertEquals("java", JavaEnvUtils.getJreExecutable("java"));
+ assertEquals("javac", JavaEnvUtils.getJdkExecutable("javac"));
+ assertEquals("foo", JavaEnvUtils.getJreExecutable("foo"));
+ assertEquals("foo", JavaEnvUtils.getJdkExecutable("foo"));
}
+ @Test
public void testGetExecutableWindows() {
- if (Os.isFamily("windows")) {
- String javaHome =
- FILE_UTILS.normalize(System.getProperty("java.home"))
- .getAbsolutePath();
-
- String j = JavaEnvUtils.getJreExecutable("java");
- assertTrue(j.endsWith(".exe"));
- assertTrue(j+" is absolute", (new File(j)).isAbsolute());
- try {
- assertTrue(j+" is normalized and in the JRE dir",
- j.startsWith(javaHome));
- } catch (AssertionFailedError e) {
- // java.home is bogus
- assertEquals("java.exe", j);
- }
-
- j = JavaEnvUtils.getJdkExecutable("javac");
- assertTrue(j.endsWith(".exe"));
- try {
- assertTrue(j+" is absolute", (new File(j)).isAbsolute());
- String javaHomeParent =
- FILE_UTILS.normalize(javaHome+"/..").getAbsolutePath();
- assertTrue(j+" is normalized and in the JDK dir",
- j.startsWith(javaHomeParent));
- assertTrue(j+" is normalized and not in the JRE dir",
- !j.startsWith(javaHome));
-
- } catch (AssertionFailedError e) {
- // java.home is bogus
- assertEquals("javac.exe", j);
- }
-
- assertEquals("foo.exe", JavaEnvUtils.getJreExecutable("foo"));
- assertEquals("foo.exe", JavaEnvUtils.getJdkExecutable("foo"));
- }
- }
-
- public void testGetExecutableMostPlatforms() {
- if (!Os.isName("netware") && !Os.isFamily("windows")) {
- String javaHome =
- FILE_UTILS.normalize(System.getProperty("java.home"))
- .getAbsolutePath();
-
- // could still be OS/2
- String extension = Os.isFamily("dos") ? ".exe" : "";
-
- String j = JavaEnvUtils.getJreExecutable("java");
- if (!extension.equals("")) {
- assertTrue(j.endsWith(extension));
- }
- assertTrue(j+" is absolute", (new File(j)).isAbsolute());
+ Assume.assumeTrue("Test only runs on windows", Os.isFamily("windows"));
+ String javaHome =
+ FILE_UTILS.normalize(System.getProperty("java.home"))
+ .getAbsolutePath();
+
+ String j = JavaEnvUtils.getJreExecutable("java");
+ assertTrue(j.endsWith(".exe"));
+ assertTrue(j+" is absolute", (new File(j)).isAbsolute());
+ try {
assertTrue(j+" is normalized and in the JRE dir",
j.startsWith(javaHome));
+ } catch (AssertionFailedError e) {
+ // java.home is bogus
+ assertEquals("java.exe", j);
+ }
- j = JavaEnvUtils.getJdkExecutable("javac");
- if (!extension.equals("")) {
- assertTrue(j.endsWith(extension));
- }
+ j = JavaEnvUtils.getJdkExecutable("javac");
+ assertTrue(j.endsWith(".exe"));
+ try {
assertTrue(j+" is absolute", (new File(j)).isAbsolute());
-
String javaHomeParent =
FILE_UTILS.normalize(javaHome+"/..").getAbsolutePath();
assertTrue(j+" is normalized and in the JDK dir",
j.startsWith(javaHomeParent));
+ assertTrue(j+" is normalized and not in the JRE dir",
+ !j.startsWith(javaHome));
- if (Os.isFamily("mac") && JavaEnvUtils.getJavaVersionNumber() <= JavaEnvUtils.VERSION_1_6) {
- assertTrue(j+" is normalized and in the JRE dir",
- j.startsWith(javaHome));
- } else {
- assertTrue(j+" is normalized and not in the JRE dir",
- !j.startsWith(javaHome));
- }
-
- assertEquals("foo"+extension,
- JavaEnvUtils.getJreExecutable("foo"));
- assertEquals("foo"+extension,
- JavaEnvUtils.getJdkExecutable("foo"));
+ } catch (AssertionFailedError e) {
+ // java.home is bogus
+ assertEquals("javac.exe", j);
+ }
+
+ assertEquals("foo.exe", JavaEnvUtils.getJreExecutable("foo"));
+ assertEquals("foo.exe", JavaEnvUtils.getJdkExecutable("foo"));
+ }
+
+ @Test
+ public void testGetExecutableMostPlatforms() {
+ Assume.assumeTrue("Test only runs on non Netware and non Windows systems",
+ !Os.isName("netware") && !Os.isFamily("windows"));
+ String javaHome =
+ FILE_UTILS.normalize(System.getProperty("java.home"))
+ .getAbsolutePath();
+
+ // could still be OS/2
+ String extension = Os.isFamily("dos") ? ".exe" : "";
+
+ String j = JavaEnvUtils.getJreExecutable("java");
+ if (!extension.equals("")) {
+ assertTrue(j.endsWith(extension));
+ }
+ assertTrue(j+" is absolute", (new File(j)).isAbsolute());
+ assertTrue(j+" is normalized and in the JRE dir",
+ j.startsWith(javaHome));
+
+ j = JavaEnvUtils.getJdkExecutable("javac");
+ if (!extension.equals("")) {
+ assertTrue(j.endsWith(extension));
+ }
+ assertTrue(j+" is absolute", (new File(j)).isAbsolute());
+
+ String javaHomeParent =
+ FILE_UTILS.normalize(javaHome+"/..").getAbsolutePath();
+ assertTrue(j+" is normalized and in the JDK dir",
+ j.startsWith(javaHomeParent));
+
+ if (Os.isFamily("mac") && JavaEnvUtils.getJavaVersionNumber() <= JavaEnvUtils.VERSION_1_6) {
+ assertTrue(j+" is normalized and in the JRE dir",
+ j.startsWith(javaHome));
+ } else {
+ assertTrue(j+" is normalized and not in the JRE dir",
+ !j.startsWith(javaHome));
}
+ assertEquals("foo"+extension,
+ JavaEnvUtils.getJreExecutable("foo"));
+ assertEquals("foo"+extension,
+ JavaEnvUtils.getJdkExecutable("foo"));
}
+ @Test
public void testIsAtLeastJavaVersion()
{
assertTrue(
diff --git a/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java b/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java
index ad48a0612..89cd3daaa 100644
--- a/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/LayoutPreservingPropertiesTest.java
@@ -24,18 +24,19 @@ import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Properties;
-import junit.framework.TestCase;
+import org.junit.Test;
-public class LayoutPreservingPropertiesTest extends TestCase {
- public LayoutPreservingPropertiesTest(String s) {
- super(s);
- }
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class LayoutPreservingPropertiesTest {
/**
* Tests that a properties file read by the
* LayoutPreservingPropertiesFile and then saves the properties in
* it.
*/
+ @Test
public void testPreserve() throws Exception {
File simple = new File(System.getProperty("root"),
"src/etc/testcases/util/simple.properties");
@@ -66,6 +67,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
* Tests that names and value are properly escaped when being
* written out.
*/
+ @Test
public void testEscaping() throws Exception {
LayoutPreservingProperties lpf = new LayoutPreservingProperties();
@@ -104,6 +106,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
* an existing property, it updates the logical line, and it doesn't
* append a new one.
*/
+ @Test
public void testOverwrite() throws Exception {
File unusual = new File(System.getProperty("root"),
"src/etc/testcases/util/unusual.properties");
@@ -131,6 +134,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
assertTrue(s.indexOf("prop\\nthree=new three") > -1);
}
+ @Test
public void testStoreWithHeader() throws Exception {
File simple = new File(System.getProperty("root"),
"src/etc/testcases/util/simple.properties");
@@ -150,6 +154,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
assertTrue("should have had header ", s.startsWith("#file-header"));
}
+ @Test
public void testClear() throws Exception {
File simple = new File(System.getProperty("root"),
"src/etc/testcases/util/simple.properties");
@@ -181,6 +186,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
s.indexOf("# now a line wrapping one") == -1);
}
+ @Test
public void testRemove() throws Exception {
File simple = new File(System.getProperty("root"),
"src/etc/testcases/util/simple.properties");
@@ -203,6 +209,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
s.indexOf("! more comment") > -1);
}
+ @Test
public void testRemoveWithComment() throws Exception {
File simple = new File(System.getProperty("root"),
"src/etc/testcases/util/simple.properties");
@@ -227,6 +234,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
s.indexOf("! more comment") == -1);
}
+ @Test
public void testClone() throws Exception {
File simple = new File(System.getProperty("root"),
"src/etc/testcases/util/simple.properties");
@@ -263,6 +271,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
assertTrue("should have had prop.new", s2.indexOf("prop.new") > -1);
}
+ @Test
public void testPreserveEscapeName() throws Exception {
LayoutPreservingProperties lpf = new LayoutPreservingProperties();
File unusual = new File(System.getProperty("root"),
@@ -296,7 +305,7 @@ public class LayoutPreservingPropertiesTest extends TestCase {
assertTrue(s.indexOf("beta set with a space") == -1);
}
- private String readFile(File f) throws IOException {
+ private static String readFile(File f) throws IOException {
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis);
String s = FileUtils.readFully(isr);
diff --git a/src/tests/junit/org/apache/tools/ant/util/LazyFileOutputStreamTest.java b/src/tests/junit/org/apache/tools/ant/util/LazyFileOutputStreamTest.java
index 394669ebe..82c363407 100644
--- a/src/tests/junit/org/apache/tools/ant/util/LazyFileOutputStreamTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/LazyFileOutputStreamTest.java
@@ -19,23 +19,25 @@ package org.apache.tools.ant.util;
import java.io.File;
import java.io.IOException;
-import junit.framework.TestCase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertTrue;
/**
* @since Ant 1.6
*/
-public class LazyFileOutputStreamTest extends TestCase {
+public class LazyFileOutputStreamTest {
private LazyFileOutputStream los;
private final static File f = new File("test.txt");
- public LazyFileOutputStreamTest(String s) {
- super(s);
- }
-
+ @Before
public void setUp() {
los = new LazyFileOutputStream(f);
}
+ @After
public void tearDown() throws IOException {
try {
los.close();
@@ -44,23 +46,27 @@ public class LazyFileOutputStreamTest extends TestCase {
}
}
+ @Test
public void testNoFileWithoutWrite() throws IOException {
los.close();
assertTrue(f + " has not been written.", !f.exists());
}
+ @Test
public void testOpen() throws IOException {
los.open();
los.close();
assertTrue(f + " has been written.", f.exists());
}
+ @Test
public void testSingleByte() throws IOException {
los.write(0);
los.close();
assertTrue(f + " has been written.", f.exists());
}
+ @Test
public void testByteArray() throws IOException {
los.write(new byte[] {0});
los.close();
diff --git a/src/tests/junit/org/apache/tools/ant/util/LineOrientedOutputStreamTest.java b/src/tests/junit/org/apache/tools/ant/util/LineOrientedOutputStreamTest.java
index b4fad70ea..1fa23e849 100644
--- a/src/tests/junit/org/apache/tools/ant/util/LineOrientedOutputStreamTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/LineOrientedOutputStreamTest.java
@@ -19,54 +19,62 @@
package org.apache.tools.ant.util;
import java.io.IOException;
-import junit.framework.TestCase;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
-/**
- */
-public class LineOrientedOutputStreamTest extends TestCase {
+public class LineOrientedOutputStreamTest {
private static String LINE = "This is a line";
private DummyStream stream;
- public LineOrientedOutputStreamTest(String name) {
- super(name);
- }
-
+
+ @Before
public void setUp() {
stream = new DummyStream();
}
+ @After
public void tearDown() throws IOException {
if (stream != null) {
stream.close();
}
}
+ @Test
public void testLineWithLinefeedArray() throws IOException {
writeByteArray();
writeAsArray('\n');
stream.assertInvoked();
}
+ @Test
public void testLineWithLinefeedSingleBytes() throws IOException {
writeSingleBytes();
stream.write('\n');
stream.assertInvoked();
}
+ @Test
public void testLineWithCariagereturnArray() throws IOException {
writeByteArray();
writeAsArray('\r');
stream.assertInvoked();
}
+ @Test
public void testLineWithCariagereturnSingleBytes() throws IOException {
writeSingleBytes();
stream.write('\r');
stream.assertInvoked();
}
+ @Test
public void testLineWithCariagereturnLinefeedArray() throws IOException {
writeByteArray();
writeAsArray('\r');
@@ -74,6 +82,7 @@ public class LineOrientedOutputStreamTest extends TestCase {
stream.assertInvoked();
}
+ @Test
public void testLineWithCariagereturnLinefeedSingleBytes() throws IOException {
writeSingleBytes();
stream.write('\r');
@@ -81,18 +90,21 @@ public class LineOrientedOutputStreamTest extends TestCase {
stream.assertInvoked();
}
+ @Test
public void testFlushArray() throws IOException {
writeByteArray();
stream.flush();
stream.assertNotInvoked();
}
+ @Test
public void testFlushSingleBytes() throws IOException {
writeSingleBytes();
stream.flush();
stream.assertNotInvoked();
}
+ @Test
public void testCloseArray() throws IOException {
writeByteArray();
stream.close();
@@ -100,6 +112,7 @@ public class LineOrientedOutputStreamTest extends TestCase {
stream = null;
}
+ @Test
public void testCloseSingleBytes() throws IOException {
writeSingleBytes();
stream.close();
@@ -134,7 +147,7 @@ public class LineOrientedOutputStreamTest extends TestCase {
assertTrue("At least one line", invoked);
}
private void assertNotInvoked() {
- assertTrue("No output", invoked==false);
+ assertTrue("No output", !invoked);
}
}
}// LineOrientedOutputStreamTest
diff --git a/src/tests/junit/org/apache/tools/ant/util/LinkedHashtableTest.java b/src/tests/junit/org/apache/tools/ant/util/LinkedHashtableTest.java
index f8c77a91e..bfd2cda7d 100644
--- a/src/tests/junit/org/apache/tools/ant/util/LinkedHashtableTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/LinkedHashtableTest.java
@@ -21,9 +21,16 @@ package org.apache.tools.ant.util;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
-import junit.framework.TestCase;
-public class LinkedHashtableTest extends TestCase {
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertEquals;
+
+public class LinkedHashtableTest {
private static final Object K1 = new Object();
private static final Object K2 = new Object();
@@ -44,6 +51,7 @@ public class LinkedHashtableTest extends TestCase {
assertTrue(h2.containsKey(K1));
}
+ @Test
public void testContainsAndPut() {
h.put(K1, V1);
assertTrue(h.contains(K1));
@@ -52,23 +60,27 @@ public class LinkedHashtableTest extends TestCase {
assertFalse(h.containsKey(K2));
}
+ @Test
public void testGet() {
assertNull(h.get(K1));
h.put(K1, V1);
assertSame(V1, h.get(K1));
}
+ @Test
public void testIsEmpty() {
assertTrue(h.isEmpty());
h.put(K1, V1);
assertFalse(h.isEmpty());
}
+ @Test
public void testPutReturnValue() {
assertNull(h.put(K1, V1));
assertSame(V1, h.put(K1, V2));
}
+ @Test
public void testPutAll() {
LinkedHashtable h2 = new LinkedHashtable();
h.put(K1, V1);
@@ -76,6 +88,7 @@ public class LinkedHashtableTest extends TestCase {
assertTrue(h2.containsKey(K1));
}
+ @Test
public void testRemove() {
h.put(K1, V1);
assertSame(V1, h.remove(K1));
@@ -83,32 +96,38 @@ public class LinkedHashtableTest extends TestCase {
assertNull(h.remove(K1));
}
+ @Test
public void testSize() {
assertEquals(0, h.size());
h.put(K1, V1);
assertEquals(1, h.size());
}
+ @Test
public void testKeys() {
multiSetup();
assertKeys(CollectionUtils.asIterator(h.keys()));
}
+ @Test
public void testKeySet() {
multiSetup();
assertKeys(h.keySet().iterator());
}
+ @Test
public void testElements() {
multiSetup();
assertValues(CollectionUtils.asIterator(h.elements()));
}
+ @Test
public void testValues() {
multiSetup();
assertValues(h.values().iterator());
}
+ @Test
public void testEntrySet() {
multiSetup();
Iterator i = h.entrySet().iterator();
diff --git a/src/tests/junit/org/apache/tools/ant/util/LoaderUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/LoaderUtilsTest.java
index 49518ea3d..9935edd67 100644
--- a/src/tests/junit/org/apache/tools/ant/util/LoaderUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/LoaderUtilsTest.java
@@ -18,17 +18,17 @@
package org.apache.tools.ant.util;
import java.io.File;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertEquals;
/**
* @since Ant 1.6
*/
-public class LoaderUtilsTest extends TestCase {
-
- public LoaderUtilsTest(String name) {
- super(name);
- }
+public class LoaderUtilsTest {
+ @Test
public void testGetXyzSource() {
File f1 = LoaderUtils.getClassSource(LoaderUtils.class);
assertNotNull(f1);
diff --git a/src/tests/junit/org/apache/tools/ant/util/PackageNameMapperTest.java b/src/tests/junit/org/apache/tools/ant/util/PackageNameMapperTest.java
index f6c859f17..fdf739315 100644
--- a/src/tests/junit/org/apache/tools/ant/util/PackageNameMapperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/PackageNameMapperTest.java
@@ -17,12 +17,15 @@
*/
package org.apache.tools.ant.util;
+import org.junit.Test;
+
import java.io.File;
-import junit.framework.TestCase;
-public class PackageNameMapperTest extends TestCase {
- public PackageNameMapperTest(String name) { super(name); }
+import static org.junit.Assert.assertEquals;
+
+public class PackageNameMapperTest {
+ @Test
public void testMapping() {
PackageNameMapper mapper = new PackageNameMapper();
mapper.setFrom("*.java");
diff --git a/src/tests/junit/org/apache/tools/ant/util/ReaderInputStreamTest.java b/src/tests/junit/org/apache/tools/ant/util/ReaderInputStreamTest.java
index ed3d81fef..bd07251e3 100644
--- a/src/tests/junit/org/apache/tools/ant/util/ReaderInputStreamTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/ReaderInputStreamTest.java
@@ -17,26 +17,33 @@
*/
package org.apache.tools.ant.util;
-import java.io.*;
+import org.junit.Test;
-import junit.framework.TestCase;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
/**
* Test for ReaderInputStream
*/
-public class ReaderInputStreamTest extends TestCase {
- public ReaderInputStreamTest(String s) {
- super(s);
- }
+public class ReaderInputStreamTest {
+ @Test
public void testSimple() throws Exception {
compareBytes("abc", "utf-8");
}
+ @Test
public void testSimple16() throws Exception {
compareBytes("a", "utf-16");
}
+ @Test
public void testSimpleAbc16() throws Exception {
// THIS WILL FAIL.
//compareBytes("abc", "utf-16");
@@ -53,10 +60,10 @@ public class ReaderInputStreamTest extends TestCase {
}
bytes = "abc".getBytes("utf-16");
// String n = new String(bytes, 0, pos, "utf-16");
- String n = new String(bytes, 0, bytes.length, "utf-16");
- System.out.println(n);
+ new String(bytes, 0, bytes.length, "utf-16");
}
+ @Test
public void testReadZero() throws Exception {
ReaderInputStream r = new ReaderInputStream(
new StringReader("abc"));
@@ -69,11 +76,13 @@ public class ReaderInputStreamTest extends TestCase {
assertEquals("abc".getBytes().length, readin);
}
+ @Test
public void testPreample() throws Exception {
byte[] bytes = "".getBytes("utf-16");
System.out.println("Preample len is " + bytes.length);
}
-
+
+ @Test
public void testIso88591ToUtf8() throws Exception {
InputStreamReader fin = null;
ReaderInputStream r = null;
diff --git a/src/tests/junit/org/apache/tools/ant/util/ResourceUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/ResourceUtilsTest.java
index 072718c44..96cc9cbfc 100644
--- a/src/tests/junit/org/apache/tools/ant/util/ResourceUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/ResourceUtilsTest.java
@@ -18,26 +18,28 @@
package org.apache.tools.ant.util;
-import junit.framework.TestCase;
-
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Echo;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceFactory;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
/**
* Tests for org.apache.tools.ant.util.ResourceUtils.
*/
-public class ResourceUtilsTest extends TestCase
- implements ResourceFactory, FileNameMapper {
+public class ResourceUtilsTest implements ResourceFactory, FileNameMapper {
private Echo taskINeedForLogging = new Echo();
- public ResourceUtilsTest(String name) {
- super(name);
+ @Before
+ public void setUp() {
taskINeedForLogging.setProject(new Project());
}
+ @Test
public void testNoDuplicates() {
Resource r = new Resource("samual vimes", true, 1, false);
Resource[] toNew =
diff --git a/src/tests/junit/org/apache/tools/ant/util/StringUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/StringUtilsTest.java
index 52e089862..53ef1b299 100644
--- a/src/tests/junit/org/apache/tools/ant/util/StringUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/StringUtilsTest.java
@@ -19,16 +19,18 @@ package org.apache.tools.ant.util;
import java.util.Vector;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
/**
* Test for StringUtils
*/
-public class StringUtilsTest extends TestCase {
- public StringUtilsTest(String s) {
- super(s);
- }
+public class StringUtilsTest {
+ @Test
public void testSplit(){
final String data = "a,b,,";
Vector res = StringUtils.split(data, ',');
@@ -39,6 +41,7 @@ public class StringUtilsTest extends TestCase {
assertEquals("", res.elementAt(3));
}
+ @Test
public void testSplitLines(){
final String data = "a\r\nb\nc\nd\ne";
Vector res = StringUtils.lineSplit(data);
@@ -50,40 +53,49 @@ public class StringUtilsTest extends TestCase {
assertEquals("e", res.elementAt(4));
}
+ @Test
public void testReplace() {
final String data = "abcabcabca";
String res = StringUtils.replace(data, "a", "");
assertEquals("bcbcbc", res);
}
+ @Test
public void testEndsWithBothEmpty() {
assertTrue( StringUtils.endsWith( new StringBuffer(), "") );
}
+ @Test
public void testEndsWithEmptyString() {
assertTrue( StringUtils.endsWith( new StringBuffer("12234545"), "") );
}
+ @Test
public void testEndsWithShorterString() {
assertTrue( StringUtils.endsWith( new StringBuffer("12345678"), "78"));
}
+ @Test
public void testEndsWithSameString() {
assertTrue( StringUtils.endsWith( new StringBuffer("123"), "123"));
}
+ @Test
public void testEndsWithLongerString() {
assertFalse( StringUtils.endsWith( new StringBuffer("12"), "1245"));
}
+ @Test
public void testEndsWithNoMatch() {
assertFalse( StringUtils.endsWith( new StringBuffer("12345678"), "789"));
}
+ @Test
public void testEndsWithEmptyBuffer() {
assertFalse( StringUtils.endsWith( new StringBuffer(""), "12345667") );
}
+ @Test
public void testEndsWithJDKPerf() {
StringBuffer buf = getFilledBuffer(1024*300, 'a');
for (int i = 0; i < 1000; i++) {
@@ -91,6 +103,7 @@ public class StringUtilsTest extends TestCase {
}
}
+ @Test
public void testEndsWithPerf() {
StringBuffer buf = getFilledBuffer(1024*300, 'a');
for (int i = 0; i < 1000; i++) {
@@ -103,7 +116,8 @@ public class StringUtilsTest extends TestCase {
for (int i = 0; i < size; i++) { buf.append(ch); };
return buf;
}
-
+
+ @Test
public void testParseHumanSizes() throws Exception {
final long KILOBYTE = 1024;
final long MEGABYTE = KILOBYTE * 1024;
@@ -117,7 +131,8 @@ public class StringUtilsTest extends TestCase {
assertEquals(StringUtils.parseHumanSizes("1P"), PETABYTE);
assertEquals(StringUtils.parseHumanSizes("1"), 1L);
}
-
+
+ @Test
public void testRemoveSuffix() {
String prefix = "Prefix";
String name = "Name";
@@ -134,7 +149,8 @@ public class StringUtilsTest extends TestCase {
StringUtils.removeSuffix(input, "bla")
);
}
-
+
+ @Test
public void testRemovePrefix() {
String prefix = "Prefix";
String name = "Name";
diff --git a/src/tests/junit/org/apache/tools/ant/util/SymlinkUtilsTest.java b/src/tests/junit/org/apache/tools/ant/util/SymlinkUtilsTest.java
index 243c1f9ef..d1de1b1a7 100644
--- a/src/tests/junit/org/apache/tools/ant/util/SymlinkUtilsTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/SymlinkUtilsTest.java
@@ -18,19 +18,22 @@
package org.apache.tools.ant.util;
+import static org.junit.Assert.assertFalse;
+
import java.io.IOException;
-import junit.framework.TestCase;
+
import org.apache.tools.ant.taskdefs.condition.Os;
+import org.junit.Assume;
+import org.junit.Test;
-public class SymlinkUtilsTest extends TestCase {
+public class SymlinkUtilsTest {
private static final SymbolicLinkUtils SYMLINK_UTILS =
SymbolicLinkUtils.getSymbolicLinkUtils();
+ @Test
public void testRootIsNoSymlink() throws IOException {
- if (Os.isFamily("windows")) {
- return; // test is meaningless on Windows
- }
+ Assume.assumeFalse("Symlink doesn't work on Windows", Os.isFamily("windows"));
assertFalse(SYMLINK_UTILS.isSymbolicLink("/"));
}
diff --git a/src/tests/junit/org/apache/tools/ant/util/UnPackageNameMapperTest.java b/src/tests/junit/org/apache/tools/ant/util/UnPackageNameMapperTest.java
index c78e1d351..7586950d5 100644
--- a/src/tests/junit/org/apache/tools/ant/util/UnPackageNameMapperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/UnPackageNameMapperTest.java
@@ -18,11 +18,13 @@
package org.apache.tools.ant.util;
import java.io.File;
-import junit.framework.TestCase;
+import org.junit.Test;
-public class UnPackageNameMapperTest extends TestCase {
- public UnPackageNameMapperTest(String name) { super(name); }
+import static org.junit.Assert.assertEquals;
+public class UnPackageNameMapperTest {
+
+ @Test
public void testMapping() {
UnPackageNameMapper mapper = new UnPackageNameMapper();
mapper.setFrom("TEST-*.xml");
diff --git a/src/tests/junit/org/apache/tools/ant/util/UnicodeUtilTest.java b/src/tests/junit/org/apache/tools/ant/util/UnicodeUtilTest.java
index 261b28d1e..cb526deba 100644
--- a/src/tests/junit/org/apache/tools/ant/util/UnicodeUtilTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/UnicodeUtilTest.java
@@ -17,10 +17,13 @@
*/
package org.apache.tools.ant.util;
-import junit.framework.TestCase;
+import org.junit.Test;
-public class UnicodeUtilTest extends TestCase {
+import static org.junit.Assert.assertEquals;
+public class UnicodeUtilTest {
+
+ @Test
public void testChineseWord() {
String word = "\u81ea\u7531";
assertEquals("u81ea", UnicodeUtil.EscapeUnicode(word.charAt(0)).toString());
diff --git a/src/tests/junit/org/apache/tools/ant/util/VectorSetTest.java b/src/tests/junit/org/apache/tools/ant/util/VectorSetTest.java
index cebf86a70..11491e3ac 100644
--- a/src/tests/junit/org/apache/tools/ant/util/VectorSetTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/VectorSetTest.java
@@ -21,47 +21,60 @@ package org.apache.tools.ant.util;
import java.util.ArrayList;
import java.util.Arrays;
-import junit.framework.TestCase;
+import org.junit.Test;
-public class VectorSetTest extends TestCase {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+public class VectorSetTest {
private static final Object O = new Object();
private VectorSet v = new VectorSet();
+ @Test
public void testAdd() {
assertTrue(v.add(O));
assertFalse(v.add(O));
assertEquals(1, v.size());
}
+ @Test
public void testAdd2() {
v.add(0, O);
v.add(1, O);
assertEquals(1, v.size());
}
+ @Test
public void testAddElement() {
v.addElement(O);
v.addElement(O);
assertEquals(1, v.size());
}
+ @Test
public void testAddAll() {
assertTrue(v.addAll(Arrays.asList(new Object[] {O, O})));
assertEquals(1, v.size());
}
+ @Test
public void testAddAll2() {
assertTrue(v.addAll(0, Arrays.asList(new Object[] {O, O})));
assertEquals(1, v.size());
}
+ @Test
public void testClear() {
v.add(O);
v.clear();
assertEquals(0, v.size());
}
-
+
+ @Test
public void testClone() {
v.add(O);
Object o = v.clone();
@@ -71,6 +84,7 @@ public class VectorSetTest extends TestCase {
assertTrue(vs.contains(O));
}
+ @Test
public void testContains() {
assertFalse(v.contains(O));
v.add(O);
@@ -78,6 +92,7 @@ public class VectorSetTest extends TestCase {
assertFalse(v.contains(null));
}
+ @Test
public void testContainsAll() {
assertFalse(v.containsAll(Arrays.asList(new Object[] {O, O})));
v.add(O);
@@ -85,12 +100,14 @@ public class VectorSetTest extends TestCase {
assertFalse(v.containsAll(Arrays.asList(new Object[] {O, null})));
}
+ @Test
public void testInsertElementAt() {
v.insertElementAt(O, 0);
v.insertElementAt(O, 1);
assertEquals(1, v.size());
}
+ @Test
public void testRemoveIndex() {
v.add(O);
assertSame(O, v.remove(0));
@@ -99,10 +116,12 @@ public class VectorSetTest extends TestCase {
v.remove(0);
fail("expected an AIOBE");
} catch (ArrayIndexOutOfBoundsException e) {
+ //TODO assert exception values
// expected
}
}
+ @Test
public void testRemoveObject() {
v.add(O);
assertTrue(v.remove(O));
@@ -110,6 +129,7 @@ public class VectorSetTest extends TestCase {
assertFalse(v.remove(O));
}
+ @Test
public void testRemoveAtEndWhenSizeEqualsCapacity() {
v = new VectorSet(3, 1);
Object a = new Object();
@@ -126,6 +146,7 @@ public class VectorSetTest extends TestCase {
assertSame(b, v.elementAt(1));
}
+ @Test
public void testRemoveAtFrontWhenSizeEqualsCapacity() {
v = new VectorSet(3, 1);
v.add(O);
@@ -142,6 +163,7 @@ public class VectorSetTest extends TestCase {
assertSame(b, v.elementAt(1));
}
+ @Test
public void testRemoveInMiddleWhenSizeEqualsCapacity() {
v = new VectorSet(3, 1);
Object a = new Object();
@@ -158,6 +180,7 @@ public class VectorSetTest extends TestCase {
assertSame(b, v.elementAt(1));
}
+ @Test
public void testRemoveAll() {
v.add(O);
assertTrue(v.removeAll(Arrays.asList(new Object[] {O, O})));
@@ -165,12 +188,14 @@ public class VectorSetTest extends TestCase {
assertFalse(v.removeAll(Arrays.asList(new Object[] {O, O})));
}
+ @Test
public void testRemoveAllElements() {
v.add(O);
v.removeAllElements();
assertEquals(0, v.size());
}
-
+
+ @Test
public void testRemoveElement() {
v.add(O);
assertTrue(v.removeElement(O));
@@ -178,6 +203,7 @@ public class VectorSetTest extends TestCase {
assertFalse(v.removeElement(O));
}
+ @Test
public void testRemoveElementAt() {
v.add(O);
v.removeElementAt(0);
@@ -186,10 +212,12 @@ public class VectorSetTest extends TestCase {
v.removeElementAt(0);
fail("expected an AIOBE");
} catch (ArrayIndexOutOfBoundsException e) {
+ //TODO assert exception values
// expected
}
}
+ @Test
public void testRemoveRange() {
Object a = new Object();
Object b = new Object();
@@ -201,6 +229,7 @@ public class VectorSetTest extends TestCase {
assertTrue(v.contains(c));
}
+ @Test
public void testRetainAll() {
Object a = new Object();
Object b = new Object();
@@ -214,6 +243,7 @@ public class VectorSetTest extends TestCase {
assertEquals(0, v.indexOf(O));
}
+ @Test
public void testRetainAllReturnValueAndEmptiness() {
v.add(1);
v.add(2);
@@ -227,6 +257,7 @@ public class VectorSetTest extends TestCase {
assertFalse(v.retainAll(Arrays.asList(4, 5)));
}
+ @Test
public void testSet() {
v.add(O);
Object a = new Object();
@@ -235,6 +266,7 @@ public class VectorSetTest extends TestCase {
assertEquals(1, v.size());
}
+ @Test
public void testSetElementAt() {
v.add(O);
Object a = new Object();
@@ -243,6 +275,7 @@ public class VectorSetTest extends TestCase {
assertEquals(1, v.size());
}
+ @Test
public void testRetainAllSpeed() {
int size = 50000;
for (int i = 0; i < size; i++) {
@@ -255,10 +288,7 @@ public class VectorSetTest extends TestCase {
list.add(i);
v.add(i);
}
- long start = System.currentTimeMillis();
assertTrue(v.retainAll(list));
- long stop = System.currentTimeMillis();
- System.out.println("testRetainAllSpeed: " + (stop - start) + "msec");
assertEquals(v.toString(), size + 4, v.size());
}
diff --git a/src/tests/junit/org/apache/tools/ant/util/XMLFragmentTest.java b/src/tests/junit/org/apache/tools/ant/util/XMLFragmentTest.java
index f139d605a..0ac938f04 100644
--- a/src/tests/junit/org/apache/tools/ant/util/XMLFragmentTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/XMLFragmentTest.java
@@ -18,23 +18,31 @@
package org.apache.tools.ant.util;
-import org.apache.tools.ant.BuildFileTest;
+import org.apache.tools.ant.BuildFileRule;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
-public class XMLFragmentTest extends BuildFileTest {
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
- public XMLFragmentTest(String name) {
- super(name);
- }
+public class XMLFragmentTest {
+
+ @Rule
+ public BuildFileRule buildRule = new BuildFileRule();
+ @Before
public void setUp() {
- configureProject("src/etc/testcases/types/xmlfragment.xml");
+ buildRule.configureProject("src/etc/testcases/types/xmlfragment.xml");
}
+ @Test
public void testNestedText() {
- XMLFragment x = (XMLFragment) getProject().getReference("nested-text");
+ XMLFragment x = (XMLFragment) buildRule.getProject().getReference("nested-text");
assertNotNull(x);
Node n = x.getFragment();
assertTrue("No attributes", !n.hasAttributes());
@@ -44,9 +52,10 @@ public class XMLFragmentTest extends BuildFileTest {
assertEquals("foo", nl.item(0).getNodeValue());
}
+ @Test
public void testNestedChildren() {
XMLFragment x =
- (XMLFragment) getProject().getReference("with-children");
+ (XMLFragment) buildRule.getProject().getReference("with-children");
assertNotNull(x);
Node n = x.getFragment();
assertTrue("No attributes", !n.hasAttributes());
diff --git a/src/tests/junit/org/apache/tools/ant/util/facade/FacadeTaskHelperTest.java b/src/tests/junit/org/apache/tools/ant/util/facade/FacadeTaskHelperTest.java
index f80b4d9af..df2d43b30 100644
--- a/src/tests/junit/org/apache/tools/ant/util/facade/FacadeTaskHelperTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/facade/FacadeTaskHelperTest.java
@@ -18,17 +18,17 @@
package org.apache.tools.ant.util.facade;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
/**
* @since Ant 1.5
*/
-public class FacadeTaskHelperTest extends TestCase {
-
- public FacadeTaskHelperTest(String name) {
- super(name);
- }
+public class FacadeTaskHelperTest {
+ @Test
public void testPrecedenceRules() {
FacadeTaskHelper fth = new FacadeTaskHelper("foo");
assertEquals("foo", fth.getImplementation());
@@ -48,6 +48,7 @@ public class FacadeTaskHelperTest extends TestCase {
assertEquals("baz", fth.getImplementation());
}
+ @Test
public void testHasBeenSet() {
FacadeTaskHelper fth = new FacadeTaskHelper("foo");
assertTrue("nothing set", !fth.hasBeenSet());
diff --git a/src/tests/junit/org/apache/tools/ant/util/facade/ImplementationSpecificArgumentTest.java b/src/tests/junit/org/apache/tools/ant/util/facade/ImplementationSpecificArgumentTest.java
index e4e7a2ae5..a1b97d1d3 100644
--- a/src/tests/junit/org/apache/tools/ant/util/facade/ImplementationSpecificArgumentTest.java
+++ b/src/tests/junit/org/apache/tools/ant/util/facade/ImplementationSpecificArgumentTest.java
@@ -18,17 +18,17 @@
package org.apache.tools.ant.util.facade;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
/**
* @since Ant 1.5
*/
-public class ImplementationSpecificArgumentTest extends TestCase {
-
- public ImplementationSpecificArgumentTest(String name) {
- super(name);
- }
+public class ImplementationSpecificArgumentTest {
+ @Test
public void testDependsOnImplementation() {
ImplementationSpecificArgument ia =
new ImplementationSpecificArgument();
diff --git a/src/tests/junit/org/apache/tools/bzip2/CBZip2StreamTest.java b/src/tests/junit/org/apache/tools/bzip2/CBZip2StreamTest.java
index 5e26c2205..50e0e576b 100644
--- a/src/tests/junit/org/apache/tools/bzip2/CBZip2StreamTest.java
+++ b/src/tests/junit/org/apache/tools/bzip2/CBZip2StreamTest.java
@@ -21,19 +21,24 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-import junit.framework.TestCase;
+import org.junit.Test;
-public class CBZip2StreamTest extends TestCase {
+import static org.junit.Assert.fail;
+public class CBZip2StreamTest {
+
+ @Test
public void testNullPointer() throws IOException {
try {
- CBZip2InputStream cb = new CBZip2InputStream(new ByteArrayInputStream(new byte[0]));
+ new CBZip2InputStream(new ByteArrayInputStream(new byte[0]));
fail("expected an exception");
} catch (IOException e) {
// expected
+ //TODO assert exception values
}
}
-
+
+ @Test
public void testDivisionByZero() throws IOException {
CBZip2OutputStream cb = new CBZip2OutputStream(new ByteArrayOutputStream());
cb.close();
diff --git a/src/tests/junit/org/apache/tools/mail/MailMessageTest.java b/src/tests/junit/org/apache/tools/mail/MailMessageTest.java
index a8e75308f..87e2f754d 100644
--- a/src/tests/junit/org/apache/tools/mail/MailMessageTest.java
+++ b/src/tests/junit/org/apache/tools/mail/MailMessageTest.java
@@ -26,31 +26,32 @@ import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.InetAddress;
-import java.net.Socket;
import java.net.ServerSocket;
+import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
-import org.apache.tools.mail.MailMessage;
+import org.apache.tools.ant.BuildException;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.internal.AssumptionViolatedException;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
/**
- * JUnit 3 testcases for org.apache.tools.mail.MailMessage.
+ * JUnit testcases for org.apache.tools.mail.MailMessage.
*
* @since Ant 1.6
*/
-public class MailMessageTest extends TestCase {
+public class MailMessageTest {
// 27224 = magic (a random port which is unlikely to be in use)
private static int TEST_PORT = 27224;
private String local = null;
- public MailMessageTest(String name) {
- super(name);
- }
-
+ @Before
public void setUp() {
try {
local = InetAddress.getLocalHost().getHostName();
@@ -64,8 +65,10 @@ public class MailMessageTest extends TestCase {
* If this testcase takes >90s to complete, it is very likely that
* the two threads are blocked waiting for each other and Thread.join()
* timed out.
+ * @throws InterruptedException
*/
- public void testAPIExample() {
+ @Test
+ public void testAPIExample() throws InterruptedException {
ServerThread testMailServer = new ServerThread();
Thread server = new Thread(testMailServer);
@@ -85,12 +88,8 @@ public class MailMessageTest extends TestCase {
Thread client = new Thread(testMailClient);
client.start();
- try {
- server.join(60 * 1000); // 60s
- client.join(30 * 1000); // a further 30s
- } catch (InterruptedException ie ) {
- fail( "InterruptedException: " + ie );
- }
+ server.join(60 * 1000); // 60s
+ client.join(30 * 1000); // a further 30s
String result = testMailServer.getResult();
String expectedResult = "220 test SMTP EmailTaskTest\r\n" +
@@ -121,7 +120,7 @@ public class MailMessageTest extends TestCase {
"250\r\n" +
"QUIT\r\n" +
"221\r\n";
- for (int icounter = 0; icounterCOMPRESS-94.
*/
+ @Test
public void testNotEquals() {
ZipEntry entry1 = new ZipEntry("foo");
ZipEntry entry2 = new ZipEntry("bar");
diff --git a/src/tests/junit/org/apache/tools/zip/ZipLongTest.java b/src/tests/junit/org/apache/tools/zip/ZipLongTest.java
index 1b729900d..a7ece044e 100644
--- a/src/tests/junit/org/apache/tools/zip/ZipLongTest.java
+++ b/src/tests/junit/org/apache/tools/zip/ZipLongTest.java
@@ -18,21 +18,22 @@
package org.apache.tools.zip;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertTrue;
/**
- * JUnit 3 testcases for org.apache.tools.zip.ZipLong.
+ * JUnit testcases for org.apache.tools.zip.ZipLong.
*
*/
-public class ZipLongTest extends TestCase {
-
- public ZipLongTest(String name) {
- super(name);
- }
+public class ZipLongTest {
/**
* Test conversion to bytes.
*/
+ @Test
public void testToBytes() {
ZipLong zl = new ZipLong(0x12345678);
byte[] result = zl.getBytes();
@@ -46,6 +47,7 @@ public class ZipLongTest extends TestCase {
/**
* Test conversion from bytes.
*/
+ @Test
public void testFromBytes() {
byte[] val = new byte[] {0x78, 0x56, 0x34, 0x12};
ZipLong zl = new ZipLong(val);
@@ -55,6 +57,7 @@ public class ZipLongTest extends TestCase {
/**
* Test the contract of the equals method.
*/
+ @Test
public void testEquals() {
ZipLong zl = new ZipLong(0x12345678);
ZipLong zl2 = new ZipLong(0x12345678);
@@ -74,11 +77,13 @@ public class ZipLongTest extends TestCase {
/**
* Test sign handling.
*/
+ @Test
public void testSign() {
ZipLong zl = new ZipLong(new byte[] {(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF});
assertEquals(0x00000000FFFFFFFFl, zl.getValue());
}
+ @Test
public void testClone() {
ZipLong s1 = new ZipLong(42);
ZipLong s2 = (ZipLong) s1.clone();
diff --git a/src/tests/junit/org/apache/tools/zip/ZipOutputStreamTest.java b/src/tests/junit/org/apache/tools/zip/ZipOutputStreamTest.java
index 19b7c0591..a69db6c18 100644
--- a/src/tests/junit/org/apache/tools/zip/ZipOutputStreamTest.java
+++ b/src/tests/junit/org/apache/tools/zip/ZipOutputStreamTest.java
@@ -18,24 +18,21 @@
package org.apache.tools.zip;
+import org.junit.Before;
+import org.junit.Test;
+
import java.util.Calendar;
import java.util.Date;
-import junit.framework.TestCase;
+import static org.junit.Assert.assertEquals;
-public class ZipOutputStreamTest extends TestCase {
+public class ZipOutputStreamTest {
private Date time;
private ZipLong zl;
-
- /**
- * Constructor
- */
- public ZipOutputStreamTest(String name) {
- super(name);
- }
-
- protected void setUp() throws Exception {
+
+ @Before
+ public void setUp() throws Exception {
time = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(time);
@@ -56,15 +53,14 @@ public class ZipOutputStreamTest extends TestCase {
zl = new ZipLong(result);
}
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
+
+ @Test
public void testZipLong() throws Exception {
ZipLong test = ZipOutputStream.toDosTime(time);
assertEquals(test.getValue(), zl.getValue());
}
+ @Test
public void testAdjustToLong() {
assertEquals((long) Integer.MAX_VALUE,
ZipOutputStream.adjustToLong(Integer.MAX_VALUE));
diff --git a/src/tests/junit/org/apache/tools/zip/ZipShortTest.java b/src/tests/junit/org/apache/tools/zip/ZipShortTest.java
index aff065dfc..a6aa3e78b 100644
--- a/src/tests/junit/org/apache/tools/zip/ZipShortTest.java
+++ b/src/tests/junit/org/apache/tools/zip/ZipShortTest.java
@@ -18,21 +18,22 @@
package org.apache.tools.zip;
-import junit.framework.TestCase;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertTrue;
/**
* JUnit 3 testcases for org.apache.tools.zip.ZipShort.
*
*/
-public class ZipShortTest extends TestCase {
-
- public ZipShortTest(String name) {
- super(name);
- }
+public class ZipShortTest {
/**
* Test conversion to bytes.
*/
+ @Test
public void testToBytes() {
ZipShort zs = new ZipShort(0x1234);
byte[] result = zs.getBytes();
@@ -44,6 +45,7 @@ public class ZipShortTest extends TestCase {
/**
* Test conversion from bytes.
*/
+ @Test
public void testFromBytes() {
byte[] val = new byte[] {0x34, 0x12};
ZipShort zs = new ZipShort(val);
@@ -53,6 +55,7 @@ public class ZipShortTest extends TestCase {
/**
* Test the contract of the equals method.
*/
+ @Test
public void testEquals() {
ZipShort zs = new ZipShort(0x1234);
ZipShort zs2 = new ZipShort(0x1234);
@@ -72,11 +75,13 @@ public class ZipShortTest extends TestCase {
/**
* Test sign handling.
*/
+ @Test
public void testSign() {
ZipShort zs = new ZipShort(new byte[] {(byte)0xFF, (byte)0xFF});
assertEquals(0x0000FFFF, zs.getValue());
}
+ @Test
public void testClone() {
ZipShort s1 = new ZipShort(42);
ZipShort s2 = (ZipShort) s1.clone();
diff --git a/src/tests/junit/org/example/junit/Timeout.java b/src/tests/junit/org/example/junit/Timeout.java
index e19d37197..6a42ee758 100644
--- a/src/tests/junit/org/example/junit/Timeout.java
+++ b/src/tests/junit/org/example/junit/Timeout.java
@@ -17,12 +17,15 @@
*/
package org.example.junit;
-import junit.framework.TestCase;
+import org.junit.After;
+import org.junit.Test;
-public class Timeout extends TestCase {
+public class Timeout {
+ @Test
public void testTimeout() throws InterruptedException {
Thread.sleep(5000);
}
+ @After
public void tearDown() {
System.out.println("tearDown called on Timeout");
}
diff --git a/src/tests/junit/org/example/junit/XmlParserTest.java b/src/tests/junit/org/example/junit/XmlParserTest.java
index ddc766dd1..e5fae55f8 100644
--- a/src/tests/junit/org/example/junit/XmlParserTest.java
+++ b/src/tests/junit/org/example/junit/XmlParserTest.java
@@ -17,21 +17,21 @@
*/
package org.example.junit;
-import junit.framework.TestCase;
+import org.junit.Test;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
+import static org.junit.Assert.assertNotNull;
+
/**
* created Aug 12, 2004 1:39:59 PM
*/
-public class XmlParserTest extends TestCase {
+public class XmlParserTest {
- public XmlParserTest(String s) {
- super(s);
- }
+ @Test
public void testXercesIsPresent() throws SAXException {
XMLReader xerces;
xerces = XMLReaderFactory.createXMLReader(
@@ -39,6 +39,7 @@ public class XmlParserTest extends TestCase {
assertNotNull(xerces);
}
+ @Test
public void testXercesHandlesSchema() throws SAXException {
XMLReader xerces;
xerces = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
@@ -46,6 +47,7 @@ public class XmlParserTest extends TestCase {
true);
}
+ @Test
public void testParserHandlesSchema() throws SAXException {
XMLReader xerces;
xerces = XMLReaderFactory.createXMLReader();