Browse Source

More uses of expected exceptions, assumptions and/or matchers

master
Gintas Grigelionis 7 years ago
parent
commit
1e61ebdcad
7 changed files with 254 additions and 269 deletions
  1. +25
    -28
      src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java
  2. +89
    -69
      src/tests/junit/org/apache/tools/ant/ProjectTest.java
  3. +80
    -101
      src/tests/junit/org/apache/tools/ant/taskdefs/AntTest.java
  4. +22
    -25
      src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java
  5. +11
    -16
      src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java
  6. +9
    -12
      src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java
  7. +18
    -18
      src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java

+ 25
- 28
src/tests/junit/org/apache/tools/ant/AntClassLoaderTest.java View File

@@ -23,7 +23,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;


import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -38,6 +37,7 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;


/** /**
* Test case for ant class loader * Test case for ant class loader
@@ -48,6 +48,9 @@ public class AntClassLoaderTest {
@Rule @Rule
public BuildFileRule buildRule = new BuildFileRule(); public BuildFileRule buildRule = new BuildFileRule();


@Rule
public ExpectedException thrown = ExpectedException.none();

private AntClassLoader loader; private AntClassLoader loader;


@Before @Before
@@ -88,39 +91,33 @@ public class AntClassLoaderTest {
assertEquals(mainjarstring + File.pathSeparator + extjarstring, path); assertEquals(mainjarstring + File.pathSeparator + extjarstring, path);
} }


/**
* The test should fail if NullPointException is thrown
*
* @throws ClassNotFoundException if a class is not found, ignored
*/
@Test @Test
public void testCleanup() throws BuildException {
public void testCleanup() throws ClassNotFoundException {
thrown.expect(ClassNotFoundException.class);
Path path = new Path(buildRule.getProject(), "."); Path path = new Path(buildRule.getProject(), ".");
loader = buildRule.getProject().createClassLoader(path); loader = buildRule.getProject().createClassLoader(path);
try { try {
// we don't expect to find this // we don't expect to find this
loader.findClass("fubar"); loader.findClass("fubar");
fail("Did not expect to find fubar class");
} catch (ClassNotFoundException e) {
// ignore expected
}

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

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




+ 89
- 69
src/tests/junit/org/apache/tools/ant/ProjectTest.java View File

@@ -31,6 +31,7 @@ import org.apache.tools.ant.types.PatternSet;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;


import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@@ -40,8 +41,8 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;


/** /**
* Very limited test class for Project. Waiting to be extended. * Very limited test class for Project. Waiting to be extended.
@@ -52,6 +53,9 @@ public class ProjectTest {
@Rule @Rule
public BuildFileRule buildRule = new BuildFileRule(); public BuildFileRule buildRule = new BuildFileRule();


@Rule
public ExpectedException thrown = ExpectedException.none();

private Project p; private Project p;
private String root; private String root;
private MockBuildListener mbl; private MockBuildListener mbl;
@@ -77,63 +81,75 @@ public class ProjectTest {
} }


/** /**
* This test has been a starting point for moving the code to FileUtils.
* This test has been a starting point for moving the code to FileUtils;
* first, the DOS/Netware-specific part.
*/
@Test
public void testResolveFileWithDriveLetter() {
assumeTrue("Not DOS or Netware", Os.isFamily("netware") || Os.isFamily("dos"));
assertEqualsIgnoreDriveCase(localize(File.separator),
p.resolveFile("/", null).getPath());
assertEqualsIgnoreDriveCase(localize(File.separator),
p.resolveFile("\\", null).getPath());
/*
* throw in drive letters
*/
String driveSpec = "C:";
String driveSpecLower = "c:";

assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpec + "/", null).getPath());
assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpec + "\\", null).getPath());
assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpecLower + "/", null).getPath());
assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpecLower + "\\", null).getPath());
/*
* promised to eliminate consecutive slashes after drive letter.
*/
assertEqualsIgnoreDriveCase(driveSpec + "\\",
p.resolveFile(driveSpec + "/////", null).getPath());
assertEqualsIgnoreDriveCase(driveSpec + "\\",
p.resolveFile(driveSpec + "\\\\\\\\\\\\", null).getPath());
}

/**
* This test has been a starting point for moving the code to FileUtils;
* now, the POSIX-specific part.
*/ */
@Test @Test
public void testResolveFile() { public void testResolveFile() {
if (Os.isFamily("netware") || Os.isFamily("dos")) {
assertEqualsIgnoreDriveCase(localize(File.separator),
assumeFalse("DOS or Netware", Os.isFamily("netware") || Os.isFamily("dos"));
/*
* Start with simple absolute file names.
*/
assertEquals(File.separator,
p.resolveFile("/", null).getPath()); p.resolveFile("/", null).getPath());
assertEqualsIgnoreDriveCase(localize(File.separator),
assertEquals(File.separator,
p.resolveFile("\\", null).getPath()); p.resolveFile("\\", null).getPath());
/*
* throw in drive letters
*/
String driveSpec = "C:";
String driveSpecLower = "c:";

assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpec + "/", null).getPath());
assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpec + "\\", null).getPath());
assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpecLower + "/", null).getPath());
assertEqualsIgnoreDriveCase(driveSpecLower + "\\",
p.resolveFile(driveSpecLower + "\\", null).getPath());
/*
* promised to eliminate consecutive slashes after drive letter.
*/
assertEqualsIgnoreDriveCase(driveSpec + "\\",
p.resolveFile(driveSpec + "/////", null).getPath());
assertEqualsIgnoreDriveCase(driveSpec + "\\",
p.resolveFile(driveSpec + "\\\\\\\\\\\\", null).getPath());
} else {
/*
* Start with simple absolute file names.
*/
assertEquals(File.separator,
p.resolveFile("/", null).getPath());
assertEquals(File.separator,
p.resolveFile("\\", null).getPath());
/*
* drive letters are not used, just to be considered as normal
* part of a name
*/
String driveSpec = "C:";
String udir = System.getProperty("user.dir") + File.separatorChar;
assertEquals(udir + driveSpec,
p.resolveFile(driveSpec + "/", null).getPath());
assertEquals(udir + driveSpec,
p.resolveFile(driveSpec + "\\", null).getPath());
String driveSpecLower = "c:";
assertEquals(udir + driveSpecLower,
p.resolveFile(driveSpecLower + "/", null).getPath());
assertEquals(udir + driveSpecLower,
p.resolveFile(driveSpecLower + "\\", null).getPath());
}
/* /*
* Now test some relative file name magic.
* drive letters are not used, just to be considered as normal
* part of a name
*/ */
String driveSpec = "C:";
String udir = System.getProperty("user.dir") + File.separatorChar;
assertEquals(udir + driveSpec,
p.resolveFile(driveSpec + "/", null).getPath());
assertEquals(udir + driveSpec,
p.resolveFile(driveSpec + "\\", null).getPath());
String driveSpecLower = "c:";
assertEquals(udir + driveSpecLower,
p.resolveFile(driveSpecLower + "/", null).getPath());
assertEquals(udir + driveSpecLower,
p.resolveFile(driveSpecLower + "\\", null).getPath());
}

/**
* Test some relative file name magic: platform-neutral.
*/
@Test
public void testResolveRelativeFile() {
assertEquals(localize("/1/2/3/4"), assertEquals(localize("/1/2/3/4"),
p.resolveFile("4", new File(localize("/1/2/3"))).getPath()); p.resolveFile("4", new File(localize("/1/2/3"))).getPath());
assertEquals(localize("/1/2/3/4"), assertEquals(localize("/1/2/3/4"),
@@ -168,8 +184,8 @@ public class ProjectTest {
* is called via resolveFile to pass under cygwin * is called via resolveFile to pass under cygwin
*/ */
private void assertEqualsIgnoreDriveCase(String s1, String s2) { private void assertEqualsIgnoreDriveCase(String s1, String s2) {
if ((Os.isFamily("dos") || Os.isFamily("netware"))
&& s1.length() >= 1 && s2.length() >= 1) {
assumeTrue("Not DOS or Netware", Os.isFamily("netware") || Os.isFamily("dos"));
if (s1.length() >= 1 && s2.length() >= 1) {
StringBuilder sb1 = new StringBuilder(s1); StringBuilder sb1 = new StringBuilder(s1);
StringBuilder sb2 = new StringBuilder(s2); StringBuilder sb2 = new StringBuilder(s2);
sb1.setCharAt(0, Character.toUpperCase(s1.charAt(0))); sb1.setCharAt(0, Character.toUpperCase(s1.charAt(0)));
@@ -180,16 +196,14 @@ public class ProjectTest {
} }
} }


private void assertTaskDefFails(final Class taskClass,
final String message) {
private void assertTaskDefFails(final Class<?> taskClass, final String message) {
final String dummyName = "testTaskDefinitionDummy"; final String dummyName = "testTaskDefinitionDummy";
thrown.expect(BuildException.class);
thrown.expectMessage(message);
try { try {
mbl.addBuildEvent(message, Project.MSG_ERR); mbl.addBuildEvent(message, Project.MSG_ERR);
p.addTaskDefinition(dummyName, taskClass); p.addTaskDefinition(dummyName, taskClass);
fail(String.format("expected BuildException(\"%s\", Project.MSG_ERR) when adding task %s",
message, taskClass));
} catch (BuildException e) {
assertEquals(message, e.getMessage());
} finally {
mbl.assertEmpty(); mbl.assertEmpty();
assertFalse(p.getTaskDefinitions().containsKey(dummyName)); assertFalse(p.getTaskDefinitions().containsKey(dummyName));
} }
@@ -251,17 +265,14 @@ public class ProjectTest {
assertTrue(p.getTaskDefinitions().contains(org.apache.tools.ant.taskdefs.Echo.class)); assertTrue(p.getTaskDefinitions().contains(org.apache.tools.ant.taskdefs.Echo.class));
} }


/**
* Fail because buildfile contains two targets with the same name
*/
@Test @Test
public void testDuplicateTargets() { public void testDuplicateTargets() {
// fail, because buildfile contains two targets with the same name
try {
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());
}
thrown.expect(BuildException.class);
thrown.expectMessage("Duplicate target 'twice'");
buildRule.configureProject("src/etc/testcases/core/duplicate-target.xml");
} }


@Test @Test
@@ -279,16 +290,22 @@ public class ProjectTest {
p.addBuildListener(new BuildListener() { p.addBuildListener(new BuildListener() {
public void buildStarted(BuildEvent event) { public void buildStarted(BuildEvent event) {
} }

public void buildFinished(BuildEvent event) { public void buildFinished(BuildEvent event) {
} }

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

public void targetFinished(BuildEvent event) { public void targetFinished(BuildEvent event) {
} }

public void taskStarted(BuildEvent event) { public void taskStarted(BuildEvent event) {
} }

public void taskFinished(BuildEvent event) { public void taskFinished(BuildEvent event) {
} }

public void messageLogged(final BuildEvent actual) { public void messageLogged(final BuildEvent actual) {
assertEquals(FOO, actual.getMessage()); assertEquals(FOO, actual.getMessage());
// each of the following lines would cause an // each of the following lines would cause an
@@ -321,6 +338,7 @@ public class ProjectTest {
@SuppressWarnings("unused") @SuppressWarnings("unused")
public DummyTaskPrivate() { public DummyTaskPrivate() {
} }

public void execute() { public void execute() {
} }
} }
@@ -328,6 +346,7 @@ public class ProjectTest {
protected class DummyTaskProtected extends Task { protected class DummyTaskProtected extends Task {
public DummyTaskProtected() { public DummyTaskProtected() {
} }

public void execute() { public void execute() {
} }
} }
@@ -335,6 +354,7 @@ public class ProjectTest {
class DummyTaskPackage extends Task { class DummyTaskPackage extends Task {
public DummyTaskPackage() { public DummyTaskPackage() {
} }

public void execute() { public void execute() {
} }
} }


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

@@ -19,8 +19,8 @@
package org.apache.tools.ant.taskdefs; package org.apache.tools.ant.taskdefs;


import java.io.File; import java.io.File;
import junit.framework.AssertionFailedError;
import java.util.Arrays;
import java.util.List;


import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildException;
@@ -42,7 +42,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame; import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;


/** /**
*/ */
@@ -61,56 +60,49 @@ public class AntTest {
buildRule.executeTarget("cleanup"); buildRule.executeTarget("cleanup");
} }


@Test
/**
* Fail due to recursive call
*/
@Test(expected = BuildException.class)
public void test1() { public void test1() {
try {
buildRule.executeTarget("test1");
fail("recursive call");
} catch (BuildException ex) {
//TODO assert exception message
}
buildRule.executeTarget("test1");
// TODO assert exception message
} }


// target must be specified
@Test
/**
* Fail due to unspecified target
*/
@Test(expected = BuildException.class)
public void test2() { public void test2() {
try {
buildRule.executeTarget("test2");
fail("required argument not specified");
} catch (BuildException ex) {
//TODO assert exception message
}
buildRule.executeTarget("test2");
// TODO assert exception message
} }


// Should fail since a recursion will occur...
@Test
/**
* Fail due to recursive call
*/
@Test(expected = BuildException.class)
public void test3() { public void test3() {
try {
buildRule.executeTarget("test1");
fail("recursive call");
} catch (BuildException ex) {
//TODO assert exception message
}
buildRule.executeTarget("test3");
// TODO assert exception message
} }


@Test
/**
* Fail due to empty target name
*/
@Test(expected = BuildException.class)
public void test4() { public void test4() {
try {
buildRule.executeTarget("test4");
fail("target attribute must not be empty");
} catch (BuildException ex) {
//TODO assert exception message
}
buildRule.executeTarget("test4");
// TODO assert exception message
} }


@Test
/**
* Fail due to nonexistent target
*/
@Test(expected = BuildException.class)
public void test4b() { public void test4b() {
try {
buildRule.executeTarget("test4b");
fail("target doesn't exist");
} catch (BuildException ex) {
//TODO assert exception message
}
buildRule.executeTarget("test4b");
// TODO assert exception message
} }


@Test @Test
@@ -165,7 +157,7 @@ public class AntTest {
BasedirChecker bc = new BasedirChecker(dirs); BasedirChecker bc = new BasedirChecker(dirs);
buildRule.getProject().addBuildListener(bc); buildRule.getProject().addBuildListener(bc);
buildRule.executeTarget(target); buildRule.executeTarget(target);
AssertionFailedError ae = bc.getError();
AssertionError ae = bc.getError();
if (ae != null) { if (ae != null) {
throw ae; throw ae;
} }
@@ -229,7 +221,7 @@ public class AntTest {
ReferenceChecker rc = new ReferenceChecker(keys, expect, value); ReferenceChecker rc = new ReferenceChecker(keys, expect, value);
buildRule.getProject().addBuildListener(rc); buildRule.getProject().addBuildListener(rc);
buildRule.executeTarget(target); buildRule.executeTarget(target);
AssertionFailedError ae = rc.getError();
AssertionError ae = rc.getError();
if (ae != null) { if (ae != null) {
throw ae; throw ae;
} }
@@ -238,21 +230,17 @@ public class AntTest {


@Test @Test
public void testLogfilePlacement() { public void testLogfilePlacement() {
File[] logFiles = new File[] {
buildRule.getProject().resolveFile("test1.log"),
buildRule.getProject().resolveFile("test2.log"),
buildRule.getProject().resolveFile("ant/test3.log"),
buildRule.getProject().resolveFile("ant/test4.log")
};
for (File logFile : logFiles) {
assertFalse(logFile.getName() + " doesn\'t exist", logFile.exists());
}
List<File> logFiles = Arrays.asList(buildRule.getProject().resolveFile("test1.log"),
buildRule.getProject().resolveFile("test2.log"),
buildRule.getProject().resolveFile("ant/test3.log"),
buildRule.getProject().resolveFile("ant/test4.log"));

logFiles.forEach(logFile -> assertFalse(logFile.getName() + " doesn\'t exist",
logFile.exists()));


buildRule.executeTarget("testLogfilePlacement"); buildRule.executeTarget("testLogfilePlacement");


for (File logFile : logFiles) {
assertTrue(logFile.getName() + " exists", logFile.exists());
}
logFiles.forEach(logFile -> assertTrue(logFile.getName() + " exists", logFile.exists()));
} }


@Test @Test
@@ -262,7 +250,7 @@ public class AntTest {
InputHandlerChecker ic = new InputHandlerChecker(ih); InputHandlerChecker ic = new InputHandlerChecker(ih);
buildRule.getProject().addBuildListener(ic); buildRule.getProject().addBuildListener(ic);
buildRule.executeTarget("tripleCall"); buildRule.executeTarget("tripleCall");
AssertionFailedError ae = ic.getError();
AssertionError ae = ic.getError();
if (ae != null) { if (ae != null) {
throw ae; throw ae;
} }
@@ -273,13 +261,11 @@ public class AntTest {
public void testRefId() { public void testRefId() {
Path testPath = new Path(buildRule.getProject()); Path testPath = new Path(buildRule.getProject());
testPath.createPath().setPath(System.getProperty("java.class.path")); testPath.createPath().setPath(System.getProperty("java.class.path"));
PropertyChecker pc =
new PropertyChecker("testprop",
new String[] {null,
testPath.toString()});
PropertyChecker pc = new PropertyChecker("testprop",
new String[] {null, testPath.toString()});
buildRule.getProject().addBuildListener(pc); buildRule.getProject().addBuildListener(pc);
buildRule.executeTarget("testRefid"); buildRule.executeTarget("testRefid");
AssertionFailedError ae = pc.getError();
AssertionError ae = pc.getError();
if (ae != null) { if (ae != null) {
throw ae; throw ae;
} }
@@ -290,7 +276,6 @@ public class AntTest {
public void testUserPropertyWinsInheritAll() { public void testUserPropertyWinsInheritAll() {
buildRule.getProject().setUserProperty("test", "7"); buildRule.getProject().setUserProperty("test", "7");
buildRule.executeTarget("test-property-override-inheritall-start"); buildRule.executeTarget("test-property-override-inheritall-start");

assertThat(buildRule.getLog(), containsString("The value of test is 7")); assertThat(buildRule.getLog(), containsString("The value of test is 7"));
} }


@@ -298,14 +283,12 @@ public class AntTest {
public void testUserPropertyWinsNoInheritAll() { public void testUserPropertyWinsNoInheritAll() {
buildRule.getProject().setUserProperty("test", "7"); buildRule.getProject().setUserProperty("test", "7");
buildRule.executeTarget("test-property-override-no-inheritall-start"); buildRule.executeTarget("test-property-override-no-inheritall-start");

assertThat(buildRule.getLog(), containsString("The value of test is 7")); assertThat(buildRule.getLog(), containsString("The value of test is 7"));
} }


@Test @Test
public void testOverrideWinsInheritAll() { public void testOverrideWinsInheritAll() {
buildRule.executeTarget("test-property-override-inheritall-start"); buildRule.executeTarget("test-property-override-inheritall-start");

assertThat(buildRule.getLog(), containsString("The value of test is 4")); assertThat(buildRule.getLog(), containsString("The value of test is 4"));
} }


@@ -323,14 +306,13 @@ public class AntTest {
assertThat(buildRule.getLog(), containsString("test1.x is 1")); assertThat(buildRule.getLog(), containsString("test1.x is 1"));
} }


@Test
/**
* Fail due to infinite recursion loop
*/
@Test(expected = BuildException.class)
public void testInfiniteLoopViaDepends() { public void testInfiniteLoopViaDepends() {
try {
buildRule.executeTarget("infinite-loop-via-depends");
fail("recursive call");
} catch (BuildException ex) {
//TODO assert exception message
}
buildRule.executeTarget("infinite-loop-via-depends");
// TODO assert exception message
} }


@Test @Test
@@ -342,7 +324,6 @@ public class AntTest {
@Test @Test
public void testTopLevelTarget() { public void testTopLevelTarget() {
buildRule.executeTarget("topleveltarget"); buildRule.executeTarget("topleveltarget");

assertEquals("Hello world", buildRule.getLog()); assertEquals("Hello world", buildRule.getLog());
} }


@@ -355,11 +336,11 @@ public class AntTest {
buildRule.getProject().addBuildListener(pcBar); buildRule.getProject().addBuildListener(pcBar);
buildRule.getProject().addBuildListener(pcFoo); buildRule.getProject().addBuildListener(pcFoo);
buildRule.executeTarget("multiple-property-file-children"); buildRule.executeTarget("multiple-property-file-children");
AssertionFailedError aeBar = pcBar.getError();
AssertionError aeBar = pcBar.getError();
if (aeBar != null) { if (aeBar != null) {
throw aeBar; throw aeBar;
} }
AssertionFailedError aeFoo = pcFoo.getError();
AssertionError aeFoo = pcFoo.getError();
if (aeFoo != null) { if (aeFoo != null) {
throw aeFoo; throw aeFoo;
} }
@@ -367,14 +348,13 @@ public class AntTest {
buildRule.getProject().removeBuildListener(pcFoo); buildRule.getProject().removeBuildListener(pcFoo);
} }


@Test
/**
* Fail due to empty target name
*/
@Test(expected = BuildException.class)
public void testBlankTarget() { public void testBlankTarget() {
try {
buildRule.executeTarget("blank-target");
fail("target name must not be empty");
} catch (BuildException ex) {
//TODO assert exception message
}
buildRule.executeTarget("blank-target");
// TODO assert exception message
} }


@Test @Test
@@ -400,7 +380,7 @@ public class AntTest {
private class BasedirChecker implements BuildListener { private class BasedirChecker implements BuildListener {
private String[] expectedBasedirs; private String[] expectedBasedirs;
private int calls = 0; private int calls = 0;
private AssertionFailedError error;
private AssertionError error;


BasedirChecker(String[] dirs) { BasedirChecker(String[] dirs) {
expectedBasedirs = dirs; expectedBasedirs = dirs;
@@ -432,16 +412,15 @@ public class AntTest {
try { try {
assertEquals(expectedBasedirs[calls++], assertEquals(expectedBasedirs[calls++],
event.getProject().getBaseDir().getAbsolutePath()); event.getProject().getBaseDir().getAbsolutePath());
} catch (AssertionFailedError e) {
} catch (AssertionError e) {
error = e; error = e;
} }
} }
} }


AssertionFailedError getError() {
AssertionError getError() {
return error; return error;
} }

} }


private class ReferenceChecker implements BuildListener { private class ReferenceChecker implements BuildListener {
@@ -449,7 +428,7 @@ public class AntTest {
private boolean[] expectSame; private boolean[] expectSame;
private Object value; private Object value;
private int calls = 0; private int calls = 0;
private AssertionFailedError error;
private AssertionError error;


ReferenceChecker(String[] keys, boolean[] expectSame, Object value) { ReferenceChecker(String[] keys, boolean[] expectSame, Object value) {
this.keys = keys; this.keys = keys;
@@ -481,8 +460,7 @@ public class AntTest {
} }
if (error == null) { if (error == null) {
try { try {
String msg =
"Call " + calls + " refid=\'" + keys[calls] + "\'";
String msg = "Call " + calls + " refid=\'" + keys[calls] + "\'";
if (value == null) { if (value == null) {
Object o = event.getProject().getReference(keys[calls]); Object o = event.getProject().getReference(keys[calls]);
if (expectSame[calls++]) { if (expectSame[calls++]) {
@@ -512,21 +490,20 @@ public class AntTest {
} }
} }
} }
} catch (AssertionFailedError e) {
} catch (AssertionError e) {
error = e; error = e;
} }
} }
} }


AssertionFailedError getError() {
AssertionError getError() {
return error; return error;
} }

} }


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


InputHandlerChecker(InputHandler value) { InputHandlerChecker(InputHandler value) {
ih = value; ih = value;
@@ -535,18 +512,23 @@ public class AntTest {
public void buildStarted(BuildEvent event) { public void buildStarted(BuildEvent event) {
check(event); check(event);
} }

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

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

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

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

public void messageLogged(BuildEvent event) { public void messageLogged(BuildEvent event) {
check(event); check(event);
} }
@@ -560,23 +542,22 @@ public class AntTest {
try { try {
assertNotNull(event.getProject().getInputHandler()); assertNotNull(event.getProject().getInputHandler());
assertSame(ih, event.getProject().getInputHandler()); assertSame(ih, event.getProject().getInputHandler());
} catch (AssertionFailedError e) {
} catch (AssertionError e) {
error = e; error = e;
} }
} }
} }


AssertionFailedError getError() {
AssertionError getError() {
return error; return error;
} }

} }


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


PropertyChecker(String key, String[] values) { PropertyChecker(String key, String[] values) {
this.key = key; this.key = key;
@@ -606,25 +587,23 @@ public class AntTest {
return; return;
} }
if (calls >= expectedValues.length) { if (calls >= expectedValues.length) {
error = new AssertionFailedError("Unexpected invocation of"
+ " target "
+ event.getTarget().getName());
error = new AssertionError("Unexpected invocation of target "
+ event.getTarget().getName());
} }


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


AssertionFailedError getError() {
AssertionError getError() {
return error; return error;
} }

} }


} }

+ 22
- 25
src/tests/junit/org/apache/tools/ant/taskdefs/ParallelTest.java View File

@@ -27,9 +27,12 @@ import org.apache.tools.ant.Project;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;


import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertTrue;


/** /**
* Test of the parallel TaskContainer * Test of the parallel TaskContainer
@@ -39,6 +42,9 @@ public class ParallelTest {
@Rule @Rule
public final BuildFileRule buildRule = new BuildFileRule(); public final BuildFileRule buildRule = new BuildFileRule();


@Rule
public ExpectedException thrown = ExpectedException.none();

/** Standard property value for the basic test */ /** Standard property value for the basic test */
public static final String DIRECT_MESSAGE = "direct"; public static final String DIRECT_MESSAGE = "direct";
/** Standard property value for the basic and fail test */ /** Standard property value for the basic and fail test */
@@ -108,6 +114,9 @@ public class ParallelTest {
int current = 0; int current = 0;
int pos = beginSlash + 1; int pos = beginSlash + 1;
while (pos < lastPipe) { while (pos < lastPipe) {
assertTrue("Only expect '+-' in result count, found " + s.charAt(pos)
+ " at position " + (pos + 1),
s.charAt(pos) == '+' || s.charAt(pos) == '-');
switch (s.charAt(pos++)) { switch (s.charAt(pos++)) {
case '+': case '+':
current++; current++;
@@ -116,13 +125,10 @@ public class ParallelTest {
current--; current--;
break; break;
default: default:
fail("Only expect '+-' in result count, found "
+ s.charAt(--pos) + " at position " + pos);
}
if (current > max) {
fail("Number of executing threads exceeded number allowed: "
+ current + " > " + max);
break;
} }
assertTrue("Number of executing threads exceeded number allowed: "
+ current + " > " + max, current <= max);
} }
return lastPipe; return lastPipe;
} }
@@ -132,15 +138,12 @@ public class ParallelTest {
@Test @Test
public void testFail() { public void testFail() {
// should get no output at all // should get no output at all
thrown.expect(BuildException.class);
thrown.expectMessage(FAILURE_MESSAGE);
Project p = buildRule.getProject(); Project p = buildRule.getProject();
p.setUserProperty("test.failure", FAILURE_MESSAGE); p.setUserProperty("test.failure", FAILURE_MESSAGE);
p.setUserProperty("test.delayed", DELAYED_MESSAGE); p.setUserProperty("test.delayed", DELAYED_MESSAGE);
try {
buildRule.executeTarget("testFail");
fail("fail task in one parallel branch");
} catch (BuildException ex) {
assertEquals(FAILURE_MESSAGE, ex.getMessage());
}
buildRule.executeTarget("testFail");
} }


/** tests the demuxing of output streams in a multithreaded situation */ /** tests the demuxing of output streams in a multithreaded situation */
@@ -168,12 +171,9 @@ public class ParallelTest {
*/ */
@Test @Test
public void testSingleExit() { public void testSingleExit() {
try {
buildRule.executeTarget("testSingleExit");
fail("ExitStatusException should have been thrown");
} catch (ExitStatusException ex) {
assertEquals(42, ex.getStatus());
}
thrown.expect(ExitStatusException.class);
thrown.expect(hasProperty("status", equalTo(42)));
buildRule.executeTarget("testSingleExit");
} }


/** /**
@@ -181,12 +181,9 @@ public class ParallelTest {
*/ */
@Test @Test
public void testExitAndOtherException() { public void testExitAndOtherException() {
try {
buildRule.executeTarget("testExitAndOtherException");
fail("ExitStatusException should have been thrown");
} catch (ExitStatusException ex) {
assertEquals(42, ex.getStatus());
}
thrown.expect(ExitStatusException.class);
thrown.expect(hasProperty("status", equalTo(42)));
buildRule.executeTarget("testExitAndOtherException");
} }


} }


+ 11
- 16
src/tests/junit/org/apache/tools/ant/taskdefs/XmlPropertyTest.java View File

@@ -36,8 +36,11 @@ import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;


import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;


/** /**
*/ */
@@ -228,18 +231,13 @@ public class XmlPropertyTest {
// *value* of the Path object, though... // *value* of the Path object, though...
Object obj = p.getReferences().get(currentKey); Object obj = p.getReferences().get(currentKey);


if (obj == null) {
fail(assertMsg + " Object ID does not exist.");
}
assertNotEquals(assertMsg + " Object ID does not exist.", null, obj);


// What is the property supposed to be? // What is the property supposed to be?
propertyValue =
propertyValue.substring(3, propertyValue.length());
propertyValue = propertyValue.substring(3, propertyValue.length());
if (propertyValue.equals("path")) { if (propertyValue.equals("path")) {
if (!(obj instanceof Path)) {
fail(assertMsg + " Path ID is a "
+ obj.getClass().getName());
}
assertThat(assertMsg + " Path ID is a " + obj.getClass().getName(),
obj, instanceOf(Path.class));
} else { } else {
assertEquals(assertMsg, propertyValue, obj.toString()); assertEquals(assertMsg, propertyValue, obj.toString());
} }
@@ -279,12 +277,9 @@ public class XmlPropertyTest {
for (Map.Entry<String, Object> entry : references.entrySet()) { for (Map.Entry<String, Object> entry : references.entrySet()) {
String currentKey = entry.getKey(); String currentKey = entry.getKey();
Object currentValue = entry.getValue(); Object currentValue = entry.getValue();

if (!(currentValue instanceof Path) && !(currentValue instanceof String)
&& !currentKey.startsWith("ant.")) {
fail(msg + "-" + inputFile.getName() + " Key="
+ currentKey + " is not a recognized type.");
}
assertTrue(msg + "-" + inputFile.getName() + " Key=" + currentKey
+ " is not a recognized type.", currentValue instanceof Path
|| currentValue instanceof String || currentKey.startsWith("ant."));
} }
} }




+ 9
- 12
src/tests/junit/org/apache/tools/ant/taskdefs/optional/RhinoScriptTest.java View File

@@ -22,6 +22,7 @@ import org.apache.tools.ant.BuildFileRule;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;


import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@@ -36,6 +37,9 @@ public class RhinoScriptTest {
@Rule @Rule
public BuildFileRule buildRule = new BuildFileRule(); public BuildFileRule buildRule = new BuildFileRule();


@Rule
public ExpectedException thrown = ExpectedException.none();

@Before @Before
public void setUp() { public void setUp() {
buildRule.configureProject("src/etc/testcases/taskdefs/optional/script.xml"); buildRule.configureProject("src/etc/testcases/taskdefs/optional/script.xml");
@@ -68,22 +72,15 @@ public class RhinoScriptTest {


@Test @Test
public void testUseSrcAndEncoding() { public void testUseSrcAndEncoding() {
final String readerEncoding = "UTF-8";
buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", readerEncoding);
buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", "UTF-8");
buildRule.executeTarget("useSrcAndEncoding"); buildRule.executeTarget("useSrcAndEncoding");
} }


@Test @Test
public void testUseSrcAndEncodingFailure() { public void testUseSrcAndEncodingFailure() {
final String readerEncoding = "ISO-8859-1";
buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", readerEncoding);
try {
buildRule.executeTarget("useSrcAndEncoding");
fail("should have failed with reader's encoding [" + readerEncoding
+ "] different from the writer's encoding ["
+ buildRule.getProject().getProperty("useSrcAndEncoding.encoding") + "]");
} catch (BuildException e) {
assertTrue(e.getMessage().matches("expected <eacute \\[\u00e9]> but was <eacute \\[\u00c3\u00a9]>"));
}
thrown.expect(BuildException.class);
thrown.expectMessage("expected <eacute [\u00e9]> but was <eacute [\u00c3\u00a9]>");
buildRule.getProject().setProperty("useSrcAndEncoding.reader.encoding", "ISO-8859-1");
buildRule.executeTarget("useSrcAndEncoding");
} }
} }

+ 18
- 18
src/tests/junit/org/apache/tools/ant/taskdefs/optional/vss/MSVSSTest.java View File

@@ -34,6 +34,7 @@ import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;


import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
@@ -65,6 +66,9 @@ public class MSVSSTest implements MSVSSConstants {
public BuildFileRule buildRule = new BuildFileRule(); public BuildFileRule buildRule = new BuildFileRule();
private Project project; private Project project;


@Rule
public ExpectedException thrown = ExpectedException.none();

@Before @Before
public void setUp() { public void setUp() {
project = new Project(); project = new Project();
@@ -115,7 +119,7 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testGetExceptions() { public void testGetExceptions() {
buildRule.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!");
expectSpecificBuildException("vssget.1", "vsspath attribute must be set!");
} }


/** Tests Label commandline generation. */ /** Tests Label commandline generation. */
@@ -168,8 +172,8 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testLabelExceptions() { public void testLabelExceptions() {
buildRule.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!");
expectSpecificBuildException("vsslabel.1", "vsspath attribute must be set!");
expectSpecificBuildException("vsslabel.2", "label attribute must be set!");
} }


/** Tests VSSHistory commandline generation with from label. */ /** Tests VSSHistory commandline generation with from label. */
@@ -262,17 +266,13 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testHistoryExceptions() { public void testHistoryExceptions() {
buildRule.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!");
expectSpecificBuildException("vsshistory.1", "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());
}
private void expectSpecificBuildException(String target, String exceptionMessage) {
thrown.expect(BuildException.class);
thrown.expectMessage(exceptionMessage);
buildRule.executeTarget(target);
} }


/** Tests CheckIn commandline generation. */ /** Tests CheckIn commandline generation. */
@@ -302,7 +302,7 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testCheckinExceptions() { public void testCheckinExceptions() {
buildRule.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!");
expectSpecificBuildException("vsscheckin.1", "vsspath attribute must be set!");
} }


/** Tests CheckOut commandline generation. */ /** Tests CheckOut commandline generation. */
@@ -338,8 +338,8 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testCheckoutExceptions() { public void testCheckoutExceptions() {
buildRule.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");
expectSpecificBuildException("vsscheckout.1", "vsspath attribute must be set!");
expectSpecificBuildException("vsscheckout.2", "blah is not a legal value for this attribute");
} }


/** Tests Add commandline generation. */ /** Tests Add commandline generation. */
@@ -371,7 +371,7 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testAddExceptions() { public void testAddExceptions() {
buildRule.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!");
expectSpecificBuildException("vssadd.1", "localPath attribute must be set!");
} }


/** Tests CP commandline generation. */ /** Tests CP commandline generation. */
@@ -398,7 +398,7 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testCpExceptions() { public void testCpExceptions() {
buildRule.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!");
expectSpecificBuildException("vsscp.1", "vsspath attribute must be set!");
} }


/** Tests Create commandline generation. */ /** Tests Create commandline generation. */
@@ -429,7 +429,7 @@ public class MSVSSTest implements MSVSSConstants {
@Test @Test
public void testCreateExceptions() { public void testCreateExceptions() {
buildRule.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!");
expectSpecificBuildException("vsscreate.1", "vsspath attribute must be set!");
} }


/** /**


Loading…
Cancel
Save