| author | Henrik Lynggaard Hansen | 2012-07-18 15:58:15 (EDT) |
|---|---|---|
| committer | Henrik Lynggaard Hansen | 2012-07-18 15:58:15 (EDT) |
| commit | 3bbb070f381a0ee601755c8a84dd621be8b9cc42 (patch) (side-by-side diff) | |
| tree | ce1ea4f543040ab00a7b69d242e628e20bcc51b8 | |
| parent | 879fa81dfc9f71094824d7c5121321a0f1ecb49d (diff) | |
| download | org.eclipse.hudson.core-3bbb070f381a0ee601755c8a84dd621be8b9cc42.zip org.eclipse.hudson.core-3bbb070f381a0ee601755c8a84dd621be8b9cc42.tar.gz org.eclipse.hudson.core-3bbb070f381a0ee601755c8a84dd621be8b9cc42.tar.bz2 | |
Reformat hudson-test-framework maven modulerefs/changes/55/6855/1
Change-Id: I9a62f94602efd61af730cb0663d25b7a64901ca7
Signed-off-by: Henrik Lynggaard Hansen <henrik@hlyh.dk>
44 files changed, 988 insertions, 866 deletions
diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/CaptureEnvironmentBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/CaptureEnvironmentBuilder.java index add9e12..0e3070d 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/CaptureEnvironmentBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/CaptureEnvironmentBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -34,20 +34,21 @@ import java.io.IOException; * @author Kohsuke Kawaguchi */ public class CaptureEnvironmentBuilder extends Builder { - + private EnvVars envVars; - public EnvVars getEnvVars() { - return envVars; - } + public EnvVars getEnvVars() { + return envVars; + } - public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { - envVars = build.getEnvironment(listener); + public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { + envVars = build.getEnvironment(listener); return true; } @Extension public static final class DescriptorImpl extends Descriptor<Builder> { + public Builder newInstance(StaplerRequest req, JSONObject data) { throw new UnsupportedOperationException(); } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ClosureExecuterAction.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ClosureExecuterAction.java index 7580a06..fea4cac 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ClosureExecuterAction.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ClosureExecuterAction.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -28,21 +28,23 @@ import java.util.Map; import java.util.UUID; /** - * Server-side logic that implements {@link HudsonTestCase#executeOnServer(Callable)}. + * Server-side logic that implements + * {@link HudsonTestCase#executeOnServer(Callable)}. * * @author Kohsuke Kawaguchi */ @Extension public final class ClosureExecuterAction implements RootAction { - private final Map<UUID,Runnable> runnables = Collections.synchronizedMap(new HashMap<UUID, Runnable>()); + + private final Map<UUID, Runnable> runnables = Collections.synchronizedMap(new HashMap<UUID, Runnable>()); public void add(UUID uuid, Runnable r) { - runnables.put(uuid,r); + runnables.put(uuid, r); } public void doIndex(StaplerResponse rsp, @QueryParameter("uuid") String uuid) throws IOException { Runnable r = runnables.remove(UUID.fromString(uuid)); - if (r!=null) { + if (r != null) { r.run(); } else { rsp.sendError(404); diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ComputerConnectorTester.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ComputerConnectorTester.java index 4dbe51b..489e02b 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ComputerConnectorTester.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ComputerConnectorTester.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -29,12 +29,14 @@ import java.io.IOException; import java.util.List; /** - * Test bed to verify the configuration roundtripness of the {@link ComputerConnector}. + * Test bed to verify the configuration roundtripness of the + * {@link ComputerConnector}. * * @author Kohsuke Kawaguchi * @see HudsonTestCase#computerConnectorTester */ public class ComputerConnectorTester extends AbstractDescribableImpl<ComputerConnectorTester> { + public final HudsonTestCase testCase; public ComputerConnector connector; @@ -49,9 +51,10 @@ public class ComputerConnectorTester extends AbstractDescribableImpl<ComputerCon public List getConnectorDescriptors() { return ComputerConnectorDescriptor.all(); } - + @Extension public static class DescriptorImpl extends Descriptor<ComputerConnectorTester> { + @Override public String getDisplayName() { return ""; diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/DefaultConstructorChecker.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/DefaultConstructorChecker.java index 2bcb3bb..664af6d 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/DefaultConstructorChecker.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/DefaultConstructorChecker.java @@ -8,7 +8,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * + * * *******************************************************************************/ @@ -22,11 +22,12 @@ import junit.framework.TestCase; * @author Kohsuke Kawaguchi */ public class DefaultConstructorChecker extends TestCase { + private final Class clazz; public DefaultConstructorChecker(Class clazz) { this.clazz = clazz; - setName(clazz.getName()+".verifyDefaultConstructor"); + setName(clazz.getName() + ".verifyDefaultConstructor"); } @Override @@ -34,9 +35,9 @@ public class DefaultConstructorChecker extends TestCase { try { clazz.getConstructor(); } catch (NoSuchMethodException e) { - throw new Error(clazz+" must have the default constructor",e); + throw new Error(clazz + " must have the default constructor", e); } catch (SecurityException e) { - throw new Error(clazz+" must have the default constructor",e); + throw new Error(clazz + " must have the default constructor", e); } } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogParser.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogParser.java index dfdd738..0e4ff51 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogParser.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogParser.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: * * Nikita Levyankov - * + * * *******************************************************************************/ @@ -37,6 +37,7 @@ import java.util.List; * @author Andrew Bayer */ public class ExtractChangeLogParser extends ChangeLogParser { + @Override public ExtractChangeLogSet parse(AbstractBuild build, File changeLogFile) throws IOException, SAXException { if (changeLogFile.exists()) { @@ -71,9 +72,9 @@ public class ExtractChangeLogParser extends ChangeLogParser { return new ExtractChangeLogSet(build, changeLog); } - @ExportedBean(defaultVisibility = 999) public static class ExtractChangeLogEntry extends ChangeLogSet.Entry { + private List<FileInZip> files = new ArrayList<FileInZip>(); private String zipFile; @@ -131,6 +132,7 @@ public class ExtractChangeLogParser extends ChangeLogParser { @ExportedBean(defaultVisibility = 999) public static class FileInZip { + private String fileName = ""; public FileInZip() { @@ -149,5 +151,4 @@ public class ExtractChangeLogParser extends ChangeLogParser { this.fileName = fileName; } } - } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogSet.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogSet.java index 64cb9d5..4d837ed 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogSet.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractChangeLogSet.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: * * Nikita Levyankov - * + * * *******************************************************************************/ @@ -23,11 +23,11 @@ import java.util.Collection; import java.util.List; import java.util.Collections; - /** * @author Andrew Bayer */ public class ExtractChangeLogSet extends ChangeLogSet<ExtractChangeLogParser.ExtractChangeLogEntry> { + private List<ExtractChangeLogParser.ExtractChangeLogEntry> changeLogs = null; public ExtractChangeLogSet(AbstractBuild<?, ?> build, List<ExtractChangeLogParser.ExtractChangeLogEntry> changeLogs) { diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceSCM.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceSCM.java index 1c8f5c7..ba6b495 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceSCM.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceSCM.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -28,26 +28,29 @@ import java.io.IOException; import java.net.URL; /** - * {@link SCM} useful for testing that extracts the given resource as a zip file. + * {@link SCM} useful for testing that extracts the given resource as a zip + * file. * * @author Kohsuke Kawaguchi */ public class ExtractResourceSCM extends NullSCM { + private final URL zip; public ExtractResourceSCM(URL zip) { - if(zip==null) + if (zip == null) { throw new IllegalArgumentException(); + } this.zip = zip; } @Override public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changeLogFile) throws IOException, InterruptedException { - if (workspace.exists()) { + if (workspace.exists()) { listener.getLogger().println("Deleting existing workspace " + workspace.getRemote()); - workspace.deleteRecursive(); - } - listener.getLogger().println("Staging "+zip); + workspace.deleteRecursive(); + } + listener.getLogger().println("Staging " + zip); workspace.unzipFrom(zip.openStream()); return true; } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceWithChangesSCM.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceWithChangesSCM.java index a2ceaad..2921b77 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceWithChangesSCM.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/ExtractResourceWithChangesSCM.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -34,26 +34,30 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** - * {@link SCM} useful for testing that extracts the given resource as a zip file. + * {@link SCM} useful for testing that extracts the given resource as a zip + * file. * * @author Kohsuke Kawaguchi */ public class ExtractResourceWithChangesSCM extends NullSCM { + private final URL firstZip; private final URL secondZip; private final String moduleRoot; - + public ExtractResourceWithChangesSCM(URL firstZip, URL secondZip) { - if ((firstZip == null) || (secondZip == null)) + if ((firstZip == null) || (secondZip == null)) { throw new IllegalArgumentException(); + } this.firstZip = firstZip; this.secondZip = secondZip; this.moduleRoot = null; } public ExtractResourceWithChangesSCM(URL firstZip, URL secondZip, String moduleRoot) { - if ((firstZip == null) || (secondZip == null)) + if ((firstZip == null) || (secondZip == null)) { throw new IllegalArgumentException(); + } this.firstZip = firstZip; this.secondZip = secondZip; this.moduleRoot = moduleRoot; @@ -61,12 +65,12 @@ public class ExtractResourceWithChangesSCM extends NullSCM { @Override public FilePath getModuleRoot(FilePath workspace) { - if (moduleRoot!=null) { + if (moduleRoot != null) { return workspace.child(moduleRoot); } return workspace; } - + @Override public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changeLogFile) throws IOException, InterruptedException { if (workspace.exists()) { @@ -85,11 +89,11 @@ public class ExtractResourceWithChangesSCM extends NullSCM { try { while ((e = zip.getNextEntry()) != null) { - if (!e.isDirectory()) + if (!e.isDirectory()) { changeLog.addFile(new ExtractChangeLogParser.FileInZip(e.getName())); + } } - } - finally { + } finally { zip.close(); } saveToChangeLog(changeLogFile, changeLog); @@ -129,7 +133,10 @@ public class ExtractResourceWithChangesSCM extends NullSCM { } /** - * Don't write 'this', so that subtypes can be implemented as anonymous class. + * Don't write 'this', so that subtypes can be implemented as anonymous + * class. */ - private Object writeReplace() { return new Object(); } + private Object writeReplace() { + return new Object(); + } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FailureBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FailureBuilder.java index 8a35e73..0888b0a 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FailureBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FailureBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -34,7 +34,7 @@ import java.io.IOException; * @author Kohsuke Kawaguchi */ public class FailureBuilder extends Builder { - + public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println("Simulating a failure"); build.setResult(Result.FAILURE); @@ -43,9 +43,11 @@ public class FailureBuilder extends Builder { @Extension public static final class DescriptorImpl extends Descriptor<Builder> { + public String getDisplayName() { return "Always fail"; } + public FailureBuilder newInstance(StaplerRequest req, JSONObject data) { return new FailureBuilder(); } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FakeLauncher.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FakeLauncher.java index eb82189..95996cf 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FakeLauncher.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/FakeLauncher.java @@ -8,7 +8,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * + * * *******************************************************************************/ @@ -27,13 +27,14 @@ import java.io.IOException; * @see MockFakeLauncher */ public interface FakeLauncher { + /** * Called whenever a {@link PretendSlave} is asked to fork a new process. * - * <p> - * The callee can inspect the {@link ProcStarter} object to determine what process is being launched, - * and if necessary, fake a process launch by either returning a valid {@link Proc} object, or let - * the normal process launch happen by returning null. + * <p> The callee can inspect the {@link ProcStarter} object to determine + * what process is being launched, and if necessary, fake a process launch + * by either returning a valid {@link Proc} object, or let the normal + * process launch happen by returning null. */ Proc onLaunch(ProcStarter p) throws IOException; @@ -41,6 +42,7 @@ public interface FakeLauncher { * Fake {@link Proc} implementation that represents a completed process. */ public class FinishedProc extends Proc { + public final int exitCode; public FinishedProc(int exitCode) { diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonHomeLoader.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonHomeLoader.java index 99138c8..d280acb 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonHomeLoader.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonHomeLoader.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -31,16 +31,16 @@ import java.net.URL; * @author Kohsuke Kawaguchi */ public interface HudsonHomeLoader { - /** + + /** * Returns a directory to be used as <tt>HUDSON_HOME</tt> * - * @throws Exception - * to cause a test to fail. + * @throws Exception to cause a test to fail. */ File allocate() throws Exception; - /** - * Allocates a new empty directory, meaning this will emulate the fresh Hudson installation. + * Allocates a new empty directory, meaning this will emulate the fresh + * Hudson installation. */ public static final HudsonHomeLoader NEW = new HudsonHomeLoader() { public File allocate() throws IOException { @@ -49,9 +49,11 @@ public interface HudsonHomeLoader { }; /** - * Allocates a new directory by copying from an existing directory, or unzipping from a zip file. + * Allocates a new directory by copying from an existing directory, or + * unzipping from a zip file. */ public static final class CopyExisting implements HudsonHomeLoader { + private final URL source; /** @@ -64,9 +66,8 @@ public interface HudsonHomeLoader { /** * Extracts from a zip file in the resource. * - * <p> - * This is useful in case you want to have a test data in the resources. - * Only file URL is supported. + * <p> This is useful in case you want to have a test data in the + * resources. Only file URL is supported. */ public CopyExisting(URL source) { this.source = source; @@ -74,17 +75,17 @@ public interface HudsonHomeLoader { public File allocate() throws Exception { File target = NEW.allocate(); - if(source.getProtocol().equals("file")) { + if (source.getProtocol().equals("file")) { File src = new File(source.toURI()); - if(src.isDirectory()) - new FilePath(src).copyRecursiveTo("**/*",new FilePath(target)); - else - if(src.getName().endsWith(".zip")) + if (src.isDirectory()) { + new FilePath(src).copyRecursiveTo("**/*", new FilePath(target)); + } else if (src.getName().endsWith(".zip")) { new FilePath(src).unzip(new FilePath(target)); + } } else { - File tmp = File.createTempFile("hudson","zip"); + File tmp = File.createTempFile("hudson", "zip"); try { - FileUtils.copyURLToFile(source,tmp); + FileUtils.copyURLToFile(source, tmp); new FilePath(tmp).unzip(new FilePath(target)); } finally { tmp.delete(); @@ -98,6 +99,7 @@ public interface HudsonHomeLoader { * Allocates a new directory by copying from a test resource */ public static final class Local implements HudsonHomeLoader { + private final Method testMethod; public Local(Method testMethod) { @@ -106,12 +108,14 @@ public interface HudsonHomeLoader { public File allocate() throws Exception { URL res = findDataResource(); - if(!res.getProtocol().equals("file")) - throw new AssertionError("Test data is not available in the file system: "+res); + if (!res.getProtocol().equals("file")) { + throw new AssertionError("Test data is not available in the file system: " + res); + } // if we picked up a directory, it's one level above config.xml File home = new File(res.toURI()); - if(!home.getName().endsWith(".zip")) + if (!home.getName().endsWith(".zip")) { home = home.getParentFile(); + } return new CopyExisting(home).allocate(); } @@ -119,17 +123,18 @@ public interface HudsonHomeLoader { private URL findDataResource() { // first, check method specific resource Class<?> clazz = testMethod.getDeclaringClass(); - - for( String middle : new String[]{ '/'+testMethod.getName(), "" }) { - for( String suffix : SUFFIXES ) { - URL res = clazz.getResource(clazz.getSimpleName() + middle+suffix); - if(res!=null) return res; + + for (String middle : new String[]{'/' + testMethod.getName(), ""}) { + for (String suffix : SUFFIXES) { + URL res = clazz.getResource(clazz.getSimpleName() + middle + suffix); + if (res != null) { + return res; + } } } - throw new AssertionError("No test resource was found for "+testMethod); + throw new AssertionError("No test resource was found for " + testMethod); } - - private static final String[] SUFFIXES = {"/config.xml",".zip"}; + private static final String[] SUFFIXES = {"/config.xml", ".zip"}; } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonPageCreator.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonPageCreator.java index cec7e15..8c280bc 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonPageCreator.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonPageCreator.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -27,17 +27,18 @@ import java.util.Locale; /** * {@link PageCreator} that understands JNLP file. - * + * * @author Kohsuke Kawaguchi */ public class HudsonPageCreator extends DefaultPageCreator { + @Override public Page createPage(WebResponse webResponse, WebWindow webWindow) throws IOException { String contentType = webResponse.getContentType().toLowerCase(Locale.ENGLISH); - if(contentType.equals("application/x-java-jnlp-file")) + if (contentType.equals("application/x-java-jnlp-file")) { return createXmlPage(webResponse, webWindow); + } return super.createPage(webResponse, webWindow); } - public static final HudsonPageCreator INSTANCE = new HudsonPageCreator(); } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonTestCase.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonTestCase.java index fd80921..6f5dc9b 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonTestCase.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonTestCase.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi, Erik Ramfelt, Yahoo! Inc., Tom Huybrechts - * + * Contributors: + * + * Kohsuke Kawaguchi, Erik Ramfelt, Yahoo! Inc., Tom Huybrechts + * * *******************************************************************************/ @@ -154,12 +154,13 @@ import org.eclipse.hudson.security.HudsonSecurityManager; /** * Base class for all Hudson test cases. * - * @see <a href="http://wiki.hudson-ci.org/display/HUDSON/Unit+Test">Wiki article about unit testing in Hudson</a> + * @see <a href="http://wiki.hudson-ci.org/display/HUDSON/Unit+Test">Wiki + * article about unit testing in Hudson</a> * @author Kohsuke Kawaguchi */ public abstract class HudsonTestCase extends TestCase implements RootAction { - public Hudson hudson; + public Hudson hudson; protected final TestEnvironment env = new TestEnvironment(this); protected HudsonHomeLoader homeLoader = HudsonHomeLoader.NEW; /** @@ -167,48 +168,41 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { */ protected int localPort; protected Server server; - /** - * Where in the {@link Server} is Hudson deployed? - * <p> - * Just like {@link ServletContext#getContextPath()}, starts with '/' but doesn't end with '/'. + * Where in the {@link Server} is Hudson deployed? <p> Just like + * {@link ServletContext#getContextPath()}, starts with '/' but doesn't end + * with '/'. */ protected String contextPath = ""; - /** * {@link Runnable}s to be invoked at {@link #tearDown()}. */ protected List<LenientRunnable> tearDowns = new ArrayList<LenientRunnable>(); - protected List<Runner> recipes = new ArrayList<Runner>(); - /** * Remember {@link WebClient}s that are created, to release them properly. */ private List<WeakReference<WebClient>> clients = new ArrayList<WeakReference<WebClient>>(); - /** - * JavaScript "debugger" that provides you information about the JavaScript call stack - * and the current values of the local variables in those stack frame. + * JavaScript "debugger" that provides you information about the JavaScript + * call stack and the current values of the local variables in those stack + * frame. * - * <p> - * Unlike Java debugger, which you as a human interfaces directly and interactively, - * this JavaScript debugger is to be interfaced by your program (or through the - * expression evaluation capability of your Java debugger.) + * <p> Unlike Java debugger, which you as a human interfaces directly and + * interactively, this JavaScript debugger is to be interfaced by your + * program (or through the expression evaluation capability of your Java + * debugger.) */ protected JavaScriptDebugger jsDebugger = new JavaScriptDebugger(); - /** - * If this test case has additional {@link WithPlugin} annotations, set to true. - * This will cause a fresh {@link PluginManager} to be created for this test. - * Leaving this to false enables the test harness to use a pre-loaded plugin manager, - * which runs faster. + * If this test case has additional {@link WithPlugin} annotations, set to + * true. This will cause a fresh {@link PluginManager} to be created for + * this test. Leaving this to false enables the test harness to use a + * pre-loaded plugin manager, which runs faster. */ public boolean useLocalPluginManager = true; // FIXME: At the new smoothie container needs the real plugin manager - public ComputerConnectorTester computerConnectorTester = new ComputerConnectorTester(this); - protected HudsonTestCase(String name) { super(name); } @@ -220,8 +214,8 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { public void runBare() throws Throwable { // override the thread name to make the thread dump more useful. Thread t = Thread.currentThread(); - String o = getClass().getName()+'.'+t.getName(); - t.setName("Executing "+getName()); + String o = getClass().getName() + '.' + t.getName(); + t.setName("Executing " + getName()); try { super.runBare(); } finally { @@ -241,18 +235,18 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { SmoothieUtil.reset(); // force-reset, some tests may not properly hit the tear-down to reset so do it again here new SmoothieContainerBootstrap().bootstrap(getClass().getClassLoader(), Hudson.class, Smoothie.class, HudsonTestCase.class, getClass()); - + try { hudson = newHudson(); } catch (Exception e) { // if Hudson instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up. Field f = Hudson.class.getDeclaredField("theInstance"); f.setAccessible(true); - f.set(null,null); + f.set(null, null); throw e; } hudson.setNoUsageStatistics(true); // collecting usage stats from tests are pointless. - + hudson.setCrumbIssuer(new TestCrumbIssuer()); final WebAppController controller = WebAppController.get(); @@ -262,7 +256,7 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // handle tests which run several times inside the same JVM Field f = WebAppController.class.getDeclaredField("context"); f.setAccessible(true); - f.set(controller,hudson.servletContext); + f.set(controller, hudson.servletContext); } try { controller.setInstallStrategy(new DefaultInstallStrategy()); @@ -271,11 +265,11 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } controller.install(hudson); - hudson.servletContext.setAttribute("version","?"); + hudson.servletContext.setAttribute("version", "?"); HudsonServletContextListener.installExpressionFactory(new ServletContextEvent(hudson.servletContext)); // set a default JDK to be the one that the harness is using. - hudson.getJDKs().add(new JDK("default",System.getProperty("java.home"))); + hudson.getJDKs().add(new JDK("default", System.getProperty("java.home"))); configureUpdateCenter(); @@ -286,16 +280,17 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // cause all the descriptors to reload. // ideally we'd like to reset them to properly emulate the behavior, but that's not possible. Mailer.descriptor().setHudsonUrl(null); - for( Descriptor d : hudson.getExtensionList(Descriptor.class) ) + for (Descriptor d : hudson.getExtensionList(Descriptor.class)) { d.load(); + } } /** - * Configures the update center setting for the test. - * By default, we load updates from local proxy to avoid network traffic as much as possible. + * Configures the update center setting for the test. By default, we load + * updates from local proxy to avoid network traffic as much as possible. */ protected void configureUpdateCenter() throws Exception { - final String updateCenterUrl = "http://localhost:"+ JavaNetReverseProxy.getInstance().localPort+"/update-center.json"; + final String updateCenterUrl = "http://localhost:" + JavaNetReverseProxy.getInstance().localPort + "/update-center.json"; // don't waste bandwidth talking to the update center DownloadService.neverUpdate = true; @@ -312,13 +307,14 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // cancel pending asynchronous operations, although this doesn't really seem to be working for (WeakReference<WebClient> client : clients) { WebClient c = client.get(); - if(c==null) continue; + if (c == null) { + continue; + } // unload the page to cancel asynchronous operations c.getPage("about:blank"); } clients.clear(); - } - finally { + } finally { server.stop(); for (LenientRunnable r : tearDowns) { r.run(); @@ -350,8 +346,7 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try { super.runTest(); - } - finally { + } finally { System.out.println("<<< Finished " + testName + " <<<"); } } @@ -369,30 +364,31 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * Creates a new instance of {@link Hudson}. If the derived class wants to create it in a different way, - * you can override it. + * Creates a new instance of {@link Hudson}. If the derived class wants to + * create it in a different way, you can override it. */ protected Hudson newHudson() throws Exception { File home = homeLoader.allocate(); - + // Create the Security Manager HudsonSecurityEntitiesHolder.setHudsonSecurityManager(new HudsonSecurityManager(home)); - - for (Runner r : recipes) - r.decorateHome(this,home); + + for (Runner r : recipes) { + r.decorateHome(this, home); + } return new Hudson(home, createWebServer(), useLocalPluginManager ? null : TestPluginManager.INSTANCE); } /** - * Prepares a webapp hosting environment to get {@link ServletContext} implementation - * that we need for testing. + * Prepares a webapp hosting environment to get {@link ServletContext} + * implementation that we need for testing. */ protected ServletContext createWebServer() throws Exception { server = new Server(); WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath); context.setClassLoader(getClass().getClassLoader()); - context.setConfigurations(new Configuration[]{new WebXmlConfiguration(),new NoListenerConfiguration()}); + context.setConfigurations(new Configuration[]{new WebXmlConfiguration(), new NoListenerConfiguration()}); server.setHandler(context); context.setMimeTypes(MIME_TYPES); @@ -412,13 +408,13 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { protected UserRealm configureUserRealm() { HashUserRealm realm = new HashUserRealm(); realm.setName("default"); // this is the magic realm name to make it effective on everywhere - realm.put("alice","alice"); - realm.put("bob","bob"); - realm.put("charlie","charlie"); + realm.put("alice", "alice"); + realm.put("bob", "bob"); + realm.put("charlie", "charlie"); - realm.addUserToRole("alice","female"); - realm.addUserToRole("bob","male"); - realm.addUserToRole("charlie","male"); + realm.addUserToRole("alice", "female"); + realm.addUserToRole("bob", "male"); + realm.addUserToRole("charlie", "male"); return realm; } @@ -430,22 +426,22 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // // set the credential to access svn.dev.java.net // hudson.getDescriptorByType(SubversionSCM.DescriptorImpl.class).postCredential("https://svn.dev.java.net/svn/hudson/","guest","",null,new PrintWriter(new NullStream())); // } - /** - * Returns the older default Maven, while still allowing specification of other bundled Mavens. + * Returns the older default Maven, while still allowing specification of + * other bundled Mavens. */ protected MavenInstallation configureDefaultMaven() throws Exception { return configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_20); } - + protected MavenInstallation configureMaven3() throws Exception { MavenInstallation mvn = configureDefaultMaven("apache-maven-3.0.1", MavenInstallation.MAVEN_30); - - MavenInstallation m3 = new MavenInstallation("apache-maven-3.0.1",mvn.getHome(), NO_PROPERTIES); + + MavenInstallation m3 = new MavenInstallation("apache-maven-3.0.1", mvn.getHome(), NO_PROPERTIES); hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(m3); return m3; - } - + } + /** * Locates Maven2 and configure that as the only Maven in the system. */ @@ -453,16 +449,16 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // first if we are running inside Maven, pick that Maven, if it meets the criteria we require.. // does it exists in the buildDirectory see maven-junit-plugin systemProperties // buildDirectory -> ${project.build.directory} (so no reason to be null ;-) ) - String buildDirectory = System.getProperty( "buildDirectory", "./target/classes/" ); + String buildDirectory = System.getProperty("buildDirectory", "./target/classes/"); File mavenAlreadyInstalled = new File(buildDirectory, mavenVersion); if (mavenAlreadyInstalled.exists()) { - MavenInstallation mavenInstallation = new MavenInstallation("default",mavenAlreadyInstalled.getAbsolutePath(), NO_PROPERTIES); + MavenInstallation mavenInstallation = new MavenInstallation("default", mavenAlreadyInstalled.getAbsolutePath(), NO_PROPERTIES); hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(mavenInstallation); return mavenInstallation; } String home = System.getProperty("maven.home"); - if(home!=null) { - MavenInstallation mavenInstallation = new MavenInstallation("default",home, NO_PROPERTIES); + if (home != null) { + MavenInstallation mavenInstallation = new MavenInstallation("default", home, NO_PROPERTIES); if (mavenInstallation.meetsMavenReqVersion(createLocalLauncher(), mavenReqVersion)) { hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(mavenInstallation); return mavenInstallation; @@ -471,20 +467,21 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // otherwise extract the copy we have. // this happens when a test is invoked from an IDE, for example. - LOGGER.warning("Extracting a copy of Maven bundled in the test harness. " + - "To avoid a performance hit, set the system property 'maven.home' to point to a Maven2 installation."); + LOGGER.warning("Extracting a copy of Maven bundled in the test harness. " + + "To avoid a performance hit, set the system property 'maven.home' to point to a Maven2 installation."); FilePath mvn = hudson.getRootPath().createTempFile("maven", "zip"); mvn.copyFrom(HudsonTestCase.class.getClassLoader().getResource(mavenVersion + "-bin.zip")); - File mvnHome = new File(buildDirectory);//createTmpDir(); + File mvnHome = new File(buildDirectory);//createTmpDir(); mvn.unzip(new FilePath(mvnHome)); // TODO: switch to tar that preserves file permissions more easily - if(!Functions.isWindows()) - Util.chmod(new File(mvnHome,mavenVersion+"/bin/mvn"), 0755); + if (!Functions.isWindows()) { + Util.chmod(new File(mvnHome, mavenVersion + "/bin/mvn"), 0755); + } MavenInstallation mavenInstallation = new MavenInstallation("default", - new File(mvnHome,mavenVersion).getAbsolutePath(), NO_PROPERTIES); - hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(mavenInstallation); - return mavenInstallation; + new File(mvnHome, mavenVersion).getAbsolutePath(), NO_PROPERTIES); + hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(mavenInstallation); + return mavenInstallation; } /** @@ -495,32 +492,32 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { if (System.getenv("ANT_HOME") != null) { antInstallation = new AntInstallation("default", System.getenv("ANT_HOME"), NO_PROPERTIES); } else { - LOGGER.warning("Extracting a copy of Ant bundled in the test harness. " + - "To avoid a performance hit, set the environment variable ANT_HOME to point to an Ant installation."); + LOGGER.warning("Extracting a copy of Ant bundled in the test harness. " + + "To avoid a performance hit, set the environment variable ANT_HOME to point to an Ant installation."); FilePath ant = hudson.getRootPath().createTempFile("ant", "zip"); ant.copyFrom(HudsonTestCase.class.getClassLoader().getResource("apache-ant-1.8.1-bin.zip")); File antHome = createTmpDir(); ant.unzip(new FilePath(antHome)); // TODO: switch to tar that preserves file permissions more easily - if(!Functions.isWindows()) - Util.chmod(new File(antHome,"apache-ant-1.8.1/bin/ant"), 0755); + if (!Functions.isWindows()) { + Util.chmod(new File(antHome, "apache-ant-1.8.1/bin/ant"), 0755); + } - antInstallation = new AntInstallation("default", new File(antHome,"apache-ant-1.8.1").getAbsolutePath(),NO_PROPERTIES); + antInstallation = new AntInstallation("default", new File(antHome, "apache-ant-1.8.1").getAbsolutePath(), NO_PROPERTIES); } - hudson.getDescriptorByType(Ant.DescriptorImpl.class).setInstallations(antInstallation); - return antInstallation; + hudson.getDescriptorByType(Ant.DescriptorImpl.class).setInstallations(antInstallation); + return antInstallation; } // // Convenience methods // - protected FreeStyleProject createFreeStyleProject() throws IOException { return createFreeStyleProject(createUniqueProjectName()); } protected FreeStyleProject createFreeStyleProject(String name) throws IOException { - return hudson.createProject(FreeStyleProject.class,name); + return hudson.createProject(FreeStyleProject.class, name); } protected MatrixProject createMatrixProject() throws IOException { @@ -528,11 +525,11 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } protected MatrixProject createMatrixProject(String name) throws IOException { - return hudson.createProject(MatrixProject.class,name); + return hudson.createProject(MatrixProject.class, name); } protected String createUniqueProjectName() { - return "test"+hudson.getItems().size(); + return "test" + hudson.getItems().size(); } /** @@ -550,31 +547,33 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } public DumbSlave createSlave() throws Exception { - return createSlave("",null); + return createSlave("", null); } /** * Creates and launches a new slave on the local host. */ public DumbSlave createSlave(Label l) throws Exception { - return createSlave(l, null); + return createSlave(l, null); } /** - * Creates a test {@link SecurityRealm} that recognizes username==password as valid. + * Creates a test {@link SecurityRealm} that recognizes username==password + * as valid. */ public SecurityRealm createDummySecurityRealm() { return new AbstractPasswordBasedSecurityRealm() { @Override protected UserDetails authenticate(String username, String password) throws AuthenticationException { - if (username.equals(password)) + if (username.equals(password)) { return loadUserByUsername(username); + } throw new BadCredentialsException(username); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { - return new org.springframework.security.userdetails.User(username,"",true,true,true,true,new GrantedAuthority[]{AUTHENTICATED_AUTHORITY}); + return new org.springframework.security.userdetails.User(username, "", true, true, true, true, new GrantedAuthority[]{AUTHENTICATED_AUTHORITY}); } @Override @@ -585,19 +584,18 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * Returns the URL of the webapp top page. - * URL ends with '/'. + * Returns the URL of the webapp top page. URL ends with '/'. */ public URL getURL() throws IOException { - return new URL("http://localhost:"+localPort+contextPath+"/"); + return new URL("http://localhost:" + localPort + contextPath + "/"); } public DumbSlave createSlave(EnvVars env) throws Exception { - return createSlave("",env); + return createSlave("", env); } public DumbSlave createSlave(Label l, EnvVars env) throws Exception { - return createSlave(l==null ? null : l.getExpression(), env); + return createSlave(l == null ? null : l.getExpression(), env); } /** @@ -610,34 +608,34 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { int sz = hudson.getNodes().size(); DumbSlave slave = new DumbSlave("slave" + sz, "dummy", - createTmpDir().getPath(), "1", Mode.NORMAL, labels==null?"":labels, createComputerLauncher(env), RetentionStrategy.NOOP, Collections.EMPTY_LIST); - hudson.addNode(slave); - return slave; - } + createTmpDir().getPath(), "1", Mode.NORMAL, labels == null ? "" : labels, createComputerLauncher(env), RetentionStrategy.NOOP, Collections.EMPTY_LIST); + hudson.addNode(slave); + return slave; + } } public PretendSlave createPretendSlave(FakeLauncher faker) throws Exception { synchronized (hudson) { int sz = hudson.getNodes().size(); PretendSlave slave = new PretendSlave("slave" + sz, createTmpDir().getPath(), "", createComputerLauncher(null), faker); - hudson.addNode(slave); - return slave; + hudson.addNode(slave); + return slave; } } /** * Creates a {@link CommandLauncher} for launching a slave locally. * - * @param env - * Environment variables to add to the slave process. Can be null. + * @param env Environment variables to add to the slave process. Can be + * null. */ public CommandLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, MalformedURLException { int sz = hudson.getNodes().size(); return new CommandLauncher( String.format("\"%s/bin/java\" %s -jar \"%s\"", - System.getProperty("java.home"), - SLAVE_DEBUG_PORT>0 ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address="+(SLAVE_DEBUG_PORT+sz): "", - new File(hudson.getJnlpJars("slave.jar").getURL().toURI()).getAbsolutePath()), + System.getProperty("java.home"), + SLAVE_DEBUG_PORT > 0 ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=" + (SLAVE_DEBUG_PORT + sz) : "", + new File(hudson.getJnlpJars("slave.jar").getURL().toURI()).getAbsolutePath()), env); } @@ -648,7 +646,7 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { public DumbSlave createOnlineSlave() throws Exception { return createOnlineSlave(null); } - + /** * Create a new slave on the local host and wait for it to come onilne * before returning. @@ -664,12 +662,12 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { public DumbSlave createOnlineSlave(Label l, EnvVars env) throws Exception { final CountDownLatch latch = new CountDownLatch(1); ComputerListener waiter = new ComputerListener() { - @Override - public void onOnline(Computer C, TaskListener t) { - latch.countDown(); - unregister(); - } - }; + @Override + public void onOnline(Computer C, TaskListener t) { + latch.countDown(); + unregister(); + } + }; waiter.register(); DumbSlave s = createSlave(l, env); @@ -677,13 +675,13 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { return s; } - + /** - * Blocks until the ENTER key is hit. - * This is useful during debugging a test so that one can inspect the state of Hudson through the web browser. + * Blocks until the ENTER key is hit. This is useful during debugging a test + * so that one can inspect the state of Hudson through the web browser. */ public void interactiveBreak() throws Exception { - System.out.println("Hudson is running at http://localhost:"+localPort+"/"); + System.out.println("Hudson is running at http://localhost:" + localPort + "/"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } @@ -691,14 +689,13 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { * Returns the last item in the list. */ protected <T> T last(List<T> items) { - return items.get(items.size()-1); + return items.get(items.size() - 1); } /** - * Pauses the execution until ENTER is hit in the console. - * <p> - * This is often very useful so that you can interact with Hudson - * from an browser, while developing a test case. + * Pauses the execution until ENTER is hit in the console. <p> This is often + * very useful so that you can interact with Hudson from an browser, while + * developing a test case. */ protected void pause() throws IOException { new BufferedReader(new InputStreamReader(System.in)).readLine(); @@ -712,7 +709,8 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * Hits the Hudson system configuration and submits without any modification. + * Hits the Hudson system configuration and submits without any + * modification. */ protected void configRoundtrip() throws Exception { submit(createWebClient().goTo("configure").getFormByName("config")); @@ -720,12 +718,11 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { /** * Loads a configuration page and submits it without any modifications, to - * perform a round-trip configuration test. - * <p> - * See http://wiki.hudson-ci.org/display/HUDSON/Unit+Test#UnitTest-Configurationroundtriptesting + * perform a round-trip configuration test. <p> See + * http://wiki.hudson-ci.org/display/HUDSON/Unit+Test#UnitTest-Configurationroundtriptesting */ protected <P extends Job> P configRoundtrip(P job) throws Exception { - submit(createWebClient().getPage(job,"configure").getFormByName("config")); + submit(createWebClient().getPage(job, "configure").getFormByName("config")); return job; } @@ -733,7 +730,6 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // submit(createWebClient().getPage(job,"configure").getFormByName("config")); // return job; // } - /** * Performs a configuration round-trip testing for a builder. */ @@ -741,7 +737,7 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { FreeStyleProject p = createFreeStyleProject(); p.getBuildersList().add(before); configRoundtrip(p); - return (B)p.getBuildersList().get(before.getClass()); + return (B) p.getBuildersList().get(before.getClass()); } /** @@ -751,36 +747,38 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { FreeStyleProject p = createFreeStyleProject(); p.getPublishersList().add(before); configRoundtrip(p); - return (P)p.getPublishersList().get(before.getClass()); + return (P) p.getPublishersList().get(before.getClass()); } protected <C extends ComputerConnector> C configRoundtrip(C before) throws Exception { computerConnectorTester.connector = before; submit(createWebClient().goTo("self/computerConnectorTester/configure").getFormByName("config")); - return (C)computerConnectorTester.connector; + return (C) computerConnectorTester.connector; } - /** * Asserts that the outcome of the build is a specific outcome. */ public <R extends Run> R assertBuildStatus(Result status, R r) throws Exception { - if(status==r.getResult()) + if (status == r.getResult()) { return r; + } // dump the build output in failure message String msg = "unexpected build status; build log was:\n------\n" + getLog(r) + "\n------\n"; - if(r instanceof MatrixBuild) { - MatrixBuild mb = (MatrixBuild)r; + if (r instanceof MatrixBuild) { + MatrixBuild mb = (MatrixBuild) r; for (MatrixRun mr : mb.getRuns()) { - msg+="--- "+mr.getParent().getCombination()+" ---\n"+getLog(mr)+"\n------\n"; + msg += "--- " + mr.getParent().getCombination() + " ---\n" + getLog(mr) + "\n------\n"; } } - assertEquals(msg, status,r.getResult()); + assertEquals(msg, status, r.getResult()); return r; } - /** Determines whether the specifed HTTP status code is generally "good" */ + /** + * Determines whether the specifed HTTP status code is generally "good" + */ public boolean isGoodHttpStatus(int status) { if ((400 <= status) && (status <= 417)) { return false; @@ -791,17 +789,18 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { return true; } - /** Assert that the specifed page can be served with a "good" HTTP status, - * eg, the page is not missing and can be served without a server error + /** + * Assert that the specifed page can be served with a "good" HTTP status, + * eg, the page is not missing and can be served without a server error + * * @param page */ public void assertGoodStatus(Page page) { assertTrue(isGoodHttpStatus(page.getWebResponse().getStatusCode())); } - public <R extends Run> R assertBuildStatusSuccess(R r) throws Exception { - assertBuildStatus(Result.SUCCESS,r); + assertBuildStatus(Result.SUCCESS, r); return r; } @@ -810,32 +809,34 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { return assertBuildStatusSuccess(r.get()); } - public <J extends AbstractProject<J,R>,R extends AbstractBuild<J,R>> R buildAndAssertSuccess(J job) throws Exception { + public <J extends AbstractProject<J, R>, R extends AbstractBuild<J, R>> R buildAndAssertSuccess(J job) throws Exception { return assertBuildStatusSuccess(job.scheduleBuild2(0)); } /** - * Avoids need for cumbersome {@code this.<J,R>buildAndAssertSuccess(...)} type hints under JDK 7 javac (and supposedly also IntelliJ). + * Avoids need for cumbersome {@code this.<J,R>buildAndAssertSuccess(...)} + * type hints under JDK 7 javac (and supposedly also IntelliJ). */ public FreeStyleBuild buildAndAssertSuccess(FreeStyleProject job) throws Exception { return assertBuildStatusSuccess(job.scheduleBuild2(0)); } /** - * Asserts that the console output of the build contains the given substring. + * Asserts that the console output of the build contains the given + * substring. */ public void assertLogContains(String substring, Run run) throws Exception { String log = getLog(run); - if(log.contains(substring)) + if (log.contains(substring)) { return; // good! - + } System.out.println(log); - fail("Console output of "+run+" didn't contain "+substring); + fail("Console output of " + run + " didn't contain " + substring); } /** - * Get entire log file (this method is deprecated in hudson.model.Run, - * but in tests it is OK to load entire log). + * Get entire log file (this method is deprecated in hudson.model.Run, but + * in tests it is OK to load entire log). */ protected static String getLog(Run run) throws IOException { return Util.loadFile(run.getLogFile(), run.getCharset()); @@ -845,19 +846,21 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { * Asserts that the XPath matches. */ public void assertXPath(HtmlPage page, String xpath) { - assertNotNull("There should be an object that matches XPath:"+xpath, + assertNotNull("There should be an object that matches XPath:" + xpath, page.getDocumentElement().selectSingleNode(xpath)); } - /** Asserts that the XPath matches the contents of a DomNode page. This - * variant of assertXPath(HtmlPage page, String xpath) allows us to - * examine XmlPages. + /** + * Asserts that the XPath matches the contents of a DomNode page. This + * variant of assertXPath(HtmlPage page, String xpath) allows us to examine + * XmlPages. + * * @param page * @param xpath */ public void assertXPath(DomNode page, String xpath) { List< ? extends Object> nodes = page.getByXPath(xpath); - assertFalse("There should be an object that matches XPath:"+xpath, nodes.isEmpty()); + assertFalse("There should be an object that matches XPath:" + xpath, nodes.isEmpty()); } public void assertXPathValue(DomNode page, String xpath, String expectedValue) { @@ -897,7 +900,6 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { assertTrue("needle found in haystack", found); } - public void assertStringContains(String message, String haystack, String needle) { if (haystack.contains(needle)) { // good @@ -917,12 +919,13 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * Asserts that help files exist for the specified properties of the given instance. + * Asserts that help files exist for the specified properties of the given + * instance. * - * @param type - * The describable class type that should have the associated help files. - * @param properties - * ','-separated list of properties whose help files should exist. + * @param type The describable class type that should have the associated + * help files. + * @param properties ','-separated list of properties whose help files + * should exist. */ public void assertHelpExists(final Class<? extends Describable> type, final String properties) throws Exception { executeOnServer(new Callable<Object>() { @@ -931,7 +934,7 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { WebClient wc = createWebClient(); for (String property : listProperties(properties)) { String url = d.getHelpFile(property); - assertNotNull("Help file for the property "+property+" is missing on "+type, url); + assertNotNull("Help file for the property " + property + " is missing on " + type, url); wc.goTo(url); // make sure it successfully loads } return null; @@ -940,8 +943,8 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * Tokenizes "foo,bar,zot,-bar" and returns "foo,zot" (the token that starts with '-' is handled as - * a cancellation. + * Tokenizes "foo,bar,zot,-bar" and returns "foo,zot" (the token that starts + * with '-' is handled as a cancellation. */ private List<String> listProperties(String properties) { List<String> props = new ArrayList<String>(Arrays.asList(properties.split(","))); @@ -957,22 +960,23 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { /** * Submits the form. * - * Plain {@link HtmlForm#submit()} doesn't work correctly due to the use of YUI in Hudson. + * Plain {@link HtmlForm#submit()} doesn't work correctly due to the use of + * YUI in Hudson. */ public HtmlPage submit(HtmlForm form) throws Exception { - return (HtmlPage)form.submit((HtmlButton)last(form.getHtmlElementsByTagName("button"))); + return (HtmlPage) form.submit((HtmlButton) last(form.getHtmlElementsByTagName("button"))); } /** * Submits the form by clikcing the submit button of the given name. * - * @param name - * This corresponds to the @name of <f:submit /> + * @param name This corresponds to the + * @name of <f:submit /> */ public HtmlPage submit(HtmlForm form, String name) throws Exception { - for( HtmlElement e : form.getHtmlElementsByTagName("button")) { - HtmlElement p = (HtmlElement)e.getParentNode().getParentNode(); - if(p.getAttribute("name").equals(name)) { + for (HtmlElement e : form.getHtmlElementsByTagName("button")) { + HtmlElement p = (HtmlElement) e.getParentNode().getParentNode(); + if (p.getAttribute("name").equals(name)) { // To make YUI event handling work, this combo seems to be necessary // the click will trigger _onClick in buton-*.js, but it doesn't submit the form // (a comment alluding to this behavior can be seen in submitForm method) @@ -981,21 +985,22 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // Just doing form.submit() doesn't work either, because it doesn't do // the preparation work needed to pass along the name of the button that // triggered a submission (more concretely, m_oSubmitTrigger is not set.) - ((HtmlButton)e).click(); - return (HtmlPage)form.submit((HtmlButton)e); + ((HtmlButton) e).click(); + return (HtmlPage) form.submit((HtmlButton) e); } } - throw new AssertionError("No such submit button with the name "+name); + throw new AssertionError("No such submit button with the name " + name); } protected HtmlInput findPreviousInputElement(HtmlElement current, String name) { - return (HtmlInput)current.selectSingleNode("(preceding::input[@name='_."+name+"'])[last()]"); + return (HtmlInput) current.selectSingleNode("(preceding::input[@name='_." + name + "'])[last()]"); } protected HtmlButton getButtonByCaption(HtmlForm f, String s) { for (HtmlElement b : f.getHtmlElementsByTagName("button")) { - if(b.getTextContent().trim().equals(s)) - return (HtmlButton)b; + if (b.getTextContent().trim().equals(s)) { + return (HtmlButton) b; + } } return null; } @@ -1008,42 +1013,40 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * Asserts that two JavaBeans are equal as far as the given list of properties are concerned. + * Asserts that two JavaBeans are equal as far as the given list of + * properties are concerned. * - * <p> - * This method takes two objects that have properties (getXyz, isXyz, or just the public xyz field), - * and makes sure that the property values for each given property are equals (by using {@link #assertEquals(Object, Object)}) + * <p> This method takes two objects that have properties (getXyz, isXyz, or + * just the public xyz field), and makes sure that the property values for + * each given property are equals (by using + * {@link #assertEquals(Object, Object)}) * - * <p> - * Property values can be null on both objects, and that is OK, but passing in a property that doesn't - * exist will fail an assertion. + * <p> Property values can be null on both objects, and that is OK, but + * passing in a property that doesn't exist will fail an assertion. * - * <p> - * This method is very convenient for comparing a large number of properties on two objects, - * for example to verify that the configuration is identical after a config screen roundtrip. + * <p> This method is very convenient for comparing a large number of + * properties on two objects, for example to verify that the configuration + * is identical after a config screen roundtrip. * - * @param lhs - * One of the two objects to be compared. - * @param rhs - * The other object to be compared - * @param properties - * ','-separated list of property names that are compared. + * @param lhs One of the two objects to be compared. + * @param rhs The other object to be compared + * @param properties ','-separated list of property names that are compared. * @since 1.297 */ public void assertEqualBeans(Object lhs, Object rhs, String properties) throws Exception { - assertNotNull("lhs is null",lhs); - assertNotNull("rhs is null",rhs); + assertNotNull("lhs is null", lhs); + assertNotNull("rhs is null", rhs); for (String p : properties.split(",")) { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(lhs, p); - Object lp,rp; - if(pd==null) { + Object lp, rp; + if (pd == null) { // field? try { Field f = lhs.getClass().getField(p); lp = f.get(lhs); rp = f.get(rhs); } catch (NoSuchFieldException e) { - assertNotNull("No such property "+p+" on "+lhs.getClass(),pd); + assertNotNull("No such property " + p + " on " + lhs.getClass(), pd); return; } } else { @@ -1051,75 +1054,83 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { rp = PropertyUtils.getProperty(rhs, p); } - if (lp!=null && rp!=null && lp.getClass().isArray() && rp.getClass().isArray()) { + if (lp != null && rp != null && lp.getClass().isArray() && rp.getClass().isArray()) { // deep array equality comparison int m = Array.getLength(lp); int n = Array.getLength(rp); - assertEquals("Array length is different for property "+p, m,n); - for (int i=0; i<m; i++) - assertEquals(p+"["+i+"] is different", Array.get(lp,i),Array.get(rp,i)); + assertEquals("Array length is different for property " + p, m, n); + for (int i = 0; i < m; i++) { + assertEquals(p + "[" + i + "] is different", Array.get(lp, i), Array.get(rp, i)); + } return; } - assertEquals("Property "+p+" is different",lp,rp); + assertEquals("Property " + p + " is different", lp, rp); } } /** - * Works like {@link #assertEqualBeans(Object, Object, String)} but figure out the properties - * via {@link DataBoundConstructor} + * Works like {@link #assertEqualBeans(Object, Object, String)} but figure + * out the properties via {@link DataBoundConstructor} */ public void assertEqualDataBoundBeans(Object lhs, Object rhs) throws Exception { - if (lhs==null && rhs==null) return; - if (lhs==null) fail("lhs is null while rhs="+rhs); - if (rhs==null) fail("rhs is null while lhs="+rhs); - + if (lhs == null && rhs == null) { + return; + } + if (lhs == null) { + fail("lhs is null while rhs=" + rhs); + } + if (rhs == null) { + fail("rhs is null while lhs=" + rhs); + } + Constructor<?> lc = findDataBoundConstructor(lhs.getClass()); Constructor<?> rc = findDataBoundConstructor(rhs.getClass()); - assertEquals("Data bound constructor mismatch. Different type?",lc,rc); + assertEquals("Data bound constructor mismatch. Different type?", lc, rc); List<String> primitiveProperties = new ArrayList<String>(); String[] names = ClassDescriptor.loadParameterNames(lc); Class<?>[] types = lc.getParameterTypes(); - assertEquals(names.length,types.length); - for (int i=0; i<types.length; i++) { + assertEquals(names.length, types.length); + for (int i = 0; i < types.length; i++) { Object lv = ReflectionUtils.getPublicProperty(lhs, names[i]); Object rv = ReflectionUtils.getPublicProperty(rhs, names[i]); if (Iterable.class.isAssignableFrom(types[i])) { Iterable lcol = (Iterable) lv; Iterable rcol = (Iterable) rv; - Iterator ltr,rtr; - for (ltr=lcol.iterator(), rtr=rcol.iterator(); ltr.hasNext() && rtr.hasNext();) { + Iterator ltr, rtr; + for (ltr = lcol.iterator(), rtr = rcol.iterator(); ltr.hasNext() && rtr.hasNext();) { Object litem = ltr.next(); Object ritem = rtr.next(); - if (findDataBoundConstructor(litem.getClass())!=null) { - assertEqualDataBoundBeans(litem,ritem); + if (findDataBoundConstructor(litem.getClass()) != null) { + assertEqualDataBoundBeans(litem, ritem); } else { - assertEquals(litem,ritem); + assertEquals(litem, ritem); } } - assertFalse("collection size mismatch between "+lhs+" and "+rhs, ltr.hasNext() ^ rtr.hasNext()); - } else - if (findDataBoundConstructor(types[i])!=null) { + assertFalse("collection size mismatch between " + lhs + " and " + rhs, ltr.hasNext() ^ rtr.hasNext()); + } else if (findDataBoundConstructor(types[i]) != null) { // recurse into nested databound objects - assertEqualDataBoundBeans(lv,rv); + assertEqualDataBoundBeans(lv, rv); } else { primitiveProperties.add(names[i]); } } // compare shallow primitive properties - if (!primitiveProperties.isEmpty()) - assertEqualBeans(lhs,rhs,Util.join(primitiveProperties,",")); + if (!primitiveProperties.isEmpty()) { + assertEqualBeans(lhs, rhs, Util.join(primitiveProperties, ",")); + } } private Constructor<?> findDataBoundConstructor(Class<?> c) { for (Constructor<?> m : c.getConstructors()) { - if (m.getAnnotation(DataBoundConstructor.class)!=null) + if (m.getAnnotation(DataBoundConstructor.class) != null) { return m; + } } return null; } @@ -1131,31 +1142,33 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { return hudson.getDescriptorByType(d); } - /** * Returns true if Hudson is building something or going to build something. */ protected boolean isSomethingHappening() { - if (!hudson.getQueue().isEmpty()) + if (!hudson.getQueue().isEmpty()) { return true; - for (Computer n : hudson.getComputers()) - if (!n.isIdle()) + } + for (Computer n : hudson.getComputers()) { + if (!n.isIdle()) { return true; + } + } return false; } /** - * Waits until Hudson finishes building everything, including those in the queue. - * <p> - * This method uses a default time out to prevent infinite hang in the automated test execution environment. + * Waits until Hudson finishes building everything, including those in the + * queue. <p> This method uses a default time out to prevent infinite hang + * in the automated test execution environment. */ protected void waitUntilNoActivity() throws Exception { - waitUntilNoActivityUpTo(60*1000); + waitUntilNoActivityUpTo(60 * 1000); } /** - * Waits until Hudson finishes building everything, including those in the queue, or fail the test - * if the specified timeout milliseconds is + * Waits until Hudson finishes building everything, including those in the + * queue, or fail the test if the specified timeout milliseconds is */ protected void waitUntilNoActivityUpTo(int timeout) throws Exception { long startTime = System.currentTimeMillis(); @@ -1163,20 +1176,24 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { while (true) { Thread.sleep(10); - if (isSomethingHappening()) - streak=0; - else + if (isSomethingHappening()) { + streak = 0; + } else { streak++; + } - if (streak>5) // the system is quiet for a while + if (streak > 5) // the system is quiet for a while + { return; + } - if (System.currentTimeMillis()-startTime > timeout) { + if (System.currentTimeMillis() - startTime > timeout) { List<Executable> building = new ArrayList<Executable>(); for (Computer c : hudson.getComputers()) { for (Executor e : c.getExecutors()) { - if (e.isBusy()) + if (e.isBusy()) { building.add(e.getCurrentExecutable()); + } } } throw new AssertionError(String.format("Hudson is still doing something after %dms: queue=%s building=%s", @@ -1185,36 +1202,35 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } } - - // // recipe methods. Control the test environments. // - /** * Called during the {@link #setUp()} to give a test case an opportunity to * control the test environment in which Hudson is run. * - * <p> - * One could override this method and call a series of {@code withXXX} methods, - * or you can use the annotations with {@link Recipe} meta-annotation. + * <p> One could override this method and call a series of {@code withXXX} + * methods, or you can use the annotations with {@link Recipe} + * meta-annotation. */ protected void recipe() throws Exception { recipeLoadCurrentPlugin(); // look for recipe meta-annotation try { - Method runMethod= getClass().getMethod(getName()); - for( final Annotation a : runMethod.getAnnotations() ) { + Method runMethod = getClass().getMethod(getName()); + for (final Annotation a : runMethod.getAnnotations()) { Recipe r = a.annotationType().getAnnotation(Recipe.class); - if(r==null) continue; + if (r == null) { + continue; + } final Runner runner = r.value().newInstance(); recipes.add(runner); tearDowns.add(new LenientRunnable() { public void run() throws Exception { - runner.tearDown(HudsonTestCase.this,a); + runner.tearDown(HudsonTestCase.this, a); } }); - runner.setup(this,a); + runner.setup(this, a); } } catch (NoSuchMethodException e) { // not a plain JUnit test. @@ -1222,17 +1238,18 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * If this test harness is launched for a Hudson plugin, locate the <tt>target/test-classes/the.hpl</tt> - * and add a recipe to install that to the new Hudson. + * If this test harness is launched for a Hudson plugin, locate the + * <tt>target/test-classes/the.hpl</tt> and add a recipe to install that to + * the new Hudson. * - * <p> - * This file is created by <tt>maven-hpi-plugin</tt> at the testCompile phase when the current - * packaging is <tt>hpi</tt>. + * <p> This file is created by <tt>maven-hpi-plugin</tt> at the testCompile + * phase when the current packaging is <tt>hpi</tt>. */ protected void recipeLoadCurrentPlugin() throws Exception { final Enumeration<URL> e = getClass().getClassLoader().getResources("the.hpl"); - if(!e.hasMoreElements()) return; // nope - + if (!e.hasMoreElements()) { + return; // nope + } final URL hpl = e.nextElement(); recipes.add(new Runner() { @@ -1244,9 +1261,10 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // make the plugin itself available Manifest m = new Manifest(hpl.openStream()); String shortName = m.getMainAttributes().getValue("Short-Name"); - if(shortName==null) - throw new Error(hpl+" doesn't have the Short-Name attribute"); - FileUtils.copyURLToFile(hpl,new File(home,"plugins/"+shortName+".hpl")); + if (shortName == null) { + throw new Error(hpl + " doesn't have the Short-Name attribute"); + } + FileUtils.copyURLToFile(hpl, new File(home, "plugins/" + shortName + ".hpl")); // make dependency plugins available // TODO: probably better to read POM, but where to read from? @@ -1257,21 +1275,21 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // For transitive dependencies, we could evaluate Plugin-Dependencies transitively. String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies"); - if(dependencies!=null) { + if (dependencies != null) { MavenEmbedder embedder = new MavenEmbedder(getClass().getClassLoader(), null); - for( String dep : dependencies.split(",")) { + for (String dep : dependencies.split(",")) { String[] tokens = dep.split(":"); String artifactId = tokens[0]; String version = tokens[1]; - File dependencyJar=null; + File dependencyJar = null; // need to search multiple group IDs // TODO: extend manifest to include groupID:artifactID:version - Exception resolutionError=null; - for (String groupId : new String[]{"org.jvnet.hudson.plugins","org.jvnet.hudson.main"}) { + Exception resolutionError = null; + for (String groupId : new String[]{"org.jvnet.hudson.plugins", "org.jvnet.hudson.main"}) { // first try to find it on the classpath. // this takes advantage of Maven POM located in POM - URL dependencyPomResource = getClass().getResource("/META-INF/maven/"+groupId+"/"+artifactId+"/pom.xml"); + URL dependencyPomResource = getClass().getResource("/META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml"); if (dependencyPomResource != null) { // found it dependencyJar = Which.jarFile(dependencyPomResource); @@ -1280,7 +1298,7 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { Artifact a; a = embedder.createArtifact(groupId, artifactId, version, "compile"/*doesn't matter*/, "hpi"); try { - embedder.resolve(a, Arrays.asList(embedder.createRepository("http://maven.glassfish.org/content/groups/public/","repo")),embedder.getLocalRepository()); + embedder.resolve(a, Arrays.asList(embedder.createRepository("http://maven.glassfish.org/content/groups/public/", "repo")), embedder.getLocalRepository()); dependencyJar = a.getFile(); } catch (AbstractArtifactResolutionException x) { // could be a wrong groupId @@ -1288,11 +1306,12 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } } } - if(dependencyJar==null) - throw new Exception("Failed to resolve plugin: "+dep,resolutionError); + if (dependencyJar == null) { + throw new Exception("Failed to resolve plugin: " + dep, resolutionError); + } File dst = new File(home, "plugins/" + artifactId + ".hpi"); - if(!dst.exists() || dst.lastModified()!=dependencyJar.lastModified()) { + if (!dst.exists() || dst.lastModified() != dependencyJar.lastModified()) { FileUtils.copyFile(dependencyJar, dst); } } @@ -1311,14 +1330,17 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } /** - * Declares that this test case expects to start with one of the preset data sets. - * See https://svn.dev.java.net/svn/hudson/trunk/hudson/main/test/src/main/preset-data/ + * Declares that this test case expects to start with one of the preset data + * sets. See + * https://svn.dev.java.net/svn/hudson/trunk/hudson/main/test/src/main/preset-data/ * for available datasets and what they mean. */ public HudsonTestCase withPresetData(String name) { name = "/" + name + ".zip"; URL res = getClass().getResource(name); - if(res==null) throw new IllegalArgumentException("No such data set found: "+name); + if (res == null) { + throw new IllegalArgumentException("No such data set found: " + name); + } return with(new CopyExisting(res)); } @@ -1328,27 +1350,24 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { return this; } - /** - * Executes the given closure on the server, by the servlet request handling thread, - * in the context of an HTTP request. + * Executes the given closure on the server, by the servlet request handling + * thread, in the context of an HTTP request. * - * <p> - * In {@link HudsonTestCase}, a thread that's executing the test code is different from the thread - * that carries out HTTP requests made through {@link WebClient}. But sometimes you want to - * make assertions and other calls with side-effect from within the request handling thread. + * <p> In {@link HudsonTestCase}, a thread that's executing the test code is + * different from the thread that carries out HTTP requests made through + * {@link WebClient}. But sometimes you want to make assertions and other + * calls with side-effect from within the request handling thread. * - * <p> - * This method allows you to do just that. It is useful for testing some methods that - * require {@link StaplerRequest} and {@link StaplerResponse}, or getting the credential - * of the current user (via {@link Hudson#getAuthentication()}, and so on. + * <p> This method allows you to do just that. It is useful for testing some + * methods that require {@link StaplerRequest} and {@link StaplerResponse}, + * or getting the credential of the current user (via + * {@link Hudson#getAuthentication()}, and so on. * - * @param c - * The closure to be executed on the server. - * @return - * The return value from the closure. - * @throws Exception - * If a closure throws any exception, that exception will be carried forward. + * @param c The closure to be executed on the server. + * @return The return value from the closure. + * @throws Exception If a closure throws any exception, that exception will + * be carried forward. */ public <V> V executeOnServer(final Callable<V> c) throws Exception { final Exception[] t = new Exception[1]; @@ -1356,7 +1375,7 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { ClosureExecuterAction cea = hudson.getExtensionList(RootAction.class).get(ClosureExecuterAction.class); UUID id = UUID.randomUUID(); - cea.add(id,new Runnable() { + cea.add(id, new Runnable() { public void run() { try { StaplerResponse rsp = Stapler.getCurrentResponse(); @@ -1368,33 +1387,37 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } } }); - createWebClient().goTo("closures/?uuid="+id); + createWebClient().goTo("closures/?uuid=" + id); - if (t[0]!=null) + if (t[0] != null) { throw t[0]; + } return r.get(0); } /** - * Sometimes a part of a test case may ends up creeping into the serialization tree of {@link Saveable#save()}, - * so detect that and flag that as an error. + * Sometimes a part of a test case may ends up creeping into the + * serialization tree of {@link Saveable#save()}, so detect that and flag + * that as an error. */ private Object writeReplace() { - throw new AssertionError("HudsonTestCase "+getName()+" is not supposed to be serialized"); + throw new AssertionError("HudsonTestCase " + getName() + " is not supposed to be serialized"); } /** - * This is to assist Groovy test clients who are incapable of instantiating the inner classes properly. + * This is to assist Groovy test clients who are incapable of instantiating + * the inner classes properly. */ public WebClient createWebClient() { return new WebClient(); } - + /** - * Extends {@link com.gargoylesoftware.htmlunit.WebClient} and provide convenience methods - * for accessing Hudson. + * Extends {@link com.gargoylesoftware.htmlunit.WebClient} and provide + * convenience methods for accessing Hudson. */ public class WebClient extends com.gargoylesoftware.htmlunit.WebClient { + public WebClient() { // default is IE6, but this causes 'n.doScroll('left')' to fail in event-debug.js:1907 as HtmlUnit doesn't implement such a method, // so trying something else, until we discover another problem. @@ -1414,18 +1437,21 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { final ErrorHandler defaultHandler = new DefaultCssErrorHandler(); public void warning(CSSParseException exception) throws CSSException { - if (!ignore(exception)) + if (!ignore(exception)) { defaultHandler.warning(exception); + } } public void error(CSSParseException exception) throws CSSException { - if (!ignore(exception)) + if (!ignore(exception)) { defaultHandler.error(exception); + } } public void fatalError(CSSParseException exception) throws CSSException { - if (!ignore(exception)) + if (!ignore(exception)) { defaultHandler.fatalError(exception); + } } private boolean ignore(CSSParseException e) { @@ -1437,8 +1463,9 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { // so as not to interfere with the 'Dim' class. getJavaScriptEngine().getContextFactory().addListener(new Listener() { public void contextCreated(Context cx) { - if (cx.getDebugger() == null) + if (cx.getDebugger() == null) { cx.setDebugger(jsDebugger, null); + } } public void contextReleased(Context cx) { @@ -1463,12 +1490,12 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { /** * Logs in to Hudson, by using the user name as the password. * - * <p> - * See {@link HudsonTestCase#configureUserRealm()} for how the container is set up with the user names - * and passwords. All the test accounts have the same user name and password. + * <p> See {@link HudsonTestCase#configureUserRealm()} for how the + * container is set up with the user names and passwords. All the test + * accounts have the same user name and password. */ public WebClient login(String username) throws Exception { - login(username,username); + login(username, username); return this; } @@ -1476,40 +1503,40 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { HtmlPage top = goTo(""); HtmlForm search = top.getFormByName("search"); search.getInputByName("q").setValueAttribute(q); - return (HtmlPage)search.submit(null); + return (HtmlPage) search.submit(null); } /** * Short for {@code getPage(r,"")}, to access the top page of a build. */ public HtmlPage getPage(Run r) throws IOException, SAXException { - return getPage(r,""); + return getPage(r, ""); } /** * Accesses a page inside {@link Run}. * - * @param relative - * Relative URL within the build URL, like "changes". Doesn't start with '/'. Can be empty. + * @param relative Relative URL within the build URL, like "changes". + * Doesn't start with '/'. Can be empty. */ public HtmlPage getPage(Run r, String relative) throws IOException, SAXException { - return goTo(r.getUrl()+relative); + return goTo(r.getUrl() + relative); } public HtmlPage getPage(Item item) throws IOException, SAXException { - return getPage(item,""); + return getPage(item, ""); } public HtmlPage getPage(Item item, String relative) throws IOException, SAXException { - return goTo(item.getUrl()+relative); + return goTo(item.getUrl() + relative); } public HtmlPage getPage(Node item) throws IOException, SAXException { - return getPage(item,""); + return getPage(item, ""); } public HtmlPage getPage(Node item, String relative) throws IOException, SAXException { - return goTo(item.toComputer().getUrl()+relative); + return goTo(item.toComputer().getUrl() + relative); } public HtmlPage getPage(View view) throws IOException, SAXException { @@ -1517,15 +1544,15 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { } public HtmlPage getPage(View view, String relative) throws IOException, SAXException { - return goTo(view.getUrl()+relative); + return goTo(view.getUrl() + relative); } /** - * @deprecated - * This method expects a full URL. This method is marked as deprecated to warn you - * that you probably should be using {@link #goTo(String)} method, which accepts - * a relative path within the Hudson being tested. (IOW, if you really need to hit - * a website on the internet, there's nothing wrong with using this method.) + * @deprecated This method expects a full URL. This method is marked as + * deprecated to warn you that you probably should be using + * {@link #goTo(String)} method, which accepts a relative path within + * the Hudson being tested. (IOW, if you really need to hit a website on + * the internet, there's nothing wrong with using this method.) */ @Override public Page getPage(String url) throws IOException, FailingHttpStatusCodeException { @@ -1535,98 +1562,102 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { /** * Requests a page within Hudson. * - * @param relative - * Relative path within Hudson. Starts without '/'. - * For example, "job/test/" to go to a job top page. + * @param relative Relative path within Hudson. Starts without '/'. For + * example, "job/test/" to go to a job top page. */ public HtmlPage goTo(String relative) throws IOException, SAXException { Page p = goTo(relative, "text/html"); if (p instanceof HtmlPage) { return (HtmlPage) p; } else { - throw new AssertionError("Expected text/html but instead the content type was "+p.getWebResponse().getContentType()); + throw new AssertionError("Expected text/html but instead the content type was " + p.getWebResponse().getContentType()); } } public Page goTo(String relative, String expectedContentType) throws IOException, SAXException { Page p = super.getPage(getContextPath() + relative); - assertEquals(expectedContentType,p.getWebResponse().getContentType()); + assertEquals(expectedContentType, p.getWebResponse().getContentType()); return p; } - /** Loads a page as XML. Useful for testing Hudson's xml api, in concert with - * assertXPath(DomNode page, String xpath) - * @param path the path part of the url to visit - * @return the XmlPage found at that url + /** + * Loads a page as XML. Useful for testing Hudson's xml api, in concert + * with assertXPath(DomNode page, String xpath) + * + * @param path the path part of the url to visit + * @return the XmlPage found at that url * @throws IOException * @throws SAXException */ public XmlPage goToXml(String path) throws IOException, SAXException { Page page = goTo(path, "application/xml"); - if (page instanceof XmlPage) + if (page instanceof XmlPage) { return (XmlPage) page; - else + } else { return null; + } } - /** - * Returns the URL of the webapp top page. - * URL ends with '/'. + * Returns the URL of the webapp top page. URL ends with '/'. */ public String getContextPath() throws IOException { return getURL().toExternalForm(); } - + /** * Adds a security crumb to the quest */ public WebRequestSettings addCrumb(WebRequestSettings req) { - NameValuePair crumb[] = { new NameValuePair() }; - + NameValuePair crumb[] = {new NameValuePair()}; + crumb[0].setName(hudson.getCrumbIssuer().getDescriptor().getCrumbRequestField()); - crumb[0].setValue(hudson.getCrumbIssuer().getCrumb( null )); - - req.setRequestParameters(Arrays.asList( crumb )); + crumb[0].setValue(hudson.getCrumbIssuer().getCrumb(null)); + + req.setRequestParameters(Arrays.asList(crumb)); return req; } - + /** - * Creates a URL with crumb parameters relative to {{@link #getContextPath()} + * Creates a URL with crumb parameters relative to + * {{@link #getContextPath()} */ public URL createCrumbedUrl(String relativePath) throws IOException { CrumbIssuer issuer = hudson.getCrumbIssuer(); String crumbName = issuer.getDescriptor().getCrumbRequestField(); String crumb = issuer.getCrumb(null); - - return new URL(getContextPath()+relativePath+"?"+crumbName+"="+crumb); + + return new URL(getContextPath() + relativePath + "?" + crumbName + "=" + crumb); } /** - * Makes an HTTP request, process it with the given request handler, and returns the response. + * Makes an HTTP request, process it with the given request handler, and + * returns the response. */ public HtmlPage eval(final Runnable requestHandler) throws IOException, SAXException { ClosureExecuterAction cea = hudson.getExtensionList(RootAction.class).get(ClosureExecuterAction.class); UUID id = UUID.randomUUID(); - cea.add(id,requestHandler); - return goTo("closures/?uuid="+id); + cea.add(id, requestHandler); + return goTo("closures/?uuid=" + id); } /** - * Starts an interactive JavaScript debugger, and break at the next JavaScript execution. + * Starts an interactive JavaScript debugger, and break at the next + * JavaScript execution. * - * <p> - * This is useful during debugging a test so that you can step execute and inspect state of JavaScript. - * This will launch a Swing GUI, and the method returns immediately. + * <p> This is useful during debugging a test so that you can step + * execute and inspect state of JavaScript. This will launch a Swing + * GUI, and the method returns immediately. * - * <p> - * Note that installing a debugger appears to make an execution of JavaScript substantially slower. + * <p> Note that installing a debugger appears to make an execution of + * JavaScript substantially slower. * - * <p> - * TODO: because each script block evaluation in HtmlUnit is done in a separate Rhino context, - * if you step over from one script block, the debugger fails to kick in on the beginning of the next script block. - * This makes it difficult to set a break point on arbitrary script block in the HTML page. We need to fix this - * by tweaking {@link Dim.StackFrame#onLineChange(Context, int)}. + * <p> TODO: because each script block evaluation in HtmlUnit is done in + * a separate Rhino context, if you step over from one script block, the + * debugger fails to kick in on the beginning of the next script block. + * This makes it difficult to set a break point on arbitrary script + * block in the HTML page. We need to fix this by tweaking + * {@link Dim.StackFrame#onLineChange(Context, int)}. */ public Dim interactiveJavaScriptDebugger() { Global global = new Global(); @@ -1641,26 +1672,26 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { return dim; } } - // needs to keep reference, or it gets GC-ed. private static final Logger XML_HTTP_REQUEST_LOGGER = Logger.getLogger(XMLHttpRequest.class.getName()); - + static { // screen scraping relies on locale being fixed. Locale.setDefault(Locale.ENGLISH); {// enable debug assistance, since tests are often run from IDE Dispatcher.TRACE = true; - MetaClass.NO_CACHE=true; + MetaClass.NO_CACHE = true; // load resources from the source dir. File dir = new File("src/main/resources"); - if(dir.exists() && MetaClassLoader.debugLoader==null) + if (dir.exists() && MetaClassLoader.debugLoader == null) { try { MetaClassLoader.debugLoader = new MetaClassLoader( - new URLClassLoader(new URL[]{dir.toURI().toURL()})); + new URLClassLoader(new URL[]{dir.toURI().toURL()})); } catch (MalformedURLException e) { throw new AssertionError(e); } + } } // suppress INFO output from Spring, which is verbose @@ -1677,21 +1708,19 @@ public abstract class HudsonTestCase extends TestCase implements RootAction { }); // remove the upper bound of the POST data size in Jetty. - System.setProperty("org.mortbay.jetty.Request.maxFormContentSize","-1"); + System.setProperty("org.mortbay.jetty.Request.maxFormContentSize", "-1"); } - private static final Logger LOGGER = Logger.getLogger(HudsonTestCase.class.getName()); - protected static final List<ToolProperty<?>> NO_PROPERTIES = Collections.<ToolProperty<?>>emptyList(); - /** - * Specify this to a TCP/IP port number to have slaves started with the debugger. + * Specify this to a TCP/IP port number to have slaves started with the + * debugger. */ - public static int SLAVE_DEBUG_PORT = Integer.getInteger(HudsonTestCase.class.getName()+".slaveDebugPort",-1); - + public static int SLAVE_DEBUG_PORT = Integer.getInteger(HudsonTestCase.class.getName() + ".slaveDebugPort", -1); public static final MimeTypes MIME_TYPES = new MimeTypes(); + static { - MIME_TYPES.addMimeMapping("js","application/javascript"); + MIME_TYPES.addMimeMapping("js", "application/javascript"); Functions.DEBUG_YUI = true; // during the unit test, predictably releasing classloader is important to avoid diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JavaNetReverseProxy.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JavaNetReverseProxy.java index 212143c..0c1fc2f 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JavaNetReverseProxy.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JavaNetReverseProxy.java @@ -8,7 +8,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * + * * *******************************************************************************/ @@ -35,15 +35,14 @@ import java.net.URL; * Acts as a reverse proxy to https://hudson.java.net/ , so that during a test * we can avoid hitting java.net. * - * <p> - * The contents are cached locally. + * <p> The contents are cached locally. * * @author Kohsuke Kawaguchi */ public class JavaNetReverseProxy extends HttpServlet { + private final Server server; public final int localPort; - private final File cacheFolder; public JavaNetReverseProxy(File cacheFolder) throws Exception { @@ -86,39 +85,41 @@ public class JavaNetReverseProxy extends HttpServlet { // data.writeTo(rsp.getOutputStream()); // } // } - @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getServletPath(); String d = Util.getDigestOf(path); File cache = new File(cacheFolder, d); - if(!cache.exists()) { + if (!cache.exists()) { URL url = new URL("http://hudson-ci.org/" + path); - FileUtils.copyURLToFile(url,cache); + FileUtils.copyURLToFile(url, cache); } resp.setContentType(getMimeType(path)); - IOUtils.copy(cache,resp.getOutputStream()); + IOUtils.copy(cache, resp.getOutputStream()); } private String getMimeType(String path) { int idx = path.indexOf('?'); - if(idx>=0) - path = path.substring(0,idx); - if(path.endsWith(".json")) return "text/javascript"; + if (idx >= 0) { + path = path.substring(0, idx); + } + if (path.endsWith(".json")) { + return "text/javascript"; + } return getServletContext().getMimeType(path); } - private static volatile JavaNetReverseProxy INSTANCE; /** * Gets the default instance. */ public static synchronized JavaNetReverseProxy getInstance() throws Exception { - if(INSTANCE==null) - // TODO: think of a better location --- ideally inside the target/ dir so that clean would wipe them out - INSTANCE = new JavaNetReverseProxy(new File(new File(System.getProperty("java.io.tmpdir")),"hudson-ci.org-cache2")); + if (INSTANCE == null) // TODO: think of a better location --- ideally inside the target/ dir so that clean would wipe them out + { + INSTANCE = new JavaNetReverseProxy(new File(new File(System.getProperty("java.io.tmpdir")), "hudson-ci.org-cache2")); + } return INSTANCE; } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JellyTestSuiteBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JellyTestSuiteBuilder.java index 5ef99b5..438fc77 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JellyTestSuiteBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/JellyTestSuiteBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -35,14 +35,17 @@ import java.util.jar.JarEntry; import java.util.jar.JarFile; /** - * Builds up a {@link TestSuite} for performing static syntax checks on Jelly scripts. + * Builds up a {@link TestSuite} for performing static syntax checks on Jelly + * scripts. * * @author Kohsuke Kawaguchi */ public class JellyTestSuiteBuilder { + /** - * Given a jar file or a class file directory, recursively search all the Jelly files and build a {@link TestSuite} - * that performs static syntax checks. + * Given a jar file or a class file directory, recursively search all the + * Jelly files and build a {@link TestSuite} that performs static syntax + * checks. */ public static TestSuite build(File res) throws Exception { TestSuite ts = new JellyTestSuite(); @@ -50,17 +53,19 @@ public class JellyTestSuiteBuilder { final JellyClassLoaderTearOff jct = new MetaClassLoader(JellyTestSuiteBuilder.class.getClassLoader()).loadTearOff(JellyClassLoaderTearOff.class); if (res.isDirectory()) { - for (final File jelly : (Collection <File>)FileUtils.listFiles(res,new String[]{"jelly"},true)) + for (final File jelly : (Collection<File>) FileUtils.listFiles(res, new String[]{"jelly"}, true)) { ts.addTest(new JellyCheck(jelly.toURI().toURL(), jct)); + } } if (res.getName().endsWith(".jar")) { String jarUrl = res.toURI().toURL().toExternalForm(); JarFile jf = new JarFile(res); Enumeration<JarEntry> e = jf.entries(); while (e.hasMoreElements()) { - JarEntry ent = e.nextElement(); - if (ent.getName().endsWith(".jelly")) - ts.addTest(new JellyCheck(new URL("jar:"+jarUrl+"!/"+ent.getName()), jct)); + JarEntry ent = e.nextElement(); + if (ent.getName().endsWith(".jelly")) { + ts.addTest(new JellyCheck(new URL("jar:" + jarUrl + "!/" + ent.getName()), jct)); + } } jf.close(); } @@ -68,6 +73,7 @@ public class JellyTestSuiteBuilder { } private static class JellyCheck extends TestCase { + private final URL jelly; private final JellyClassLoaderTearOff jct; @@ -86,14 +92,16 @@ public class JellyTestSuiteBuilder { } /** - * Makes sure that <label for=...> is not used inside config.jelly nor global.jelly + * Makes sure that <label for=...> is not used inside config.jelly + * nor global.jelly */ private void checkLabelFor(Document dom) { if (isConfigJelly() || isGlobalJelly()) { - if (!dom.selectNodes("//label[@for]").isEmpty()) - throw new AssertionError("<label for=...> shouldn't be used because it doesn't work " + - "when the configuration item is repeated. Use <label class=\"attach-previous\"> " + - "to have your label attach to the previous DOM node instead."); + if (!dom.selectNodes("//label[@for]").isEmpty()) { + throw new AssertionError("<label for=...> shouldn't be used because it doesn't work " + + "when the configuration item is repeated. Use <label class=\"attach-previous\"> " + + "to have your label attach to the previous DOM node instead."); + } } } @@ -107,10 +115,13 @@ public class JellyTestSuiteBuilder { } /** - * Execute all the Jelly tests in a servlet request handling context. To do so, we reuse HudsonTestCase + * Execute all the Jelly tests in a servlet request handling context. To do + * so, we reuse HudsonTestCase */ private static final class JellyTestSuite extends GroupedTest { - HudsonTestCase h = new HudsonTestCase("Jelly test wrapper") {}; + + HudsonTestCase h = new HudsonTestCase("Jelly test wrapper") { + }; @Override protected void setUp() throws Exception { diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/LenientRunnable.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/LenientRunnable.java index ba05c5c..596a106 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/LenientRunnable.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/LenientRunnable.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -22,5 +22,6 @@ package org.jvnet.hudson.test; * @author Kohsuke Kawaguchi */ public interface LenientRunnable { + public void run() throws Exception; } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/MockBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/MockBuilder.java index 6207af9..c87f8f4 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/MockBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/MockBuilder.java @@ -8,7 +8,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * + * * *******************************************************************************/ @@ -33,6 +33,7 @@ import org.kohsuke.stapler.StaplerRequest; * @author Kohsuke Kawaguchi */ public class MockBuilder extends Builder { + public final Result result; public MockBuilder(Result result) { @@ -40,13 +41,14 @@ public class MockBuilder extends Builder { } public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { - listener.getLogger().println("Simulating a specific result code "+result); + listener.getLogger().println("Simulating a specific result code " + result); build.setResult(result); return true; } @Extension public static final class DescriptorImpl extends Descriptor<Builder> { + public Builder newInstance(StaplerRequest req, JSONObject data) { throw new UnsupportedOperationException(); } @@ -56,4 +58,3 @@ public class MockBuilder extends Builder { } } } - diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/NoListenerConfiguration.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/NoListenerConfiguration.java index ffe4934..140be74 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/NoListenerConfiguration.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/NoListenerConfiguration.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -26,13 +26,13 @@ import hudson.model.Hudson; /** * Kills off {@link ServletContextListener}s loaded from web.xml. * - * <p> - * This is so that the harness can create the {@link Hudson} object. - * with the home directory of our choice. + * <p> This is so that the harness can create the {@link Hudson} object. with + * the home directory of our choice. * * @author Kohsuke Kawaguchi */ final class NoListenerConfiguration implements Configuration { + private WebAppContext context; public void setWebAppContext(WebAppContext context) { diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PluginAutomaticTestBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PluginAutomaticTestBuilder.java index a36806b..91632ef 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PluginAutomaticTestBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PluginAutomaticTestBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -27,33 +27,34 @@ import java.util.Map; * @author Kohsuke Kawaguchi */ public class PluginAutomaticTestBuilder { + /** - * @param params - * Various information about the plugin that maven-hpi-plugin adds. - * As of 1.52, this includes the followings: + * @param params Various information about the plugin that maven-hpi-plugin + * adds. As of 1.52, this includes the followings: * - * basedir (String) : directory that contains pom.xml - * artifactId (String) : artifact ID of the plugin - * outputDirectory (String) : target/classes dir where class files and resources can be found - * testOutputDirectory (String) : target/test-classes. + * basedir (String) : directory that contains pom.xml artifactId (String) : + * artifact ID of the plugin outputDirectory (String) : target/classes dir + * where class files and resources can be found testOutputDirectory (String) + * : target/test-classes. */ - public static TestSuite build(Map<String,?> params) throws Exception { + public static TestSuite build(Map<String, ?> params) throws Exception { TestSuite suite = new TestSuite(); // automatic Jelly tests if (params.containsKey("outputDirectory") // shouldn't happen, but be defensive - || notSkipTests("JellyTest")) { - File outputDirectory = new File((String)params.get("outputDirectory")); + || notSkipTests("JellyTest")) { + File outputDirectory = new File((String) params.get("outputDirectory")); suite.addTest(JellyTestSuiteBuilder.build(outputDirectory)); } - + return suite; } /** - * Provides an escape hatch for plugin developers to skip auto-generated tests. + * Provides an escape hatch for plugin developers to skip auto-generated + * tests. */ private static boolean notSkipTests(String propertyName) { - return !Boolean.getBoolean("hpiTest.skip"+propertyName); + return !Boolean.getBoolean("hpiTest.skip" + propertyName); } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PretendSlave.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PretendSlave.java index 987b7f4..85f793b 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PretendSlave.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/PretendSlave.java @@ -8,7 +8,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * + * * *******************************************************************************/ @@ -32,26 +32,25 @@ import java.util.Collections; * Slave that pretends to fork processes. * * @author Kohsuke Kawaguchi - * @see HudsonTestCase#createPretendSlave(FakeLauncher) + * @see HudsonTestCase#createPretendSlave(FakeLauncher) */ public class PretendSlave extends Slave { - private transient FakeLauncher faker; + private transient FakeLauncher faker; /** * Number of processed that are launched. */ public int numLaunch; public PretendSlave(String name, String remoteFS, int numExecutors, Mode mode, String labelString, ComputerLauncher launcher, FakeLauncher faker) throws IOException, FormException { - super(name, "pretending a slave", remoteFS, String.valueOf(numExecutors), mode, labelString, launcher, RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList()); + super(name, "pretending a slave", remoteFS, String.valueOf(numExecutors), mode, labelString, launcher, RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList()); this.faker = faker; } public PretendSlave(String name, String remoteFS, String labelString, ComputerLauncher launcher, FakeLauncher faker) throws IOException, FormException { - this(name, remoteFS, 1, Mode.NORMAL, labelString, launcher, faker); + this(name, remoteFS, 1, Mode.NORMAL, labelString, launcher, faker); } - @Override public Launcher createLauncher(TaskListener listener) { return new LocalLauncher(listener) { @@ -60,7 +59,9 @@ public class PretendSlave extends Slave { numLaunch++; } Proc p = faker.onLaunch(starter); - if (p!=null) return p; + if (p != null) { + return p; + } return super.launch(starter); } }; @@ -68,6 +69,7 @@ public class PretendSlave extends Slave { @Extension public static final class DescriptorImpl extends SlaveDescriptor { + public String getDisplayName() { return "Test mock up slave"; } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SequenceLock.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SequenceLock.java index 4dcd4c8..157be4a 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SequenceLock.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SequenceLock.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -22,34 +22,37 @@ package org.jvnet.hudson.test; * @author Kohsuke Kawaguchi */ public class SequenceLock { + /** * Currently executing phase N. */ private int n; - /** * This thread is executing the phase */ private Thread t; - private boolean aborted; /** - * Blocks until all the previous phases are completed, and returns when the specified phase <i>i</i> is started. - * If the calling thread was executing an earlier phase, that phase is marked as completed. + * Blocks until all the previous phases are completed, and returns when the + * specified phase <i>i</i> is started. If the calling thread was executing + * an earlier phase, that phase is marked as completed. * - * @throws IllegalStateException - * if the sequential lock protocol is aborted, or the thread that owns the current phase has quit. + * @throws IllegalStateException if the sequential lock protocol is aborted, + * or the thread that owns the current phase has quit. */ public synchronized void phase(int i) throws InterruptedException { done(); // mark the previous phase done - while (i!=n) { - if (aborted) + while (i != n) { + if (aborted) { throw new IllegalStateException("SequenceLock aborted"); - if (t!=null && !t.isAlive()) - throw new IllegalStateException("Owner thread of the current phase has quit"+t); - if (i<n) - throw new IllegalStateException("Phase "+i+" is already completed"); + } + if (t != null && !t.isAlive()) { + throw new IllegalStateException("Owner thread of the current phase has quit" + t); + } + if (i < n) { + throw new IllegalStateException("Phase " + i + " is already completed"); + } wait(); } @@ -59,12 +62,11 @@ public class SequenceLock { /** * Marks the current phase completed that the calling thread was executing. * - * <p> - * This is only necessary when the thread exits the last phase, as {@link #phase(int)} call implies the - * {@link #done()} call. + * <p> This is only necessary when the thread exits the last phase, as + * {@link #phase(int)} call implies the {@link #done()} call. */ public synchronized void done() { - if (t==Thread.currentThread()) { + if (t == Thread.currentThread()) { // phase N done n++; t = null; @@ -73,13 +75,13 @@ public class SequenceLock { } /** - * Tell all the threads that this sequencing was aborted. - * Everyone waiting for future phases will receive an error. + * Tell all the threads that this sequencing was aborted. Everyone waiting + * for future phases will receive an error. * - * <p> - * Calling this method from the finally block prevents a dead lock if one of the participating thread - * aborts with an exception, as without the explicit abort operation, other threads will block forever - * for a phase that'll never come. + * <p> Calling this method from the finally block prevents a dead lock if + * one of the participating thread aborts with an exception, as without the + * explicit abort operation, other threads will block forever for a phase + * that'll never come. */ public synchronized void abort() { aborted = true; diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SingleFileSCM.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SingleFileSCM.java index 32973ca..6f14e4b 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SingleFileSCM.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SingleFileSCM.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi, Seiji Sogabe - * + * Contributors: + * + * Kohsuke Kawaguchi, Seiji Sogabe + * * *******************************************************************************/ @@ -37,6 +37,7 @@ import org.apache.commons.io.IOUtils; * @author Kohsuke Kawaguchi */ public class SingleFileSCM extends NullSCM { + private final String path; private final byte[] contents; @@ -51,7 +52,8 @@ public class SingleFileSCM extends NullSCM { } /** - * When a check out is requested, serve the contents of the URL and place it with the given path name. + * When a check out is requested, serve the contents of the URL and place it + * with the given path name. */ public SingleFileSCM(String path, URL resource) throws IOException { this.path = path; @@ -60,7 +62,7 @@ public class SingleFileSCM extends NullSCM { @Override public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changeLogFile) throws IOException, InterruptedException { - listener.getLogger().println("Staging "+path); + listener.getLogger().println("Staging " + path); OutputStream os = workspace.child(path).write(); IOUtils.write(contents, os); os.close(); @@ -68,7 +70,10 @@ public class SingleFileSCM extends NullSCM { } /** - * Don't write 'this', so that subtypes can be implemented as anonymous class. + * Don't write 'this', so that subtypes can be implemented as anonymous + * class. */ - private Object writeReplace() { return new Object(); } + private Object writeReplace() { + return new Object(); + } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SleepBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SleepBuilder.java index 827f40b..81041f8 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SleepBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/SleepBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -27,10 +27,11 @@ import java.io.IOException; /** * {@link Builder} that just sleeps for the specified amount of milli-seconds. - * + * * @author Kohsuke Kawaguchi */ public class SleepBuilder extends Builder { + public final long time; public SleepBuilder(long time) { @@ -38,13 +39,14 @@ public class SleepBuilder extends Builder { } public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { - listener.getLogger().println("Sleeping "+time+"ms"); + listener.getLogger().println("Sleeping " + time + "ms"); Thread.sleep(time); return true; } @Extension public static final class DescriptorImpl extends Descriptor<Builder> { + public String getDisplayName() { return "Sleep"; } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TemporaryDirectoryAllocator.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TemporaryDirectoryAllocator.java index a5486f4..1f6141d 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TemporaryDirectoryAllocator.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TemporaryDirectoryAllocator.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -26,14 +26,15 @@ import java.util.Set; /** * Allocates temporary directories and cleans it up at the end. + * * @author Kohsuke Kawaguchi */ public class TemporaryDirectoryAllocator { + /** * Remember allocated directories to delete them later. */ private final Set<File> tmpDirectories = new HashSet<File>(); - /** * Directory in which we allocate temporary directories. */ @@ -50,8 +51,8 @@ public class TemporaryDirectoryAllocator { /** * Allocates a new empty temporary directory and returns it. * - * This directory will be wiped out when {@link TemporaryDirectoryAllocator} gets disposed. - * When this method returns, the directory already exists. + * This directory will be wiped out when {@link TemporaryDirectoryAllocator} + * gets disposed. When this method returns, the directory already exists. */ public synchronized File allocate() throws IOException { try { @@ -61,7 +62,7 @@ public class TemporaryDirectoryAllocator { tmpDirectories.add(f); return f; } catch (IOException e) { - throw new IOException2("Failed to create a temporary directory in "+base,e); + throw new IOException2("Failed to create a temporary directory in " + base, e); } } @@ -70,12 +71,13 @@ public class TemporaryDirectoryAllocator { */ public synchronized void dispose() throws IOException, InterruptedException { IOException x = null; - for (File dir : tmpDirectories) + for (File dir : tmpDirectories) { try { new FilePath(dir).deleteRecursive(); } catch (IOException e) { e.printStackTrace(); } + } tmpDirectories.clear(); } @@ -86,9 +88,9 @@ public class TemporaryDirectoryAllocator { final Set<File> tbr = new HashSet<File>(tmpDirectories); tmpDirectories.clear(); - new Thread("Disposing "+base) { + new Thread("Disposing " + base) { public void run() { - for (File dir : tbr) + for (File dir : tbr) { try { new FilePath(dir).deleteRecursive(); } catch (IOException e) { @@ -96,6 +98,7 @@ public class TemporaryDirectoryAllocator { } catch (InterruptedException e) { e.printStackTrace(); } + } } }.start(); } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestBuilder.java index f996690..e967d48 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -25,11 +25,12 @@ import hudson.Launcher; import java.io.IOException; /** - * Partial {@link Builder} implementation for writing a one-off throw-away builder used during tests. + * Partial {@link Builder} implementation for writing a one-off throw-away + * builder used during tests. * - * <p> - * Because this builder tends to be written as an inner class, this builder doesn't write itself - * to a disk when persisted. Configuration screen won't work, either. + * <p> Because this builder tends to be written as an inner class, this builder + * doesn't write itself to a disk when persisted. Configuration screen won't + * work, either. * * @author Kohsuke Kawaguchi */ @@ -41,5 +42,7 @@ public abstract class TestBuilder extends Builder { throw new UnsupportedOperationException(); } - private Object writeReplace() { return new Object(); } + private Object writeReplace() { + return new Object(); + } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestCrumbIssuer.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestCrumbIssuer.java index 4660b31..c5ff676 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestCrumbIssuer.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestCrumbIssuer.java @@ -8,7 +8,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * + * * *******************************************************************************/ @@ -27,26 +27,25 @@ import hudson.security.csrf.CrumbIssuerDescriptor; /** * A crumb issuer that issues a constant crumb value. Used for unit testing. + * * @author dty */ -public class TestCrumbIssuer extends CrumbIssuer -{ +public class TestCrumbIssuer extends CrumbIssuer { + @Override - protected String issueCrumb( ServletRequest request, String salt ) - { + protected String issueCrumb(ServletRequest request, String salt) { return "test"; } @Override - public boolean validateCrumb( ServletRequest request, String salt, String crumb ) - { + public boolean validateCrumb(ServletRequest request, String salt, String crumb) { return "test".equals(crumb); } @Extension public static final class DescriptorImpl extends CrumbIssuerDescriptor<TestCrumbIssuer> implements ModelObject { - public DescriptorImpl() - { + + public DescriptorImpl() { super(null, null); load(); } @@ -55,10 +54,9 @@ public class TestCrumbIssuer extends CrumbIssuer public String getDisplayName() { return "Test Crumb"; } - + public TestCrumbIssuer newInstance(StaplerRequest req, JSONObject formData) throws FormException { return new TestCrumbIssuer(); } } - } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestEnvironment.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestEnvironment.java index e28db93..c86ef49 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestEnvironment.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestEnvironment.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -22,17 +22,17 @@ import hudson.model.Hudson; import java.io.IOException; /** - * TODO: deprecate this, and just consolidate this to {@link HudsonTestCase}. - * We can then pin down the current HudsonTestCase to the thread for easier access. + * TODO: deprecate this, and just consolidate this to {@link HudsonTestCase}. We + * can then pin down the current HudsonTestCase to the thread for easier access. * * @author Kohsuke Kawaguchi */ public class TestEnvironment { + /** * Current test case being run. */ public final HudsonTestCase testCase; - public final TemporaryDirectoryAllocator temporaryDirectoryAllocator = new TemporaryDirectoryAllocator(); public TestEnvironment(HudsonTestCase testCase) { @@ -47,15 +47,15 @@ public class TestEnvironment { temporaryDirectoryAllocator.dispose(); CURRENT = null; } - /** - * We used to use {@link InheritableThreadLocal} here, but it turns out this is not reliable, - * especially in the {@link Computer#threadPoolForRemoting}, where threads can inherit - * the wrong test environment depending on when it's created. + * We used to use {@link InheritableThreadLocal} here, but it turns out this + * is not reliable, especially in the + * {@link Computer#threadPoolForRemoting}, where threads can inherit the + * wrong test environment depending on when it's created. * - * <p> - * Since the rest of Hudson still relies on static {@link Hudson#theInstance}, changing this - * to a static field for now shouldn't cause any problem. + * <p> Since the rest of Hudson still relies on static + * {@link Hudson#theInstance}, changing this to a static field for now + * shouldn't cause any problem. */ private static TestEnvironment CURRENT; diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtension.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtension.java index 30969be..22811b0 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtension.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtension.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -27,11 +27,12 @@ import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** - * Works like {@link Extension} except used for inserting extensions during unit tests. + * Works like {@link Extension} except used for inserting extensions during unit + * tests. * - * <p> - * This annotation must be used on a method/field of a test case class, or an nested type of the test case. - * The extensions are activated only when the outer test class is being run. + * <p> This annotation must be used on a method/field of a test case class, or + * an nested type of the test case. The extensions are activated only when the + * outer test class is being run. * * @author Kohsuke Kawaguchi * @see TestExtensionLoader @@ -41,9 +42,11 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({TYPE, FIELD, METHOD}) @Documented public @interface TestExtension { + /** - * To make this extension only active for one test case, specify the test method name. - * Otherwise, leave it unspecified and it'll apply to all the test methods defined in the same class. + * To make this extension only active for one test case, specify the test + * method name. Otherwise, leave it unspecified and it'll apply to all the + * test methods defined in the same class. * * <h2>Example</h2> * <pre> diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtensionLoader.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtensionLoader.java index 4a2f79d..3f74ef8 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtensionLoader.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestExtensionLoader.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -39,6 +39,7 @@ import java.util.logging.Logger; */ @Extension public class TestExtensionLoader extends ExtensionFinder { + @Override public <T> Collection<ExtensionComponent<T>> find(Class<T> type, Hudson hudson) { TestEnvironment env = TestEnvironment.get(); @@ -46,39 +47,43 @@ public class TestExtensionLoader extends ExtensionFinder { List<ExtensionComponent<T>> result = new ArrayList<ExtensionComponent<T>>(); ClassLoader cl = hudson.getPluginManager().uberClassLoader; - for (IndexItem<TestExtension,Object> item : Index.load(TestExtension.class, Object.class, cl)) { + for (IndexItem<TestExtension, Object> item : Index.load(TestExtension.class, Object.class, cl)) { try { AnnotatedElement e = item.element(); Class<?> extType; if (e instanceof Class) { extType = (Class) e; - if (!isActive(env, extType)) continue; - } else - if (e instanceof Field) { + if (!isActive(env, extType)) { + continue; + } + } else if (e instanceof Field) { Field f = (Field) e; - if (!f.getDeclaringClass().isInstance(env.testCase)) + if (!f.getDeclaringClass().isInstance(env.testCase)) { continue; // not executing the enclosing test + } extType = f.getType(); - } else - if (e instanceof Method) { + } else if (e instanceof Method) { Method m = (Method) e; - if (!m.getDeclaringClass().isInstance(env.testCase)) + if (!m.getDeclaringClass().isInstance(env.testCase)) { continue; // not executing the enclosing test + } extType = m.getReturnType(); - } else + } else { throw new AssertionError(); + } String testName = item.annotation().value(); - if (testName.length()>0 && !env.testCase.getName().equals(testName)) + if (testName.length() > 0 && !env.testCase.getName().equals(testName)) { continue; // doesn't apply to this test - - if(type.isAssignableFrom(extType)) { + } + if (type.isAssignableFrom(extType)) { Object instance = item.instance(); - if(instance!=null) + if (instance != null) { result.add(new ExtensionComponent<T>(type.cast(instance))); + } } } catch (InstantiationException e) { - LOGGER.log(Level.WARNING, "Failed to load "+item.className(),e); + LOGGER.log(Level.WARNING, "Failed to load " + item.className(), e); } } @@ -86,11 +91,12 @@ public class TestExtensionLoader extends ExtensionFinder { } private boolean isActive(TestEnvironment env, Class<?> extType) { - for (Class<?> outer = extType; outer!=null; outer=outer.getEnclosingClass()) - if (outer.isInstance(env.testCase)) + for (Class<?> outer = extType; outer != null; outer = outer.getEnclosingClass()) { + if (outer.isInstance(env.testCase)) { return true; // enclosed + } + } return false; } - private static final Logger LOGGER = Logger.getLogger(TestExtensionLoader.class.getName()); } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestPluginManager.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestPluginManager.java index 755a713..2dd198f 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestPluginManager.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TestPluginManager.java @@ -7,9 +7,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * * - * * Kohsuke Kawaguchi * *******************************************************************************/ @@ -35,16 +35,17 @@ import java.util.logging.Logger; /** * {@link PluginManager} to speed up unit tests. * - * <p> - * Instead of loading every plugin for every test case, this allows them to reuse a single plugin manager. + * <p> Instead of loading every plugin for every test case, this allows them to + * reuse a single plugin manager. + * + * <p> TODO: {@link Plugin} start/stop/postInitialize invocation semantics gets + * different. Perhaps * - * <p> - * TODO: {@link Plugin} start/stop/postInitialize invocation semantics gets different. Perhaps - * * @author Kohsuke Kawaguchi * @see HudsonTestCase#useLocalPluginManager */ public class TestPluginManager extends PluginManager { + public static final PluginManager INSTANCE; private TestPluginManager() throws IOException { @@ -56,45 +57,47 @@ public class TestPluginManager extends PluginManager { protected Collection<String> loadBundledPlugins() throws Exception { Set<String> names = new HashSet<String>(); - File[] children = new File(WarExploder.getExplodedDir(),"WEB-INF/plugins").listFiles(); + File[] children = new File(WarExploder.getExplodedDir(), "WEB-INF/plugins").listFiles(); for (File child : children) { try { names.add(child.getName()); copyBundledPlugin(child.toURI().toURL(), child.getName()); } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Failed to extract the bundled plugin "+child,e); + LOGGER.log(Level.SEVERE, "Failed to extract the bundled plugin " + child, e); } } // If running tests for a plugin, include the plugin being tested URL u = getClass().getClassLoader().getResource("the.hpl"); - if (u!=null) try { - names.add("the.hpl"); - copyBundledPlugin(u, "the.hpl"); - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Failed to copy the.hpl",e); + if (u != null) { + try { + names.add("the.hpl"); + copyBundledPlugin(u, "the.hpl"); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Failed to copy the.hpl", e); + } } // and pick up test dependency *.hpi that are placed by maven-hpi-plugin TestDependencyMojo. // and copy them into $HUDSON_HOME/plugins. URL index = getClass().getResource("/test-dependencies/index"); - if (index!=null) {// if built with maven-hpi-plugin < 1.52 this file won't exist. - BufferedReader r = new BufferedReader(new InputStreamReader(index.openStream(),"UTF-8")); + if (index != null) {// if built with maven-hpi-plugin < 1.52 this file won't exist. + BufferedReader r = new BufferedReader(new InputStreamReader(index.openStream(), "UTF-8")); String line; - while ((line=r.readLine())!=null) { + while ((line = r.readLine()) != null) { copyBundledPlugin(new URL(index, line + ".hpi"), line + ".hpi"); } } return names; } - + @Override public void stop() { - for (PluginWrapper p : activePlugins) + for (PluginWrapper p : activePlugins) { p.stop(); + } } - private static final Logger LOGGER = Logger.getLogger(TestPluginManager.class.getName()); static { diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TouchBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TouchBuilder.java index 92697d5..ed7643a 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TouchBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/TouchBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -26,13 +26,14 @@ import java.io.IOException; import java.io.Serializable; public class TouchBuilder extends Builder implements Serializable { - @Override - public boolean perform(AbstractBuild<?, ?> build, - Launcher launcher, BuildListener listener) - throws InterruptedException, IOException { - for (FilePath f : build.getWorkspace().list()) { - f.touch(System.currentTimeMillis()); - } - return true; + + @Override + public boolean perform(AbstractBuild<?, ?> build, + Launcher launcher, BuildListener listener) + throws InterruptedException, IOException { + for (FilePath f : build.getWorkspace().list()) { + f.touch(System.currentTimeMillis()); } + return true; } +} diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/UnstableBuilder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/UnstableBuilder.java index 64bd3bc..3d96b43 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/UnstableBuilder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/UnstableBuilder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -34,7 +34,7 @@ import java.io.IOException; * @author Kohsuke Kawaguchi */ public class UnstableBuilder extends Builder { - + public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { listener.getLogger().println("Simulating an unstable build"); build.setResult(Result.UNSTABLE); @@ -43,9 +43,11 @@ public class UnstableBuilder extends Builder { @Extension public static final class DescriptorImpl extends Descriptor<Builder> { + public String getDisplayName() { return "Make build unstable"; } + public UnstableBuilder newInstance(StaplerRequest req, JSONObject data) { return new UnstableBuilder(); } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/WarExploder.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/WarExploder.java index 2e22ef3..5fb2e92 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/WarExploder.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/WarExploder.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi, Martin Eigenbrodt - * + * Contributors: + * + * Kohsuke Kawaguchi, Martin Eigenbrodt + * * *******************************************************************************/ @@ -27,9 +27,9 @@ import java.net.URL; /** * Ensures that <tt>hudson.war</tt> is exploded. * - * <p> - * Depending on where the test is run (for example, inside Maven vs IDE), this code attempts to - * use hudson.war from the right place, thereby improving the productivity. + * <p> Depending on where the test is run (for example, inside Maven vs IDE), + * this code attempts to use hudson.war from the right place, thereby improving + * the productivity. * * @author Kohsuke Kawaguchi */ @@ -39,10 +39,11 @@ final class WarExploder { // rethrow an exception every time someone tries to do this, so that when explode() // fails, you can see the cause no matter which test case you look at. // see http://www.nabble.com/Failing-tests-in-test-harness-module-on-hudson.ramfelt.se-td19258722.html - if(FAILURE !=null) throw new Exception("Failed to initialize exploded war", FAILURE); + if (FAILURE != null) { + throw new Exception("Failed to initialize exploded war", FAILURE); + } return EXPLODE_DIR; } - private static File EXPLODE_DIR; private static Exception FAILURE; @@ -68,11 +69,11 @@ final class WarExploder { return new File(d, "main/war/target/hudson"); } - for( ; d!=null; d=d.getParentFile()) { - if(new File(d,".hudson").exists()) { - File dir = new File(d,"war/target/hudson"); - if(dir.exists()) { - System.out.println("Using hudson.war resources from "+dir); + for (; d != null; d = d.getParentFile()) { + if (new File(d, ".hudson").exists()) { + File dir = new File(d, "war/target/hudson"); + if (dir.exists()) { + System.out.println("Using hudson.war resources from " + dir); return dir; } } @@ -82,18 +83,20 @@ final class WarExploder { File war = Which.jarFile(Class.forName("org.eclipse.hudson.war.Executable")); File explodeDir = new File("./target/hudson-for-test").getAbsoluteFile(); - File timestamp = new File(explodeDir,".timestamp"); + File timestamp = new File(explodeDir, ".timestamp"); - if(!timestamp.exists() || (timestamp.lastModified()!=war.lastModified())) { - System.out.println("Exploding hudson.war at "+war); + if (!timestamp.exists() || (timestamp.lastModified() != war.lastModified())) { + System.out.println("Exploding hudson.war at " + war); new FilePath(explodeDir).deleteRecursive(); new FilePath(war).unzip(new FilePath(explodeDir)); - if(!explodeDir.exists()) // this is supposed to be impossible, but I'm investigating HUDSON-2605 - throw new IOException("Failed to explode "+war); + if (!explodeDir.exists()) // this is supposed to be impossible, but I'm investigating HUDSON-2605 + { + throw new IOException("Failed to explode " + war); + } new FileOutputStream(timestamp).close(); timestamp.setLastModified(war.lastModified()); } else { - System.out.println("Picking up existing exploded hudson.war at "+explodeDir.getAbsolutePath()); + System.out.println("Picking up existing exploded hudson.war at " + explodeDir.getAbsolutePath()); } return explodeDir; diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/FailedTest.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/FailedTest.java index 00598ed..a963e5e 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/FailedTest.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/FailedTest.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -19,12 +19,13 @@ package org.jvnet.hudson.test.junit; import junit.framework.TestCase; /** - * {@link TestCase} implementation that has already failed. - * Used to represent a problem happened during a test suite construction. + * {@link TestCase} implementation that has already failed. Used to represent a + * problem happened during a test suite construction. * * @author Kohsuke Kawaguchi */ public class FailedTest extends TestCase { + /** * The failure. If null, the test will succeed, despite the class name. */ @@ -36,12 +37,13 @@ public class FailedTest extends TestCase { } public FailedTest(Class name, Throwable problem) { - this(name.getName(),problem); + this(name.getName(), problem); } @Override protected void runTest() throws Throwable { - if (problem!=null) + if (problem != null) { throw problem; + } } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/GroupedTest.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/GroupedTest.java index e611f51..34844c4 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/GroupedTest.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/junit/GroupedTest.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: + * Contributors: + * + * * - * - * * *******************************************************************************/ @@ -20,17 +20,18 @@ import junit.framework.TestSuite; import junit.framework.TestResult; /** - * {@link TestSuite} that requires some set up and tear down for executing nested tests. + * {@link TestSuite} that requires some set up and tear down for executing + * nested tests. * - * <p> - * The failure in the set up or tear down will be reported as a failure. + * <p> The failure in the set up or tear down will be reported as a failure. * * @author Kohsuke Kawaguchi */ public class GroupedTest extends TestSuite { + @Override public int countTestCases() { - return super.countTestCases()+1; + return super.countTestCases() + 1; } @Override @@ -43,10 +44,10 @@ public class GroupedTest extends TestSuite { tearDown(); } // everything went smoothly. report a successful test to make the ends meet - runTest(new FailedTest(getClass(),null),result); + runTest(new FailedTest(getClass(), null), result); } catch (Throwable e) { // something went wrong - runTest(new FailedTest(getClass(),e),result); + runTest(new FailedTest(getClass(), e), result); } } @@ -59,6 +60,7 @@ public class GroupedTest extends TestSuite { protected void setUp() throws Exception { } + protected void tearDown() throws Exception { } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/package-info.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/package-info.java index cc4c305..9683eea 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/package-info.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/package-info.java @@ -1,17 +1,18 @@ -/******************************************************************************* +/** + * ***************************************************************************** * * Copyright (c) 2004-2009 Oracle Corporation. * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at + * All rights reserved. This program and the accompanying materials are made + * available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * +* Kohsuke Kawaguchi * - *******************************************************************************/ - + * + ****************************************************************************** + */ package org.jvnet.hudson.test; diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/LocalData.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/LocalData.java index 04f1c81..355539d 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/LocalData.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/LocalData.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -28,35 +28,30 @@ import static java.lang.annotation.ElementType.METHOD; /** * Runs a test case with a data set local to test method or the test class. * - * <p> - * This recipe allows your test case to start with the preset <tt>HUDSON_HOME</tt> data loaded - * either from your test method or from the test class. + * <p> This recipe allows your test case to start with the preset + * <tt>HUDSON_HOME</tt> data loaded either from your test method or from the + * test class. * - * <p> - * For example, if the test method if <tt>org.acme.FooTest.testBar()</tt>, then - * you can have your test data in one of the following places in resources folder - * (typically <tt>src/test/resources</tt>): + * <p> For example, if the test method if <tt>org.acme.FooTest.testBar()</tt>, + * then you can have your test data in one of the following places in resources + * folder (typically <tt>src/test/resources</tt>): * - * <ol> - * <li> - * Under <tt>org/acme/FooTest/testBar</tt> directory (that is, you'll have - * <tt>org/acme/FooTest/testBar/config.xml</tt>), in the same layout as in the real <tt>HUDSON_HOME</tt> directory. - * <li> - * In <tt>org/acme/FooTest/testBar.zip</tt> as a zip file. - * <li> - * Under <tt>org/acme/FooTest</tt> directory (that is, you'll have - * <tt>org/acme/FooTest/config.xml</tt>), in the same layout as in the real <tt>HUDSON_HOME</tt> directory. - * <li> - * In <tt>org/acme/FooTest.zip</tt> as a zip file. - * </ol> + * <ol> <li> Under <tt>org/acme/FooTest/testBar</tt> directory (that is, you'll + * have <tt>org/acme/FooTest/testBar/config.xml</tt>), in the same layout as in + * the real <tt>HUDSON_HOME</tt> directory. <li> In + * <tt>org/acme/FooTest/testBar.zip</tt> as a zip file. <li> Under + * <tt>org/acme/FooTest</tt> directory (that is, you'll have + * <tt>org/acme/FooTest/config.xml</tt>), in the same layout as in the real + * <tt>HUDSON_HOME</tt> directory. <li> In <tt>org/acme/FooTest.zip</tt> as a + * zip file. </ol> * - * <p> - * Search is performed in this specific order. The fall back mechanism allows you to write - * one test class that interacts with different aspects of the same data set, by associating - * the dataset with a test class, or have a data set local to a specific test method. + * <p> Search is performed in this specific order. The fall back mechanism + * allows you to write one test class that interacts with different aspects of + * the same data set, by associating the dataset with a test class, or have a + * data set local to a specific test method. * - * <p> - * The choice of zip and directory depends on the nature of the test data, as well as the size of it. + * <p> The choice of zip and directory depends on the nature of the test data, + * as well as the size of it. * * @author Kohsuke Kawaguchi */ @@ -65,7 +60,9 @@ import static java.lang.annotation.ElementType.METHOD; @Target(METHOD) @Retention(RUNTIME) public @interface LocalData { + public class RunnerImpl extends Recipe.Runner<LocalData> { + public void setup(HudsonTestCase testCase, LocalData recipe) throws Exception { testCase.with(new Local(testCase.getClass().getMethod(testCase.getName()))); } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/PresetData.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/PresetData.java index f31233d..a865884 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/PresetData.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/PresetData.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -36,27 +36,29 @@ import java.util.Locale; @Target(METHOD) @Retention(RUNTIME) public @interface PresetData { + /** * One of the preset data to choose from. */ DataSet value(); public enum DataSet { + /** - * Secured Hudson that has no anonymous read access. - * Any logged in user can do anything. + * Secured Hudson that has no anonymous read access. Any logged in user + * can do anything. */ NO_ANONYMOUS_READACCESS, /** - * Secured Hudson where anonymous user is read-only, - * and any logged in user has a full access. + * Secured Hudson where anonymous user is read-only, and any logged in + * user has a full access. */ - ANONYMOUS_READONLY, - } + ANONYMOUS_READONLY,} public class RunnerImpl extends Recipe.Runner<PresetData> { + public void setup(HudsonTestCase testCase, PresetData recipe) { - testCase.withPresetData(recipe.value().name().toLowerCase(Locale.ENGLISH).replace('_','-')); + testCase.withPresetData(recipe.value().name().toLowerCase(Locale.ENGLISH).replace('_', '-')); } } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/Recipe.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/Recipe.java index ee4afc6..221366d 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/Recipe.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/Recipe.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -29,10 +29,9 @@ import java.io.File; import junit.framework.TestCase; import hudson.model.Hudson; - /** - * Meta-annotation for recipe annotations, which controls - * the test environment set up. + * Meta-annotation for recipe annotations, which controls the test environment + * set up. * * @author Kohsuke Kawaguchi */ @@ -40,35 +39,40 @@ import hudson.model.Hudson; @Documented @Target(ANNOTATION_TYPE) public @interface Recipe { + /** * Specifies the class that sets up the test environment. * - * <p> - * When a recipe annotation is placed on a test method, + * <p> When a recipe annotation is placed on a test method, */ Class<? extends Runner> value(); /** * The code that implements the recipe semantics. * - * @param <T> - * The recipe annotation associated with this runner. + * @param <T> The recipe annotation associated with this runner. */ public abstract class Runner<T extends Annotation> { + /** - * Called during {@link TestCase#setUp()} to prepare the test environment. + * Called during {@link TestCase#setUp()} to prepare the test + * environment. */ - public void setup(HudsonTestCase testCase, T recipe) throws Exception {} + public void setup(HudsonTestCase testCase, T recipe) throws Exception { + } /** - * Called right before {@link Hudson#Hudson(File, ServletContext)} is invoked - * to decorate the hudson home directory. + * Called right before {@link Hudson#Hudson(File, ServletContext)} is + * invoked to decorate the hudson home directory. */ - public void decorateHome(HudsonTestCase testCase, File home) throws Exception {} + public void decorateHome(HudsonTestCase testCase, File home) throws Exception { + } /** - * Called during {@link TestCase#tearDown()} to shut down the test environment. + * Called during {@link TestCase#tearDown()} to shut down the test + * environment. */ - public void tearDown(HudsonTestCase testCase, T recipe) throws Exception {} + public void tearDown(HudsonTestCase testCase, T recipe) throws Exception { + } } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/WithPlugin.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/WithPlugin.java index c38b09c..9a52b26 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/WithPlugin.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/WithPlugin.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -28,7 +28,7 @@ import java.lang.annotation.Target; import java.net.URL; /** - * Installs the specified plugin before launching Hudson. + * Installs the specified plugin before launching Hudson. * * @author Kohsuke Kawaguchi */ @@ -37,15 +37,18 @@ import java.net.URL; @Target(METHOD) @Retention(RUNTIME) public @interface WithPlugin { + /** * Name of the plugin. * - * For now, this has to be one of the plugins statically available in resources - * "/plugins/NAME". TODO: support retrieval through Maven repository. + * For now, this has to be one of the plugins statically available in + * resources "/plugins/NAME". TODO: support retrieval through Maven + * repository. */ String value(); public class RunnerImpl extends Recipe.Runner<WithPlugin> { + private WithPlugin a; @Override @@ -57,7 +60,7 @@ public @interface WithPlugin { @Override public void decorateHome(HudsonTestCase testCase, File home) throws Exception { URL res = getClass().getClassLoader().getResource("plugins/" + a.value()); - FileUtils.copyURLToFile(res,new File(home,"plugins/"+a.value())); + FileUtils.copyURLToFile(res, new File(home, "plugins/" + a.value())); } } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/package-info.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/package-info.java index 1f2ac48..a986ecd 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/package-info.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/recipes/package-info.java @@ -1,17 +1,18 @@ -/******************************************************************************* +/** + * ***************************************************************************** * * Copyright (c) 2004-2009 Oracle Corporation. * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at + * All rights reserved. This program and the accompanying materials are made + * available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * +* Kohsuke Kawaguchi * - *******************************************************************************/ - + * + ****************************************************************************** + */ package org.jvnet.hudson.test.recipes; diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/CallStackFrame.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/CallStackFrame.java index 87226c7..0865fb2 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/CallStackFrame.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/CallStackFrame.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -30,6 +30,7 @@ import java.util.TreeMap; * @author Kohsuke Kawaguchi */ public class CallStackFrame implements DebugFrame { + /** * {@link JavaScriptDebugger} that this stack frame lives in. */ @@ -38,7 +39,6 @@ public class CallStackFrame implements DebugFrame { * The function being executed. */ public final DebuggableScript fnOrScript; - private Scriptable activation; private Scriptable thisObj; private Object[] args; @@ -60,11 +60,12 @@ public class CallStackFrame implements DebugFrame { // can't simply call removeFirst, because due to tail call elimination, // intermediate frames can be dropped at any time // TODO: shouldn't it be suffice to just check the end? - for( int i=owner.callStack.size()-1; i>=0; i-- ) - if(owner.callStack.get(i)==this) { + for (int i = owner.callStack.size() - 1; i >= 0; i--) { + if (owner.callStack.get(i) == this) { owner.callStack.remove(i); break; } + } activation = null; thisObj = null; @@ -85,31 +86,34 @@ public class CallStackFrame implements DebugFrame { /** * In-scope variables. */ - public SortedMap<String,Object> getVariables() { - SortedMap<String,Object> r = new TreeMap<String,Object>(); - for( int i=fnOrScript.getParamAndVarCount()-1; i>=0; i-- ) { - String name =fnOrScript.getParamOrVarName(i); - r.put(name,activation.get(name,activation)); + public SortedMap<String, Object> getVariables() { + SortedMap<String, Object> r = new TreeMap<String, Object>(); + for (int i = fnOrScript.getParamAndVarCount() - 1; i >= 0; i--) { + String name = fnOrScript.getParamOrVarName(i); + r.put(name, activation.get(name, activation)); } return r; } /** - * Formats this call stack, arguments, and its local variables as a human readable string. + * Formats this call stack, arguments, and its local variables as a human + * readable string. */ public String toString() { StringBuilder buf = new StringBuilder(); buf.append(fnOrScript.getFunctionName()); buf.append('('); - for( int i=0; i<args.length; i++ ) { - if(i!=0) buf.append(','); + for (int i = 0; i < args.length; i++) { + if (i != 0) { + buf.append(','); + } buf.append(args[i]); } buf.append(')'); buf.append("\n at ").append(fnOrScript.getSourceName()).append('#').append(line); buf.append("\n variables=").append(getVariables()); - + return buf.toString(); } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/JavaScriptDebugger.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/JavaScriptDebugger.java index 34330a2..bdc3509 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/JavaScriptDebugger.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/JavaScriptDebugger.java @@ -7,10 +7,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * + * Kohsuke Kawaguchi + * * *******************************************************************************/ @@ -26,26 +26,25 @@ import java.util.List; import java.util.ArrayList; /** - * Monitors the execution of the JavaScript inside HtmlUnit, and provides debug information - * such as call stacks, variables, arguments, etc. + * Monitors the execution of the JavaScript inside HtmlUnit, and provides debug + * information such as call stacks, variables, arguments, etc. * - * <h2>Usage</h2> - * <p> - * When you set a break point in Java code that are directly/indirectly invoked through JavaScript, - * use {@link #toString()} to see the JavaScript stack trace (and variables at each stack frame.) - * This helps you see where the problem is. + * <h2>Usage</h2> <p> When you set a break point in Java code that are + * directly/indirectly invoked through JavaScript, use {@link #toString()} to + * see the JavaScript stack trace (and variables at each stack frame.) This + * helps you see where the problem is. * - * <p> - * TODO: add programmatic break point API, selective method invocation tracing, and - * allow arbitrary script evaluation in arbitrary stack frame. + * <p> TODO: add programmatic break point API, selective method invocation + * tracing, and allow arbitrary script evaluation in arbitrary stack frame. * * @author Kohsuke Kawaguchi * @see HudsonTestCase#jsDebugger */ public class JavaScriptDebugger implements Debugger { + /** - * Call stack as a list. The list grows at the end, so the first element in the list - * is the oldest stack frame. + * Call stack as a list. The list grows at the end, so the first element in + * the list is the oldest stack frame. */ public final List<CallStackFrame> callStack = new ArrayList<CallStackFrame>(); @@ -53,7 +52,7 @@ public class JavaScriptDebugger implements Debugger { } public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript) { - return new CallStackFrame(this,fnOrScript); + return new CallStackFrame(this, fnOrScript); } /** @@ -61,8 +60,9 @@ public class JavaScriptDebugger implements Debugger { */ public String toString() { StringBuilder buf = new StringBuilder(); - for( int i=callStack.size()-1; i>=0; i-- ) + for (int i = callStack.size() - 1; i >= 0; i--) { buf.append(callStack.get(i)).append('\n'); + } return buf.toString(); } } diff --git a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/package-info.java b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/package-info.java index a65027e..8592c12 100644 --- a/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/package-info.java +++ b/hudson-test-framework/src/main/java/org/jvnet/hudson/test/rhino/package-info.java @@ -1,17 +1,18 @@ -/******************************************************************************* +/** + * ***************************************************************************** * * Copyright (c) 2004-2009 Oracle Corporation. * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at + * All rights reserved. This program and the accompanying materials are made + * available under the terms of the Eclipse Public License v1.0 which + * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * Contributors: -* -* Kohsuke Kawaguchi - * + * Contributors: + * +* Kohsuke Kawaguchi * - *******************************************************************************/ - + * + ****************************************************************************** + */ package org.jvnet.hudson.test.rhino; |

