public class JsonAPITest {
@Rule
public JenkinsRule j = new JenkinsRule();
private static String GET_API_URL = "custom-api/get-example-param?paramValue=hello";
@Test
public void testGetJSON() throws Exception {
JenkinsRule.WebClient webClient = j.createWebClient();
// Testing a simple GET that should answer 200 OK and a JSON
JenkinsRule.JSONWebResponse response = webClient.getJSON(GET_API_URL);
assertTrue(response.getContentAsString().contains("I am JenkinsRule hello"));
assertEquals(response.getStatusCode(), 200);
}
@Test
public void testAdvancedGetJSON() throws Exception {
//Given a Jenkins setup with a user "admin"
MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
.grant(Jenkins.ADMINISTER).everywhere().to("admin");
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
j.jenkins.setAuthorizationStrategy(auth);
//We need to setup the WebClient, we use it to call the HTTP API
JenkinsRule.WebClient webClient = j.createWebClient();
//By default if the status code is not ok, WebClient throw an exception
//Since we want to assert the error status code, we need to set to false.
webClient.setThrowExceptionOnFailingStatusCode(false);
// - simple call without authentication should be forbidden
response = webClient.getJSON(GET_API_URL);
assertEquals(response.getStatusCode(), 403);
// - same call but authenticated using withBasicApiToken() should be fine
response = webClient.withBasicApiToken("admin").getJSON(GET_API_URL);
assertEquals(response.getStatusCode(), 200);
}