import static org.hamcrest.MatcherAssert.assertThat;
import jenkins.model.Jenkins;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.JenkinsRule.JSONWebResponse;
import org.jvnet.hudson.test.MockAuthorizationStrategy;
import org.jvnet.hudson.test.junit.jupiter.WithJenkins;
@WithJenkins
class JsonAPITest {
    private static final String GET_API_URL = "custom-api/get-example-param?paramValue=hello";
    @Test
    void testGetJSON(JenkinsRule j) throws Exception {
        JenkinsRule.WebClient webClient = j.createWebClient();
        JSONWebResponse response = webClient.getJSON(GET_API_URL);
        assertThat(response.getContentAsString(), Matchers.containsString("I am Jenkins hello"));
        assertThat(response.getStatusCode(), Matchers.equalTo(200));
    }
    @Test
    void testAdvancedGetJSON(JenkinsRule j) 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
        JSONWebResponse response = webClient.getJSON(GET_API_URL);
        assertThat(response.getStatusCode(), Matchers.equalTo(403));
        // - same call but authenticated using withBasicApiToken() should be fine
        response = webClient.withBasicApiToken("admin").getJSON(GET_API_URL);
        assertThat(response.getStatusCode(), Matchers.equalTo(200));
    }
}