提交 73c6974d 编写于 作者: W Wadeck Follonier

[JENKINS-53511] Improve discoverability of new feature in WebClient

上级 3bb56b81
...@@ -33,6 +33,8 @@ import org.jvnet.hudson.test.JenkinsRule; ...@@ -33,6 +33,8 @@ import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockAuthorizationStrategy;
import org.jvnet.hudson.test.SmokeTest; import org.jvnet.hudson.test.SmokeTest;
import java.net.HttpURLConnection;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
...@@ -55,19 +57,19 @@ public class AboutJenkinsTest { ...@@ -55,19 +57,19 @@ public class AboutJenkinsTest {
.grant(Jenkins.READ).everywhere().to(USER) .grant(Jenkins.READ).everywhere().to(USER)
); );
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
{ // user cannot see it { // user cannot see it
wc.login(USER); wc.login(USER);
HtmlPage page = wc.goTo("about/"); HtmlPage page = wc.goTo("about/");
assertEquals(403, page.getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode());
} }
{ // admin can access it { // admin can access it
wc.login(ADMIN); wc.login(ADMIN);
HtmlPage page = wc.goTo("about/"); HtmlPage page = wc.goTo("about/");
assertEquals(200, page.getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode());
assertThat(page.getWebResponse().getContentAsString(), containsString("Mavenized dependencies")); assertThat(page.getWebResponse().getContentAsString(), containsString("Mavenized dependencies"));
} }
} }
......
package hudson; package hudson;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.TextPage; import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.remoting.Base64;
import java.io.IOException; import java.net.HttpURLConnection;
import java.security.KeyFactory; import java.net.URL;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.annotation.Nullable;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import jenkins.model.identity.InstanceIdentityProvider;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.TestExtension;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
public class TcpSlaveAgentListenerTest { public class TcpSlaveAgentListenerTest {
...@@ -37,15 +23,15 @@ public class TcpSlaveAgentListenerTest { ...@@ -37,15 +23,15 @@ public class TcpSlaveAgentListenerTest {
@Test @Test
public void headers() throws Exception { public void headers() throws Exception {
WebClient wc = r.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
r.getInstance().setSlaveAgentPort(-1); r.getInstance().setSlaveAgentPort(-1);
try { wc.assertFails("tcpSlaveAgentListener", HttpURLConnection.HTTP_NOT_FOUND);
r.createWebClient().goTo("tcpSlaveAgentListener");
fail("Should get 404");
} catch (FailingHttpStatusCodeException e) {
assertThat(e.getStatusCode(), is(404));
}
r.getInstance().setSlaveAgentPort(0); r.getInstance().setSlaveAgentPort(0);
Page p = r.createWebClient().goTo("tcpSlaveAgentListener", "text/plain"); Page p = wc.goTo("tcpSlaveAgentListener", "text/plain");
assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode());
assertThat(p.getWebResponse().getResponseHeaderValue("X-Instance-Identity"), notNullValue()); assertThat(p.getWebResponse().getResponseHeaderValue("X-Instance-Identity"), notNullValue());
} }
...@@ -54,15 +40,13 @@ public class TcpSlaveAgentListenerTest { ...@@ -54,15 +40,13 @@ public class TcpSlaveAgentListenerTest {
r.getInstance().setSlaveAgentPort(0); r.getInstance().setSlaveAgentPort(0);
int p = r.jenkins.getTcpSlaveAgentListener().getPort(); int p = r.jenkins.getTcpSlaveAgentListener().getPort();
WebClient wc = r.createWebClient(); WebClient wc = r.createWebClient();
TextPage text = (TextPage) wc.getPage("http://localhost:"+p+"/");
TextPage text = wc.getPage(new URL("http://localhost:" + p + "/"));
String c = text.getContent(); String c = text.getContent();
assertThat(c,containsString(Jenkins.VERSION)); assertThat(c, containsString(Jenkins.VERSION));
try { wc.setThrowExceptionOnFailingStatusCode(false);
wc.getPage("http://localhost:"+p+"/xxx"); Page page = wc.getPage(new URL("http://localhost:" + p + "/xxx"));
fail("Expected 404"); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, page.getWebResponse().getStatusCode());
} catch (FailingHttpStatusCodeException e) {
assertThat(e.getStatusCode(),equalTo(404));
}
} }
} }
...@@ -37,6 +37,7 @@ import java.io.ByteArrayOutputStream; ...@@ -37,6 +37,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
...@@ -234,11 +235,12 @@ public class CLITest { ...@@ -234,11 +235,12 @@ public class CLITest {
sshd.start(); sshd.start();
// Sanity check // Sanity check
JenkinsRule.WebClient wc = r.createWebClient(); JenkinsRule.WebClient wc = r.createWebClient()
wc.getOptions().setRedirectEnabled(false); .withRedirectEnabled(false)
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebResponse rsp = wc.goTo("cli-proxy/").getWebResponse(); WebResponse rsp = wc.goTo("cli-proxy/").getWebResponse();
assertEquals(rsp.getContentAsString(), 302, rsp.getStatusCode()); assertEquals(rsp.getContentAsString(), HttpURLConnection.HTTP_MOVED_TEMP, rsp.getStatusCode());
assertEquals(rsp.getContentAsString(), null, rsp.getResponseHeaderValue("X-Jenkins")); assertEquals(rsp.getContentAsString(), null, rsp.getResponseHeaderValue("X-Jenkins"));
assertEquals(rsp.getContentAsString(), null, rsp.getResponseHeaderValue("X-Jenkins-CLI-Port")); assertEquals(rsp.getContentAsString(), null, rsp.getResponseHeaderValue("X-Jenkins-CLI-Port"));
assertEquals(rsp.getContentAsString(), null, rsp.getResponseHeaderValue("X-SSH-Endpoint")); assertEquals(rsp.getContentAsString(), null, rsp.getResponseHeaderValue("X-SSH-Endpoint"));
...@@ -308,7 +310,7 @@ public class CLITest { ...@@ -308,7 +310,7 @@ public class CLITest {
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
rsp.setHeader("Location", url); rsp.setHeader("Location", url);
rsp.setContentType("text/html"); rsp.setContentType("text/html");
rsp.setStatus(302); rsp.setStatus(HttpURLConnection.HTTP_MOVED_TEMP);
PrintWriter w = rsp.getWriter(); PrintWriter w = rsp.getWriter();
w.append("Redirect to ").append(url); w.append("Redirect to ").append(url);
} }
......
...@@ -5,14 +5,13 @@ import static org.junit.Assert.assertFalse; ...@@ -5,14 +5,13 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair; import com.gargoylesoftware.htmlunit.util.NameValuePair;
import hudson.model.User; import hudson.model.User;
import hudson.security.GlobalMatrixAuthorizationStrategy; import hudson.security.GlobalMatrixAuthorizationStrategy;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import jenkins.security.apitoken.ApiTokenPropertyConfiguration;
import jenkins.security.apitoken.ApiTokenTestHelper; import jenkins.security.apitoken.ApiTokenTestHelper;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
...@@ -24,6 +23,7 @@ import com.gargoylesoftware.htmlunit.html.HtmlForm; ...@@ -24,6 +23,7 @@ import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Collections; import java.util.Collections;
...@@ -63,7 +63,8 @@ public class HudsonHomeDiskUsageMonitorTest { ...@@ -63,7 +63,8 @@ public class HudsonHomeDiskUsageMonitorTest {
public void noAccessForNonAdmin() throws Exception { public void noAccessForNonAdmin() throws Exception {
ApiTokenTestHelper.enableLegacyBehavior(); ApiTokenTestHelper.enableLegacyBehavior();
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
// TODO: Use MockAuthorizationStrategy in later versions // TODO: Use MockAuthorizationStrategy in later versions
JenkinsRule.DummySecurityRealm realm = j.createDummySecurityRealm(); JenkinsRule.DummySecurityRealm realm = j.createDummySecurityRealm();
...@@ -85,26 +86,19 @@ public class HudsonHomeDiskUsageMonitorTest { ...@@ -85,26 +86,19 @@ public class HudsonHomeDiskUsageMonitorTest {
HudsonHomeDiskUsageMonitor mon = HudsonHomeDiskUsageMonitor.get(); HudsonHomeDiskUsageMonitor mon = HudsonHomeDiskUsageMonitor.get();
wc.withBasicApiToken(bob); wc.withBasicApiToken(bob);
try { Page p = wc.getPage(request);
wc.getPage(request); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, p.getWebResponse().getStatusCode());
fail();
} catch (FailingHttpStatusCodeException e) {
assertEquals(403, e.getStatusCode());
}
assertTrue(mon.isEnabled()); assertTrue(mon.isEnabled());
WebRequest requestReadOnly = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET); WebRequest requestReadOnly = new WebRequest(new URL(wc.getContextPath() + "administrativeMonitor/hudsonHomeIsFull"), HttpMethod.GET);
try { p = wc.getPage(requestReadOnly);
wc.getPage(requestReadOnly); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, p.getWebResponse().getStatusCode());
fail();
} catch (FailingHttpStatusCodeException e) {
assertEquals(403, e.getStatusCode());
}
wc.withBasicApiToken(administrator); wc.withBasicApiToken(administrator);
wc.getPage(request); p = wc.getPage(request);
assertEquals(HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode());
assertFalse(mon.isEnabled()); assertFalse(mon.isEnabled());
} }
/** /**
......
...@@ -26,22 +26,22 @@ package hudson.jobs; ...@@ -26,22 +26,22 @@ package hudson.jobs;
import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import hudson.AbortException; import com.gargoylesoftware.htmlunit.Page;
import hudson.model.Failure; import hudson.model.Failure;
import hudson.model.Item; import hudson.model.Item;
import hudson.model.ItemGroup; import hudson.model.ItemGroup;
import hudson.model.listeners.ItemListener; import hudson.model.listeners.ItemListener;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.text.MessageFormat; import java.text.MessageFormat;
import org.acegisecurity.AccessDeniedException;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
import hudson.model.FreeStyleProject; import hudson.model.FreeStyleProject;
...@@ -54,7 +54,6 @@ import org.jvnet.hudson.test.TestExtension; ...@@ -54,7 +54,6 @@ import org.jvnet.hudson.test.TestExtension;
* @author Christopher Simons * @author Christopher Simons
*/ */
public class CreateItemTest { public class CreateItemTest {
private static final int ERROR_PRESET = (-1);
@Rule @Rule
public JenkinsRule rule = new JenkinsRule(); public JenkinsRule rule = new JenkinsRule();
...@@ -78,15 +77,13 @@ public class CreateItemTest { ...@@ -78,15 +77,13 @@ public class CreateItemTest {
WebRequest request = new WebRequest(apiURL, HttpMethod.POST); WebRequest request = new WebRequest(apiURL, HttpMethod.POST);
deleteContentTypeHeader(request); deleteContentTypeHeader(request);
int result = ERROR_PRESET;
try {
result = rule.createWebClient()
.getPage(request).getWebResponse().getStatusCode();
} catch (FailingHttpStatusCodeException e) {
result = e.getResponse().getStatusCode();
}
assertEquals("Creating job from copy should succeed.", 200, result); Page p = rule.createWebClient()
.withThrowExceptionOnFailingStatusCode(false)
.getPage(request);
assertEquals("Creating job from copy should succeed.",
HttpURLConnection.HTTP_OK,
p.getWebResponse().getStatusCode());
} }
@Issue("JENKINS-34691") @Issue("JENKINS-34691")
...@@ -104,15 +101,14 @@ public class CreateItemTest { ...@@ -104,15 +101,14 @@ public class CreateItemTest {
WebRequest request = new WebRequest(apiURL, HttpMethod.POST); WebRequest request = new WebRequest(apiURL, HttpMethod.POST);
deleteContentTypeHeader(request); deleteContentTypeHeader(request);
int result = ERROR_PRESET;
try {
result = rule.createWebClient()
.getPage(request).getWebResponse().getStatusCode();
} catch (FailingHttpStatusCodeException e) {
result = e.getResponse().getStatusCode();
}
assertEquals("Creating job from copy should fail.", 400, result); Page p = rule.createWebClient()
.withThrowExceptionOnFailingStatusCode(false)
.getPage(request);
assertEquals("Creating job from copy should fail.",
HttpURLConnection.HTTP_BAD_REQUEST,
p.getWebResponse().getStatusCode());
assertThat(rule.jenkins.getItem("newJob"), nullValue()); assertThat(rule.jenkins.getItem("newJob"), nullValue());
} }
...@@ -125,9 +121,13 @@ public class CreateItemTest { ...@@ -125,9 +121,13 @@ public class CreateItemTest {
rule.jenkins.setCrumbIssuer(null); rule.jenkins.setCrumbIssuer(null);
rule.createFolder("d1").createProject(FreeStyleProject.class, "p"); rule.createFolder("d1").createProject(FreeStyleProject.class, "p");
MockFolder d2 = rule.createFolder("d2"); MockFolder d2 = rule.createFolder("d2");
rule.createWebClient().getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p"), HttpMethod.POST));
JenkinsRule.WebClient wc = rule.createWebClient();
wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p2&from=../d1/p"), HttpMethod.POST));
assertNotNull(d2.getItem("p2")); assertNotNull(d2.getItem("p2"));
rule.createWebClient().getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p"), HttpMethod.POST));
wc.getPage(new WebRequest(new URL(d2.getAbsoluteUrl() + "createItem?mode=copy&name=p3&from=/d1/p"), HttpMethod.POST));
assertNotNull(d2.getItem("p3")); assertNotNull(d2.getItem("p3"));
} }
......
package hudson.model; package hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair; import com.gargoylesoftware.htmlunit.util.NameValuePair;
import hudson.security.ACL; import hudson.security.ACL;
...@@ -9,6 +9,7 @@ import hudson.security.ACLContext; ...@@ -9,6 +9,7 @@ import hudson.security.ACLContext;
import hudson.security.AccessDeniedException2; import hudson.security.AccessDeniedException2;
import hudson.util.FormValidation; import hudson.util.FormValidation;
import java.io.File; import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Arrays; import java.util.Arrays;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
...@@ -117,18 +118,17 @@ public class AbstractItemTest { ...@@ -117,18 +118,17 @@ public class AbstractItemTest {
WebRequest wr = new WebRequest(w.createCrumbedUrl(p.getUrl() + "confirmRename"), HttpMethod.POST); WebRequest wr = new WebRequest(w.createCrumbedUrl(p.getUrl() + "confirmRename"), HttpMethod.POST);
wr.setRequestParameters(Arrays.asList(new NameValuePair("newName", "bar"))); wr.setRequestParameters(Arrays.asList(new NameValuePair("newName", "bar")));
w.login("alice", "alice"); w.login("alice", "alice");
assertThat(getPath(w.getPage(wr).getUrl()), equalTo(p.getUrl())); Page page = w.getPage(wr);
assertThat(getPath(page.getUrl()), equalTo(p.getUrl()));
assertThat(p.getName(), equalTo("bar")); assertThat(p.getName(), equalTo("bar"));
wr = new WebRequest(w.createCrumbedUrl(p.getUrl() + "confirmRename"), HttpMethod.POST); wr = new WebRequest(w.createCrumbedUrl(p.getUrl() + "confirmRename"), HttpMethod.POST);
wr.setRequestParameters(Arrays.asList(new NameValuePair("newName", "baz"))); wr.setRequestParameters(Arrays.asList(new NameValuePair("newName", "baz")));
w.login("bob", "bob"); w.login("bob", "bob");
try {
assertThat(getPath(w.getPage(wr).getUrl()), equalTo(p.getUrl())); w.setThrowExceptionOnFailingStatusCode(false);
fail("Expecting HTTP 403 Forbidden"); page = w.getPage(wr);
} catch (FailingHttpStatusCodeException e) { assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode());
assertThat(e.getStatusCode(), equalTo(403));
}
assertThat(p.getName(), equalTo("bar")); assertThat(p.getName(), equalTo("bar"));
} }
......
...@@ -24,8 +24,8 @@ ...@@ -24,8 +24,8 @@
package hudson.model; package hudson.model;
import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.ElementNotFoundException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlForm;
...@@ -120,16 +120,13 @@ public class AbstractProjectTest { ...@@ -120,16 +120,13 @@ public class AbstractProjectTest {
FreeStyleBuild b = project.scheduleBuild2(0).get(); FreeStyleBuild b = project.scheduleBuild2(0).get();
assert b.getWorkspace().exists() : "Workspace should exist by now"; assertTrue("Workspace should exist by now", b.getWorkspace().exists());
// make sure that the action link is protected // make sure that the action link is protected
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
try { .withThrowExceptionOnFailingStatusCode(false);
wc.getPage(new WebRequest(new URL(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST)); Page page = wc.getPage(new WebRequest(new URL(wc.getContextPath() + project.getUrl() + "doWipeOutWorkspace"), HttpMethod.POST));
fail("Expected HTTP status code 403"); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode());
} catch (FailingHttpStatusCodeException e) {
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
}
} }
/** /**
...@@ -148,7 +145,7 @@ public class AbstractProjectTest { ...@@ -148,7 +145,7 @@ public class AbstractProjectTest {
JenkinsRule.WebClient webClient = j.createWebClient(); JenkinsRule.WebClient webClient = j.createWebClient();
HtmlPage page = webClient.getPage(j.jenkins.getItem("test0")); HtmlPage page = webClient.getPage(j.jenkins.getItem("test0"));
page = (HtmlPage) page.getAnchorByText("Workspace").click(); page = page.getAnchorByText("Workspace").click();
try { try {
String wipeOutLabel = ResourceBundle.getBundle("hudson/model/AbstractProject/sidepanel").getString("Wipe Out Workspace"); String wipeOutLabel = ResourceBundle.getBundle("hudson/model/AbstractProject/sidepanel").getString("Wipe Out Workspace");
page.getAnchorByText(wipeOutLabel); page.getAnchorByText(wipeOutLabel);
...@@ -405,24 +402,21 @@ public class AbstractProjectTest { ...@@ -405,24 +402,21 @@ public class AbstractProjectTest {
j.jenkins.setNumExecutors(0); j.jenkins.setNumExecutors(0);
FreeStyleProject p = j.createFreeStyleProject(); FreeStyleProject p = j.createFreeStyleProject();
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
WebResponse rsp = wc.getPage(j.getURL() + p.getUrl() + "build").getWebResponse(); WebResponse rsp = wc.goTo(p.getUrl() + "build", null).getWebResponse();
assertEquals(201, rsp.getStatusCode()); assertEquals(HttpURLConnection.HTTP_CREATED, rsp.getStatusCode());
assertNotNull(rsp.getResponseHeaderValue("Location")); assertNotNull(rsp.getResponseHeaderValue("Location"));
WebResponse rsp2 = wc.getPage(j.getURL() + p.getUrl() + "build").getWebResponse(); WebResponse rsp2 = wc.goTo(p.getUrl() + "build", null).getWebResponse();
assertEquals(201, rsp2.getStatusCode()); assertEquals(HttpURLConnection.HTTP_CREATED, rsp2.getStatusCode());
assertEquals(rsp.getResponseHeaderValue("Location"), rsp2.getResponseHeaderValue("Location")); assertEquals(rsp.getResponseHeaderValue("Location"), rsp2.getResponseHeaderValue("Location"));
p.makeDisabled(true); p.makeDisabled(true);
try { WebResponse rsp3 = wc.goTo(p.getUrl() + "build", null).getWebResponse();
wc.getPage(j.getURL() + p.getUrl() + "build"); assertEquals(HttpURLConnection.HTTP_CONFLICT, rsp3.getStatusCode());
fail();
} catch (FailingHttpStatusCodeException e) {
// request should fail
}
} }
/** /**
......
...@@ -34,9 +34,10 @@ import org.jvnet.hudson.test.JenkinsRule; ...@@ -34,9 +34,10 @@ import org.jvnet.hudson.test.JenkinsRule;
import java.io.File; import java.io.File;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** /**
* @author Kohsuke Kawaguchi * @author Kohsuke Kawaguchi
...@@ -82,17 +83,13 @@ public class ApiTest { ...@@ -82,17 +83,13 @@ public class ApiTest {
@Issue("SECURITY-165") @Issue("SECURITY-165")
@Test public void xPathDocumentFunction() throws Exception { @Test public void xPathDocumentFunction() throws Exception {
File f = new File(j.jenkins.getRootDir(), "queue.xml"); File f = new File(j.jenkins.getRootDir(), "queue.xml");
JenkinsRule.WebClient client = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
try {
client.goTo("api/xml?xpath=document(\"" + f.getAbsolutePath() + "\")", "application/xml"); // could expect application/xml but as an error occurred it's a text/html that is returned
fail("Should become 500 error"); Page page = wc.goTo("api/xml?xpath=document(\"" + f.getAbsolutePath() + "\")", null);
} catch (com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException e) { assertEquals(HttpURLConnection.HTTP_INTERNAL_ERROR, page.getWebResponse().getStatusCode());
String contentAsString = e.getResponse().getContentAsString(); assertThat(page.getWebResponse().getContentAsString(), containsString("Illegal function: document"));
j.assertStringContains(
contentAsString,
"Illegal function: document");
}
} }
@Test @Test
......
...@@ -24,7 +24,6 @@ ...@@ -24,7 +24,6 @@
package hudson.model; package hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPage;
import static org.junit.Assert.*; import static org.junit.Assert.*;
...@@ -41,16 +40,10 @@ public class AsynchPeopleTest { ...@@ -41,16 +40,10 @@ public class AsynchPeopleTest {
@Issue("JENKINS-18641") @Issue("JENKINS-18641")
@Test public void display() throws Exception { @Test public void display() throws Exception {
User.get("bob"); User.getById( "bob", true);
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient();
HtmlPage page;
try { HtmlPage page = wc.goTo("asynchPeople");
page = wc.goTo("asynchPeople");
} catch (FailingHttpStatusCodeException x) {
System.err.println(x.getResponse().getResponseHeaders());
System.err.println(x.getResponse().getContentAsString());
throw x;
}
assertEquals(0, wc.waitForBackgroundJavaScript(120000)); assertEquals(0, wc.waitForBackgroundJavaScript(120000));
boolean found = false; boolean found = false;
for (DomElement table : page.getElementsByTagName("table")) { for (DomElement table : page.getElementsByTagName("table")) {
......
...@@ -25,15 +25,15 @@ package hudson.model; ...@@ -25,15 +25,15 @@ package hudson.model;
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.xml.XmlPage; import com.gargoylesoftware.htmlunit.xml.XmlPage;
import java.io.File; import java.io.File;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
...@@ -80,19 +80,16 @@ public class ComputerTest { ...@@ -80,19 +80,16 @@ public class ComputerTest {
Node nodeA = j.createSlave("nodeA", null, null); Node nodeA = j.createSlave("nodeA", null, null);
Node nodeB = j.createSlave("nodeB", null, null); Node nodeB = j.createSlave("nodeB", null, null);
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
HtmlForm form = wc.getPage(nodeB, "configure").getFormByName("config"); HtmlForm form = wc.getPage(nodeB, "configure").getFormByName("config");
form.getInputByName("_.name").setValueAttribute("nodeA"); form.getInputByName("_.name").setValueAttribute("nodeA");
try { Page page = j.submit(form);
j.submit(form); assertEquals(NOTE, HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode());
fail(NOTE); assertThat(NOTE, page.getWebResponse().getContentAsString(),
} catch (FailingHttpStatusCodeException e) {
assertThat(NOTE, e.getStatusCode(), equalTo(400));
assertThat(NOTE, e.getResponse().getContentAsString(),
containsString("Agent called ‘nodeA’ already exists")); containsString("Agent called ‘nodeA’ already exists"));
} }
}
@Test @Test
public void doNotShowUserDetailsInOfflineCause() throws Exception { public void doNotShowUserDetailsInOfflineCause() throws Exception {
......
...@@ -184,8 +184,8 @@ public class DirectlyModifiableViewTest { ...@@ -184,8 +184,8 @@ public class DirectlyModifiableViewTest {
} }
private Page doPost(View view, String path) throws Exception { private Page doPost(View view, String path) throws Exception {
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebRequest req = new WebRequest( WebRequest req = new WebRequest(
new URL(j.jenkins.getRootUrl() + view.getUrl() + path), new URL(j.jenkins.getRootUrl() + view.getUrl() + path),
HttpMethod.POST HttpMethod.POST
......
...@@ -23,7 +23,6 @@ ...@@ -23,7 +23,6 @@
*/ */
package hudson.model; package hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
...@@ -243,13 +242,8 @@ public class DirectoryBrowserSupportTest { ...@@ -243,13 +242,8 @@ public class DirectoryBrowserSupportTest {
p.getPublishersList().add(new ArtifactArchiver("f")); p.getPublishersList().add(new ArtifactArchiver("f"));
j.buildAndAssertSuccess(p); j.buildAndAssertSuccess(p);
HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/"); HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/");
try {
Page download = page.getAnchorByText("f").click(); Page download = page.getAnchorByText("f").click();
assertEquals("Hello world!", download.getWebResponse().getContentAsString()); assertEquals("Hello world!", download.getWebResponse().getContentAsString());
} catch (FailingHttpStatusCodeException x) {
IOUtils.copy(x.getResponse().getContentAsStream(), System.err);
throw x;
}
} }
/** Simulation of a storage service with URLs unrelated to {@link Run#doArtifact}. */ /** Simulation of a storage service with URLs unrelated to {@link Run#doArtifact}. */
@TestExtension("externalURLDownload") @TestExtension("externalURLDownload")
......
...@@ -25,7 +25,6 @@ package hudson.model; ...@@ -25,7 +25,6 @@ package hudson.model;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
...@@ -169,20 +168,19 @@ public class HudsonTest { ...@@ -169,20 +168,19 @@ public class HudsonTest {
public void deleteHudsonComputer() throws Exception { public void deleteHudsonComputer() throws Exception {
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient();
HtmlPage page = wc.goTo("computer/(master)/"); HtmlPage page = wc.goTo("computer/(master)/");
for (HtmlAnchor a : page.getAnchors()) for (HtmlAnchor a : page.getAnchors()) {
assertFalse(a.getHrefAttribute(),a.getHrefAttribute().endsWith("delete")); assertFalse(a.getHrefAttribute(), a.getHrefAttribute().endsWith("delete"));
}
wc.setThrowExceptionOnFailingStatusCode(false);
// try to delete it by hitting the final URL directly // try to delete it by hitting the final URL directly
WebRequest req = new WebRequest(new URL(wc.getContextPath()+"computer/(master)/doDelete"), HttpMethod.POST); WebRequest req = new WebRequest(new URL(wc.getContextPath()+"computer/(master)/doDelete"), HttpMethod.POST);
try { page = wc.getPage(wc.addCrumb(req));
wc.getPage(wc.addCrumb(req)); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode());
fail("Error code expected");
} catch (FailingHttpStatusCodeException e) {
assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, e.getStatusCode());
}
// the master computer object should be still here // the master computer object should be still here
wc.goTo("computer/(master)/"); page = wc.goTo("computer/(master)/");
assertEquals(HttpURLConnection.HTTP_OK, page.getWebResponse().getStatusCode());
} }
/** /**
......
...@@ -191,9 +191,10 @@ public class ItemsTest { ...@@ -191,9 +191,10 @@ public class ItemsTest {
/** Use the REST command to create an empty project (normally used only from the UI in the New Item dialog). */ /** Use the REST command to create an empty project (normally used only from the UI in the New Item dialog). */
REST_EMPTY { REST_EMPTY {
@Override void run(JenkinsRule r, String target) throws Exception { @Override void run(JenkinsRule r, String target) throws Exception {
JenkinsRule.WebClient wc = wc(r); JenkinsRule.WebClient wc = wc(r)
wc.getOptions().setRedirectEnabled(false); // redirect perversely counts as a failure
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); // redirect perversely counts as a failure .withRedirectEnabled(false)
.withThrowExceptionOnFailingStatusCode(false);
WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject"), HttpMethod.POST)).getWebResponse(); WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=hudson.model.FreeStyleProject"), HttpMethod.POST)).getWebResponse();
if (webResponse.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { if (webResponse.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
throw new FailingHttpStatusCodeException(webResponse); throw new FailingHttpStatusCodeException(webResponse);
...@@ -204,9 +205,9 @@ public class ItemsTest { ...@@ -204,9 +205,9 @@ public class ItemsTest {
REST_COPY { REST_COPY {
@Override void run(JenkinsRule r, String target) throws Exception { @Override void run(JenkinsRule r, String target) throws Exception {
r.createFreeStyleProject("dupe"); r.createFreeStyleProject("dupe");
JenkinsRule.WebClient wc = wc(r); JenkinsRule.WebClient wc = wc(r)
wc.getOptions().setRedirectEnabled(false); .withRedirectEnabled(false)
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe"), HttpMethod.POST)).getWebResponse(); WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "createItem?name=" + target + "&mode=copy&from=dupe"), HttpMethod.POST)).getWebResponse();
r.jenkins.getItem("dupe").delete(); r.jenkins.getItem("dupe").delete();
if (webResponse.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { if (webResponse.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
...@@ -228,9 +229,9 @@ public class ItemsTest { ...@@ -228,9 +229,9 @@ public class ItemsTest {
REST_RENAME { REST_RENAME {
@Override void run(JenkinsRule r, String target) throws Exception { @Override void run(JenkinsRule r, String target) throws Exception {
r.createFreeStyleProject("dupe"); r.createFreeStyleProject("dupe");
JenkinsRule.WebClient wc = wc(r); JenkinsRule.WebClient wc = wc(r)
wc.getOptions().setRedirectEnabled(false); .withRedirectEnabled(false)
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "job/dupe/doRename?newName=" + target), HttpMethod.POST)).getWebResponse(); WebResponse webResponse = wc.getPage(new WebRequest(new URL(wc.getContextPath() + "job/dupe/doRename?newName=" + target), HttpMethod.POST)).getWebResponse();
if (webResponse.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { if (webResponse.getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) {
r.jenkins.getItem("dupe").delete(); r.jenkins.getItem("dupe").delete();
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
*/ */
package hudson.model; package hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebAssert; import com.gargoylesoftware.htmlunit.WebAssert;
import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlFormUtil; import com.gargoylesoftware.htmlunit.html.HtmlFormUtil;
...@@ -52,7 +52,6 @@ import java.util.concurrent.CountDownLatch; ...@@ -52,7 +52,6 @@ import java.util.concurrent.CountDownLatch;
import jenkins.model.ProjectNamingStrategy; import jenkins.model.ProjectNamingStrategy;
import jenkins.security.apitoken.ApiTokenPropertyConfiguration;
import jenkins.security.apitoken.ApiTokenTestHelper; import jenkins.security.apitoken.ApiTokenTestHelper;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Rule; import org.junit.Rule;
...@@ -221,14 +220,19 @@ public class JobTest { ...@@ -221,14 +220,19 @@ public class JobTest {
try { try {
wc.assertFails("job/testJob/config.xml", HttpURLConnection.HTTP_FORBIDDEN); wc.assertFails("job/testJob/config.xml", HttpURLConnection.HTTP_FORBIDDEN);
wc.withBasicApiToken(User.getById("alice", true)); // Has CONFIGURE and EXTENDED_READ permission wc.setThrowExceptionOnFailingStatusCode(false);
tryConfigDotXml(wc, 500, "Both perms; should get 500");
wc.withBasicApiToken(User.getById("bob", true)); // Has only CONFIGURE permission (this should imply EXTENDED_READ) // Has CONFIGURE and EXTENDED_READ permission
tryConfigDotXml(wc, 500, "Config perm should imply EXTENDED_READ"); wc.withBasicApiToken(User.getById("alice", true));
tryConfigDotXml(wc, HttpURLConnection.HTTP_INTERNAL_ERROR, "Both perms; should get 500");
wc.withBasicApiToken(User.getById("charlie", true)); // Has only EXTENDED_READ permission // Has only CONFIGURE permission (this should imply EXTENDED_READ)
tryConfigDotXml(wc, 403, "No permission, should get 403"); wc.withBasicApiToken(User.getById("bob", true));
tryConfigDotXml(wc, HttpURLConnection.HTTP_INTERNAL_ERROR, "Config perm should imply EXTENDED_READ");
// Has only EXTENDED_READ permission
wc.withBasicApiToken(User.getById("charlie", true));
tryConfigDotXml(wc, HttpURLConnection.HTTP_FORBIDDEN, "No permission, should get 403");
} finally { } finally {
Item.EXTENDED_READ.setEnabled(saveEnabled); Item.EXTENDED_READ.setEnabled(saveEnabled);
} }
...@@ -236,17 +240,17 @@ public class JobTest { ...@@ -236,17 +240,17 @@ public class JobTest {
private static void tryConfigDotXml(JenkinsRule.WebClient wc, int status, String msg) throws Exception { private static void tryConfigDotXml(JenkinsRule.WebClient wc, int status, String msg) throws Exception {
// Verify we can GET the config.xml: // Verify we can GET the config.xml:
wc.goTo("job/testJob/config.xml", "application/xml"); Page p = wc.goTo("job/testJob/config.xml", "application/xml");
assertEquals("Retrieving config.xml should be ok", HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode());
// This page is a simple form to POST to /job/testJob/config.xml // This page is a simple form to POST to /job/testJob/config.xml
// But it posts invalid data so we expect 500 if we have permission, 403 if not // But it posts invalid data so we expect 500 if we have permission, 403 if not
HtmlPage page = wc.goTo("userContent/post.html"); HtmlPage page = wc.goTo("userContent/post.html");
try { p = HtmlFormUtil.submit(page.getForms().get(0));
HtmlFormUtil.submit(page.getForms().get(0)); assertEquals(msg, status, p.getWebResponse().getStatusCode());
fail("Expected exception: " + msg);
} catch (FailingHttpStatusCodeException expected) { p = wc.goTo("logout");
assertEquals(msg, status, expected.getStatusCode()); assertEquals("To logout should be ok", HttpURLConnection.HTTP_OK, p.getWebResponse().getStatusCode());
}
wc.goTo("logout");
} }
@LocalData @Issue("JENKINS-6371") @LocalData @Issue("JENKINS-6371")
......
...@@ -23,7 +23,6 @@ ...@@ -23,7 +23,6 @@
*/ */
package hudson.model; package hudson.model;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
...@@ -448,12 +447,10 @@ public class NodeTest { ...@@ -448,12 +447,10 @@ public class NodeTest {
WebRequest settings = new WebRequest(wc.createCrumbedUrl("computer/(master)/config.xml")); WebRequest settings = new WebRequest(wc.createCrumbedUrl("computer/(master)/config.xml"));
settings.setHttpMethod(HttpMethod.POST); settings.setHttpMethod(HttpMethod.POST);
settings.setRequestBody("<hudson/>"); settings.setRequestBody("<hudson/>");
try {
wc.setThrowExceptionOnFailingStatusCode(false);
Page page = wc.getPage(settings); Page page = wc.getPage(settings);
fail(page.getWebResponse().getContentAsString()); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, page.getWebResponse().getStatusCode());
} catch (FailingHttpStatusCodeException x) {
assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, x.getStatusCode());
}
} }
/** /**
......
...@@ -51,22 +51,22 @@ public class ParametersTest { ...@@ -51,22 +51,22 @@ public class ParametersTest {
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder(); CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder); project.getBuildersList().add(builder);
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec"); HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters"); HtmlForm form = page.getFormByName("parameters");
HtmlElement element = (HtmlElement) DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='string']"); HtmlElement element = DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='string']");
assertNotNull(element); assertNotNull(element);
assertEquals("string description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent()); assertEquals("string description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
HtmlTextInput stringParameterInput = (HtmlTextInput) DomNodeUtil.selectSingleNode(element, ".//input[@name='value']"); HtmlTextInput stringParameterInput = DomNodeUtil.selectSingleNode(element, ".//input[@name='value']");
assertEquals("defaultValue", stringParameterInput.getAttribute("value")); assertEquals("defaultValue", stringParameterInput.getAttribute("value"));
assertEquals("string", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent()); assertEquals("string", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
stringParameterInput.setAttribute("value", "newValue"); stringParameterInput.setAttribute("value", "newValue");
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='boolean']"); element = DomNodeUtil.selectSingleNode(form, "//tr[td/div/input/@value='boolean']");
assertNotNull(element); assertNotNull(element);
assertEquals("boolean description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent()); assertEquals("boolean description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
Object o = DomNodeUtil.selectSingleNode(element, ".//input[@name='value']"); Object o = DomNodeUtil.selectSingleNode(element, ".//input[@name='value']");
...@@ -75,12 +75,12 @@ public class ParametersTest { ...@@ -75,12 +75,12 @@ public class ParametersTest {
assertEquals(true, booleanParameterInput.isChecked()); assertEquals(true, booleanParameterInput.isChecked());
assertEquals("boolean", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent()); assertEquals("boolean", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']"); element = DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']");
assertNotNull(element); assertNotNull(element);
assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent()); assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent()); assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='run']"); element = DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='run']");
assertNotNull(element); assertNotNull(element);
assertEquals("run description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent()); assertEquals("run description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("run", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent()); assertEquals("run", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
...@@ -105,16 +105,16 @@ public class ParametersTest { ...@@ -105,16 +105,16 @@ public class ParametersTest {
CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder(); CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
project.getBuildersList().add(builder); project.getBuildersList().add(builder);
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec"); HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters"); HtmlForm form = page.getFormByName("parameters");
HtmlElement element = (HtmlElement) DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']"); HtmlElement element = DomNodeUtil.selectSingleNode(form, ".//tr[td/div/input/@value='choice']");
assertNotNull(element); assertNotNull(element);
assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent()); assertEquals("choice description", ((HtmlElement) DomNodeUtil.selectSingleNode(element.getNextSibling().getNextSibling(), "td[@class='setting-description']")).getTextContent());
assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent()); assertEquals("choice", ((HtmlElement) DomNodeUtil.selectSingleNode(element, "td[@class='setting-name']")).getTextContent());
HtmlOption opt = (HtmlOption)DomNodeUtil.selectSingleNode(element, "td/div/select/option[@value='Choice <2>']"); HtmlOption opt = DomNodeUtil.selectSingleNode(element, "td/div/select/option[@value='Choice <2>']");
assertNotNull(opt); assertNotNull(opt);
assertEquals("Choice <2>", opt.asText()); assertEquals("Choice <2>", opt.asText());
opt.setSelected(true); opt.setSelected(true);
...@@ -192,8 +192,8 @@ public class ParametersTest { ...@@ -192,8 +192,8 @@ public class ParametersTest {
new FileParameterDefinition("filename", "description")); new FileParameterDefinition("filename", "description"));
project.addProperty(pdp); project.addProperty(pdp);
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec"); HtmlPage page = wc.goTo("job/" + project.getName() + "/build?delay=0sec");
HtmlForm form = page.getFormByName("parameters"); HtmlForm form = page.getFormByName("parameters");
...@@ -215,12 +215,13 @@ public class ParametersTest { ...@@ -215,12 +215,13 @@ public class ParametersTest {
); );
p.addProperty(pdb); p.addProperty(pdb);
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); // Ignore 405 // Ignore 405
.withThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.getPage(p, "build"); HtmlPage page = wc.getPage(p, "build");
// java.lang.IllegalArgumentException: No such parameter definition: <gibberish>. // java.lang.IllegalArgumentException: No such parameter definition: <gibberish>.
wc.getOptions().setThrowExceptionOnFailingStatusCode(true); wc.setThrowExceptionOnFailingStatusCode(true);
final HtmlForm form = page.getFormByName("parameters"); final HtmlForm form = page.getFormByName("parameters");
HtmlFormUtil.submit(form, HtmlFormUtil.getButtonByCaption(form, "Build")); HtmlFormUtil.submit(form, HtmlFormUtil.getButtonByCaption(form, "Build"));
} }
...@@ -233,8 +234,8 @@ public class ParametersTest { ...@@ -233,8 +234,8 @@ public class ParametersTest {
StringParameterDefinition param = new StringParameterDefinition("<param name>", "<param default>", "<param description>"); StringParameterDefinition param = new StringParameterDefinition("<param name>", "<param default>", "<param description>");
assertEquals("<b>[</b>param description<b>]</b>", param.getFormattedDescription()); assertEquals("<b>[</b>param description<b>]</b>", param.getFormattedDescription());
p.addProperty(new ParametersDefinitionProperty(param)); p.addProperty(new ParametersDefinitionProperty(param));
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage page = wc.getPage(p, "build?delay=0sec"); HtmlPage page = wc.getPage(p, "build?delay=0sec");
collector.checkThat(page.getWebResponse().getStatusCode(), is(HttpStatus.SC_METHOD_NOT_ALLOWED)); // 405 to dissuade scripts from thinking this triggered the build collector.checkThat(page.getWebResponse().getStatusCode(), is(HttpStatus.SC_METHOD_NOT_ALLOWED)); // 405 to dissuade scripts from thinking this triggered the build
String text = page.getWebResponse().getContentAsString(); String text = page.getWebResponse().getContentAsString();
......
...@@ -71,8 +71,9 @@ public class PasswordParameterDefinitionTest { ...@@ -71,8 +71,9 @@ public class PasswordParameterDefinitionTest {
User admin = User.getById("admin", true); User admin = User.getById("admin", true);
User dev = User.getById("dev", true); User dev = User.getById("dev", true);
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); // ParametersDefinitionProperty/index.jelly sends a 405 but really it is OK // ParametersDefinitionProperty/index.jelly sends a 405 but really it is OK
.withThrowExceptionOnFailingStatusCode(false);
// Control case: admin can use default value. // Control case: admin can use default value.
j.submit(wc.withBasicApiToken(admin).getPage(p, "build?delay=0sec").getFormByName("parameters")); j.submit(wc.withBasicApiToken(admin).getPage(p, "build?delay=0sec").getFormByName("parameters"));
j.waitUntilNoActivity(); j.waitUntilNoActivity();
......
...@@ -59,9 +59,9 @@ public class QueueSEC891Test { ...@@ -59,9 +59,9 @@ public class QueueSEC891Test {
WebRequest request = new WebRequest(new URL(r.getURL() + urlProvider.apply(currentOne)), HttpMethod.POST); WebRequest request = new WebRequest(new URL(r.getURL() + urlProvider.apply(currentOne)), HttpMethod.POST);
{ // user without right cannot cancel { // user without right cannot cancel
JenkinsRule.WebClient wc = r.createWebClient(); JenkinsRule.WebClient wc = r.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withRedirectEnabled(false)
wc.getOptions().setRedirectEnabled(false); .withThrowExceptionOnFailingStatusCode(false);
wc.login("user"); wc.login("user");
Page p = wc.getPage(request); Page p = wc.getPage(request);
// currently the endpoint return a redirection to the previously visited page, none in our case // currently the endpoint return a redirection to the previously visited page, none in our case
...@@ -71,9 +71,9 @@ public class QueueSEC891Test { ...@@ -71,9 +71,9 @@ public class QueueSEC891Test {
assertFalse(currentOne.getFuture().isCancelled()); assertFalse(currentOne.getFuture().isCancelled());
} }
{ // user with right can { // user with right can
JenkinsRule.WebClient wc = r.createWebClient(); JenkinsRule.WebClient wc = r.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withRedirectEnabled(false)
wc.getOptions().setRedirectEnabled(false); .withThrowExceptionOnFailingStatusCode(false);
wc.login("admin"); wc.login("admin");
Page p = wc.getPage(request); Page p = wc.getPage(request);
assertThat(p.getWebResponse().getStatusCode(), lessThan(400)); assertThat(p.getWebResponse().getStatusCode(), lessThan(400));
......
...@@ -32,16 +32,16 @@ public class UserRestartSEC897Test { ...@@ -32,16 +32,16 @@ public class UserRestartSEC897Test {
User.getById("admin", true).save(); User.getById("admin", true).save();
{ // attempt with ".." { // attempt with ".."
JenkinsRule.WebClient wc = rr.j.createWebClient(); JenkinsRule.WebClient wc = rr.j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebRequest request = new WebRequest(new URL(rr.j.jenkins.getRootUrl() + "whoAmI/api/xml")); WebRequest request = new WebRequest(new URL(rr.j.jenkins.getRootUrl() + "whoAmI/api/xml"));
request.setAdditionalHeader("Authorization", base64("..", "any-password")); request.setAdditionalHeader("Authorization", base64("..", "any-password"));
wc.getPage(request); wc.getPage(request);
} }
{ // attempt with "../users/.." { // attempt with "../users/.."
JenkinsRule.WebClient wc = rr.j.createWebClient(); JenkinsRule.WebClient wc = rr.j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebRequest request = new WebRequest(new URL(rr.j.jenkins.getRootUrl() + "whoAmI/api/xml")); WebRequest request = new WebRequest(new URL(rr.j.jenkins.getRootUrl() + "whoAmI/api/xml"));
request.setAdditionalHeader("Authorization", base64("../users/..", "any-password")); request.setAdditionalHeader("Authorization", base64("../users/..", "any-password"));
......
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
package hudson.model; package hudson.model;
import com.cloudbees.hudson.plugins.folder.Folder; import com.cloudbees.hudson.plugins.folder.Folder;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.DomNodeUtil; import com.gargoylesoftware.htmlunit.html.DomNodeUtil;
import com.gargoylesoftware.htmlunit.util.NameValuePair; import com.gargoylesoftware.htmlunit.util.NameValuePair;
...@@ -31,7 +32,6 @@ import jenkins.model.Jenkins; ...@@ -31,7 +32,6 @@ import jenkins.model.Jenkins;
import org.jenkins.ui.icon.Icon; import org.jenkins.ui.icon.Icon;
import org.jenkins.ui.icon.IconSet; import org.jenkins.ui.icon.IconSet;
import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.Issue;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlForm;
...@@ -56,6 +56,7 @@ import hudson.util.FormValidation; ...@@ -56,6 +56,7 @@ import hudson.util.FormValidation;
import hudson.util.HudsonIsLoading; import hudson.util.HudsonIsLoading;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
...@@ -120,19 +121,19 @@ public class ViewTest { ...@@ -120,19 +121,19 @@ public class ViewTest {
@Test public void conflictingName() throws Exception { @Test public void conflictingName() throws Exception {
assertNull(j.jenkins.getView("foo")); assertNull(j.jenkins.getView("foo"));
HtmlForm form = j.createWebClient().goTo("newView").getFormByName("createItem"); WebClient wc = j.createWebClient();
HtmlForm form = wc.goTo("newView").getFormByName("createItem");
form.getInputByName("name").setValueAttribute("foo"); form.getInputByName("name").setValueAttribute("foo");
form.getRadioButtonsByName("mode").get(0).setChecked(true); form.getRadioButtonsByName("mode").get(0).setChecked(true);
j.submit(form); j.submit(form);
assertNotNull(j.jenkins.getView("foo")); assertNotNull(j.jenkins.getView("foo"));
wc.setThrowExceptionOnFailingStatusCode(false);
// do it again and verify an error // do it again and verify an error
try { Page page = j.submit(form);
j.submit(form); assertEquals("shouldn't be allowed to create two views of the same name.",
fail("shouldn't be allowed to create two views of the same name."); HttpURLConnection.HTTP_BAD_REQUEST,
} catch (FailingHttpStatusCodeException e) { page.getWebResponse().getStatusCode());
assertEquals(400, e.getStatusCode());
}
} }
@Test public void privateView() throws Exception { @Test public void privateView() throws Exception {
...@@ -209,23 +210,24 @@ public class ViewTest { ...@@ -209,23 +210,24 @@ public class ViewTest {
IconSet.icons.addIcon(new Icon("icon-folder icon-md", "24x24/folder.gif", "width: 24px; height: 24px;")); IconSet.icons.addIcon(new Icon("icon-folder icon-md", "24x24/folder.gif", "width: 24px; height: 24px;"));
} }
WebClient webClient = j.createWebClient(); WebClient webClient = j.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setJavaScriptEnabled(false); webClient.getOptions().setJavaScriptEnabled(false);
j.assertAllImageLoadSuccessfully(webClient.goTo("asynchPeople")); j.assertAllImageLoadSuccessfully(webClient.goTo("asynchPeople"));
} }
@Issue("JENKINS-16608") @Issue("JENKINS-16608")
@Test public void notAllowedName() throws Exception { @Test public void notAllowedName() throws Exception {
HtmlForm form = j.createWebClient().goTo("newView").getFormByName("createItem"); WebClient wc = j.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
HtmlForm form = wc.goTo("newView").getFormByName("createItem");
form.getInputByName("name").setValueAttribute(".."); form.getInputByName("name").setValueAttribute("..");
form.getRadioButtonsByName("mode").get(0).setChecked(true); form.getRadioButtonsByName("mode").get(0).setChecked(true);
try { HtmlPage page = j.submit(form);
j.submit(form); assertEquals("\"..\" should not be allowed.",
fail("\"..\" should not be allowed."); HttpURLConnection.HTTP_BAD_REQUEST,
} catch (FailingHttpStatusCodeException e) { page.getWebResponse().getStatusCode());
assertEquals(400, e.getStatusCode());
}
} }
@Ignore("verified manually in Winstone but org.mortbay.JettyResponse.sendRedirect (6.1.26) seems to mangle the location") @Ignore("verified manually in Winstone but org.mortbay.JettyResponse.sendRedirect (6.1.26) seems to mangle the location")
......
...@@ -27,12 +27,13 @@ import static org.junit.Assert.assertEquals; ...@@ -27,12 +27,13 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.model.FreeStyleProject; import hudson.model.FreeStyleProject;
import hudson.model.ListView; import hudson.model.ListView;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -43,7 +44,6 @@ import hudson.model.User; ...@@ -43,7 +44,6 @@ import hudson.model.User;
import hudson.model.View; import hudson.model.View;
import hudson.security.ACL; import hudson.security.ACL;
import hudson.security.ACLContext; import hudson.security.ACLContext;
import hudson.security.AuthorizationStrategy;
import hudson.security.GlobalMatrixAuthorizationStrategy; import hudson.security.GlobalMatrixAuthorizationStrategy;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import net.sf.json.JSONArray; import net.sf.json.JSONArray;
...@@ -58,8 +58,6 @@ import org.jvnet.hudson.test.JenkinsRule.WebClient; ...@@ -58,8 +58,6 @@ import org.jvnet.hudson.test.JenkinsRule.WebClient;
import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.MockAuthorizationStrategy;
import org.jvnet.hudson.test.MockFolder; import org.jvnet.hudson.test.MockFolder;
import com.gargoylesoftware.htmlunit.AlertHandler;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.Page;
/** /**
...@@ -74,12 +72,10 @@ public class SearchTest { ...@@ -74,12 +72,10 @@ public class SearchTest {
*/ */
@Test @Test
public void testFailure() throws Exception { public void testFailure() throws Exception {
try { WebClient wc = j.createWebClient()
j.search("no-such-thing"); .withThrowExceptionOnFailingStatusCode(false);
fail("404 expected"); HtmlPage resultPage = wc.search("no-such-thing");
} catch (FailingHttpStatusCodeException e) { assertEquals(HttpURLConnection.HTTP_NOT_FOUND, resultPage.getWebResponse().getStatusCode());
assertEquals(404,e.getResponse().getStatusCode());
}
} }
/** /**
...@@ -88,18 +84,13 @@ public class SearchTest { ...@@ -88,18 +84,13 @@ public class SearchTest {
@Issue("JENKINS-3415") @Issue("JENKINS-3415")
@Test @Test
public void testXSS() throws Exception { public void testXSS() throws Exception {
try { WebClient wc = j.createWebClient()
WebClient wc = j.createWebClient(); .withThrowExceptionOnFailingStatusCode(false);
wc.setAlertHandler(new AlertHandler() { wc.setAlertHandler((page, message) -> {
public void handleAlert(Page page, String message) {
throw new AssertionError(); throw new AssertionError();
}
}); });
wc.search("<script>alert('script');</script>"); HtmlPage resultPage = wc.search("<script>alert('script');</script>");
fail("404 expected"); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, resultPage.getWebResponse().getStatusCode());
} catch (FailingHttpStatusCodeException e) {
assertEquals(404,e.getResponse().getStatusCode());
}
} }
@Test @Test
......
...@@ -6,10 +6,8 @@ ...@@ -6,10 +6,8 @@
package hudson.security.csrf; package hudson.security.csrf;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPage;
import jenkins.model.Jenkins;
import junit.framework.Assert;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
...@@ -60,13 +58,11 @@ public class DefaultCrumbIssuerTest { ...@@ -60,13 +58,11 @@ public class DefaultCrumbIssuerTest {
HtmlPage p = wc.goTo("configure"); HtmlPage p = wc.goTo("configure");
wc.removeRequestHeader(HEADER_NAME); wc.removeRequestHeader(HEADER_NAME);
try {
wc.setThrowExceptionOnFailingStatusCode(false);
// The crumb should no longer match if we remove the proxy info // The crumb should no longer match if we remove the proxy info
r.submit(p.getFormByName("config")); Page page = r.submit(p.getFormByName("config"));
} assertEquals(HttpURLConnection.HTTP_FORBIDDEN, page.getWebResponse().getStatusCode());
catch (FailingHttpStatusCodeException e) {
assertEquals(403,e.getStatusCode());
}
} }
@Issue("JENKINS-3854") @Issue("JENKINS-3854")
...@@ -139,17 +135,19 @@ public class DefaultCrumbIssuerTest { ...@@ -139,17 +135,19 @@ public class DefaultCrumbIssuerTest {
@Issue("JENKINS-34254") @Issue("JENKINS-34254")
@Test public void testRequirePostErrorPageCrumb() throws Exception { @Test public void testRequirePostErrorPageCrumb() throws Exception {
Jenkins.getInstance().setCrumbIssuer(new DefaultCrumbIssuer(false)); r.jenkins.setCrumbIssuer(new DefaultCrumbIssuer(false));
WebClient wc = r.createWebClient(); WebClient wc = r.createWebClient()
try { .withThrowExceptionOnFailingStatusCode(false);
wc.goTo("quietDown");
fail("expected failure"); Page page = wc.goTo("quietDown");
} catch (FailingHttpStatusCodeException ex) { assertEquals("expect HTTP 405 method not allowed",
Assert.assertEquals("expect HTTP 405 method not allowed", 405, ex.getStatusCode()); HttpURLConnection.HTTP_BAD_METHOD,
} page.getWebResponse().getStatusCode());
HtmlPage retry = (HtmlPage) wc.getCurrentWindow().getEnclosedPage(); HtmlPage retry = (HtmlPage) wc.getCurrentWindow().getEnclosedPage();
HtmlPage success = r.submit(retry.getFormByName("retry")); HtmlPage success = r.submit(retry.getFormByName("retry"));
Assert.assertTrue("quieting down", r.jenkins.isQuietingDown()); assertEquals(HttpURLConnection.HTTP_OK, success.getWebResponse().getStatusCode());
assertTrue("quieting down", r.jenkins.isQuietingDown());
} }
} }
...@@ -45,6 +45,7 @@ import org.jvnet.hudson.test.MockAuthorizationStrategy; ...@@ -45,6 +45,7 @@ import org.jvnet.hudson.test.MockAuthorizationStrategy;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
...@@ -87,12 +88,12 @@ public class ZipExtractionInstallerTest { ...@@ -87,12 +88,12 @@ public class ZipExtractionInstallerTest {
JenkinsRule.WebClient adminWc = j.createWebClient(); JenkinsRule.WebClient adminWc = j.createWebClient();
adminWc.login(ADMIN); adminWc.login(ADMIN);
assertEquals(200, adminWc.getPage(request).getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_OK, adminWc.getPage(request).getWebResponse().getStatusCode());
JenkinsRule.WebClient userWc = j.createWebClient(); JenkinsRule.WebClient userWc = j.createWebClient()
userWc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
userWc.login(USER); userWc.login(USER);
assertEquals(403, userWc.getPage(request).getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, userWc.getPage(request).getWebResponse().getStatusCode());
} }
@Test @Test
......
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
package hudson.util; package hudson.util;
import com.gargoylesoftware.htmlunit.Page;
import hudson.cli.CLICommandInvoker; import hudson.cli.CLICommandInvoker;
import hudson.diagnosis.OldDataMonitor; import hudson.diagnosis.OldDataMonitor;
import hudson.model.AbstractDescribableImpl; import hudson.model.AbstractDescribableImpl;
...@@ -38,6 +39,7 @@ import hudson.model.User; ...@@ -38,6 +39,7 @@ import hudson.model.User;
import hudson.security.ACL; import hudson.security.ACL;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
...@@ -45,7 +47,6 @@ import java.util.Map; ...@@ -45,7 +47,6 @@ import java.util.Map;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import jenkins.security.apitoken.ApiTokenPropertyConfiguration;
import jenkins.security.apitoken.ApiTokenTestHelper; import jenkins.security.apitoken.ApiTokenTestHelper;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
...@@ -59,7 +60,6 @@ import org.jvnet.hudson.test.recipes.LocalData; ...@@ -59,7 +60,6 @@ import org.jvnet.hudson.test.recipes.LocalData;
import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerRequest;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebRequest; import com.gargoylesoftware.htmlunit.WebRequest;
...@@ -236,18 +236,17 @@ public class RobustReflectionConverterTest { ...@@ -236,18 +236,17 @@ public class RobustReflectionConverterTest {
// Configure a bad keyword via REST. // Configure a bad keyword via REST.
r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
WebClient wc = r.createWebClient(); WebClient wc = r.createWebClient()
.withThrowExceptionOnFailingStatusCode(false);
wc.withBasicApiToken(test); wc.withBasicApiToken(test);
WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST); WebRequest req = new WebRequest(new URL(wc.getContextPath() + String.format("%s/config.xml", p.getUrl())), HttpMethod.POST);
req.setEncodingType(null); req.setEncodingType(null);
req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue")); req.setRequestBody(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue"));
try { Page page = wc.getPage(req);
wc.getPage(req); assertEquals("Submitting unacceptable configuration via REST should fail.",
fail("Submitting unacceptable configuration via REST should fail."); HttpURLConnection.HTTP_INTERNAL_ERROR,
} catch (FailingHttpStatusCodeException e) { page.getWebResponse().getStatusCode());
// pass
}
// Configuration should not be updated for a failure of the critical field, // Configuration should not be updated for a failure of the critical field,
assertNotEquals("badvalue", p.getProperty(KeywordProperty.class).getCriticalField().getKeyword()); assertNotEquals("badvalue", p.getProperty(KeywordProperty.class).getCriticalField().getKeyword());
......
...@@ -337,33 +337,30 @@ public class JenkinsTest { ...@@ -337,33 +337,30 @@ public class JenkinsTest {
grant(Jenkins.READ).everywhere().to("bob"). grant(Jenkins.READ).everywhere().to("bob").
grantWithoutImplication(Jenkins.ADMINISTER, Jenkins.READ).everywhere().to("charlie")); grantWithoutImplication(Jenkins.ADMINISTER, Jenkins.READ).everywhere().to("charlie"));
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
.withThrowExceptionOnFailingStatusCode(false)
.withBasicApiToken(User.getById("alice", true));
wc.withBasicApiToken(User.getById("alice", true));
wc.assertFails("eval", HttpURLConnection.HTTP_BAD_METHOD); wc.assertFails("eval", HttpURLConnection.HTTP_BAD_METHOD);
assertEquals("3", eval(wc)); assertEquals("3", eval(wc).getWebResponse().getContentAsString());
wc.withBasicApiToken(User.getById("bob", true)); wc.withBasicApiToken(User.getById("bob", true));
try { Page page = eval(wc);
eval(wc); assertEquals("bob has only READ",
fail("bob has only READ"); HttpURLConnection.HTTP_FORBIDDEN,
} catch (FailingHttpStatusCodeException e) { page.getWebResponse().getStatusCode());
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
}
wc.withBasicApiToken(User.getById("charlie", true)); wc.withBasicApiToken(User.getById("charlie", true));
try { page = eval(wc);
eval(wc); assertEquals("charlie has ADMINISTER but not RUN_SCRIPTS",
fail("charlie has ADMINISTER but not RUN_SCRIPTS"); HttpURLConnection.HTTP_FORBIDDEN,
} catch (FailingHttpStatusCodeException e) { page.getWebResponse().getStatusCode());
assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode());
}
} }
private String eval(WebClient wc) throws Exception { private Page eval(WebClient wc) throws Exception {
WebRequest req = new WebRequest(new URL(wc.getContextPath() + "eval"), HttpMethod.POST); WebRequest req = new WebRequest(new URL(wc.getContextPath() + "eval"), HttpMethod.POST);
req.setEncodingType(null); req.setEncodingType(null);
req.setRequestBody("<j:jelly xmlns:j='jelly:core'>${1+2}</j:jelly>"); req.setRequestBody("<j:jelly xmlns:j='jelly:core'>${1+2}</j:jelly>");
return wc.getPage(req).getWebResponse().getContentAsString(); return wc.getPage(req);
} }
@TestExtension("testUnprotectedRootAction") @TestExtension("testUnprotectedRootAction")
...@@ -411,13 +408,13 @@ public class JenkinsTest { ...@@ -411,13 +408,13 @@ public class JenkinsTest {
j.jenkins.setAuthorizationStrategy(auth); j.jenkins.setAuthorizationStrategy(auth);
// no anonymous read access // no anonymous read access
assertTrue(!Jenkins.getInstance().hasPermission(Jenkins.ANONYMOUS,Jenkins.READ)); assertTrue(!Jenkins.get().hasPermission(Jenkins.ANONYMOUS, Jenkins.READ));
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("error/reportError"); HtmlPage p = wc.goTo("error/reportError");
assertEquals(p.asText(), 400, p.getWebResponse().getStatusCode()); // not 403 forbidden assertEquals(p.asText(), HttpURLConnection.HTTP_BAD_REQUEST, p.getWebResponse().getStatusCode()); // not 403 forbidden
assertTrue(p.getWebResponse().getContentAsString().contains("My car is black")); assertTrue(p.getWebResponse().getContentAsString().contains("My car is black"));
} }
...@@ -462,8 +459,8 @@ public class JenkinsTest { ...@@ -462,8 +459,8 @@ public class JenkinsTest {
URL url = new URL(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)"); URL url = new URL(j.getURL(), "computer/" + slave.getNodeName() + "/scriptText?script=println(42)");
WebClient wc = j.createWebClient(); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebRequest req = new WebRequest(url, HttpMethod.POST); WebRequest req = new WebRequest(url, HttpMethod.POST);
Page page = wc.getPage(wc.addCrumb(req)); Page page = wc.getPage(wc.addCrumb(req));
......
...@@ -24,6 +24,8 @@ import hudson.model.FreeStyleProject; ...@@ -24,6 +24,8 @@ import hudson.model.FreeStyleProject;
import hudson.model.User; import hudson.model.User;
import hudson.security.ACL; import hudson.security.ACL;
import hudson.security.ACLContext; import hudson.security.ACLContext;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
...@@ -139,12 +141,14 @@ public class ApiTokenPropertyTest { ...@@ -139,12 +141,14 @@ public class ApiTokenPropertyTest {
final ApiTokenProperty.DescriptorImpl descriptor = (ApiTokenProperty.DescriptorImpl) t.getDescriptor(); final ApiTokenProperty.DescriptorImpl descriptor = (ApiTokenProperty.DescriptorImpl) t.getDescriptor();
// Make sure that Admin can reset a token of another user // Make sure that Admin can reset a token of another user
WebClient wc = createClientForUser("bar"); WebClient wc = createClientForUser("bar")
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage requirePOST = wc.goTo(foo.getUrl() + "/" + descriptor.getDescriptorUrl()+ "/changeToken"); HtmlPage requirePOST = wc.goTo(foo.getUrl() + "/" + descriptor.getDescriptorUrl()+ "/changeToken");
assertEquals("method should not be allowed", 405, requirePOST.getWebResponse().getStatusCode()); assertEquals("method should not be allowed",
HttpURLConnection.HTTP_BAD_METHOD,
requirePOST.getWebResponse().getStatusCode());
wc.getOptions().setThrowExceptionOnFailingStatusCode(true); wc.setThrowExceptionOnFailingStatusCode(true);
WebRequest request = new WebRequest(new URL(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl()+ "/changeToken"), HttpMethod.POST); WebRequest request = new WebRequest(new URL(j.getURL().toString() + foo.getUrl() + "/" + descriptor.getDescriptorUrl()+ "/changeToken"), HttpMethod.POST);
HtmlPage res = wc.getPage(request); HtmlPage res = wc.getPage(request);
...@@ -163,7 +167,7 @@ public class ApiTokenPropertyTest { ...@@ -163,7 +167,7 @@ public class ApiTokenPropertyTest {
WebClient wc = createClientForUser("foo"); WebClient wc = createClientForUser("foo");
WebRequest wr = new WebRequest(new URL(j.getURL(), "job/bar/build"), HttpMethod.POST); WebRequest wr = new WebRequest(new URL(j.getURL(), "job/bar/build"), HttpMethod.POST);
assertEquals(201, wc.getPage(wr).getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_CREATED, wc.getPage(wr).getWebResponse().getStatusCode());
j.waitUntilNoActivity(); j.waitUntilNoActivity();
......
...@@ -19,8 +19,8 @@ public class Security177Test { ...@@ -19,8 +19,8 @@ public class Security177Test {
@Test @Test
public void nosniff() throws Exception { public void nosniff() throws Exception {
WebClient wc = jenkins.createWebClient(); WebClient wc = jenkins.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
URL u = jenkins.getURL(); URL u = jenkins.getURL();
verifyNoSniff(wc.getPage(new URL(u, "adjuncts/507db12b/nosuch/adjunct.js"))); verifyNoSniff(wc.getPage(new URL(u, "adjuncts/507db12b/nosuch/adjunct.js")));
......
...@@ -67,8 +67,9 @@ public class ApiTokenStatsTest { ...@@ -67,8 +67,9 @@ public class ApiTokenStatsTest {
assertNotNull(t.getTokenStats()); assertNotNull(t.getTokenStats());
// test the authentication via Token // test the authentication via Token
WebClient wc = j.createWebClient().withBasicCredentials(u.getId()); WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withBasicCredentials(u.getId())
.withThrowExceptionOnFailingStatusCode(false);
final String TOKEN_NAME = "New Token Name"; final String TOKEN_NAME = "New Token Name";
......
...@@ -33,6 +33,7 @@ import org.jvnet.hudson.test.Issue; ...@@ -33,6 +33,7 @@ import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestPluginManager; import org.jvnet.hudson.test.TestPluginManager;
import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
...@@ -53,8 +54,8 @@ public class Security914Test { ...@@ -53,8 +54,8 @@ public class Security914Test {
} }
j.createWebClient().goTo("plugin/credentials/images/24x24/credentials.png", "image/png"); j.createWebClient().goTo("plugin/credentials/images/24x24/credentials.png", "image/png");
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.xml")); WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.xml"));
// plugin deployed in: test\target\jenkins7375296945862059919tmp // plugin deployed in: test\target\jenkins7375296945862059919tmp
// rootDir is in : test\target\jenkinsTests.tmp\jenkins1274934531848159942test // rootDir is in : test\target\jenkinsTests.tmp\jenkins1274934531848159942test
...@@ -62,7 +63,7 @@ public class Security914Test { ...@@ -62,7 +63,7 @@ public class Security914Test {
request.setAdditionalHeader("Accept-Language", "../../../../jenkinsTests.tmp/" + j.jenkins.getRootDir().getName() + "/config"); request.setAdditionalHeader("Accept-Language", "../../../../jenkinsTests.tmp/" + j.jenkins.getRootDir().getName() + "/config");
Page p = wc.getPage(request); Page p = wc.getPage(request);
assertEquals(p.getWebResponse().getStatusCode(), 404); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, p.getWebResponse().getStatusCode());
assertNotEquals(p.getWebResponse().getContentType(), "application/xml"); assertNotEquals(p.getWebResponse().getContentType(), "application/xml");
} }
...@@ -75,14 +76,14 @@ public class Security914Test { ...@@ -75,14 +76,14 @@ public class Security914Test {
} }
j.createWebClient().goTo("plugin/credentials/images/24x24/credentials.png", "image/png"); j.createWebClient().goTo("plugin/credentials/images/24x24/credentials.png", "image/png");
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.ini")); WebRequest request = new WebRequest(new URL(j.getURL() + "plugin/credentials/.ini"));
// ../ can be multiply to infinity, no impact, we just need to have enough to reach the root // ../ can be multiply to infinity, no impact, we just need to have enough to reach the root
request.setAdditionalHeader("Accept-Language", "../../../../../../../../../../../../windows/win"); request.setAdditionalHeader("Accept-Language", "../../../../../../../../../../../../windows/win");
Page p = wc.getPage(request); Page p = wc.getPage(request);
assertEquals(p.getWebResponse().getStatusCode(), 404); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, p.getWebResponse().getStatusCode());
assertEquals(p.getWebResponse().getContentType(), "text/html"); assertEquals(p.getWebResponse().getContentType(), "text/html");
} }
} }
...@@ -99,8 +99,8 @@ public class ExpandableTextboxTest { ...@@ -99,8 +99,8 @@ public class ExpandableTextboxTest {
private void checkRegularCase(TestRootAction testParams) throws Exception { private void checkRegularCase(TestRootAction testParams) throws Exception {
testParams.paramName = "testName"; testParams.paramName = "testName";
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
HtmlElementUtil.click(getExpandButton(p)); HtmlElementUtil.click(getExpandButton(p));
...@@ -110,8 +110,8 @@ public class ExpandableTextboxTest { ...@@ -110,8 +110,8 @@ public class ExpandableTextboxTest {
private void checkInjectionInName(TestRootAction testParams) throws Exception { private void checkInjectionInName(TestRootAction testParams) throws Exception {
testParams.paramName = "testName',document.title='hacked'+'"; testParams.paramName = "testName',document.title='hacked'+'";
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
HtmlElementUtil.click(getExpandButton(p)); HtmlElementUtil.click(getExpandButton(p));
......
...@@ -128,8 +128,8 @@ public class ValidateButtonTest { ...@@ -128,8 +128,8 @@ public class ValidateButtonTest {
descriptor.paramMethod = "validateInjection"; descriptor.paramMethod = "validateInjection";
descriptor.paramWith = "a,b"; descriptor.paramWith = "a,b";
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
descriptor.wasCalled = false; descriptor.wasCalled = false;
...@@ -142,8 +142,8 @@ public class ValidateButtonTest { ...@@ -142,8 +142,8 @@ public class ValidateButtonTest {
descriptor.paramMethod = "validateInjection',document.title='hacked'+'"; descriptor.paramMethod = "validateInjection',document.title='hacked'+'";
descriptor.paramWith = "a,b"; descriptor.paramWith = "a,b";
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
// no check on wasCalled because the button that is expected by the method is not passed (arguments are shifted due to the injection) // no check on wasCalled because the button that is expected by the method is not passed (arguments are shifted due to the injection)
...@@ -156,8 +156,8 @@ public class ValidateButtonTest { ...@@ -156,8 +156,8 @@ public class ValidateButtonTest {
descriptor.paramMethod = "validateInjection"; descriptor.paramMethod = "validateInjection";
descriptor.paramWith = "a,b',document.title='hacked'+'"; descriptor.paramWith = "a,b',document.title='hacked'+'";
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
descriptor.wasCalled = false; descriptor.wasCalled = false;
......
...@@ -41,6 +41,8 @@ import org.kohsuke.stapler.WebMethod; ...@@ -41,6 +41,8 @@ import org.kohsuke.stapler.WebMethod;
import javax.annotation.CheckForNull; import javax.annotation.CheckForNull;
import java.net.HttpURLConnection;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
...@@ -111,8 +113,8 @@ public class ConfirmationLinkTest { ...@@ -111,8 +113,8 @@ public class ConfirmationLinkTest {
} }
private Page getPageAfterClick() throws Exception { private Page getPageAfterClick() throws Exception {
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
return HtmlElementUtil.click(getClickableLink(p)); return HtmlElementUtil.click(getClickableLink(p));
...@@ -124,15 +126,15 @@ public class ConfirmationLinkTest { ...@@ -124,15 +126,15 @@ public class ConfirmationLinkTest {
testParams.paramClass = null; testParams.paramClass = null;
testParams.paramPost = null; testParams.paramPost = null;
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
Page pageAfterClick = HtmlElementUtil.click(getClickableLink(p)); Page pageAfterClick = HtmlElementUtil.click(getClickableLink(p));
assertNotEquals("hacked", p.getTitleText()); assertNotEquals("hacked", p.getTitleText());
assertTrue(p.getWebResponse().getContentAsString().contains("Message to confirm the click")); assertTrue(p.getWebResponse().getContentAsString().contains("Message to confirm the click"));
// the url it clicks on is escaped and so does not exist // the url it clicks on is escaped and so does not exist
assertEquals(404, pageAfterClick.getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, pageAfterClick.getWebResponse().getStatusCode());
} }
private void checkInjectionInMessage(TestRootAction testParams) throws Exception { private void checkInjectionInMessage(TestRootAction testParams) throws Exception {
...@@ -141,14 +143,14 @@ public class ConfirmationLinkTest { ...@@ -141,14 +143,14 @@ public class ConfirmationLinkTest {
testParams.paramClass = null; testParams.paramClass = null;
testParams.paramPost = null; testParams.paramPost = null;
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
Page pageAfterClick = HtmlElementUtil.click(getClickableLink(p)); Page pageAfterClick = HtmlElementUtil.click(getClickableLink(p));
assertNotEquals("hacked", p.getTitleText()); assertNotEquals("hacked", p.getTitleText());
// the url is normally the same page so it's ok // the url is normally the same page so it's ok
assertEquals(200, pageAfterClick.getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_OK, pageAfterClick.getWebResponse().getStatusCode());
} }
private void checkInjectionInPost(TestRootAction testParams) throws Exception { private void checkInjectionInPost(TestRootAction testParams) throws Exception {
...@@ -157,15 +159,15 @@ public class ConfirmationLinkTest { ...@@ -157,15 +159,15 @@ public class ConfirmationLinkTest {
testParams.paramClass = null; testParams.paramClass = null;
testParams.paramPost = postPayload; testParams.paramPost = postPayload;
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
Page pageAfterClick = HtmlElementUtil.click(getClickableLink(p)); Page pageAfterClick = HtmlElementUtil.click(getClickableLink(p));
assertNotEquals("hacked", p.getTitleText()); assertNotEquals("hacked", p.getTitleText());
assertTrue(p.getWebResponse().getContentAsString().contains("Message to confirm the click")); assertTrue(p.getWebResponse().getContentAsString().contains("Message to confirm the click"));
// the url is normally the same page so it's ok // the url is normally the same page so it's ok
assertEquals(200, pageAfterClick.getWebResponse().getStatusCode()); assertEquals(HttpURLConnection.HTTP_OK, pageAfterClick.getWebResponse().getStatusCode());
} }
private HtmlAnchor getClickableLink(HtmlPage page){ private HtmlAnchor getClickableLink(HtmlPage page){
......
...@@ -77,8 +77,8 @@ public class StopButtonTest { ...@@ -77,8 +77,8 @@ public class StopButtonTest {
testParams.paramAlt = "Alternative text for icon"; testParams.paramAlt = "Alternative text for icon";
testParams.paramConfirm = null; testParams.paramConfirm = null;
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
HtmlElementUtil.click(getStopLink(p)); HtmlElementUtil.click(getStopLink(p));
...@@ -91,8 +91,8 @@ public class StopButtonTest { ...@@ -91,8 +91,8 @@ public class StopButtonTest {
testParams.paramAlt = "Alternative text for icon"; testParams.paramAlt = "Alternative text for icon";
testParams.paramConfirm = "Confirm message"; testParams.paramConfirm = "Confirm message";
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
HtmlElementUtil.click(getStopLink(p)); HtmlElementUtil.click(getStopLink(p));
...@@ -105,8 +105,8 @@ public class StopButtonTest { ...@@ -105,8 +105,8 @@ public class StopButtonTest {
testParams.paramAlt = "Alternative text for icon"; testParams.paramAlt = "Alternative text for icon";
testParams.paramConfirm = postPayload; testParams.paramConfirm = postPayload;
JenkinsRule.WebClient wc = j.createWebClient(); JenkinsRule.WebClient wc = j.createWebClient()
wc.getOptions().setThrowExceptionOnFailingStatusCode(false); .withThrowExceptionOnFailingStatusCode(false);
HtmlPage p = wc.goTo("test"); HtmlPage p = wc.goTo("test");
HtmlElementUtil.click(getStopLink(p)); HtmlElementUtil.click(getStopLink(p));
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册