Java Code Examples for com.cloudbees.plugins.credentials.CredentialsScope#GLOBAL

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsScope#GLOBAL . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DockerServerCredentialsTest.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
@Test
public void configRoundTripUpdateCertificates() throws Exception {
    CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next();
    assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
    Domain domain = new Domain("docker", "A domain for docker credentials", Collections.singletonList(new DockerServerDomainSpecification()));
    DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("key"), "client-cert", "ca-cert");
    store.addDomain(domain, credentials);

    HtmlForm form = getUpdateForm(domain, credentials);
    for (HtmlElement button : form.getElementsByAttribute("input", "class", "secret-update-btn")) {
        button.click();
    }

    form.getTextAreaByName("_.clientKeySecret").setText("new key");
    form.getTextAreaByName("_.clientCertificate").setText("new cert");
    form.getTextAreaByName("_.serverCaCertificate").setText("new ca cert");
    j.submit(form);

    DockerServerCredentials expected = new DockerServerCredentials(
            credentials.getScope(), credentials.getId(), credentials.getDescription(),
            Secret.fromString("new key"), "new cert", "new ca cert");
    j.assertEqualDataBoundBeans(expected, findFirstWithId(credentials.getId()));
}
 
Example 2
Source File: BuildWrapperOrderCredentialsBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-37871")
@Test public void secretBuildWrapperRunsBeforeNormalWrapper() throws Exception {
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample1", Secret.fromString(password));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding(bindingKey, credentialsId)));

    FreeStyleProject f = r.createFreeStyleProject("buildWrapperOrder");

    f.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo $PASS_1"));
    f.getBuildWrappersList().add(new BuildWrapperOrder());
    f.getBuildWrappersList().add(wrapper);

    // configRoundtrip makes sure the ordinal of SecretBuildWrapper extension is applied correctly.
    r.configRoundtrip(f);

    FreeStyleBuild b = r.buildAndAssertSuccess(f);
    r.assertLogContains("Secret found!", b);
}
 
Example 3
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a JSON credential without a "jenkins_token" field and without a proper DC/OS service account value
 * results in a 401 and only 1 web request.
 *
 * @throws Exception
 */
@Test
public void testRecorderInvalidToken() throws Exception {
    final FreeStyleProject                       project         = j.createFreeStyleProject();
    final SystemCredentialsProvider.ProviderImpl system          = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore     = system.getStore(j.getInstance());
    final String                                 credentialValue = "{\"field1\":\"some value\"}";
    final Secret                                 secret          = Secret.fromString(credentialValue);
    final StringCredentials                      credential      = new StringCredentialsImpl(CredentialsScope.GLOBAL, "invalidtoken", "a token for JSON token test", secret);
    TestUtils.enqueueFailureResponse(httpServer, 401);

    systemStore.addCredentials(Domain.global(), credential);

    addBuilders(TestUtils.loadFixture("idonly.json"), project);

    // add post-builder
    addPostBuilders(project, "invalidtoken");

    final FreeStyleBuild build = j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon] Authentication to Marathon instance failed:", build);
    j.assertLogContains("[Marathon] Invalid DC/OS service account JSON", build);
    assertEquals("Only 1 request should have been made.", 1, httpServer.getRequestCount());
}
 
Example 4
Source File: Security1446Test.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@Issue("SECURITY-1446")
public void testExportWithEnvVar() throws Exception {
    final String message = "Hello, world! PATH=${PATH} JAVA_HOME=^${JAVA_HOME}";
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);

    DataBoundConfigurator<UsernamePasswordCredentialsImpl> configurator = new DataBoundConfigurator<>(UsernamePasswordCredentialsImpl.class);
    UsernamePasswordCredentialsImpl creds = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test",
            message, "foo", "bar");
    final CNode config = configurator.describe(creds, context);
    final Node valueNode = ConfigurationAsCode.get().toYaml(config);
    final String exported;
    try (StringWriter writer = new StringWriter()) {
        ConfigurationAsCode.serializeYamlNode(valueNode, writer);
        exported = writer.toString();
    } catch (IOException e) {
        throw new YAMLException(e);
    }

    assertThat("Message was not escaped", exported, not(containsString(message)));
    assertThat("Improper masking for PATH", exported, containsString("^${PATH}"));
    assertThat("Improper masking for JAVA_HOME", exported, containsString("^^${JAVA_HOME}"));
}
 
Example 5
Source File: CertificateMultiBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Test
public void basicsPipeline() throws Exception {
	// create the Credentials
	String alias = "androiddebugkey";
	String password = "android";
	StandardCertificateCredentials c = new CertificateCredentialsImpl(CredentialsScope.GLOBAL, "my-certificate", alias,
			password, new CertificateCredentialsImpl.FileOnMasterKeyStoreSource(certificate.getAbsolutePath()));
	CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
	// create the Pipeline job
	WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
	String pipelineScript = IOUtils.toString(getTestResourceInputStream("basicsPipeline-Jenkinsfile"));
	p.setDefinition(new CpsFlowDefinition(pipelineScript, true));
	// copy resources into workspace
	FilePath workspace = r.jenkins.getWorkspaceFor(p);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.sh", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.sh", 0755);
	// execute the pipeline
	WorkflowRun b = p.scheduleBuild2(0).waitForStart();
	r.waitForCompletion(b);
	r.assertBuildStatusSuccess(b);
}
 
Example 6
Source File: BuildStatusConfigTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies doFillCredentialsIdItems adds values from the credentials store
 * @throws IOException
 */
@Test
public void testDoFillHttpCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
    StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
    CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);

    BuildStatusConfig instance = new BuildStatusConfig();
    instance.setCredentialsId(testCredentials);

    ListBoxModel model = instance.doFillHttpCredentialsIdItems(testCredentials);

    assertEquals(2, model.size());
    ListBoxModel.Option item1 = model.get(0);
    assertEquals("", item1.value);
    assertEquals("- none -", item1.name);

    ListBoxModel.Option item2 = model.get(1);
    assertEquals(testCredentials, item2.value);
}
 
Example 7
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutRepoMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example 8
Source File: SSLTest.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@BeforeClass
public static void setupClass() throws IOException, InterruptedException {
    assumeTrue(hasDockerDaemon());
    container.initAndUnsealVault();
    container.setBasicSecrets();

    pipeline = j.createProject(WorkflowJob.class, "Pipeline");
    String pipelineText =  IOUtils.toString(TestConstants.class.getResourceAsStream("pipeline.groovy"));
    pipeline.setDefinition(new CpsFlowDefinition(pipelineText, true));

    VaultTokenCredential c = new VaultTokenCredential(CredentialsScope.GLOBAL,
        credentialsId, "fake description", Secret.fromString(container.getRootToken()));
    CredentialsProvider.lookupStores(j.jenkins).iterator().next()
        .addCredentials(Domain.global(), c);
}
 
Example 9
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildEnterprise() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.when(ghb.withEndpoint("https://api.example.com")).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example 10
Source File: AwsKeyCredentialsTest.java    From jenkins-deployment-dashboard-plugin with MIT License 5 votes vote down vote up
@Test
public void testAwsKeyCredentials() {
    final AwsKeyCredentials credentials = new AwsKeyCredentials(CredentialsScope.GLOBAL, ID, DESC, ACCESS, SECRET);
    assertThat(credentials.key, is(ACCESS));
    assertThat(credentials.secret, is(SECRET));
    assertThat(credentials.getId(), is(ID));
    assertThat(credentials.getScope(), is(CredentialsScope.GLOBAL));
}
 
Example 11
Source File: RegistryEndpointStepTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test
public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception {
    assumeNotWindows();

    r.getInstance().setSecurityRealm(r.createDummySecurityRealm());
    MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
            .grant(Jenkins.READ).everywhere().to("alice", "bob")
            .grant(Computer.BUILD).everywhere().to("alice", "bob")
            // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById
            // uses when determining whether to include item-scope credentials in the search.
            .grant(Item.CONFIGURE).everywhere().to("alice");
    r.getInstance().setAuthorizationStrategy(auth);

    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials);

    String script = "node {\n" +
            "  mockDockerLoginWithEcho {\n" +
            "    withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" +
            "    }\n" +
            "  }\n" +
            "}";
    WorkflowJob p1 = r.createProject(WorkflowJob.class, "prj1");
    p1.setDefinition(new CpsFlowDefinition(script, true));
    WorkflowJob p2 = r.createProject(WorkflowJob.class, "prj2");
    p2.setDefinition(new CpsFlowDefinition(script, true));

    Map<String, Authentication> jobsToAuths = new HashMap<>();
    jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate());
    jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate());
    QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths));

    // Alice has Credentials.USE_ITEM permission and should be able to use the credential.
    WorkflowRun b1 = r.buildAndAssertSuccess(p1);
    r.assertLogContains("docker login -u me -p pass https://my-reg:1234", b1);

    // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential.
    r.assertBuildStatus(Result.FAILURE, p2.scheduleBuild2(0));
}
 
Example 12
Source File: InfluxDbNotifierConfigTest.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetCredentialsEmpty() {
    StandardUsernameCredentials credentials = 
            new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, 
                    influxDbCredentialsId, 
                    "Description", 
                    influxDbUser, 
                    influxDbPassword);
    when(BuildStatusConfig.getCredentials(any(), any()))
            .thenReturn(credentials);
    InfluxDbNotifierConfig instance
            = InfluxDbNotifierConfig.fromGlobalConfig("", "", branch);
    assertNotNull(influxDbCredentialsId, instance.getCredentials());
}
 
Example 13
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutAccountMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "repo: 'acceptance-test-harness',  " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example 14
Source File: PersonalAccessTokenImplTest.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void configRoundtrip() throws Exception {
    PersonalAccessTokenImpl expected = new PersonalAccessTokenImpl(
        CredentialsScope.GLOBAL,
        "magic-id",
        "configRoundtrip",
        "sAf_Xasnou47yxoAsC");
    CredentialsBuilder builder = new CredentialsBuilder(expected);
    j.configRoundtrip(builder);
    j.assertEqualDataBoundBeans(expected, builder.credentials);
}
 
Example 15
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithWrongRepoMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(null);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);


    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.INVALID_REPO, b1);
}
 
Example 16
Source File: GitHubSCMBuilderTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    owner = j.createProject(WorkflowMultiBranchProject.class);
    Credentials userPasswordCredential = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "user-pass", null, "git-user", "git-secret");
    Credentials sshPrivateKeyCredential = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "user-key", "git",
            new BasicSSHUserPrivateKey.UsersPrivateKeySource(), null, null);
    SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(),
            Arrays.asList(userPasswordCredential, sshPrivateKeyCredential)));
}
 
Example 17
Source File: JiraSendDeploymentInfoStepTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 4 votes vote down vote up
private static BaseStandardCredentials secretCredential() {
    return new StringCredentialsImpl(
            CredentialsScope.GLOBAL, CREDENTIAL_ID, "test-secret", Secret.fromString("secret"));
}
 
Example 18
Source File: GerritCheckStepTest.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void gerritCheckStepInvokeTest() throws Exception {
  int changeId = 4321;
  int revision = 1;
  String checkerUuid = "checker";
  String checkStatus = "SUCCESSFUL";
  String message = "Does work";
  String branch = String.format("%02d/%d/%d", changeId % 100, changeId, revision);

  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "q");
  p.setDefinition(
      new CpsFlowDefinition(
          String.format(
              ""
                  + "node {\n"
                  + "  withEnv([\n"
                  + "    'GERRIT_API_URL=https://%s:%s/a/project',\n"
                  + "    'GERRIT_API_INSECURE_HTTPS=true',\n"
                  + "    'GERRIT_CREDENTIALS_ID=cid',\n"
                  + "    'BRANCH_NAME=%s',\n"
                  + "  ]) {\n"
                  + "    gerritCheck checks: [%s: '%s'], message: '%s'\n"
                  + "  }\n"
                  + "}",
              g.getClient().remoteAddress().getHostString(),
              g.getClient().remoteAddress().getPort(),
              branch,
              checkerUuid,
              checkStatus,
              message),
          true));

  String expectedUrl = String.format("/a/changes/%s/revisions/%s/checks/", changeId, revision);

  CheckInput checkInput = new CheckInputForObjectMapper();
  checkInput.checkerUuid = checkerUuid;
  checkInput.state = CheckState.valueOf(checkStatus);
  checkInput.message = message;
  checkInput.url = j.getURL().toString() + p.getUrl() + "1/console";
  g.getClient()
      .when(
          HttpRequest.request(expectedUrl).withMethod("POST").withBody(JsonBody.json(checkInput)))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(Collections.emptyMap())));

  WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
  String log = JenkinsRule.getLog(run);

  g.getClient().verify(HttpRequest.request(expectedUrl), VerificationTimes.once());
}
 
Example 19
Source File: HttpNotifierTest.java    From github-autostatus-plugin with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
  mockConfig = mock(HttpNotifierConfig.class);

  when(mockConfig.getHttpEndpoint()).thenReturn("https://mock.com/jenkins");
  when(mockConfig.getRepoName()).thenReturn(repoName);
  when(mockConfig.getRepoOwner()).thenReturn(repoOwner);
  when(mockConfig.getBranchName()).thenReturn("");
  when(mockConfig.getHttpCredentialsId()).thenReturn(credentialId);
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, credentialId, "description", username, password);
  when(mockConfig.getCredentials()).thenReturn(credentials);
  when(mockConfig.getHttpVerifySSL()).thenReturn(true);

  mockHttpClient = mock(CloseableHttpClient.class);
  when(mockConfig.getHttpClient(false)).thenReturn(mockHttpClient);

  CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
  mockStatusLine = mock(StatusLine.class);
  when(mockStatusLine.getStatusCode()).thenReturn(200);
  when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);

  when(mockHttpClient.execute(any())).thenAnswer((InvocationOnMock invocation) -> {
    HttpPost httpPost = (HttpPost) invocation.getArguments()[0];
    Header[] headers = httpPost.getAllHeaders();
    for (Header header : headers) {
      requestHeaders.put(header.getName(), header.getValue());
    }
    HttpEntity entity = httpPost.getEntity();
    bodyData = EntityUtils.toString(entity);
    return mockResponse;
  });

  Cause mockCause = mock(Cause.UserIdCause.UserIdCause.class);
  when(mockCause.getShortDescription()).thenReturn(trigger);

  mockRun = mock(AbstractBuild.class);
  when(mockRun.getCause(Cause.class)).thenReturn(mockCause);
  when(mockRun.getNumber()).thenReturn(buildNumber);
  when(mockRun.getUrl()).thenReturn(buildUrl);

  mockStageMap = mock(HashMap.class);
  notifier = new HttpNotifier(mockConfig);
  notifier.stageMap = mockStageMap;

  Jenkins jenkins = mock(Jenkins.class);
  when(jenkins.getRootUrl()).thenReturn(jenkinsUrl);
  PowerMockito.mockStatic(Jenkins.class);
  when(Jenkins.get()).thenReturn(jenkins);
}
 
Example 20
Source File: JiraSendBuildInfoStepTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 4 votes vote down vote up
private static BaseStandardCredentials secretCredential() {
    return new StringCredentialsImpl(
            CredentialsScope.GLOBAL, CREDENTIAL_ID, "test-secret", Secret.fromString("secret"));
}