mirror of
https://github.com/jenkinsci/jenkins.git
synced 2026-11-17 22:12:25 +00:00
Merge branch 'master' of https://github.com/jenkinsci/jenkins
This commit is contained in:
commit
791bf56822
345 files changed
+6509
-5366
No files matched your search
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright 2015 Jesse Glick.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package org.jvnet.hudson.test;
|
||||
|
||||
import hudson.Extension;
|
||||
import hudson.console.AnnotatedLargeText;
|
||||
import hudson.console.LineTransformationOutputStream;
|
||||
import hudson.model.Run;
|
||||
import hudson.model.TaskListener;
|
||||
import hudson.model.listeners.RunListener;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.junit.rules.ExternalResource;
|
||||
|
||||
/**
|
||||
* Echoes build output to standard error as it arrives.
|
||||
* Usage: <pre>{@code @ClassRule public static BuildWatcher buildWatcher = new BuildWatcher();}</pre>
|
||||
* Should work in combination with {@link JenkinsRule} or {@link RestartableJenkinsRule}.
|
||||
* @see JenkinsRule#waitForCompletion
|
||||
* @see JenkinsRule#waitForMessage
|
||||
* @since 1.607
|
||||
*/
|
||||
public final class BuildWatcher extends ExternalResource {
|
||||
|
||||
private static boolean active;
|
||||
private static final Map<File,RunningBuild> builds = new ConcurrentHashMap<File,RunningBuild>();
|
||||
|
||||
private Thread thread;
|
||||
|
||||
@Override protected void before() throws Throwable {
|
||||
active = true;
|
||||
thread = new Thread("watching builds") {
|
||||
@Override public void run() {
|
||||
try {
|
||||
while (active) {
|
||||
for (RunningBuild build : builds.values()) {
|
||||
build.copy();
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
} catch (InterruptedException x) {
|
||||
// stopped
|
||||
}
|
||||
// last chance
|
||||
for (RunningBuild build : builds.values()) {
|
||||
build.copy();
|
||||
}
|
||||
}
|
||||
};
|
||||
thread.setDaemon(true);
|
||||
thread.start();
|
||||
}
|
||||
|
||||
@Override protected void after() {
|
||||
active = false;
|
||||
thread.interrupt();
|
||||
}
|
||||
|
||||
@Extension public static final class Listener extends RunListener<Run<?,?>> {
|
||||
|
||||
@Override public void onStarted(Run<?,?> r, TaskListener listener) {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
RunningBuild build = new RunningBuild(r);
|
||||
RunningBuild orig = builds.put(r.getLogFile(), build);
|
||||
if (orig != null) {
|
||||
System.err.println(r + " was started twice?!");
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onFinalized(Run<?,?> r) {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
RunningBuild build = builds.remove(r.getLogFile());
|
||||
if (build != null) {
|
||||
build.copy();
|
||||
} else {
|
||||
System.err.println(r + " was finalized but not started?!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final class RunningBuild {
|
||||
|
||||
private final AnnotatedLargeText<?> log;
|
||||
private final OutputStream sink;
|
||||
private long pos;
|
||||
|
||||
RunningBuild(Run<?,?> r) {
|
||||
log = r.getLogText();
|
||||
sink = new LogLinePrefixOutputFilter(System.err, "[" + r + "] ");
|
||||
}
|
||||
|
||||
synchronized void copy() {
|
||||
try {
|
||||
pos = log.writeLogTo(pos, sink);
|
||||
// Note that !log.isComplete() after the initial call to copy, even if the build is complete, because Run.getLogText never calls markComplete!
|
||||
// That is why Run.writeWholeLogTo calls getLogText repeatedly.
|
||||
// Even if it did call markComplete this might not work from RestartableJenkinsRule since you would have a different Run object after the restart.
|
||||
// Anyway we can just rely on onFinalized to let us know when to stop.
|
||||
} catch (FileNotFoundException x) {
|
||||
// build deleted or not started
|
||||
} catch (Exception x) {
|
||||
x.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Copied from WorkflowRun.
|
||||
private static final class LogLinePrefixOutputFilter extends LineTransformationOutputStream {
|
||||
|
||||
private final PrintStream logger;
|
||||
private final String prefix;
|
||||
|
||||
LogLinePrefixOutputFilter(PrintStream logger, String prefix) {
|
||||
this.logger = logger;
|
||||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
@Override protected void eol(byte[] b, int len) throws IOException {
|
||||
logger.append(prefix);
|
||||
logger.write(b, 0, len);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1148,6 +1148,33 @@ public class JenkinsRule implements TestRule, MethodRule, RootAction {
|
||||
return Util.loadFile(run.getLogFile(), run.getCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a build to complete.
|
||||
* Useful in conjunction with {@link BuildWatcher}.
|
||||
* @return the same build, once done
|
||||
* @since 1.607
|
||||
*/
|
||||
public <R extends Run<?,?>> R waitForCompletion(R r) throws InterruptedException {
|
||||
// Could be using com.jayway.awaitility:awaitility but it seems like overkill here.
|
||||
while (r.isBuilding()) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a build log to contain a specified string.
|
||||
* Useful in conjunction with {@link BuildWatcher}.
|
||||
* @return the same build, once it does
|
||||
* @since 1.607
|
||||
*/
|
||||
public <R extends Run<?,?>> R waitForMessage(String message, R r) throws IOException, InterruptedException {
|
||||
while (!getLog(r).contains(message)) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the XPath matches.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2015 Red Hat, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package org.jvnet.hudson.test;
|
||||
|
||||
import hudson.tasks.BuildStepDescriptor;
|
||||
import hudson.tasks.BuildStepMonitor;
|
||||
import hudson.tasks.Notifier;
|
||||
import hudson.tasks.Publisher;
|
||||
import hudson.model.AbstractProject;
|
||||
|
||||
/**
|
||||
* Partial {@link Notifier} implementation to facilitate notifier implementation for testing.
|
||||
*/
|
||||
public abstract class TestNotifier extends Notifier {
|
||||
|
||||
@Override
|
||||
public BuildStepDescriptor<Publisher> getDescriptor() {
|
||||
return new BuildStepDescriptor<Publisher>() {
|
||||
@Override
|
||||
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDisplayName() {
|
||||
return "Bogus";
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public BuildStepMonitor getRequiredMonitorService() {
|
||||
return BuildStepMonitor.NONE;
|
||||
}
|
||||
|
||||
private Object writeReplace() { return new Object(); }
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
/*
|
||||
* The MIT License
|
||||
*
|
||||
*
|
||||
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
|
||||
*
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -400,7 +400,6 @@ public class AbstractProjectTest extends HudsonTestCase {
|
||||
public void testQueueSuccessBehavior() {
|
||||
// prevent any builds to test the behaviour
|
||||
jenkins.numExecutors = 0;
|
||||
jenkins.updateComputerList(false);
|
||||
|
||||
def p = createFreeStyleProject()
|
||||
def f = p.scheduleBuild2(0)
|
||||
@@ -419,7 +418,6 @@ public class AbstractProjectTest extends HudsonTestCase {
|
||||
public void testQueueSuccessBehaviorOverHTTP() {
|
||||
// prevent any builds to test the behaviour
|
||||
jenkins.numExecutors = 0;
|
||||
jenkins.updateComputerList(false);
|
||||
|
||||
def p = createFreeStyleProject()
|
||||
def wc = createWebClient();
|
||||
|
||||
@@ -96,7 +96,7 @@ class SlaveTest {
|
||||
def d = j.jenkins.getDescriptorByType(DumbSlave.DescriptorImpl.class)
|
||||
assert d.doCheckRemoteFS("c:\\")==FormValidation.ok();
|
||||
assert d.doCheckRemoteFS("/tmp")==FormValidation.ok();
|
||||
assert d.doCheckRemoteFS("relative/path").kind==ERROR;
|
||||
assert d.doCheckRemoteFS("relative/path").kind==WARNING;
|
||||
assert d.doCheckRemoteFS("/net/foo/bar/zot").kind==WARNING;
|
||||
assert d.doCheckRemoteFS("\\\\machine\\folder\\foo").kind==WARNING;
|
||||
}
|
||||
|
||||
@@ -40,13 +40,13 @@ import org.jvnet.hudson.test.JenkinsRule;
|
||||
/**
|
||||
* Contains tests for {@link ProcStarter} class.
|
||||
* @author Oleg Nenashev <nenashev@synopsys.com>, Synopsys Inc.
|
||||
* @since TODO: define a version
|
||||
* @since 1.568
|
||||
*/
|
||||
public class ProcStarterTest {
|
||||
|
||||
@Rule
|
||||
public JenkinsRule rule = new JenkinsRule();
|
||||
|
||||
|
||||
@Test
|
||||
@Issue("JENKINS-20559")
|
||||
public void testNonInitializedEnvsNPE() throws Exception {
|
||||
@@ -92,7 +92,7 @@ public class ProcStarterTest {
|
||||
return new Environment() {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@Extension
|
||||
public static class DescriptorImpl extends TestWrapperDescriptor {
|
||||
}
|
||||
@@ -121,7 +121,7 @@ public class ProcStarterTest {
|
||||
return new Environment() {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@Extension
|
||||
public static class DescriptorImpl extends TestWrapperDescriptor {
|
||||
}
|
||||
|
||||
@@ -49,6 +49,14 @@ public class ApiTest {
|
||||
j.createWebClient().goTo("api/xml?xpath=/*[1]", "application/xml");
|
||||
}
|
||||
|
||||
@Issue("JENKINS-27607")
|
||||
@Test public void json() throws Exception {
|
||||
FreeStyleProject p = j.createFreeStyleProject("p");
|
||||
JenkinsRule.WebClient wc = j.createWebClient();
|
||||
assertEquals("{\"name\":\"p\"}", wc.goTo(p.getUrl() + "api/json?tree=name", "application/json").getWebResponse().getContentAsString());
|
||||
assertEquals("wrap({\"name\":\"p\"})", wc.goTo(p.getUrl() + "api/json?tree=name&jsonp=wrap", "application/javascript").getWebResponse().getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Issue("JENKINS-3267")
|
||||
public void wrappedZeroItems() throws Exception {
|
||||
|
||||
@@ -45,7 +45,7 @@ public class BuildExecutionTest {
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
p.getPublishersList().add(new BrokenPublisher());
|
||||
FreeStyleBuild b = r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
|
||||
r.assertLogContains("Post-build steps failed", b);
|
||||
r.assertLogContains(Messages.Build_post_build_steps_failed(), b);
|
||||
FilePath ws = r.jenkins.getWorkspaceFor(p);
|
||||
WorkspaceList.Lease lease = r.jenkins.toComputer().getWorkspaceList().allocate(ws);
|
||||
try {
|
||||
|
||||
@@ -24,14 +24,27 @@
|
||||
|
||||
package hudson.model;
|
||||
|
||||
import hudson.Launcher;
|
||||
import hudson.model.Descriptor.PropertyType;
|
||||
import hudson.tasks.BuildStepDescriptor;
|
||||
import hudson.tasks.Builder;
|
||||
import hudson.tasks.Shell;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import jenkins.model.Jenkins;
|
||||
import net.sf.json.JSONObject;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.TestExtension;
|
||||
import org.kohsuke.stapler.DataBoundConstructor;
|
||||
import org.kohsuke.stapler.StaplerRequest;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public class DescriptorTest {
|
||||
|
||||
public @Rule JenkinsRule rule = new JenkinsRule();
|
||||
@@ -51,4 +64,147 @@ public class DescriptorTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Issue("JENKINS-26781")
|
||||
@Test public void overriddenId() throws Exception {
|
||||
FreeStyleProject p = rule.createFreeStyleProject();
|
||||
p.getBuildersList().add(new BuilderImpl("builder-a"));
|
||||
rule.configRoundtrip(p);
|
||||
List<Builder> builders = p.getBuildersList();
|
||||
assertEquals(1, builders.size());
|
||||
assertEquals(BuilderImpl.class, builders.get(0).getClass());
|
||||
assertEquals("builder-a", ((BuilderImpl) builders.get(0)).id);
|
||||
rule.assertLogContains("running builder-a", rule.buildAndAssertSuccess(p));
|
||||
p.getBuildersList().replace(new BuilderImpl("builder-b"));
|
||||
rule.configRoundtrip(p);
|
||||
builders = p.getBuildersList();
|
||||
assertEquals(1, builders.size());
|
||||
assertEquals(BuilderImpl.class, builders.get(0).getClass());
|
||||
assertEquals("builder-b", ((BuilderImpl) builders.get(0)).id);
|
||||
rule.assertLogContains("running builder-b", rule.buildAndAssertSuccess(p));
|
||||
}
|
||||
private static final class BuilderImpl extends Builder {
|
||||
private final String id;
|
||||
BuilderImpl(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
@Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
listener.getLogger().println("running " + getDescriptor().getId());
|
||||
return true;
|
||||
}
|
||||
@Override public Descriptor<Builder> getDescriptor() {
|
||||
return (Descriptor<Builder>) Jenkins.getInstance().getDescriptorByName(id);
|
||||
}
|
||||
}
|
||||
private static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
|
||||
private final String id;
|
||||
DescriptorImpl(String id) {
|
||||
super(BuilderImpl.class);
|
||||
this.id = id;
|
||||
}
|
||||
@Override public String getId() {
|
||||
return id;
|
||||
}
|
||||
@Override public Builder newInstance(StaplerRequest req, JSONObject formData) throws Descriptor.FormException {
|
||||
return new BuilderImpl(id);
|
||||
}
|
||||
@Override public String getDisplayName() {
|
||||
return id;
|
||||
}
|
||||
@Override public boolean isApplicable(Class<? extends AbstractProject> jobType) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@TestExtension("overriddenId") public static final BuildStepDescriptor<Builder> builderA = new DescriptorImpl("builder-a");
|
||||
@TestExtension("overriddenId") public static final BuildStepDescriptor<Builder> builderB = new DescriptorImpl("builder-b");
|
||||
|
||||
@Issue("JENKINS-28110")
|
||||
@Test public void nestedDescribableOverridingId() throws Exception {
|
||||
FreeStyleProject p = rule.createFreeStyleProject("p");
|
||||
p.getBuildersList().add(new B1(Arrays.asList(new D1(), new D2())));
|
||||
rule.configRoundtrip(p);
|
||||
rule.assertLogContains("[D 1, D 2]", rule.buildAndAssertSuccess(p));
|
||||
}
|
||||
public static abstract class D extends AbstractDescribableImpl<D> {
|
||||
@Override public String toString() {return getDescriptor().getDisplayName();}
|
||||
}
|
||||
public static class D1 extends D {
|
||||
@DataBoundConstructor public D1() {}
|
||||
@TestExtension("nestedDescribableOverridingId") public static class DescriptorImpl extends Descriptor<D> {
|
||||
@Override public String getDisplayName() {return "D 1";}
|
||||
@Override public String getId() {return "D1-id";}
|
||||
}
|
||||
}
|
||||
public static class D2 extends D {
|
||||
@DataBoundConstructor public D2() {}
|
||||
@TestExtension("nestedDescribableOverridingId") public static class DescriptorImpl extends Descriptor<D> {
|
||||
@Override public String getDisplayName() {return "D 2";}
|
||||
@Override public String getId() {return "D2-id";}
|
||||
}
|
||||
}
|
||||
public static class B1 extends Builder {
|
||||
public final List<D> ds;
|
||||
@DataBoundConstructor public B1(List<D> ds) {
|
||||
this.ds = ds;
|
||||
}
|
||||
@Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
listener.getLogger().println(ds);
|
||||
return true;
|
||||
}
|
||||
@TestExtension("nestedDescribableOverridingId") public static class DescriptorImpl extends Descriptor<Builder> {
|
||||
@Override public String getDisplayName() {return "B1";}
|
||||
}
|
||||
}
|
||||
|
||||
@Ignore("never worked: TypePair.convertJSON looks for @DataBoundConstructor on D3 (Stapler does not grok Descriptor)")
|
||||
@Issue("JENKINS-28110")
|
||||
@Test public void nestedDescribableSharingClass() throws Exception {
|
||||
FreeStyleProject p = rule.createFreeStyleProject("p");
|
||||
p.getBuildersList().add(new B2(Arrays.asList(new D3("d3a"), new D3("d3b"))));
|
||||
rule.configRoundtrip(p);
|
||||
rule.assertLogContains("[d3a, d3b]", rule.buildAndAssertSuccess(p));
|
||||
}
|
||||
public static class D3 implements Describable<D3> {
|
||||
private final String id;
|
||||
D3(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
@Override public String toString() {
|
||||
return id;
|
||||
}
|
||||
@Override public Descriptor<D3> getDescriptor() {
|
||||
return Jenkins.getInstance().getDescriptorByName(id);
|
||||
}
|
||||
}
|
||||
public static class D3D extends Descriptor<D3> {
|
||||
private final String id;
|
||||
public D3D(String id) {
|
||||
super(D3.class);
|
||||
this.id = id;
|
||||
}
|
||||
@Override public String getId() {
|
||||
return id;
|
||||
}
|
||||
@Override public D3 newInstance(StaplerRequest req, JSONObject formData) throws Descriptor.FormException {
|
||||
return new D3(id);
|
||||
}
|
||||
@Override public String getDisplayName() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@TestExtension("nestedDescribableSharingClass") public static final Descriptor<D3> d3a = new D3D("d3a");
|
||||
@TestExtension("nestedDescribableSharingClass") public static final Descriptor<D3> d3b = new D3D("d3b");
|
||||
public static class B2 extends Builder {
|
||||
public final List<D3> ds;
|
||||
@DataBoundConstructor public B2(List<D3> ds) {
|
||||
this.ds = ds;
|
||||
}
|
||||
@Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
listener.getLogger().println(ds);
|
||||
return true;
|
||||
}
|
||||
@TestExtension("nestedDescribableSharingClass") public static class DescriptorImpl extends Descriptor<Builder> {
|
||||
@Override public String getDisplayName() {return "B2";}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -34,7 +34,6 @@ public class ExecutorTest {
|
||||
@Test
|
||||
public void yank() throws Exception {
|
||||
j.jenkins.setNumExecutors(1);
|
||||
j.jenkins.updateComputerList(true);
|
||||
Computer c = j.jenkins.toComputer();
|
||||
final Executor e = c.getExecutors().get(0);
|
||||
|
||||
@@ -59,7 +58,6 @@ public class ExecutorTest {
|
||||
@Issue("JENKINS-4756")
|
||||
public void whenAnExecutorIsYankedANewExecutorTakesItsPlace() throws Exception {
|
||||
j.jenkins.setNumExecutors(1);
|
||||
j.jenkins.updateComputerList(true);
|
||||
|
||||
Computer c = j.jenkins.toComputer();
|
||||
Executor e = getExecutorByNumber(c, 0);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package hudson.model;
|
||||
|
||||
import hudson.model.FreeStyleBuild;
|
||||
import hudson.model.FreeStyleProject;
|
||||
import hudson.model.Result;
|
||||
import hudson.model.utils.AbortExceptionPublisher;
|
||||
import hudson.model.utils.IOExceptionPublisher;
|
||||
import hudson.model.utils.ResultWriterPublisher;
|
||||
import hudson.model.utils.TrueFalsePublisher;
|
||||
import hudson.tasks.ArtifactArchiver;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Freestyle publishers statuses tests
|
||||
*
|
||||
* @author Kanstantsin Shautsou
|
||||
*/
|
||||
public class FreestyleJobPublisherTest {
|
||||
@Rule
|
||||
public JenkinsRule j = new JenkinsRule();
|
||||
|
||||
/**
|
||||
* Execute all publishers even one of publishers return false.
|
||||
*/
|
||||
@Issue("JENKINS-26964")
|
||||
@Test
|
||||
public void testFreestyleWithFalsePublisher() throws Exception {
|
||||
FreeStyleProject p = j.createFreeStyleProject();
|
||||
|
||||
p.getPublishersList().add(new TrueFalsePublisher(true)); // noop
|
||||
p.getPublishersList().add(new TrueFalsePublisher(false)); // FAIL build with false
|
||||
p.getPublishersList().add(new ResultWriterPublisher("result.txt")); // catch result to file
|
||||
final ArtifactArchiver artifactArchiver = new ArtifactArchiver("result.txt");
|
||||
artifactArchiver.setOnlyIfSuccessful(false);
|
||||
p.getPublishersList().add(artifactArchiver); // transfer file to build dir
|
||||
|
||||
FreeStyleBuild b = p.scheduleBuild2(0).get();
|
||||
assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE);
|
||||
File file = new File(b.getArtifactsDir(), "result.txt");
|
||||
assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists());
|
||||
assertTrue("Publisher, after publisher with return false status, must see FAILURE status",
|
||||
FileUtils.readFileToString(file).equals(Result.FAILURE.toString()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all publishers even one of them throws AbortException.
|
||||
*/
|
||||
@Issue("JENKINS-26964")
|
||||
@Test
|
||||
public void testFreestyleWithExceptionPublisher() throws Exception {
|
||||
FreeStyleProject p = j.createFreeStyleProject();
|
||||
|
||||
p.getPublishersList().add(new TrueFalsePublisher(true)); // noop
|
||||
p.getPublishersList().add(new AbortExceptionPublisher()); // FAIL build with AbortException
|
||||
p.getPublishersList().add(new ResultWriterPublisher("result.txt")); // catch result to file
|
||||
final ArtifactArchiver artifactArchiver = new ArtifactArchiver("result.txt");
|
||||
artifactArchiver.setOnlyIfSuccessful(false);
|
||||
p.getPublishersList().add(artifactArchiver); // transfer file to build dir
|
||||
|
||||
FreeStyleBuild b = p.scheduleBuild2(0).get();
|
||||
|
||||
assertEquals("Build must fail, because we used AbortExceptionPublisher", b.getResult(), Result.FAILURE);
|
||||
j.assertLogNotContains("\tat", b); // log must not contain stacktrace
|
||||
j.assertLogContains("Threw AbortException from publisher!", b); // log must contain exact error message
|
||||
File file = new File(b.getArtifactsDir(), "result.txt");
|
||||
assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists());
|
||||
assertTrue("Third publisher must see FAILURE status",
|
||||
FileUtils.readFileToString(file).equals(Result.FAILURE.toString()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all publishers even one of them throws any Exceptions.
|
||||
*/
|
||||
@Issue("JENKINS-26964")
|
||||
@Test
|
||||
public void testFreestyleWithIOExceptionPublisher() throws Exception {
|
||||
FreeStyleProject p = j.createFreeStyleProject();
|
||||
|
||||
p.getPublishersList().add(new TrueFalsePublisher(true)); // noop
|
||||
p.getPublishersList().add(new IOExceptionPublisher()); // fail with IOException
|
||||
p.getPublishersList().add(new ResultWriterPublisher("result.txt")); //catch result to file
|
||||
final ArtifactArchiver artifactArchiver = new ArtifactArchiver("result.txt");
|
||||
artifactArchiver.setOnlyIfSuccessful(false);
|
||||
p.getPublishersList().add(artifactArchiver); // transfer file to build dir
|
||||
|
||||
FreeStyleBuild b = p.scheduleBuild2(0).get();
|
||||
|
||||
assertEquals("Build must fail, because we used FalsePublisher", b.getResult(), Result.FAILURE);
|
||||
j.assertLogContains("\tat hudson.model.utils.IOExceptionPublisher", b); // log must contain stacktrace
|
||||
j.assertLogContains("Threw IOException from publisher!", b); // log must contain exact error message
|
||||
File file = new File(b.getArtifactsDir(), "result.txt");
|
||||
assertTrue("ArtifactArchiver is executed even prior publisher fails", file.exists());
|
||||
assertTrue("Third publisher must see FAILURE status",
|
||||
FileUtils.readFileToString(file).equals(Result.FAILURE.toString()));
|
||||
}
|
||||
}
|
||||
@@ -20,27 +20,27 @@ import org.jvnet.hudson.test.HudsonTestCase;
|
||||
|
||||
/**
|
||||
* Tests that getEnvironment() calls outside of builds are safe.
|
||||
*
|
||||
*
|
||||
* @author kutzi
|
||||
*/
|
||||
@Issue("JENKINS-11592")
|
||||
public class GetEnvironmentOutsideBuildTest extends HudsonTestCase {
|
||||
|
||||
private int oldExecNum;
|
||||
|
||||
|
||||
@Override
|
||||
protected void runTest() throws Throwable {
|
||||
// Disable tests
|
||||
|
||||
|
||||
// It's unfortunately not working, yet, as whenJenkinsMasterHasNoExecutors is not working as expected
|
||||
}
|
||||
|
||||
public void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
|
||||
this.oldExecNum = Jenkins.getInstance().getNumExecutors();
|
||||
}
|
||||
|
||||
|
||||
public void tearDown() throws Exception {
|
||||
restoreOldNumExecutors();
|
||||
super.tearDown();
|
||||
@@ -48,10 +48,9 @@ public class GetEnvironmentOutsideBuildTest extends HudsonTestCase {
|
||||
|
||||
private void restoreOldNumExecutors() throws IOException {
|
||||
Jenkins.getInstance().setNumExecutors(this.oldExecNum);
|
||||
Jenkins.getInstance().setNodes(Jenkins.getInstance().getNodes());
|
||||
assertNotNull(Jenkins.getInstance().toComputer());
|
||||
}
|
||||
|
||||
|
||||
private MavenModuleSet createSimpleMavenProject() throws Exception {
|
||||
MavenModuleSet project = createMavenProject();
|
||||
MavenInstallation mi = configureMaven3();
|
||||
@@ -61,36 +60,34 @@ public class GetEnvironmentOutsideBuildTest extends HudsonTestCase {
|
||||
project.setGoals("validate");
|
||||
return project;
|
||||
}
|
||||
|
||||
|
||||
private void whenJenkinsMasterHasNoExecutors() throws IOException {
|
||||
Jenkins.getInstance().setNumExecutors(0);
|
||||
// force update of nodes:
|
||||
Jenkins.getInstance().setNodes(Jenkins.getInstance().getNodes());
|
||||
assertNull(Jenkins.getInstance().toComputer());
|
||||
}
|
||||
|
||||
|
||||
public void testMaven() throws Exception {
|
||||
MavenModuleSet m = createSimpleMavenProject();
|
||||
|
||||
|
||||
assertGetEnvironmentCallOutsideBuildWorks(m);
|
||||
}
|
||||
|
||||
|
||||
public void testFreestyle() throws Exception {
|
||||
FreeStyleProject project = createFreeStyleProject();
|
||||
|
||||
|
||||
assertGetEnvironmentCallOutsideBuildWorks(project);
|
||||
}
|
||||
|
||||
|
||||
public void testMatrix() throws Exception {
|
||||
MatrixProject createMatrixProject = createMatrixProject();
|
||||
|
||||
|
||||
assertGetEnvironmentCallOutsideBuildWorks(createMatrixProject);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
private void assertGetEnvironmentCallOutsideBuildWorks(AbstractProject job) throws Exception {
|
||||
AbstractBuild build = buildAndAssertSuccess(job);
|
||||
|
||||
|
||||
assertGetEnvironmentWorks(build);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package hudson.model;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import hudson.model.Descriptor.FormException;
|
||||
import hudson.model.LoadStatistics.LoadStatisticsUpdater;
|
||||
import hudson.model.MultiStageTimeSeries.TimeScale;
|
||||
@@ -12,16 +10,21 @@ import hudson.model.queue.SubTask;
|
||||
import hudson.slaves.DumbSlave;
|
||||
import hudson.slaves.NodeProperty;
|
||||
import hudson.slaves.RetentionStrategy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.Bug;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.SleepBuilder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Test that a {@link Label}'s {@link LoadStatistics#queueLength} correctly
|
||||
@@ -103,11 +106,14 @@ public class LabelLoadStatisticsQueueLengthTest {
|
||||
|
||||
maintainQueueAndForceRunOfLoadStatisticsUpdater(project);
|
||||
|
||||
assertEquals("The job is still queued as often as it was scheduled.", 3, j
|
||||
.getInstance().getQueue().getItems(project).size());
|
||||
|
||||
|
||||
float labelQueueLength = label.loadStatistics.queueLength
|
||||
.getLatest(TimeScale.SEC10);
|
||||
assertTrue(
|
||||
"After LoadStatisticsUpdater runs, the queue length load statistic for the label is greater than 0.",
|
||||
labelQueueLength > 0f);
|
||||
assertThat("After LoadStatisticsUpdater runs, the queue length load statistic for the label is greater than 0.",
|
||||
labelQueueLength, greaterThan(0f));
|
||||
|
||||
// Assign an alternate label to the project and update the load stats.
|
||||
project.setAssignedLabel(altLabel);
|
||||
@@ -116,9 +122,9 @@ public class LabelLoadStatisticsQueueLengthTest {
|
||||
// Verify that the queue length load stat continues to reflect the labels assigned to the items in the queue.
|
||||
float labelQueueLengthNew = label.loadStatistics.queueLength
|
||||
.getLatest(TimeScale.SEC10);
|
||||
assertTrue(
|
||||
"After assigning an alternate label to the job, the queue length load statistic for the queued builds should not decrease.",
|
||||
labelQueueLengthNew >= labelQueueLength);
|
||||
assertThat("After assigning an alternate label to the job, the queue length load statistic for the "
|
||||
+ "queued builds should not decrease.",
|
||||
labelQueueLengthNew, greaterThan(labelQueueLength));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -25,9 +25,10 @@ package hudson.model;
|
||||
|
||||
import hudson.EnvVars;
|
||||
import hudson.FilePath;
|
||||
import hudson.maven.MavenModuleSet;
|
||||
import hudson.model.Node.Mode;
|
||||
import hudson.model.Queue.WaitingItem;
|
||||
import hudson.model.labels.LabelAtom;
|
||||
import hudson.model.labels.*;
|
||||
import hudson.model.queue.CauseOfBlockage;
|
||||
import hudson.security.ACL;
|
||||
import hudson.security.GlobalMatrixAuthorizationStrategy;
|
||||
@@ -40,20 +41,20 @@ import hudson.slaves.OfflineCause;
|
||||
import hudson.slaves.OfflineCause.ByCLI;
|
||||
import hudson.slaves.OfflineCause.UserCause;
|
||||
import hudson.util.TagCloud;
|
||||
import hudson.util.TagCloud.Entry;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.List;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import jenkins.model.Jenkins;
|
||||
import jenkins.security.QueueItemAuthenticatorConfiguration;
|
||||
import org.acegisecurity.context.SecurityContextHolder;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.RunLoadCounter;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.MockQueueItemAuthenticator;
|
||||
import org.jvnet.hudson.test.TestExtension;
|
||||
@@ -63,20 +64,20 @@ import org.jvnet.hudson.test.TestExtension;
|
||||
* @author Lucie Votypkova
|
||||
*/
|
||||
public class NodeTest {
|
||||
|
||||
|
||||
@Rule public JenkinsRule j = new JenkinsRule();
|
||||
public static boolean addDynamicLabel = false;
|
||||
public static boolean notTake = false;
|
||||
|
||||
|
||||
@Before
|
||||
public void before(){
|
||||
addDynamicLabel = false;
|
||||
notTake = false;
|
||||
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testSetTemporaryOfflineCause() throws Exception {
|
||||
public void testSetTemporaryOfflineCause() throws Exception {
|
||||
Node node = j.createOnlineSlave();
|
||||
FreeStyleProject project = j.createFreeStyleProject();
|
||||
project.setAssignedLabel(j.jenkins.getLabel(node.getDisplayName()));
|
||||
@@ -102,7 +103,7 @@ public class NodeTest {
|
||||
|
||||
computer.doToggleOffline("original message");
|
||||
cause = (UserCause) computer.getOfflineCause();
|
||||
assertEquals("Disconnected by someone@somewhere.com : original message", cause.toString());
|
||||
assertTrue(cause.toString(), cause.toString().matches("^.*?Disconnected by someone@somewhere.com : original message"));
|
||||
assertEquals(someone, cause.getUser());
|
||||
|
||||
final User root = User.get("root@localhost");
|
||||
@@ -110,7 +111,7 @@ public class NodeTest {
|
||||
|
||||
computer.doChangeOfflineCause("new message");
|
||||
cause = (UserCause) computer.getOfflineCause();
|
||||
assertEquals("Disconnected by root@localhost : new message", cause.toString());
|
||||
assertTrue(cause.toString(), cause.toString().matches("^.*?Disconnected by root@localhost : new message"));
|
||||
assertEquals(root, cause.getUser());
|
||||
|
||||
computer.doToggleOffline(null);
|
||||
@@ -125,7 +126,7 @@ public class NodeTest {
|
||||
project.setAssignedLabel(j.jenkins.getLabel("label1"));
|
||||
TagCloud<LabelAtom> cloud = node.getLabelCloud();
|
||||
for(int i =0; i< cloud.size(); i ++){
|
||||
Entry e = cloud.get(i);
|
||||
TagCloud.Entry e = cloud.get(i);
|
||||
if(e.item.equals(j.jenkins.getLabel("label1"))){
|
||||
assertEquals("Label label1 should have one tied project.", 1, e.weight, 0);
|
||||
}
|
||||
@@ -133,11 +134,11 @@ public class NodeTest {
|
||||
assertEquals("Label " + e.item + " should not have any tied project.", 0, e.weight, 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGetAssignedLabels() throws Exception {
|
||||
public void testGetAssignedLabels() throws Exception {
|
||||
Node node = j.createOnlineSlave();
|
||||
node.setLabelString("label1 label2");
|
||||
LabelAtom notContained = j.jenkins.getLabelAtom("notContained");
|
||||
@@ -145,10 +146,10 @@ public class NodeTest {
|
||||
assertTrue("Node should have label1.", node.getAssignedLabels().contains(j.jenkins.getLabelAtom("label1")));
|
||||
assertTrue("Node should have label2.", node.getAssignedLabels().contains(j.jenkins.getLabelAtom("label2")));
|
||||
assertTrue("Node should have dynamicly added dynamicLabel.", node.getAssignedLabels().contains(j.jenkins.getLabelAtom("dynamicLabel")));
|
||||
assertFalse("Node should not have label notContained.", node.getAssignedLabels().contains(notContained));
|
||||
assertFalse("Node should not have label notContained.", node.getAssignedLabels().contains(notContained));
|
||||
assertTrue("Node should have self label.", node.getAssignedLabels().contains(node.getSelfLabel()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCanTake() throws Exception {
|
||||
Node node = j.createOnlineSlave();
|
||||
@@ -175,7 +176,7 @@ public class NodeTest {
|
||||
assertNotNull("Node should not take project because node property not alow it.", node.canTake(item));
|
||||
assertTrue("Cause of blockage should be bussy label.", node.canTake(item) instanceof CauseOfBlockage.BecauseLabelIsBusy);
|
||||
User user = User.get("John");
|
||||
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
|
||||
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
|
||||
j.jenkins.setAuthorizationStrategy(auth);
|
||||
j.jenkins.setCrumbIssuer(null);
|
||||
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
|
||||
@@ -187,7 +188,7 @@ public class NodeTest {
|
||||
message = Messages._Node_LackingBuildPermission(item.authenticate().getName(),node.getNodeName()).toString();
|
||||
assertEquals("Cause of blockage should be bussy label.", message, node.canTake(item).getShortDescription());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCreatePath() throws Exception {
|
||||
Node node = j.createOnlineSlave();
|
||||
@@ -196,7 +197,7 @@ public class NodeTest {
|
||||
FilePath path = node.createPath(absolutPath);
|
||||
assertNotNull("Path should be created.", path);
|
||||
assertNotNull("Channel should be set.", path.getChannel());
|
||||
assertEquals("Channel should be equals to channel of node.", node.getChannel(), path.getChannel());
|
||||
assertEquals("Channel should be equals to channel of node.", node.getChannel(), path.getChannel());
|
||||
path = node2.createPath(absolutPath);
|
||||
assertNull("Path should be null if slave have channel null.", path);
|
||||
}
|
||||
@@ -204,7 +205,7 @@ public class NodeTest {
|
||||
@Test
|
||||
public void testHasPermission() throws Exception {
|
||||
Node node = j.createOnlineSlave();
|
||||
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
|
||||
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
|
||||
j.jenkins.setAuthorizationStrategy(auth);
|
||||
j.jenkins.setCrumbIssuer(null);
|
||||
HudsonPrivateSecurityRealm realm = new HudsonPrivateSecurityRealm(false);
|
||||
@@ -217,13 +218,13 @@ public class NodeTest {
|
||||
auth.add(Jenkins.ADMINISTER, user.getId());
|
||||
assertTrue("Current user should have permission read, because he has permission administer.", user.hasPermission(Permission.READ));
|
||||
SecurityContextHolder.getContext().setAuthentication(Jenkins.ANONYMOUS);
|
||||
|
||||
|
||||
user = User.get("anonymous");
|
||||
assertFalse("Current user should not have permission read, because does not have global permission read and authentication is anonymous.", user.hasPermission(Permission.READ));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testGetChannel() throws Exception {
|
||||
public void testGetChannel() throws Exception {
|
||||
Slave slave = j.createOnlineSlave();
|
||||
Node nodeOffline = j.createSlave();
|
||||
Node node = new DumbSlave("slave2", "description", slave.getRemoteFS(), "1", Mode.NORMAL, "", slave.getLauncher(), slave.getRetentionStrategy(), slave.getNodeProperties());
|
||||
@@ -231,7 +232,7 @@ public class NodeTest {
|
||||
assertNull("Channel of node should be null because assigned computer is offline.", nodeOffline.getChannel());
|
||||
assertNotNull("Channel of node should not be null.", slave.getChannel());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testToComputer() throws Exception {
|
||||
Slave slave = j.createOnlineSlave();
|
||||
@@ -239,7 +240,30 @@ public class NodeTest {
|
||||
assertNull("Slave which is not added into Jenkins list nodes should not have assigned computer.", node.toComputer());
|
||||
assertNotNull("Slave which is added into Jenkins list nodes should have assigned computer.", slave.toComputer());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Verify that the Label#getTiedJobCount does not perform a lazy loading operation.
|
||||
*/
|
||||
@Issue("JENKINS-26391")
|
||||
@Test
|
||||
public void testGetAssignedLabelWithJobs() throws Exception {
|
||||
final Node node = j.createOnlineSlave();
|
||||
node.setLabelString("label1 label2");
|
||||
MavenModuleSet mavenProject = j.createMavenProject();
|
||||
mavenProject.setAssignedLabel(j.jenkins.getLabel("label1"));
|
||||
RunLoadCounter.prepare(mavenProject);
|
||||
j.assertBuildStatus(Result.FAILURE, mavenProject.scheduleBuild2(0).get());
|
||||
Integer labelCount = RunLoadCounter.assertMaxLoads(mavenProject, 0, new Callable<Integer>() {
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
return j.jenkins.getLabel("label1").getTiedJobCount();
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals("Should have only one job tied to label.",
|
||||
1, labelCount.intValue());
|
||||
}
|
||||
|
||||
@Issue("JENKINS-27188")
|
||||
@Test public void envPropertiesImmutable() throws Exception {
|
||||
Slave slave = j.createSlave();
|
||||
@@ -253,6 +277,171 @@ public class NodeTest {
|
||||
assertNotSame(slave.getComputer().getEnvironment(), slave.getComputer().getEnvironment());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create two projects which have the same label and verify that both are accounted for when getting a count
|
||||
* of the jobs tied to the current label.
|
||||
*
|
||||
*/
|
||||
@Issue("JENKINS-26391")
|
||||
@Test
|
||||
public void testGetAssignedLabelMultipleSlaves() throws Exception {
|
||||
final Node node1 = j.createOnlineSlave();
|
||||
node1.setLabelString("label1");
|
||||
final Node node2 = j.createOnlineSlave();
|
||||
node1.setLabelString("label1");
|
||||
|
||||
MavenModuleSet project = j.createMavenProject();
|
||||
project.setAssignedLabel(j.jenkins.getLabel("label1"));
|
||||
j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
|
||||
|
||||
MavenModuleSet project2 = j.createMavenProject();
|
||||
project2.setAssignedLabel(j.jenkins.getLabel("label1"));
|
||||
j.assertBuildStatus(Result.FAILURE, project2.scheduleBuild2(0).get());
|
||||
|
||||
assertEquals("Two jobs should be tied to this label.",
|
||||
2, j.jenkins.getLabel("label1").getTiedJobCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that when a label is removed from a job that the tied job count does not include the removed job.
|
||||
*/
|
||||
@Issue("JENKINS-26391")
|
||||
@Test
|
||||
public void testGetAssignedLabelWhenLabelRemoveFromProject() throws Exception {
|
||||
final Node node = j.createOnlineSlave();
|
||||
node.setLabelString("label1");
|
||||
|
||||
MavenModuleSet project = j.createMavenProject();
|
||||
project.setAssignedLabel(j.jenkins.getLabel("label1"));
|
||||
j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
|
||||
|
||||
project.setAssignedLabel(null);
|
||||
assertEquals("Label1 should have no tied jobs after the job label was removed.",
|
||||
0, j.jenkins.getLabel("label1").getTiedJobCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a project with the OR label expression.
|
||||
*/
|
||||
@Issue("JENKINS-26391")
|
||||
@Test
|
||||
public void testGetAssignedLabelWithLabelOrExpression() throws Exception {
|
||||
Node node = j.createOnlineSlave();
|
||||
node.setLabelString("label1 label2");
|
||||
|
||||
FreeStyleProject project = j.createFreeStyleProject();
|
||||
project.setAssignedLabel(new LabelExpression.Or(j.jenkins.getLabel("label1"), j.jenkins.getLabel("label2")));
|
||||
|
||||
TagCloud<LabelAtom> cloud = node.getLabelCloud();
|
||||
assertThatCloudLabelContains(cloud, "label1", 0);
|
||||
assertThatCloudLabelContains(cloud, "label2", 0);
|
||||
}
|
||||
|
||||
@Issue("JENKINS-26391")
|
||||
@Test
|
||||
public void testGetAssignedLabelWithLabelAndExpression() throws Exception {
|
||||
Node node = j.createOnlineSlave();
|
||||
node.setLabelString("label1 label2");
|
||||
|
||||
FreeStyleProject project = j.createFreeStyleProject();
|
||||
project.setAssignedLabel(new LabelExpression.And(j.jenkins.getLabel("label1"), j.jenkins.getLabel("label2")));
|
||||
|
||||
TagCloud<LabelAtom> cloud = node.getLabelCloud();
|
||||
assertThatCloudLabelContains(cloud, "label1", 0);
|
||||
assertThatCloudLabelContains(cloud, "label2", 0);
|
||||
}
|
||||
|
||||
@Issue("JENKINS-26391")
|
||||
@Test
|
||||
public void testGetAssignedLabelWithBothAndOrExpression() throws Exception {
|
||||
Node n1 = j.createOnlineSlave();
|
||||
Node n2 = j.createOnlineSlave();
|
||||
Node n3 = j.createOnlineSlave();
|
||||
Node n4 = j.createOnlineSlave();
|
||||
|
||||
n1.setLabelString("label1 label2 label3");
|
||||
n2.setLabelString("label1");
|
||||
n3.setLabelString("label1 label2");
|
||||
n4.setLabelString("label1 label");
|
||||
|
||||
FreeStyleProject p = j.createFreeStyleProject();
|
||||
p.setAssignedLabel(LabelExpression.parseExpression("label1 && (label2 || label3)"));
|
||||
|
||||
// Node 1 should not be tied to any labels
|
||||
TagCloud<LabelAtom> n1LabelCloud = n1.getLabelCloud();
|
||||
assertThatCloudLabelContains(n1LabelCloud, "label1", 0);
|
||||
assertThatCloudLabelContains(n1LabelCloud, "label2", 0);
|
||||
assertThatCloudLabelContains(n1LabelCloud, "label3", 0);
|
||||
|
||||
// Node 2 should not be tied to any labels
|
||||
TagCloud<LabelAtom> n2LabelCloud = n1.getLabelCloud();
|
||||
assertThatCloudLabelContains(n2LabelCloud, "label1", 0);
|
||||
|
||||
// Node 3 should not be tied to any labels
|
||||
TagCloud<LabelAtom> n3LabelCloud = n1.getLabelCloud();
|
||||
assertThatCloudLabelContains(n3LabelCloud, "label1", 0);
|
||||
assertThatCloudLabelContains(n3LabelCloud, "label2", 0);
|
||||
|
||||
// Node 4 should not be tied to any labels
|
||||
TagCloud<LabelAtom> n4LabelCloud = n1.getLabelCloud();
|
||||
assertThatCloudLabelContains(n4LabelCloud, "label1", 0);
|
||||
}
|
||||
|
||||
@Issue("JENKINS-26391")
|
||||
@Test
|
||||
public void testGetAssignedLabelWithSpaceOnly() throws Exception {
|
||||
Node n = j.createOnlineSlave();
|
||||
n.setLabelString("label1 label2");
|
||||
|
||||
FreeStyleProject p = j.createFreeStyleProject();
|
||||
p.setAssignedLabel(j.jenkins.getLabel("label1 label2"));
|
||||
|
||||
TagCloud<LabelAtom> cloud = n.getLabelCloud();
|
||||
assertThatCloudLabelDoesNotContain(cloud, "label1 label2", 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that a tag cloud contains label name and weight.
|
||||
*/
|
||||
public void assertThatCloudLabel(boolean contains, TagCloud<LabelAtom> tagCloud, String expectedLabel, int expectedWeight) {
|
||||
StringBuilder containsFailureMessage = new StringBuilder().append("Unable to find label cloud. Expected: [")
|
||||
.append(expectedLabel).append(", ").append(expectedWeight).append("]").append(" Actual: [");
|
||||
|
||||
for (TagCloud.Entry entry : tagCloud) {
|
||||
if (expectedLabel.equals(((LabelAtom) entry.item).getName())) {
|
||||
if (expectedWeight == entry.weight) {
|
||||
if (!contains) {
|
||||
fail("Cloud label should not contain [" + expectedLabel + ", " + expectedWeight + "]");
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Gather information for failure message just in case.
|
||||
containsFailureMessage.append("{").append(entry.item.toString()).append(", ").append(entry.weight).append("}");
|
||||
}
|
||||
|
||||
// If a label should be part of the cloud label then fail.
|
||||
if (contains) {
|
||||
fail(containsFailureMessage.toString() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that a tag cloud does not contain the label name and weight.
|
||||
*/
|
||||
public void assertThatCloudLabelDoesNotContain(TagCloud<LabelAtom> tagCloud, String expectedLabel, int expectedWeight) {
|
||||
assertThatCloudLabel(false, tagCloud, expectedLabel, expectedWeight);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that a tag cloud contains label name and weight.
|
||||
*/
|
||||
public void assertThatCloudLabelContains(TagCloud<LabelAtom> tagCloud, String expectedLabel, int expectedWeight) {
|
||||
assertThatCloudLabel(true, tagCloud, expectedLabel, expectedWeight);
|
||||
}
|
||||
|
||||
@TestExtension
|
||||
public static class LabelFinderImpl extends LabelFinder{
|
||||
|
||||
@@ -263,14 +452,14 @@ public class NodeTest {
|
||||
atoms.add(Jenkins.getInstance().getLabelAtom("dynamicLabel"));
|
||||
}
|
||||
return atoms;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@TestExtension
|
||||
public static class NodePropertyImpl extends NodeProperty{
|
||||
|
||||
|
||||
@Override
|
||||
public CauseOfBlockage canTake(Queue.BuildableItem item){
|
||||
if(notTake)
|
||||
@@ -278,5 +467,5 @@ public class NodeTest {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
/*
|
||||
* The MIT License
|
||||
*
|
||||
*
|
||||
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
|
||||
*
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -26,6 +26,7 @@ package hudson.model;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlFileInput;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
import com.gargoylesoftware.htmlunit.xml.XmlPage;
|
||||
import hudson.Launcher;
|
||||
import hudson.XmlFile;
|
||||
import hudson.matrix.AxisList;
|
||||
@@ -49,6 +50,7 @@ import hudson.security.SparseACL;
|
||||
import hudson.slaves.DumbSlave;
|
||||
import hudson.slaves.DummyCloudImpl;
|
||||
import hudson.slaves.NodeProvisionerRule;
|
||||
import hudson.tasks.BuildTrigger;
|
||||
import hudson.tasks.Shell;
|
||||
import hudson.triggers.SCMTrigger.SCMTriggerCause;
|
||||
import hudson.triggers.TimerTrigger.TimerTriggerCause;
|
||||
@@ -90,6 +92,7 @@ import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.MockQueueItemAuthenticator;
|
||||
import org.jvnet.hudson.test.SequenceLock;
|
||||
import org.jvnet.hudson.test.SleepBuilder;
|
||||
import org.jvnet.hudson.test.TestBuilder;
|
||||
import org.jvnet.hudson.test.recipes.LocalData;
|
||||
import org.mortbay.jetty.Server;
|
||||
@@ -112,7 +115,6 @@ public class QueueTest {
|
||||
|
||||
// prevent execution to push stuff into the queue
|
||||
r.jenkins.setNumExecutors(0);
|
||||
r.jenkins.setNodes(r.jenkins.getNodes());
|
||||
|
||||
FreeStyleProject testProject = r.createFreeStyleProject("test");
|
||||
testProject.scheduleBuild(new UserIdCause());
|
||||
@@ -129,7 +131,7 @@ public class QueueTest {
|
||||
assertEquals(1, q.getItems().length);
|
||||
|
||||
// did it bind back to the same object?
|
||||
assertSame(q.getItems()[0].task,testProject);
|
||||
assertSame(q.getItems()[0].task,testProject);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -161,7 +163,6 @@ public class QueueTest {
|
||||
|
||||
// prevent execution to push stuff into the queue
|
||||
r.jenkins.setNumExecutors(0);
|
||||
r.jenkins.setNodes(r.jenkins.getNodes());
|
||||
|
||||
FreeStyleProject testProject = r.createFreeStyleProject("test");
|
||||
testProject.scheduleBuild(new UserIdCause());
|
||||
@@ -392,7 +393,7 @@ public class QueueTest {
|
||||
assertEquals(1, runs.size());
|
||||
assertEquals("slave0", runs.get(0).getBuiltOnStr());
|
||||
}
|
||||
|
||||
|
||||
@Issue("JENKINS-10944")
|
||||
@Test public void flyweightTasksBlockedByShutdown() throws Exception {
|
||||
r.jenkins.doQuietDown(true, 0);
|
||||
@@ -421,6 +422,27 @@ public class QueueTest {
|
||||
assert task.exec instanceof OneOffExecutor : task.exec;
|
||||
}
|
||||
|
||||
@Issue("JENKINS-27256")
|
||||
@Test public void inQueueTaskLookupByAPI() throws Exception {
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
Label label = Label.get("unknown-slave");
|
||||
|
||||
// Give the project an "unknown-slave" label, forcing it to
|
||||
// stay in the queue after we schedule it, allowing us to query it.
|
||||
p.setAssignedLabel(label);
|
||||
p.scheduleBuild2(0);
|
||||
|
||||
JenkinsRule.WebClient webclient = r.createWebClient();
|
||||
|
||||
XmlPage queueItems = webclient.goToXml("queue/api/xml");
|
||||
String queueTaskId = queueItems.getXmlDocument().getElementsByTagName("id").item(0).getTextContent();
|
||||
assertNotNull(queueTaskId);
|
||||
XmlPage queueItem = webclient.goToXml("queue/item/" + queueTaskId + "/api/xml");
|
||||
assertNotNull(queueItem);
|
||||
String tagName = queueItem.getDocumentElement().getTagName();
|
||||
assertTrue(tagName.equals("blockedItem") || tagName.equals("buildableItem"));
|
||||
}
|
||||
|
||||
private static class TestFlyweightTask extends TestTask implements Queue.FlyweightTask {
|
||||
Executor exec;
|
||||
private final Label assignedLabel;
|
||||
@@ -585,8 +607,8 @@ public class QueueTest {
|
||||
@Override
|
||||
public Label getAssignedLabel(){
|
||||
throw new IllegalArgumentException("Test exception"); //cause dead of executor
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(){
|
||||
//do not need save
|
||||
@@ -613,7 +635,7 @@ public class QueueTest {
|
||||
break; // executor is dead due to exception
|
||||
}
|
||||
if(e.isIdle()){
|
||||
assertTrue("Node went to idle before project had" + project2.getDisplayName() + " been started", v.isDone());
|
||||
assertTrue("Node went to idle before project had" + project2.getDisplayName() + " been started", v.isDone());
|
||||
}
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
@@ -622,37 +644,37 @@ public class QueueTest {
|
||||
Queue.getInstance().cancel(projectError); // cancel job which cause dead of executor
|
||||
e.doYank(); //restart executor
|
||||
while(!e.isIdle()){ //executor should take project2 from queue
|
||||
Thread.sleep(1000);
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
//project2 should not be in pendings
|
||||
List<Queue.BuildableItem> items = Queue.getInstance().getPendingItems();
|
||||
for(Queue.BuildableItem item : items){
|
||||
assertFalse("Project " + project2.getDisplayName() + " stuck in pendings",item.task.getName().equals(project2.getName()));
|
||||
assertFalse("Project " + project2.getDisplayName() + " stuck in pendings",item.task.getName().equals(project2.getName()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test public void cancelInQueue() throws Exception {
|
||||
// parepare an offline slave.
|
||||
DumbSlave slave = r.createOnlineSlave();
|
||||
assertFalse(slave.toComputer().isOffline());
|
||||
slave.toComputer().disconnect(null).get();
|
||||
assertTrue(slave.toComputer().isOffline());
|
||||
|
||||
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
p.setAssignedNode(slave);
|
||||
|
||||
|
||||
QueueTaskFuture<FreeStyleBuild> f = p.scheduleBuild2(0);
|
||||
try {
|
||||
f.get(3, TimeUnit.SECONDS);
|
||||
fail("Should time out (as the slave is offline).");
|
||||
} catch (TimeoutException e) {
|
||||
}
|
||||
|
||||
|
||||
Queue.Item item = Queue.getInstance().getItem(p);
|
||||
assertNotNull(item);
|
||||
Queue.getInstance().doCancelItem(item.getId());
|
||||
assertNull(Queue.getInstance().getItem(p));
|
||||
|
||||
|
||||
try {
|
||||
f.get(10, TimeUnit.SECONDS);
|
||||
fail("Should not get (as it is cancelled).");
|
||||
@@ -687,5 +709,38 @@ public class QueueTest {
|
||||
fail("Expected an CancellationException to be thrown");
|
||||
} catch (CancellationException e) {}
|
||||
}
|
||||
|
||||
|
||||
@Issue("JENKINS-27871")
|
||||
@Test public void testBlockBuildWhenUpstreamBuildingLock() throws Exception {
|
||||
final String prefix = "JENKINS-27871";
|
||||
r.getInstance().setNumExecutors(4);
|
||||
r.getInstance().save();
|
||||
|
||||
final FreeStyleProject projectA = r.createFreeStyleProject(prefix+"A");
|
||||
projectA.getBuildersList().add(new SleepBuilder(5000));
|
||||
|
||||
final FreeStyleProject projectB = r.createFreeStyleProject(prefix+"B");
|
||||
projectB.getBuildersList().add(new SleepBuilder(10000));
|
||||
projectB.setBlockBuildWhenUpstreamBuilding(true);
|
||||
|
||||
final FreeStyleProject projectC = r.createFreeStyleProject(prefix+"C");
|
||||
projectC.getBuildersList().add(new SleepBuilder(10000));
|
||||
projectC.setBlockBuildWhenUpstreamBuilding(true);
|
||||
|
||||
projectA.getPublishersList().add(new BuildTrigger(Arrays.asList(projectB), Result.SUCCESS));
|
||||
projectB.getPublishersList().add(new BuildTrigger(Arrays.asList(projectC), Result.SUCCESS));
|
||||
|
||||
final QueueTaskFuture<FreeStyleBuild> taskA = projectA.scheduleBuild2(0, new TimerTriggerCause());
|
||||
Thread.sleep(1000);
|
||||
final QueueTaskFuture<FreeStyleBuild> taskB = projectB.scheduleBuild2(0, new TimerTriggerCause());
|
||||
final QueueTaskFuture<FreeStyleBuild> taskC = projectC.scheduleBuild2(0, new TimerTriggerCause());
|
||||
|
||||
final FreeStyleBuild buildA = taskA.get(60, TimeUnit.SECONDS);
|
||||
final FreeStyleBuild buildB = taskB.get(60, TimeUnit.SECONDS);
|
||||
final FreeStyleBuild buildC = taskC.get(60, TimeUnit.SECONDS);
|
||||
long buildBEndTime = buildB.getStartTimeInMillis() + buildB.getDuration();
|
||||
assertTrue("Project B build should be finished before the build of project C starts. " +
|
||||
"B finished at " + buildBEndTime + ", C started at " + buildC.getStartTimeInMillis(),
|
||||
buildC.getStartTimeInMillis() >= buildBEndTime);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
|
||||
import com.gargoylesoftware.htmlunit.WebAssert;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
import hudson.security.AccessDeniedException2;
|
||||
import hudson.security.GlobalMatrixAuthorizationStrategy;
|
||||
import hudson.security.HudsonPrivateSecurityRealm;
|
||||
@@ -41,9 +42,13 @@ import java.util.Collections;
|
||||
|
||||
import jenkins.model.IdStrategy;
|
||||
import jenkins.model.Jenkins;
|
||||
import jenkins.security.ApiTokenProperty;
|
||||
|
||||
import org.acegisecurity.AccessDeniedException;
|
||||
import org.acegisecurity.Authentication;
|
||||
import org.acegisecurity.context.SecurityContext;
|
||||
import org.acegisecurity.context.SecurityContextHolder;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assume.*;
|
||||
import org.junit.Rule;
|
||||
@@ -498,6 +503,42 @@ public class UserTest {
|
||||
assertTrue("But once storage is allocated, he can be deleted", user3.canDelete());
|
||||
}
|
||||
|
||||
@Test
|
||||
// @Issue("SECURITY-180")
|
||||
public void security180() throws Exception {
|
||||
final GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
|
||||
j.jenkins.setAuthorizationStrategy(auth);
|
||||
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
|
||||
|
||||
User alice = User.get("alice");
|
||||
User bob = User.get("bob");
|
||||
User admin = User.get("admin");
|
||||
|
||||
auth.add(Jenkins.READ, alice.getId());
|
||||
auth.add(Jenkins.READ, bob.getId());
|
||||
auth.add(Jenkins.ADMINISTER, admin.getId());
|
||||
|
||||
// Admin can change everyone's token
|
||||
SecurityContextHolder.getContext().setAuthentication(admin.impersonate());
|
||||
admin.getProperty(ApiTokenProperty.class).changeApiToken();
|
||||
alice.getProperty(ApiTokenProperty.class).changeApiToken();
|
||||
|
||||
// User can change only own token
|
||||
SecurityContextHolder.getContext().setAuthentication(bob.impersonate());
|
||||
bob.getProperty(ApiTokenProperty.class).changeApiToken();
|
||||
try {
|
||||
alice.getProperty(ApiTokenProperty.class).changeApiToken();
|
||||
fail("Bob should not be authorized to change alice's token");
|
||||
} catch (AccessDeniedException expected) { }
|
||||
|
||||
// ANONYMOUS can not change any token
|
||||
SecurityContextHolder.getContext().setAuthentication(Jenkins.ANONYMOUS);
|
||||
try {
|
||||
alice.getProperty(ApiTokenProperty.class).changeApiToken();
|
||||
fail("Anonymous should not be authorized to change alice's token");
|
||||
} catch (AccessDeniedException expected) { }
|
||||
}
|
||||
|
||||
public static class SomeUserProperty extends UserProperty {
|
||||
|
||||
@TestExtension
|
||||
|
||||
@@ -26,16 +26,20 @@ package hudson.model;
|
||||
|
||||
import hudson.FilePath;
|
||||
import hudson.remoting.VirtualChannel;
|
||||
import hudson.scm.NullSCM;
|
||||
import hudson.slaves.DumbSlave;
|
||||
import hudson.util.StreamTaskListener;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.logging.ConsoleHandler;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import jenkins.MasterToSlaveFileCallable;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Assume;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
@@ -43,12 +47,10 @@ import org.junit.Test;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.MockFolder;
|
||||
import org.jvnet.hudson.test.WithoutJenkins;
|
||||
|
||||
public class WorkspaceCleanupThreadTest {
|
||||
|
||||
// TODO test that new workspaces are skipped
|
||||
// TODO test that SCM.processWorkspaceBeforeDeletion can reject
|
||||
|
||||
@Rule public JenkinsRule r = new JenkinsRule();
|
||||
|
||||
private static final Logger logger = Logger.getLogger(WorkspaceCleanupThread.class.getName());
|
||||
@@ -58,49 +60,38 @@ public class WorkspaceCleanupThreadTest {
|
||||
handler.setLevel(Level.ALL);
|
||||
logger.addHandler(handler);
|
||||
}
|
||||
|
||||
|
||||
@Test public void cleanUpSlaves() throws Exception {
|
||||
DumbSlave s1 = r.createOnlineSlave();
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
p.setAssignedNode(s1);
|
||||
FreeStyleBuild b1 = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
|
||||
assertEquals(s1, b1.getBuiltOn());
|
||||
FilePath ws1 = b1.getWorkspace();
|
||||
assertNotNull(ws1);
|
||||
ws1.act(new Detouch());
|
||||
DumbSlave s2 = r.createOnlineSlave();
|
||||
p.setAssignedNode(s2);
|
||||
FreeStyleBuild b2 = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
|
||||
assertEquals(s2, b2.getBuiltOn());
|
||||
FilePath ws2 = b2.getWorkspace();
|
||||
assertNotNull(ws2);
|
||||
ws2.act(new Detouch());
|
||||
|
||||
FilePath ws1 = createOldWorkspaceOn(r.createOnlineSlave(), p);
|
||||
|
||||
p.setAssignedNode(r.jenkins);
|
||||
FreeStyleBuild b3 = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
|
||||
assertEquals(r.jenkins, b3.getBuiltOn());
|
||||
assertEquals(r.jenkins, p.getLastBuiltOn());
|
||||
new WorkspaceCleanupThread().execute(StreamTaskListener.fromStdout());
|
||||
assertFalse(ws1.exists());
|
||||
assertFalse(ws2.exists());
|
||||
FreeStyleBuild b = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
|
||||
assertEquals(r.jenkins, b.getBuiltOn());
|
||||
FilePath ws2 = b.getWorkspace();
|
||||
|
||||
FilePath ws3 = createOldWorkspaceOn(r.createOnlineSlave(), p);
|
||||
|
||||
performCleanup();
|
||||
|
||||
assertFalse(ws1.exists()); // Old one - deleted
|
||||
assertTrue(ws2.exists()); // Not old enough - kept
|
||||
assertTrue(ws3.exists()); // Latest - kept
|
||||
}
|
||||
|
||||
@Issue("JENKINS-21023")
|
||||
@Test public void modernMasterWorkspaceLocation() throws Exception {
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
FreeStyleBuild b1 = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
|
||||
assertEquals(r.jenkins, b1.getBuiltOn());
|
||||
FilePath ws1 = b1.getWorkspace();
|
||||
assertNotNull(ws1);
|
||||
ws1.act(new Detouch());
|
||||
|
||||
FilePath ws1 = createOldWorkspaceOn(r.jenkins, p);
|
||||
|
||||
DumbSlave s = r.createOnlineSlave();
|
||||
p.setAssignedNode(s);
|
||||
FreeStyleBuild b2 = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
|
||||
assertEquals(s, b2.getBuiltOn());
|
||||
FilePath ws2 = b2.getWorkspace();
|
||||
assertNotNull(ws2);
|
||||
ws2.act(new Detouch());
|
||||
FilePath ws2 = createOldWorkspaceOn(s, p);
|
||||
assertEquals(s, p.getLastBuiltOn());
|
||||
new WorkspaceCleanupThread().execute(StreamTaskListener.fromStdout());
|
||||
|
||||
performCleanup();
|
||||
|
||||
assertFalse(ws1.exists());
|
||||
assertTrue(ws2.exists());
|
||||
}
|
||||
@@ -109,47 +100,125 @@ public class WorkspaceCleanupThreadTest {
|
||||
@Test public void jobInFolder() throws Exception {
|
||||
MockFolder d = r.createFolder("d");
|
||||
FreeStyleProject p1 = d.createProject(FreeStyleProject.class, "p");
|
||||
FreeStyleBuild b1 = r.assertBuildStatusSuccess(p1.scheduleBuild2(0));
|
||||
assertEquals(r.jenkins, b1.getBuiltOn());
|
||||
FilePath ws1 = b1.getWorkspace();
|
||||
assertNotNull(ws1);
|
||||
ws1.act(new Detouch());
|
||||
FilePath ws1 = createOldWorkspaceOn(r.jenkins, p1);
|
||||
|
||||
DumbSlave s1 = r.createOnlineSlave();
|
||||
p1.setAssignedNode(s1);
|
||||
FreeStyleBuild b2 = r.assertBuildStatusSuccess(p1.scheduleBuild2(0));
|
||||
assertEquals(s1, b2.getBuiltOn());
|
||||
FilePath ws2 = b2.getWorkspace();
|
||||
assertNotNull(ws2);
|
||||
ws2.act(new Detouch());
|
||||
FilePath ws2 = createOldWorkspaceOn(s1, p1);
|
||||
DumbSlave s2 = r.createOnlineSlave();
|
||||
p1.setAssignedNode(s2);
|
||||
FreeStyleBuild b3 = r.assertBuildStatusSuccess(p1.scheduleBuild2(0));
|
||||
assertEquals(s2, b3.getBuiltOn());
|
||||
FilePath ws3 = b3.getWorkspace();
|
||||
assertNotNull(ws3);
|
||||
ws3.act(new Detouch());
|
||||
FilePath ws3 = createOldWorkspaceOn(s2, p1);
|
||||
assertEquals(s2, p1.getLastBuiltOn());
|
||||
|
||||
FreeStyleProject p2 = d.createProject(FreeStyleProject.class, "p2");
|
||||
p2.setAssignedNode(s1);
|
||||
FreeStyleBuild b4 = r.assertBuildStatusSuccess(p2.scheduleBuild2(0));
|
||||
assertEquals(s1, b4.getBuiltOn());
|
||||
FilePath ws4 = b4.getWorkspace();
|
||||
assertNotNull(ws4);
|
||||
ws4.act(new Detouch());
|
||||
FilePath ws4 = createOldWorkspaceOn(s1, p2);
|
||||
assertEquals(s1, p2.getLastBuiltOn());
|
||||
ws2.getParent().act(new Detouch()); // ${s1.rootPath}/workspace/d/
|
||||
new WorkspaceCleanupThread().execute(StreamTaskListener.fromStdout());
|
||||
ws2.getParent().act(new Touch(0)); // ${s1.rootPath}/workspace/d/
|
||||
|
||||
performCleanup();
|
||||
|
||||
assertFalse(ws1.exists());
|
||||
assertFalse(ws2.exists());
|
||||
assertTrue(ws3.exists());
|
||||
assertTrue(ws4.exists());
|
||||
}
|
||||
|
||||
private static final class Detouch extends MasterToSlaveFileCallable<Void> {
|
||||
@Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
|
||||
Assume.assumeTrue("failed to reset lastModified on " + f, f.setLastModified(0));
|
||||
return null;
|
||||
@Test public void doNothingIfDisabled() throws Exception {
|
||||
WorkspaceCleanupThread.disabled = true;
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
|
||||
FilePath ws = createOldWorkspaceOn(r.jenkins, p);
|
||||
createOldWorkspaceOn(r.createOnlineSlave(), p);
|
||||
|
||||
performCleanup();
|
||||
|
||||
assertTrue(ws.exists());
|
||||
|
||||
WorkspaceCleanupThread.disabled = false;
|
||||
performCleanup();
|
||||
|
||||
assertFalse(ws.exists());
|
||||
}
|
||||
|
||||
@Test public void removeOnlyWhatIsOldEnough() throws Exception {
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
FilePath ws = createOldWorkspaceOn(r.jenkins, p);
|
||||
createOldWorkspaceOn(r.createOnlineSlave(), p);
|
||||
|
||||
long twoDaysOld = System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000;
|
||||
ws.act(new Touch(twoDaysOld));
|
||||
|
||||
WorkspaceCleanupThread.retainForDays = 3;
|
||||
performCleanup();
|
||||
|
||||
assertTrue(ws.exists());
|
||||
|
||||
WorkspaceCleanupThread.retainForDays = 1;
|
||||
performCleanup();
|
||||
|
||||
assertFalse(ws.exists());
|
||||
}
|
||||
|
||||
@Test @WithoutJenkins public void reocurencePeriodIsInhours() {
|
||||
assertEquals(
|
||||
WorkspaceCleanupThread.recurrencePeriodHours * 60 * 60 * 1000 ,
|
||||
new WorkspaceCleanupThread().getRecurrencePeriod()
|
||||
);
|
||||
}
|
||||
|
||||
@Test public void vetoByScm() throws Exception {
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
FilePath ws = createOldWorkspaceOn(r.jenkins, p);
|
||||
createOldWorkspaceOn(r.createOnlineSlave(), p);
|
||||
|
||||
p.setScm(new VetoSCM(false));
|
||||
performCleanup();
|
||||
|
||||
assertTrue(ws.exists());
|
||||
|
||||
p.setScm(new VetoSCM(true));
|
||||
performCleanup();
|
||||
|
||||
assertFalse(ws.exists());
|
||||
}
|
||||
|
||||
private FilePath createOldWorkspaceOn(Node slave, FreeStyleProject p) throws Exception {
|
||||
p.setAssignedNode(slave);
|
||||
FreeStyleBuild b1 = r.assertBuildStatusSuccess(p.scheduleBuild2(0));
|
||||
assertEquals(slave, b1.getBuiltOn());
|
||||
FilePath ws = b1.getWorkspace();
|
||||
assertNotNull(ws);
|
||||
ws.act(new Touch(0));
|
||||
return ws;
|
||||
}
|
||||
|
||||
private void performCleanup() throws InterruptedException, IOException {
|
||||
new WorkspaceCleanupThread().execute(StreamTaskListener.fromStdout());
|
||||
}
|
||||
|
||||
private static final class VetoSCM extends NullSCM {
|
||||
private final boolean answer;
|
||||
public VetoSCM(boolean answer) {
|
||||
this.answer = answer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processWorkspaceBeforeDeletion(
|
||||
Job<?, ?> project, FilePath workspace, Node node
|
||||
) throws IOException, InterruptedException {
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Touch extends MasterToSlaveFileCallable<Void> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final long time;
|
||||
|
||||
public Touch(long time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
@Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
|
||||
Assume.assumeTrue("failed to reset lastModified on " + f, f.setLastModified(time));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package hudson.model.utils;
|
||||
|
||||
import hudson.AbortException;
|
||||
import hudson.Extension;
|
||||
import hudson.Launcher;
|
||||
import hudson.model.AbstractBuild;
|
||||
import hudson.model.AbstractProject;
|
||||
import hudson.model.BuildListener;
|
||||
import hudson.tasks.BuildStepDescriptor;
|
||||
import hudson.tasks.BuildStepMonitor;
|
||||
import hudson.tasks.Publisher;
|
||||
import hudson.tasks.Recorder;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Publisher that throws AbortException
|
||||
*/
|
||||
public class AbortExceptionPublisher extends Recorder {
|
||||
@Override
|
||||
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
throw new AbortException("Threw AbortException from publisher!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; }
|
||||
|
||||
@Extension
|
||||
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
|
||||
@Override
|
||||
public String getDisplayName() { return "ThrowAbortExceptionRecorder"; }
|
||||
@Override
|
||||
public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package hudson.model.utils;
|
||||
|
||||
import hudson.Extension;
|
||||
import hudson.Launcher;
|
||||
import hudson.model.AbstractBuild;
|
||||
import hudson.model.AbstractProject;
|
||||
import hudson.model.BuildListener;
|
||||
import hudson.tasks.BuildStepDescriptor;
|
||||
import hudson.tasks.BuildStepMonitor;
|
||||
import hudson.tasks.Publisher;
|
||||
import hudson.tasks.Recorder;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Publisher that throw IOException
|
||||
* @author Kanstantsin Shautsou
|
||||
*/
|
||||
public class IOExceptionPublisher extends Recorder {
|
||||
@Override
|
||||
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
throw new IOException("Threw IOException from publisher!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; }
|
||||
|
||||
@Extension
|
||||
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
|
||||
@Override
|
||||
public String getDisplayName() { return "Throw IOException Publisher"; }
|
||||
@Override
|
||||
public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package hudson.model.utils;
|
||||
|
||||
import hudson.Extension;
|
||||
import hudson.FilePath;
|
||||
import hudson.Launcher;
|
||||
import hudson.model.AbstractBuild;
|
||||
import hudson.model.AbstractProject;
|
||||
import hudson.model.BuildListener;
|
||||
import hudson.tasks.BuildStepDescriptor;
|
||||
import hudson.tasks.BuildStepMonitor;
|
||||
import hudson.tasks.Publisher;
|
||||
import hudson.tasks.Recorder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
/**
|
||||
* Wrote build status to file
|
||||
* @author Kanstantsin Shautsou
|
||||
*/
|
||||
public class ResultWriterPublisher extends Recorder {
|
||||
private final String fileName;
|
||||
|
||||
public ResultWriterPublisher(String fileName) {
|
||||
this.fileName = fileName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BuildStepMonitor getRequiredMonitorService() {
|
||||
return BuildStepMonitor.NONE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
FilePath file = build.getWorkspace().child(fileName);
|
||||
file.write(build.getResult().toString(), Charset.defaultCharset().name());
|
||||
return true;
|
||||
}
|
||||
|
||||
@Extension
|
||||
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
|
||||
@Override
|
||||
public String getDisplayName() { return "wrote result to file"; }
|
||||
@Override
|
||||
public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package hudson.model.utils;
|
||||
|
||||
import hudson.Extension;
|
||||
import hudson.Launcher;
|
||||
import hudson.model.AbstractBuild;
|
||||
import hudson.model.AbstractProject;
|
||||
import hudson.model.BuildListener;
|
||||
import hudson.tasks.BuildStepDescriptor;
|
||||
import hudson.tasks.BuildStepMonitor;
|
||||
import hudson.tasks.Publisher;
|
||||
import hudson.tasks.Recorder;
|
||||
import org.kohsuke.stapler.DataBoundConstructor;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* @author Kanstantsin Shautsou
|
||||
*/
|
||||
public class TrueFalsePublisher extends Recorder {
|
||||
private final boolean b;
|
||||
|
||||
@DataBoundConstructor
|
||||
public TrueFalsePublisher(boolean b) {
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
return b;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; }
|
||||
|
||||
@Extension
|
||||
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
|
||||
@Override
|
||||
public String getDisplayName() { return "return true or false"; }
|
||||
@Override
|
||||
public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; }
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ import static org.junit.Assert.fail;
|
||||
import hudson.model.FreeStyleProject;
|
||||
import hudson.model.ListView;
|
||||
|
||||
import java.net.URL;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@@ -105,6 +107,37 @@ public class SearchTest {
|
||||
assertTrue(contents.contains(String.format("<title>%s [Jenkins]</title>", projectName)));
|
||||
}
|
||||
|
||||
@Issue("JENKINS-24433")
|
||||
@Test
|
||||
public void testSearchByProjectNameBehindAFolder() throws Exception {
|
||||
FreeStyleProject myFreeStyleProject = j.createFreeStyleProject("testSearchByProjectName");
|
||||
MockFolder myMockFolder = j.createFolder("my-folder-1");
|
||||
|
||||
Page result = j.createWebClient().goTo(myMockFolder.getUrl() + "search?q="+ myFreeStyleProject.getName());
|
||||
|
||||
assertNotNull(result);
|
||||
j.assertGoodStatus(result);
|
||||
|
||||
URL resultUrl = result.getWebResponse().getUrl();
|
||||
assertTrue(resultUrl.toString().equals(j.getInstance().getRootUrl() + myFreeStyleProject.getUrl()));
|
||||
}
|
||||
|
||||
@Issue("JENKINS-24433")
|
||||
@Test
|
||||
public void testSearchByProjectNameInAFolder() throws Exception {
|
||||
|
||||
MockFolder myMockFolder = j.createFolder("my-folder-1");
|
||||
FreeStyleProject myFreeStyleProject = myMockFolder.createProject(FreeStyleProject.class, "my-job-1");
|
||||
|
||||
Page result = j.createWebClient().goTo(myMockFolder.getUrl() + "search?q=" + myFreeStyleProject.getFullName());
|
||||
|
||||
assertNotNull(result);
|
||||
j.assertGoodStatus(result);
|
||||
|
||||
URL resultUrl = result.getWebResponse().getUrl();
|
||||
assertTrue(resultUrl.toString().equals(j.getInstance().getRootUrl() + myFreeStyleProject.getUrl()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSearchByDisplayName() throws Exception {
|
||||
final String displayName = "displayName9999999";
|
||||
@@ -220,11 +253,98 @@ public class SearchTest {
|
||||
foundDispayName = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
assertTrue(foundProjectName);
|
||||
assertTrue(foundDispayName);
|
||||
}
|
||||
|
||||
@Issue("JENKINS-24433")
|
||||
@Test
|
||||
public void testProjectNameBehindAFolderDisplayName() throws Exception {
|
||||
final String projectName1 = "job-1";
|
||||
final String displayName1 = "job-1 display";
|
||||
|
||||
final String projectName2 = "job-2";
|
||||
final String displayName2 = "job-2 display";
|
||||
|
||||
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
|
||||
project1.setDisplayName(displayName1);
|
||||
|
||||
MockFolder myMockFolder = j.createFolder("my-folder-1");
|
||||
|
||||
FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2);
|
||||
project2.setDisplayName(displayName2);
|
||||
|
||||
WebClient wc = j.createWebClient();
|
||||
Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName1, "application/json");
|
||||
assertNotNull(result);
|
||||
j.assertGoodStatus(result);
|
||||
|
||||
String content = result.getWebResponse().getContentAsString();
|
||||
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
|
||||
assertNotNull(jsonContent);
|
||||
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
|
||||
assertNotNull(jsonArray);
|
||||
|
||||
assertEquals(2, jsonArray.size());
|
||||
|
||||
boolean foundDisplayName = false;
|
||||
for(Object suggestion : jsonArray) {
|
||||
JSONObject jsonSuggestion = (JSONObject)suggestion;
|
||||
|
||||
String name = (String)jsonSuggestion.get("name");
|
||||
if(projectName1.equals(name)) {
|
||||
foundDisplayName = true;
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(foundDisplayName);
|
||||
}
|
||||
|
||||
@Issue("JENKINS-24433")
|
||||
@Test
|
||||
public void testProjectNameInAFolderDisplayName() throws Exception {
|
||||
final String projectName1 = "job-1";
|
||||
final String displayName1 = "job-1 display";
|
||||
|
||||
final String projectName2 = "job-2";
|
||||
final String displayName2 = "my-folder-1 job-2";
|
||||
|
||||
FreeStyleProject project1 = j.createFreeStyleProject(projectName1);
|
||||
project1.setDisplayName(displayName1);
|
||||
|
||||
MockFolder myMockFolder = j.createFolder("my-folder-1");
|
||||
|
||||
FreeStyleProject project2 = myMockFolder.createProject(FreeStyleProject.class, projectName2);
|
||||
project2.setDisplayName(displayName2);
|
||||
|
||||
WebClient wc = j.createWebClient();
|
||||
Page result = wc.goTo(myMockFolder.getUrl() + "search/suggest?query=" + projectName2, "application/json");
|
||||
assertNotNull(result);
|
||||
j.assertGoodStatus(result);
|
||||
|
||||
String content = result.getWebResponse().getContentAsString();
|
||||
JSONObject jsonContent = (JSONObject)JSONSerializer.toJSON(content);
|
||||
assertNotNull(jsonContent);
|
||||
JSONArray jsonArray = jsonContent.getJSONArray("suggestions");
|
||||
assertNotNull(jsonArray);
|
||||
|
||||
assertEquals(1, jsonArray.size());
|
||||
|
||||
boolean foundDisplayName = false;
|
||||
for(Object suggestion : jsonArray) {
|
||||
JSONObject jsonSuggestion = (JSONObject)suggestion;
|
||||
|
||||
String name = (String)jsonSuggestion.get("name");
|
||||
|
||||
if(displayName2.equals(name)) {
|
||||
foundDisplayName = true;
|
||||
}
|
||||
}
|
||||
|
||||
assertTrue(foundDisplayName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable/enable status shouldn't affect the search
|
||||
*/
|
||||
|
||||
@@ -23,18 +23,24 @@
|
||||
*/
|
||||
package hudson.tasks;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
import static org.junit.Assert.*;
|
||||
import hudson.Launcher;
|
||||
import hudson.maven.MavenModuleSet;
|
||||
import hudson.maven.MavenModuleSetBuild;
|
||||
import hudson.model.AbstractBuild;
|
||||
import hudson.model.AbstractProject;
|
||||
import hudson.model.Action;
|
||||
import hudson.model.BuildListener;
|
||||
import hudson.model.Cause;
|
||||
import hudson.model.Computer;
|
||||
import hudson.model.FreeStyleBuild;
|
||||
import hudson.model.FreeStyleProject;
|
||||
import hudson.model.DependencyGraph;
|
||||
import hudson.model.DependencyGraph.Dependency;
|
||||
import hudson.model.Item;
|
||||
import hudson.model.Result;
|
||||
import hudson.model.Run;
|
||||
import hudson.model.TaskListener;
|
||||
import hudson.model.User;
|
||||
import hudson.security.ACL;
|
||||
import hudson.security.AuthorizationMatrixProperty;
|
||||
@@ -42,53 +48,60 @@ import hudson.security.LegacySecurityRealm;
|
||||
import hudson.security.Permission;
|
||||
import hudson.security.ProjectMatrixAuthorizationStrategy;
|
||||
import hudson.util.FormValidation;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.List;
|
||||
|
||||
import javax.annotation.CheckForNull;
|
||||
|
||||
import jenkins.model.Jenkins;
|
||||
import jenkins.security.QueueItemAuthenticatorConfiguration;
|
||||
import jenkins.triggers.ReverseBuildTriggerTest;
|
||||
|
||||
import org.acegisecurity.Authentication;
|
||||
import org.acegisecurity.context.SecurityContext;
|
||||
import org.acegisecurity.context.SecurityContextHolder;
|
||||
import org.dom4j.DocumentException;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.ExtractResourceSCM;
|
||||
import org.jvnet.hudson.test.HudsonTestCase;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.JenkinsRule.WebClient;
|
||||
import org.jvnet.hudson.test.TestBuilder;
|
||||
import org.jvnet.hudson.test.TestNotifier;
|
||||
import org.jvnet.hudson.test.MockBuilder;
|
||||
import org.jvnet.hudson.test.MockQueueItemAuthenticator;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
/**
|
||||
* Tests for hudson.tasks.BuildTrigger
|
||||
* @author Alan.Harder@sun.com
|
||||
*/
|
||||
public class BuildTriggerTest extends HudsonTestCase {
|
||||
public class BuildTriggerTest {
|
||||
|
||||
public @Rule JenkinsRule j = new JenkinsRule();
|
||||
|
||||
private FreeStyleProject createDownstreamProject() throws Exception {
|
||||
FreeStyleProject dp = createFreeStyleProject("downstream");
|
||||
|
||||
// Hm, no setQuietPeriod, have to submit form..
|
||||
WebClient webClient = new WebClient();
|
||||
HtmlPage page = webClient.getPage(dp,"configure");
|
||||
HtmlForm form = page.getFormByName("config");
|
||||
form.getInputByName("hasCustomQuietPeriod").click();
|
||||
form.getInputByName("quiet_period").setValueAttribute("0");
|
||||
submit(form);
|
||||
assertEquals("set quiet period", 0, dp.getQuietPeriod());
|
||||
|
||||
FreeStyleProject dp = j.createFreeStyleProject("downstream");
|
||||
dp.setQuietPeriod(0);
|
||||
return dp;
|
||||
}
|
||||
|
||||
private void doTriggerTest(boolean evenWhenUnstable, Result triggerResult,
|
||||
Result dontTriggerResult) throws Exception {
|
||||
FreeStyleProject p = createFreeStyleProject(),
|
||||
dp = createDownstreamProject();
|
||||
FreeStyleProject p = j.createFreeStyleProject();
|
||||
FreeStyleProject dp = createDownstreamProject();
|
||||
p.getPublishersList().add(new BuildTrigger("downstream", evenWhenUnstable));
|
||||
p.getBuildersList().add(new MockBuilder(dontTriggerResult));
|
||||
jenkins.rebuildDependencyGraph();
|
||||
j.jenkins.rebuildDependencyGraph();
|
||||
|
||||
// First build should not trigger downstream job
|
||||
FreeStyleBuild b = p.scheduleBuild2(0).get();
|
||||
@@ -103,22 +116,25 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
private void assertNoDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
Thread.sleep(200);
|
||||
assertTrue("downstream build should not run! upstream log: " + getLog(b),
|
||||
assertTrue("downstream build should not run! upstream log: " + b.getLog(),
|
||||
!dp.isInQueue() && !dp.isBuilding() && dp.getLastBuild()==null);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {
|
||||
private FreeStyleBuild assertDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {
|
||||
// Wait for downstream build
|
||||
for (int i = 0; dp.getLastBuild()==null && i < 20; i++) Thread.sleep(100);
|
||||
assertNotNull("downstream build didn't run.. upstream log: " + getLog(b), dp.getLastBuild());
|
||||
assertNotNull("downstream build didn't run.. upstream log: " + b.getLog(), dp.getLastBuild());
|
||||
return dp.getLastBuild();
|
||||
}
|
||||
|
||||
public void testBuildTrigger() throws Exception {
|
||||
@Test
|
||||
public void buildTrigger() throws Exception {
|
||||
doTriggerTest(false, Result.SUCCESS, Result.UNSTABLE);
|
||||
}
|
||||
|
||||
public void testTriggerEvenWhenUnstable() throws Exception {
|
||||
@Test
|
||||
public void triggerEvenWhenUnstable() throws Exception {
|
||||
doTriggerTest(true, Result.UNSTABLE, Result.FAILURE);
|
||||
}
|
||||
|
||||
@@ -129,13 +145,13 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
new SAXReader().read(problematic);
|
||||
} catch (DocumentException x) {
|
||||
x.printStackTrace();
|
||||
return;
|
||||
// JUnit 4: Assume.assumeNoException("somehow maven-surefire-plugin-2.4.3.pom got corrupted on CI builders", x);
|
||||
// somehow maven-surefire-plugin-2.4.3.pom got corrupted on CI builders
|
||||
Assume.assumeNoException(x);
|
||||
}
|
||||
}
|
||||
FreeStyleProject dp = createDownstreamProject();
|
||||
configureDefaultMaven();
|
||||
MavenModuleSet m = createMavenProject();
|
||||
j.configureDefaultMaven();
|
||||
MavenModuleSet m = j.createMavenProject();
|
||||
m.getPublishersList().add(new BuildTrigger("downstream", evenWhenUnstable));
|
||||
if (!evenWhenUnstable) {
|
||||
// Configure for UNSTABLE
|
||||
@@ -160,23 +176,26 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
assertDownstreamBuild(dp, b);
|
||||
}
|
||||
|
||||
public void testMavenBuildTrigger() throws Exception {
|
||||
@Test
|
||||
public void mavenBuildTrigger() throws Exception {
|
||||
doMavenTriggerTest(false);
|
||||
}
|
||||
|
||||
public void testMavenTriggerEvenWhenUnstable() throws Exception {
|
||||
@Test
|
||||
public void mavenTriggerEvenWhenUnstable() throws Exception {
|
||||
doMavenTriggerTest(true);
|
||||
}
|
||||
|
||||
/** @see ReverseBuildTriggerTest#upstreamProjectSecurity */
|
||||
public void testDownstreamProjectSecurity() throws Exception {
|
||||
jenkins.setSecurityRealm(new LegacySecurityRealm());
|
||||
@Test
|
||||
public void downstreamProjectSecurity() throws Exception {
|
||||
j.jenkins.setSecurityRealm(new LegacySecurityRealm());
|
||||
ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy();
|
||||
auth.add(Jenkins.READ, "alice");
|
||||
auth.add(Computer.BUILD, "alice");
|
||||
auth.add(Computer.BUILD, "anonymous");
|
||||
jenkins.setAuthorizationStrategy(auth);
|
||||
final FreeStyleProject upstream = createFreeStyleProject("upstream");
|
||||
j.jenkins.setAuthorizationStrategy(auth);
|
||||
final FreeStyleProject upstream =j. createFreeStyleProject("upstream");
|
||||
Authentication alice = User.get("alice").impersonate();
|
||||
QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new MockQueueItemAuthenticator(Collections.singletonMap("upstream", alice)));
|
||||
Map<Permission,Set<String>> perms = new HashMap<Permission,Set<String>>();
|
||||
@@ -184,9 +203,9 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
perms.put(Item.CONFIGURE, Collections.singleton("alice"));
|
||||
upstream.addProperty(new AuthorizationMatrixProperty(perms));
|
||||
String downstreamName = "d0wnstr3am"; // do not clash with English messages!
|
||||
FreeStyleProject downstream = createFreeStyleProject(downstreamName);
|
||||
FreeStyleProject downstream = j.createFreeStyleProject(downstreamName);
|
||||
upstream.getPublishersList().add(new BuildTrigger(downstreamName, Result.SUCCESS));
|
||||
jenkins.rebuildDependencyGraph();
|
||||
j.jenkins.rebuildDependencyGraph();
|
||||
/* The long way:
|
||||
WebClient wc = createWebClient();
|
||||
wc.login("alice");
|
||||
@@ -201,9 +220,9 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
assertEquals(Collections.singletonList(downstream), upstream.getDownstreamProjects());
|
||||
// Downstream projects whose existence we are not aware of will silently not be triggered:
|
||||
assertDoCheck(alice, Messages.BuildTrigger_NoSuchProject(downstreamName, "upstream"), upstream, downstreamName);
|
||||
FreeStyleBuild b = buildAndAssertSuccess(upstream);
|
||||
assertLogNotContains(downstreamName, b);
|
||||
waitUntilNoActivity();
|
||||
FreeStyleBuild b = j.buildAndAssertSuccess(upstream);
|
||||
j.assertLogNotContains(downstreamName, b);
|
||||
j.waitUntilNoActivity();
|
||||
assertNull(downstream.getLastBuild());
|
||||
// If we can see them, but not build them, that is a warning (but this is in cleanUp so the build is still considered a success):
|
||||
Map<Permission,Set<String>> grantedPermissions = new HashMap<Permission,Set<String>>();
|
||||
@@ -211,9 +230,9 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
AuthorizationMatrixProperty amp = new AuthorizationMatrixProperty(grantedPermissions);
|
||||
downstream.addProperty(amp);
|
||||
assertDoCheck(alice, Messages.BuildTrigger_you_have_no_permission_to_build_(downstreamName), upstream, downstreamName);
|
||||
b = buildAndAssertSuccess(upstream);
|
||||
assertLogContains(downstreamName, b);
|
||||
waitUntilNoActivity();
|
||||
b = j.buildAndAssertSuccess(upstream);
|
||||
j.assertLogContains(downstreamName, b);
|
||||
j.waitUntilNoActivity();
|
||||
assertNull(downstream.getLastBuild());
|
||||
// If we can build them, then great:
|
||||
grantedPermissions.put(Item.BUILD, Collections.singleton("alice"));
|
||||
@@ -221,9 +240,9 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
amp = new AuthorizationMatrixProperty(grantedPermissions);
|
||||
downstream.addProperty(amp);
|
||||
assertDoCheck(alice, null, upstream, downstreamName);
|
||||
b = buildAndAssertSuccess(upstream);
|
||||
assertLogContains(downstreamName, b);
|
||||
waitUntilNoActivity();
|
||||
b = j.buildAndAssertSuccess(upstream);
|
||||
j.assertLogContains(downstreamName, b);
|
||||
j.waitUntilNoActivity();
|
||||
FreeStyleBuild b2 = downstream.getLastBuild();
|
||||
assertNotNull(b2);
|
||||
Cause.UpstreamCause cause = b2.getCause(Cause.UpstreamCause.class);
|
||||
@@ -232,10 +251,10 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
// Now if we have configured some QIA’s but they are not active on this job, we should run as anonymous. Which would normally have no permissions:
|
||||
QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(Collections.<String,Authentication>emptyMap()));
|
||||
assertDoCheck(alice, Messages.BuildTrigger_you_have_no_permission_to_build_(downstreamName), upstream, downstreamName);
|
||||
b = buildAndAssertSuccess(upstream);
|
||||
assertLogNotContains(downstreamName, b);
|
||||
assertLogContains(Messages.BuildTrigger_warning_this_build_has_no_associated_aut(), b);
|
||||
waitUntilNoActivity();
|
||||
b = j.buildAndAssertSuccess(upstream);
|
||||
j.assertLogNotContains(downstreamName, b);
|
||||
j.assertLogContains(Messages.BuildTrigger_warning_this_build_has_no_associated_aut(), b);
|
||||
j.waitUntilNoActivity();
|
||||
assertEquals(1, downstream.getLastBuild().number);
|
||||
// Unless we explicitly granted them:
|
||||
grantedPermissions.put(Item.READ, Collections.singleton("anonymous"));
|
||||
@@ -244,14 +263,14 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
amp = new AuthorizationMatrixProperty(grantedPermissions);
|
||||
downstream.addProperty(amp);
|
||||
assertDoCheck(alice, null, upstream, downstreamName);
|
||||
b = buildAndAssertSuccess(upstream);
|
||||
assertLogContains(downstreamName, b);
|
||||
waitUntilNoActivity();
|
||||
b = j.buildAndAssertSuccess(upstream);
|
||||
j.assertLogContains(downstreamName, b);
|
||||
j.waitUntilNoActivity();
|
||||
assertEquals(2, downstream.getLastBuild().number);
|
||||
FreeStyleProject simple = createFreeStyleProject("simple");
|
||||
FreeStyleBuild b3 = buildAndAssertSuccess(simple);
|
||||
FreeStyleProject simple = j.createFreeStyleProject("simple");
|
||||
FreeStyleBuild b3 = j.buildAndAssertSuccess(simple);
|
||||
// See discussion in BuildTrigger for why this is necessary:
|
||||
assertLogContains(Messages.BuildTrigger_warning_this_build_has_no_associated_aut(), b3);
|
||||
j.assertLogContains(Messages.BuildTrigger_warning_this_build_has_no_associated_aut(), b3);
|
||||
// Finally, in legacy mode we run as SYSTEM:
|
||||
grantedPermissions.clear(); // similar behavior but different message if DescriptorImpl removed
|
||||
downstream.removeProperty(amp);
|
||||
@@ -259,19 +278,19 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
downstream.addProperty(amp);
|
||||
QueueItemAuthenticatorConfiguration.get().getAuthenticators().clear();
|
||||
assertDoCheck(alice, Messages.BuildTrigger_NoSuchProject(downstreamName, "upstream"), upstream, downstreamName);
|
||||
b = buildAndAssertSuccess(upstream);
|
||||
assertLogContains(downstreamName, b);
|
||||
assertLogContains(Messages.BuildTrigger_warning_access_control_for_builds_in_glo(), b);
|
||||
waitUntilNoActivity();
|
||||
b = j.buildAndAssertSuccess(upstream);
|
||||
j.assertLogContains(downstreamName, b);
|
||||
j.assertLogContains(Messages.BuildTrigger_warning_access_control_for_builds_in_glo(), b);
|
||||
j.waitUntilNoActivity();
|
||||
assertEquals(3, downstream.getLastBuild().number);
|
||||
b3 = buildAndAssertSuccess(simple);
|
||||
assertLogNotContains(Messages.BuildTrigger_warning_access_control_for_builds_in_glo(), b3);
|
||||
b3 = j.buildAndAssertSuccess(simple);
|
||||
j.assertLogNotContains(Messages.BuildTrigger_warning_access_control_for_builds_in_glo(), b3);
|
||||
}
|
||||
private void assertDoCheck(Authentication auth, @CheckForNull String expectedError, AbstractProject project, String value) {
|
||||
private void assertDoCheck(Authentication auth, @CheckForNull String expectedError, AbstractProject<?, ?> project, String value) {
|
||||
FormValidation result;
|
||||
SecurityContext orig = ACL.impersonate(auth);
|
||||
try {
|
||||
result = jenkins.getDescriptorByType(BuildTrigger.DescriptorImpl.class).doCheck(project, value);
|
||||
result = j.jenkins.getDescriptorByType(BuildTrigger.DescriptorImpl.class).doCheck(project, value);
|
||||
} finally {
|
||||
SecurityContextHolder.setContext(orig);
|
||||
}
|
||||
@@ -283,4 +302,123 @@ public class BuildTriggerTest extends HudsonTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@Test @Issue("JENKINS-20989")
|
||||
public void downstreamProjectShouldObserveCompletedParent() throws Exception {
|
||||
j.jenkins.setNumExecutors(2);
|
||||
|
||||
final FreeStyleProject us = j.createFreeStyleProject();
|
||||
us.getPublishersList().add(new BuildTrigger("downstream", true));
|
||||
us.getPublishersList().add(new TestNotifier() {
|
||||
@Override
|
||||
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
Thread.sleep(5000); // Build does not complete just after the BuildTrigger
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
FreeStyleProject ds = createDownstreamProject();
|
||||
ds.getBuildersList().add(new AssertTriggerBuildCompleted(us, j.createWebClient()));
|
||||
|
||||
j.jenkins.rebuildDependencyGraph();
|
||||
|
||||
j.buildAndAssertSuccess(us);
|
||||
|
||||
final FreeStyleBuild dsb = ds.getBuildByNumber(1);
|
||||
j.waitForCompletion(dsb);
|
||||
j.assertBuildStatusSuccess(dsb);
|
||||
}
|
||||
|
||||
@Test @Issue("JENKINS-20989")
|
||||
public void allDownstreamProjectsShouldObserveCompletedParent() throws Exception {
|
||||
j.jenkins.setNumExecutors(3);
|
||||
|
||||
final FreeStyleProject us = j.createFreeStyleProject();
|
||||
us.getPublishersList().add(new SlowTrigger("downstream,downstream2"));
|
||||
|
||||
FreeStyleProject ds = createDownstreamProject();
|
||||
ds.getBuildersList().add(new AssertTriggerBuildCompleted(us, j.createWebClient()));
|
||||
FreeStyleProject ds2 = j.createFreeStyleProject("downstream2");
|
||||
ds2.setQuietPeriod(0);
|
||||
ds2.getBuildersList().add(new AssertTriggerBuildCompleted(us, j.createWebClient()));
|
||||
|
||||
j.jenkins.rebuildDependencyGraph();
|
||||
|
||||
FreeStyleBuild upstream = j.buildAndAssertSuccess(us);
|
||||
|
||||
FreeStyleBuild dsb = assertDownstreamBuild(ds, upstream);
|
||||
j.waitForCompletion(dsb);
|
||||
j.assertBuildStatusSuccess(dsb);
|
||||
|
||||
dsb = assertDownstreamBuild(ds2, upstream);
|
||||
j.waitForCompletion(dsb);
|
||||
j.assertBuildStatusSuccess(dsb);
|
||||
}
|
||||
|
||||
// Trigger that goes through dependencies very slowly
|
||||
private static final class SlowTrigger extends BuildTrigger {
|
||||
|
||||
private static final class Dep extends Dependency {
|
||||
private static boolean block = false;
|
||||
private Dep(AbstractProject upstream, AbstractProject downstream) {
|
||||
super(upstream, downstream);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener, List<Action> actions) {
|
||||
if (block) {
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException ex) {
|
||||
throw new AssertionError(ex);
|
||||
}
|
||||
}
|
||||
block = true;
|
||||
final boolean should = super.shouldTriggerBuild(build, listener, actions);
|
||||
return should;
|
||||
}
|
||||
}
|
||||
|
||||
public SlowTrigger(String childProjects) {
|
||||
super(childProjects, true);
|
||||
}
|
||||
|
||||
@Override @SuppressWarnings("rawtypes")
|
||||
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) {
|
||||
for (AbstractProject ch: getChildProjects(owner)) {
|
||||
graph.addDependency(new Dep(owner, ch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fail downstream build if upstream is not completed yet
|
||||
private static final class AssertTriggerBuildCompleted extends TestBuilder {
|
||||
private final FreeStyleProject us;
|
||||
private final WebClient wc;
|
||||
|
||||
private AssertTriggerBuildCompleted(FreeStyleProject us, WebClient wc) {
|
||||
this.us = us;
|
||||
this.wc = wc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
FreeStyleBuild success = us.getLastSuccessfulBuild();
|
||||
FreeStyleBuild last = us.getLastBuild();
|
||||
try {
|
||||
assertFalse("Upstream build is not completed after downstream started", last.isBuilding());
|
||||
assertNotNull("Upstream build permalink not correctly updated", success);
|
||||
assertEquals(1, success.getNumber());
|
||||
} catch (AssertionError ex) {
|
||||
System.err.println("Upstream build log: " + last.getLog());
|
||||
throw ex;
|
||||
}
|
||||
|
||||
try {
|
||||
wc.getPage(us, "lastSuccessfulBuild");
|
||||
} catch (SAXException ex) {
|
||||
throw new AssertionError(ex);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,27 +23,38 @@
|
||||
*/
|
||||
package hudson.tasks;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import hudson.Launcher;
|
||||
import hudson.model.AbstractBuild;
|
||||
import hudson.model.BuildListener;
|
||||
import hudson.model.Descriptor;
|
||||
import hudson.model.FreeStyleBuild;
|
||||
import hudson.model.FreeStyleProject;
|
||||
import hudson.model.Result;
|
||||
import hudson.model.Run;
|
||||
import hudson.model.queue.QueueTaskFuture;
|
||||
import hudson.tasks.ArtifactArchiverTest.CreateArtifact;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.FailureBuilder;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.TestBuilder;
|
||||
|
||||
/**
|
||||
* Verifies that the last successful and stable builds of a job will be kept if requested.
|
||||
@@ -136,6 +147,59 @@ public class LogRotatorTest {
|
||||
assertTrue(project.getBuildByNumber(7).getHasArtifacts());
|
||||
assertTrue(project.getBuildByNumber(8).getHasArtifacts());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Issue("JENKINS-27836")
|
||||
public void artifactsRetainedWhileBuilding() throws Exception {
|
||||
j.getInstance().setNumExecutors(3);
|
||||
FreeStyleProject p = j.createFreeStyleProject();
|
||||
p.setBuildDiscarder(new LogRotator(-1, 3, -1, 1));
|
||||
StallBuilder sync = new StallBuilder();
|
||||
p.getBuildersList().replaceBy(Arrays.asList(new CreateArtifact(), sync));
|
||||
p.setConcurrentBuild(true);
|
||||
QueueTaskFuture<FreeStyleBuild> futureRun1 = p.scheduleBuild2(0);
|
||||
FreeStyleBuild run1 = futureRun1.waitForStart();
|
||||
sync.waitFor(run1.getNumber(), 1, TimeUnit.SECONDS);
|
||||
QueueTaskFuture<FreeStyleBuild> futureRun2 = p.scheduleBuild2(0);
|
||||
FreeStyleBuild run2 = futureRun2.waitForStart();
|
||||
sync.waitFor(run2.getNumber(), 1, TimeUnit.SECONDS);
|
||||
QueueTaskFuture<FreeStyleBuild> futureRun3 = p.scheduleBuild2(0);
|
||||
FreeStyleBuild run3 = futureRun3.waitForStart();
|
||||
sync.waitFor(run3.getNumber(), 1, TimeUnit.SECONDS);
|
||||
assertThat("we haven't released run1's guard", run1.isBuilding(), is(true));
|
||||
assertThat("we haven't released run2's guard", run2.isBuilding(), is(true));
|
||||
assertThat("we haven't released run3's guard", run3.isBuilding(), is(true));
|
||||
assertThat("we have artifacts in run1", run1.getHasArtifacts(), is(true));
|
||||
assertThat("we have artifacts in run2", run2.getHasArtifacts(), is(true));
|
||||
assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true));
|
||||
sync.release(run1.getNumber());
|
||||
futureRun1.get();
|
||||
assertThat("we have released run1's guard", run1.isBuilding(), is(false));
|
||||
assertThat("we haven't released run2's guard", run2.isBuilding(), is(true));
|
||||
assertThat("we haven't released run3's guard", run3.isBuilding(), is(true));
|
||||
assertThat("run1 is last stable build", p.getLastStableBuild(), is(run1));
|
||||
assertThat("run1 is last successful build", p.getLastSuccessfulBuild(), is(run1));
|
||||
assertThat("we have artifacts in run1", run1.getHasArtifacts(), is(true));
|
||||
assertThat("CRITICAL ASSERTION: we have artifacts in run2", run2.getHasArtifacts(), is(true));
|
||||
assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true));
|
||||
sync.release(run2.getNumber());
|
||||
futureRun2.get();
|
||||
assertThat("we have released run2's guard", run2.isBuilding(), is(false));
|
||||
assertThat("we haven't released run3's guard", run3.isBuilding(), is(true));
|
||||
assertThat("we have no artifacts in run1", run1.getHasArtifacts(), is(false));
|
||||
assertThat("run2 is last stable build", p.getLastStableBuild(), is(run2));
|
||||
assertThat("run2 is last successful build", p.getLastSuccessfulBuild(), is(run2));
|
||||
assertThat("we have artifacts in run2", run2.getHasArtifacts(), is(true));
|
||||
assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true));
|
||||
sync.release(run3.getNumber());
|
||||
futureRun3.get();
|
||||
assertThat("we have released run3's guard", run3.isBuilding(), is(false));
|
||||
assertThat("we have no artifacts in run1", run1.getHasArtifacts(), is(false));
|
||||
assertThat("we have no artifacts in run2", run2.getHasArtifacts(), is(false));
|
||||
assertThat("run3 is last stable build", p.getLastStableBuild(), is(run3));
|
||||
assertThat("run3 is last successful build", p.getLastSuccessfulBuild(), is(run3));
|
||||
assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true));
|
||||
}
|
||||
|
||||
static Result build(FreeStyleProject project) throws Exception {
|
||||
return project.scheduleBuild2(0).get().getResult();
|
||||
@@ -163,4 +227,71 @@ public class LogRotatorTest {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
static class StallBuilder extends TestBuilder {
|
||||
|
||||
private int syncBuildNumber;
|
||||
|
||||
private final Object syncLock = new Object();
|
||||
|
||||
private int waitBuildNumber;
|
||||
|
||||
private final Object waitLock = new Object();
|
||||
|
||||
private final ArtifactArchiver archiver = new ArtifactArchiver("f");
|
||||
|
||||
public @Override boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener)
|
||||
throws IOException, InterruptedException {
|
||||
archiver.perform(build, launcher, listener);
|
||||
Logger.getAnonymousLogger().log(Level.INFO, "Building #{0}", build.getNumber());
|
||||
synchronized (waitLock) {
|
||||
if (waitBuildNumber < build.getNumber()) {
|
||||
waitBuildNumber = build.getNumber();
|
||||
waitLock.notifyAll();
|
||||
}
|
||||
}
|
||||
Logger.getAnonymousLogger().log(Level.INFO, "Waiting #{0}", build.getNumber());
|
||||
synchronized (syncLock) {
|
||||
while (build.getNumber() > syncBuildNumber) {
|
||||
try {
|
||||
syncLock.wait(10);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace(listener.fatalError("Interrupted: %s", e.getMessage()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Logger.getAnonymousLogger().log(Level.INFO, "Done #{0}", build.getNumber());
|
||||
return true;
|
||||
}
|
||||
|
||||
public void release(int upToBuildNumber) {
|
||||
synchronized (syncLock) {
|
||||
if (syncBuildNumber < upToBuildNumber) {
|
||||
Logger.getAnonymousLogger().log(Level.INFO, "Signal #{0}", upToBuildNumber);
|
||||
syncBuildNumber = upToBuildNumber;
|
||||
syncLock.notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void waitFor(int buildNumber, long timeout, TimeUnit units) throws TimeoutException,
|
||||
InterruptedException {
|
||||
long giveUp = System.nanoTime() + units.toNanos(timeout);
|
||||
synchronized (waitLock) {
|
||||
while (waitBuildNumber < buildNumber) {
|
||||
long remaining = giveUp - System.nanoTime();
|
||||
if (remaining < 0) {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
waitLock.wait(remaining/1000000L, (int)(remaining%1000000L));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public BuildStepMonitor getRequiredMonitorService() {
|
||||
return BuildStepMonitor.NONE;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ public class JenkinsReloadConfigurationTest {
|
||||
}
|
||||
|
||||
private void modifyNode(Node node) throws Exception {
|
||||
replace("config.xml", "oldLabel", "newLabel");
|
||||
replace(node.getNodeName().equals("") ? "config.xml" : String.format("nodes/%s/config.xml",node.getNodeName()), "oldLabel", "newLabel");
|
||||
|
||||
assertEquals("oldLabel", node.getLabelString());
|
||||
|
||||
|
||||
@@ -23,14 +23,20 @@
|
||||
*/
|
||||
package jenkins.model;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
|
||||
import com.gargoylesoftware.htmlunit.HttpMethod;
|
||||
import com.gargoylesoftware.htmlunit.Page;
|
||||
import com.gargoylesoftware.htmlunit.WebRequestSettings;
|
||||
import com.gargoylesoftware.htmlunit.WebResponse;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlForm;
|
||||
import com.gargoylesoftware.htmlunit.html.HtmlPage;
|
||||
|
||||
@@ -49,13 +55,16 @@ import hudson.security.GlobalMatrixAuthorizationStrategy;
|
||||
import hudson.security.LegacySecurityRealm;
|
||||
import hudson.security.Permission;
|
||||
import hudson.slaves.ComputerListener;
|
||||
import hudson.slaves.DumbSlave;
|
||||
import hudson.slaves.OfflineCause;
|
||||
import hudson.util.FormValidation;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.ExtractResourceSCM;
|
||||
import org.jvnet.hudson.test.HudsonTestCase;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.JenkinsRule.WebClient;
|
||||
import org.jvnet.hudson.test.TestExtension;
|
||||
import org.kohsuke.stapler.HttpResponse;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -68,16 +77,18 @@ import java.net.URL;
|
||||
* @author kingfai
|
||||
*
|
||||
*/
|
||||
public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction {
|
||||
public class JenkinsTest {
|
||||
|
||||
@Rule public JenkinsRule j = new JenkinsRule();
|
||||
|
||||
@Test
|
||||
public void testIsDisplayNameUniqueTrue() throws Exception {
|
||||
final String curJobName = "curJobName";
|
||||
final String jobName = "jobName";
|
||||
FreeStyleProject curProject = createFreeStyleProject(curJobName);
|
||||
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
|
||||
curProject.setDisplayName("currentProjectDisplayName");
|
||||
|
||||
FreeStyleProject p = createFreeStyleProject(jobName);
|
||||
FreeStyleProject p = j.createFreeStyleProject(jobName);
|
||||
p.setDisplayName("displayName");
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
@@ -91,10 +102,10 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
final String jobName = "jobName";
|
||||
final String displayName = "displayName";
|
||||
|
||||
FreeStyleProject curProject = createFreeStyleProject(curJobName);
|
||||
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
|
||||
curProject.setDisplayName("currentProjectDisplayName");
|
||||
|
||||
FreeStyleProject p = createFreeStyleProject(jobName);
|
||||
FreeStyleProject p = j.createFreeStyleProject(jobName);
|
||||
p.setDisplayName(displayName);
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
@@ -106,21 +117,20 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
final String curJobName = "curJobName";
|
||||
final String displayName = "currentProjectDisplayName";
|
||||
|
||||
FreeStyleProject curProject = createFreeStyleProject(curJobName);
|
||||
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
|
||||
curProject.setDisplayName(displayName);
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
// should be true as we don't test against the current job
|
||||
assertTrue(jenkins.isDisplayNameUnique(displayName, curJobName));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsNameUniqueTrue() throws Exception {
|
||||
final String curJobName = "curJobName";
|
||||
final String jobName = "jobName";
|
||||
createFreeStyleProject(curJobName);
|
||||
createFreeStyleProject(jobName);
|
||||
j.createFreeStyleProject(curJobName);
|
||||
j.createFreeStyleProject(jobName);
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
assertTrue(jenkins.isNameUnique("jobName1", curJobName));
|
||||
@@ -130,8 +140,8 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
public void testIsNameUniqueFalse() throws Exception {
|
||||
final String curJobName = "curJobName";
|
||||
final String jobName = "jobName";
|
||||
createFreeStyleProject(curJobName);
|
||||
createFreeStyleProject(jobName);
|
||||
j.createFreeStyleProject(curJobName);
|
||||
j.createFreeStyleProject(jobName);
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
assertFalse(jenkins.isNameUnique(jobName, curJobName));
|
||||
@@ -141,8 +151,8 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
public void testIsNameUniqueSameAsCurrentJob() throws Exception {
|
||||
final String curJobName = "curJobName";
|
||||
final String jobName = "jobName";
|
||||
createFreeStyleProject(curJobName);
|
||||
createFreeStyleProject(jobName);
|
||||
j.createFreeStyleProject(curJobName);
|
||||
j.createFreeStyleProject(jobName);
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
// true because we don't test against the current job
|
||||
@@ -153,10 +163,10 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
public void testDoCheckDisplayNameUnique() throws Exception {
|
||||
final String curJobName = "curJobName";
|
||||
final String jobName = "jobName";
|
||||
FreeStyleProject curProject = createFreeStyleProject(curJobName);
|
||||
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
|
||||
curProject.setDisplayName("currentProjectDisplayName");
|
||||
|
||||
FreeStyleProject p = createFreeStyleProject(jobName);
|
||||
FreeStyleProject p = j.createFreeStyleProject(jobName);
|
||||
p.setDisplayName("displayName");
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
@@ -169,10 +179,10 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
final String curJobName = "curJobName";
|
||||
final String jobName = "jobName";
|
||||
final String displayName = "displayName";
|
||||
FreeStyleProject curProject = createFreeStyleProject(curJobName);
|
||||
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
|
||||
curProject.setDisplayName("currentProjectDisplayName");
|
||||
|
||||
FreeStyleProject p = createFreeStyleProject(jobName);
|
||||
FreeStyleProject p = j.createFreeStyleProject(jobName);
|
||||
p.setDisplayName(displayName);
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
@@ -185,10 +195,10 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
final String curJobName = "curJobName";
|
||||
final String jobName = "jobName";
|
||||
final String displayName = "displayName";
|
||||
FreeStyleProject curProject = createFreeStyleProject(curJobName);
|
||||
FreeStyleProject curProject = j.createFreeStyleProject(curJobName);
|
||||
curProject.setDisplayName("currentProjectDisplayName");
|
||||
|
||||
FreeStyleProject p = createFreeStyleProject(jobName);
|
||||
FreeStyleProject p = j.createFreeStyleProject(jobName);
|
||||
p.setDisplayName(displayName);
|
||||
|
||||
Jenkins jenkins = Jenkins.getInstance();
|
||||
@@ -224,15 +234,15 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
}
|
||||
}
|
||||
|
||||
@Issue("JENKINS-12251")
|
||||
@Test @Issue("JENKINS-12251")
|
||||
public void testItemFullNameExpansion() throws Exception {
|
||||
HtmlForm f = createWebClient().goTo("/configure").getFormByName("config");
|
||||
HtmlForm f = j.createWebClient().goTo("configure").getFormByName("config");
|
||||
f.getInputByName("_.rawBuildsDir").setValueAttribute("${JENKINS_HOME}/test12251_builds/${ITEM_FULL_NAME}");
|
||||
f.getInputByName("_.rawWorkspaceDir").setValueAttribute("${JENKINS_HOME}/test12251_ws/${ITEM_FULL_NAME}");
|
||||
submit(f);
|
||||
j.submit(f);
|
||||
|
||||
// build a dummy project
|
||||
MavenModuleSet m = createMavenProject();
|
||||
MavenModuleSet m = j.createMavenProject();
|
||||
m.setScm(new ExtractResourceSCM(getClass().getResource("/simple-projects.zip")));
|
||||
MavenModuleSetBuild b = m.scheduleBuild2(0).get();
|
||||
|
||||
@@ -244,23 +254,24 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
/**
|
||||
* Makes sure access to "/foobar" for UnprotectedRootAction gets through.
|
||||
*/
|
||||
@Issue("JENKINS-14113")
|
||||
@Test @Issue("JENKINS-14113")
|
||||
public void testUnprotectedRootAction() throws Exception {
|
||||
jenkins.setSecurityRealm(createDummySecurityRealm());
|
||||
jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
|
||||
WebClient wc = createWebClient();
|
||||
wc.goTo("/foobar");
|
||||
wc.goTo("/foobar/");
|
||||
wc.goTo("/foobar/zot");
|
||||
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
|
||||
j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
|
||||
WebClient wc = j.createWebClient();
|
||||
wc.goTo("foobar");
|
||||
wc.goTo("foobar/");
|
||||
wc.goTo("foobar/zot");
|
||||
|
||||
// and make sure this fails
|
||||
wc.assertFails("/foobar-zot/", HttpURLConnection.HTTP_INTERNAL_ERROR);
|
||||
wc.assertFails("foobar-zot/", HttpURLConnection.HTTP_INTERNAL_ERROR);
|
||||
|
||||
assertEquals(3,jenkins.getExtensionList(RootAction.class).get(RootActionImpl.class).count);
|
||||
assertEquals(3,j.jenkins.getExtensionList(RootAction.class).get(RootActionImpl.class).count);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoScript() throws Exception {
|
||||
jenkins.setSecurityRealm(new LegacySecurityRealm());
|
||||
j.jenkins.setSecurityRealm(new LegacySecurityRealm());
|
||||
GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy() {
|
||||
@Override public boolean hasPermission(String sid, Permission p) {
|
||||
return p == Jenkins.RUN_SCRIPTS ? hasExplicitPermission(sid, p) : super.hasPermission(sid, p);
|
||||
@@ -270,8 +281,8 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
gmas.add(Jenkins.RUN_SCRIPTS, "alice");
|
||||
gmas.add(Jenkins.READ, "bob");
|
||||
gmas.add(Jenkins.ADMINISTER, "charlie");
|
||||
jenkins.setAuthorizationStrategy(gmas);
|
||||
WebClient wc = createWebClient();
|
||||
j.jenkins.setAuthorizationStrategy(gmas);
|
||||
WebClient wc = j.createWebClient();
|
||||
wc.login("alice");
|
||||
wc.goTo("script");
|
||||
wc.assertFails("script?script=System.setProperty('hack','me')", HttpURLConnection.HTTP_BAD_METHOD);
|
||||
@@ -289,8 +300,9 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
wc.assertFails("script", HttpURLConnection.HTTP_FORBIDDEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoEval() throws Exception {
|
||||
jenkins.setSecurityRealm(new LegacySecurityRealm());
|
||||
j.jenkins.setSecurityRealm(new LegacySecurityRealm());
|
||||
GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy() {
|
||||
@Override public boolean hasPermission(String sid, Permission p) {
|
||||
return p == Jenkins.RUN_SCRIPTS ? hasExplicitPermission(sid, p) : super.hasPermission(sid, p);
|
||||
@@ -300,8 +312,8 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
gmas.add(Jenkins.RUN_SCRIPTS, "alice");
|
||||
gmas.add(Jenkins.READ, "bob");
|
||||
gmas.add(Jenkins.ADMINISTER, "charlie");
|
||||
jenkins.setAuthorizationStrategy(gmas);
|
||||
WebClient wc = createWebClient();
|
||||
j.jenkins.setAuthorizationStrategy(gmas);
|
||||
WebClient wc = j.createWebClient();
|
||||
wc.login("alice");
|
||||
wc.assertFails("eval", HttpURLConnection.HTTP_BAD_METHOD);
|
||||
assertEquals("3", eval(wc));
|
||||
@@ -368,41 +380,73 @@ public class JenkinsTest extends HudsonTestCase implements UnprotectedRootAction
|
||||
}
|
||||
}
|
||||
|
||||
@Issue("JENKINS-20866")
|
||||
@Test @Issue("JENKINS-20866")
|
||||
public void testErrorPageShouldBeAnonymousAccessible() throws Exception {
|
||||
HudsonPrivateSecurityRealm s = new HudsonPrivateSecurityRealm(false, false, null);
|
||||
User alice = s.createAccount("alice", "alice");
|
||||
jenkins.setSecurityRealm(s);
|
||||
j.jenkins.setSecurityRealm(s);
|
||||
|
||||
GlobalMatrixAuthorizationStrategy auth = new GlobalMatrixAuthorizationStrategy();
|
||||
jenkins.setAuthorizationStrategy(auth);
|
||||
j.jenkins.setAuthorizationStrategy(auth);
|
||||
|
||||
// no anonymous read access
|
||||
assertTrue(!Jenkins.getInstance().getACL().hasPermission(Jenkins.ANONYMOUS,Jenkins.READ));
|
||||
|
||||
WebClient wc = createWebClient();
|
||||
WebClient wc = j.createWebClient();
|
||||
wc.setThrowExceptionOnFailingStatusCode(false);
|
||||
HtmlPage p = wc.goTo("/self/reportError");
|
||||
HtmlPage p = wc.goTo("error/reportError");
|
||||
|
||||
assertEquals(400, p.getWebResponse().getStatusCode()); // not 403 forbidden
|
||||
assertEquals(p.asText(), 400, p.getWebResponse().getStatusCode()); // not 403 forbidden
|
||||
assertTrue(p.getWebResponse().getContentAsString().contains("My car is black"));
|
||||
}
|
||||
|
||||
public HttpResponse doReportError() {
|
||||
return new Failure("My car is black");
|
||||
@TestExtension("testErrorPageShouldBeAnonymousAccessible")
|
||||
public static class ReportError implements UnprotectedRootAction {
|
||||
|
||||
public String getIconFileName() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getUrlName() {
|
||||
return "error";
|
||||
}
|
||||
|
||||
public HttpResponse doReportError() {
|
||||
return new Failure("My car is black");
|
||||
}
|
||||
}
|
||||
|
||||
@Issue("JENKINS-23551")
|
||||
@Test @Issue("JENKINS-23551")
|
||||
public void testComputerListenerNotifiedOnRestart() {
|
||||
// Simulate restart calling listeners
|
||||
for (RestartListener listener : RestartListener.all())
|
||||
listener.onRestart();
|
||||
|
||||
ArgumentCaptor<OfflineCause> captor = ArgumentCaptor.forClass(OfflineCause.class);
|
||||
Mockito.verify(listenerMock).onOffline(Mockito.eq(jenkins.toComputer()), captor.capture());
|
||||
Mockito.verify(listenerMock).onOffline(Mockito.eq(j.jenkins.toComputer()), captor.capture());
|
||||
assertTrue(captor.getValue().toString().contains("restart"));
|
||||
}
|
||||
|
||||
@TestExtension(value = "testComputerListenerNotifiedOnRestart")
|
||||
public static final ComputerListener listenerMock = Mockito.mock(ComputerListener.class);
|
||||
|
||||
@Test
|
||||
public void runScriptOnOfflineComputer() throws Exception {
|
||||
DumbSlave slave = j.createSlave();
|
||||
URL url = new URL(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)");
|
||||
|
||||
WebClient wc = j.createWebClient();
|
||||
wc.setThrowExceptionOnFailingStatusCode(false);
|
||||
|
||||
WebRequestSettings req = new WebRequestSettings(url, HttpMethod.POST);
|
||||
Page page = wc.getPage(wc.addCrumb(req));
|
||||
WebResponse rsp = page.getWebResponse();
|
||||
|
||||
assertThat(rsp.getContentAsString(), containsString("Node is offline"));
|
||||
assertThat(rsp.getStatusCode(), equalTo(404));
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,6 @@ import java.io.StringWriter;
|
||||
|
||||
import jenkins.security.s2m.AdminWhitelistRule;
|
||||
import jenkins.security.s2m.DefaultFilePathFilter;
|
||||
import jenkins.security.s2m.MasterKillSwitchConfiguration;
|
||||
import org.jenkinsci.remoting.RoleChecker;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -42,6 +41,7 @@ import org.junit.Rule;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
|
||||
public class DefaultFilePathFilterTest {
|
||||
|
||||
@@ -111,4 +111,12 @@ public class DefaultFilePathFilterTest {
|
||||
throw new NoSuchMethodError(); // simulate legacy Callable impls
|
||||
}
|
||||
}
|
||||
|
||||
@Issue("JENKINS-27055")
|
||||
@Test public void matchBuildDir() throws Exception {
|
||||
File f = new File(r.buildAndAssertSuccess(r.createFreeStyleProject()).getRootDir(), "whatever");
|
||||
rule.setMasterKillSwitch(false);
|
||||
assertTrue(rule.checkFileAccess("write", f));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package jenkins.security;
|
||||
|
||||
import com.gargoylesoftware.htmlunit.Page;
|
||||
import java.net.URL;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.JenkinsRule.WebClient;
|
||||
|
||||
/**
|
||||
* @author Kohsuke Kawaguchi
|
||||
*/
|
||||
@Issue("SECURITY-177")
|
||||
public class Security177Test {
|
||||
@Rule
|
||||
public JenkinsRule jenkins = new JenkinsRule();
|
||||
|
||||
@Test
|
||||
public void nosniff() throws Exception {
|
||||
WebClient wc = jenkins.createWebClient();
|
||||
wc.setThrowExceptionOnFailingStatusCode(false);
|
||||
|
||||
URL u = jenkins.getURL();
|
||||
verifyNoSniff(wc.getPage(new URL(u, "adjuncts/507db12b/nosuch/adjunct.js")));
|
||||
verifyNoSniff(wc.getPage(new URL(u, "no-such-page")));
|
||||
verifyNoSniff(wc.getPage(new URL(u, "images/title.svg")));
|
||||
verifyNoSniff(wc.getPage(u));
|
||||
}
|
||||
|
||||
private void verifyNoSniff(Page p) {
|
||||
String v = p.getWebResponse().getResponseHeaderValue("X-Content-Type-Options");
|
||||
assertEquals(v,"nosniff");
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,11 @@ import hudson.EnvVars;
|
||||
import hudson.FilePath;
|
||||
import hudson.Functions;
|
||||
import hudson.Launcher;
|
||||
import hudson.console.ConsoleLogFilter;
|
||||
import hudson.console.LineTransformationOutputStream;
|
||||
import hudson.model.AbstractBuild;
|
||||
import hudson.model.AbstractProject;
|
||||
import hudson.model.BuildListener;
|
||||
import hudson.model.Computer;
|
||||
import hudson.model.Descriptor;
|
||||
import hudson.model.FreeStyleBuild;
|
||||
@@ -45,18 +49,26 @@ import hudson.tasks.BuildWrapperDescriptor;
|
||||
import hudson.tasks.Shell;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.util.Collections;
|
||||
import java.util.Locale;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Assume;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
import org.jvnet.hudson.test.BuildWatcher;
|
||||
import org.jvnet.hudson.test.CaptureEnvironmentBuilder;
|
||||
import org.jvnet.hudson.test.Issue;
|
||||
import org.jvnet.hudson.test.JenkinsRule;
|
||||
import org.jvnet.hudson.test.TestBuilder;
|
||||
import org.jvnet.hudson.test.TestExtension;
|
||||
|
||||
public class SimpleBuildWrapperTest {
|
||||
|
||||
@ClassRule public static BuildWatcher buildWatcher = new BuildWatcher();
|
||||
@Rule public JenkinsRule r = new JenkinsRule();
|
||||
@Rule public TemporaryFolder tmp = new TemporaryFolder();
|
||||
|
||||
@@ -162,7 +174,44 @@ public class SimpleBuildWrapperTest {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Issue("JENKINS-27392")
|
||||
@Test public void loggerDecorator() throws Exception {
|
||||
FreeStyleProject p = r.createFreeStyleProject();
|
||||
p.getBuildWrappersList().add(new WrapperWithLogger());
|
||||
p.getBuildersList().add(new TestBuilder() {
|
||||
@Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
|
||||
listener.getLogger().println("sending a message");
|
||||
return true;
|
||||
}
|
||||
});
|
||||
r.assertLogContains("SENDING A MESSAGE", r.buildAndAssertSuccess(p));
|
||||
}
|
||||
public static class WrapperWithLogger extends SimpleBuildWrapper {
|
||||
@Override public void setUp(Context context, Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {}
|
||||
@Override public ConsoleLogFilter createLoggerDecorator(Run<?,?> build) {
|
||||
return new UpcaseFilter();
|
||||
}
|
||||
private static class UpcaseFilter extends ConsoleLogFilter implements Serializable {
|
||||
private static final long serialVersionUID = 1;
|
||||
@SuppressWarnings("rawtypes") // inherited
|
||||
@Override public OutputStream decorateLogger(AbstractBuild _ignore, final OutputStream logger) throws IOException, InterruptedException {
|
||||
return new LineTransformationOutputStream() {
|
||||
@Override protected void eol(byte[] b, int len) throws IOException {
|
||||
logger.write(new String(b, 0, len).toUpperCase(Locale.ROOT).getBytes());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@TestExtension("loggerDecorator") public static class DescriptorImpl extends BuildWrapperDescriptor {
|
||||
@Override public String getDisplayName() {
|
||||
return "WrapperWithLogger";
|
||||
}
|
||||
@Override public boolean isApplicable(AbstractProject<?,?> item) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?jelly escape-by-default='true'?>
|
||||
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
|
||||
<f:block>
|
||||
<f:repeatableHeteroProperty field="ds"/>
|
||||
</f:block>
|
||||
</j:jelly>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?jelly escape-by-default='true'?>
|
||||
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form">
|
||||
<f:block>
|
||||
<f:repeatableHeteroProperty field="ds"/>
|
||||
</f:block>
|
||||
</j:jelly>
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?jelly escape-by-default='true'?>
|
||||
<j:jelly xmlns:j="jelly:core"/>
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?jelly escape-by-default='true'?>
|
||||
<j:jelly xmlns:j="jelly:core"/>
|
||||
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?jelly escape-by-default='true'?>
|
||||
<j:jelly xmlns:j="jelly:core"/>
|
||||
Reference in new issue
Block a user