类hudson.util.LogTaskListener源码实例Demo

下面列出了怎么用hudson.util.LogTaskListener的API类实例代码及写法,或者点击链接到github查看源代码。

@Before
public void setUp() throws Exception {
    github = Connector.connect("http://localhost:" + githubApi.port(), null);

    resetAllScenarios();

    handler = new RingBufferLogHandler(1000);
    final Logger logger = Logger.getLogger(getClass().getName());
    logger.addHandler(handler);
    listener = new LogTaskListener(logger, Level.INFO);

    // Set the random to a known state for testing
    ApiRateLimitChecker.setEntropy(entropy);

    // Default the expiration window to a small but measurable time for testing
    ApiRateLimitChecker.setExpirationWaitMillis(20);

    // Default the notification interval to a small but measurable time for testing
    ApiRateLimitChecker. setNotificationWaitMillis(60);
}
 
@Test
public void given_basicJob_then_singleNotification() throws Exception {
    List<GitHubSCMSource> srcs = Arrays.asList(
            new GitHubSCMSource("example", "test", null, false),
            new GitHubSCMSource("", "", "http://github.com/example/test", true)
    );
    for( GitHubSCMSource src: srcs) {
        FreeStyleProject job = j.createFreeStyleProject();
        FreeStyleBuild run = j.buildAndAssertSuccess(job);
        DefaultGitHubNotificationStrategy instance = new DefaultGitHubNotificationStrategy();
        List<GitHubNotificationRequest> notifications =
                instance.notifications(GitHubNotificationContext.build(job, run, src, new BranchSCMHead("master")),
                        new LogTaskListener(
                                Logger.getLogger(getClass().getName()), Level.INFO));
        assertThat(notifications, hasSize(1));
    }
}
 
@Test
public void given_jobOrRun_then_differentURLs() throws Exception {
    List<GitHubSCMSource> srcs = Arrays.asList(
            new GitHubSCMSource("example", "test", null, false),
            new GitHubSCMSource("", "", "http://github.com/example/test", true)
    );
    for( GitHubSCMSource src: srcs) {
        FreeStyleProject job = j.createFreeStyleProject();
        FreeStyleBuild run = j.buildAndAssertSuccess(job);
        DefaultGitHubNotificationStrategy instance = new DefaultGitHubNotificationStrategy();
        String urlA = instance.notifications(GitHubNotificationContext.build(null, run, src, new BranchSCMHead("master")),
                new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO)).get(0).getUrl();
        String urlB = instance.notifications(GitHubNotificationContext.build(job, null, src, new BranchSCMHead("master")),
                new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO)).get(0).getUrl();
        assertNotEquals(urlA, urlB);
    }
}
 
/**
 * {@inheritDoc}
 */
@Deprecated
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision) {
    return isAutomaticBuild(source, head, currRevision, prevRevision, new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
}
 
/**
 * {@inheritDoc}
 */
@Deprecated
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision) {
    return isAutomaticBuild(source, head, currRevision, prevRevision, new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
}
 
/**
 * {@inheritDoc}
 */
@Deprecated
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision) {
    return isAutomaticBuild(source, head, currRevision, prevRevision, new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
}
 
/**
 * {@inheritDoc}
 */
@Deprecated
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision) {
    return isAutomaticBuild(source, head, currRevision, prevRevision, new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
}
 
/**
 * {@inheritDoc}
 */
@Deprecated
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision) {
    return isAutomaticBuild(source, head, currRevision, prevRevision, new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
}
 
/**
 * {@inheritDoc}
 */
@Deprecated
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision) {
    return isAutomaticBuild(source, head, currRevision, prevRevision, new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
}
 
@Test
public void testProvisionCreateThenTerminatePod() throws Exception {
    KafkaKubernetesCloud cloud = new KafkaKubernetesCloud("kafka-kubernetes");
    cloud.setServerUrl(k.getMockServer().url("/").toString());
    cloud.setSkipTlsVerify(true);
    j.jenkins.clouds.add(cloud);

    Collection<NodeProvisioner.PlannedNode> provisionedNodes = cloud.provision(new LabelAtom("test"), 1);
    assertThat(provisionedNodes, hasSize(1));
    KafkaCloudSlave agent = (KafkaCloudSlave) provisionedNodes.iterator().next().future.get();
    TaskListener listener = new LogTaskListener(Logger.getLogger(KafkaKubernetesCloudTest.class.getName()), Level.INFO);
    PodResource<Pod, DoneablePod> pod = k.getClient().pods().inNamespace(cloud.getNamespace()).withName(agent.getNodeName());

    assertNull(pod.get());

    // Poll for pod creation
    j.jenkins.addNode(agent);
    final int TIMEOUT = 30;
    for(int i = 0; i < TIMEOUT; i++) {
        if (pod.get() != null) break;
        TimeUnit.SECONDS.sleep(1);
    }
    assertNotNull(pod.get());

    agent._terminate(listener);
    assertNull(pod.get());
}
 
源代码11 项目: jenkins-mattermost-plugin   文件: ActiveNotifier.java
String getExpandedCustomMessage(AbstractBuild build) {
  String result = "";
  if (notifier.getIncludeCustomMessage()) {
    String customMessage = notifier.getCustomMessage();
    EnvVars envVars = new EnvVars();
    try {
      envVars = build.getEnvironment(new LogTaskListener(logger, INFO));
    } catch (IOException | InterruptedException e) {
      logger.log(SEVERE, e.getMessage(), e);
    }
    result = envVars.expand(customMessage);
  }
  return result;
}
 
@Test
public void given_differentSCMheads_then_distinctNotifications() throws Exception {
    List<GitHubSCMSource> srcs = Arrays.asList(
            new GitHubSCMSource("example", "test", "http://github.com/ignored/ignored", false),
            new GitHubSCMSource("", "", "http://github.com/example/test", true)
    );
    for( GitHubSCMSource src: srcs) {
        FreeStyleProject job = j.createFreeStyleProject();
        FreeStyleBuild run = j.buildAndAssertSuccess(job);
        DefaultGitHubNotificationStrategy instance = new DefaultGitHubNotificationStrategy();
        BranchSCMHead testBranch = new BranchSCMHead("master");
        List<GitHubNotificationRequest> notificationsA =
                instance.notifications(GitHubNotificationContext.build(job, run, src, testBranch),
                        new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
        List<GitHubNotificationRequest> notificationsB =
                instance.notifications(GitHubNotificationContext.build(job, run, src,
                        new PullRequestSCMHead("test-pr", "owner", "repo", "branch",
                                1, testBranch, SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.MERGE)),
                        new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
        List<GitHubNotificationRequest> notificationsC =
                instance.notifications(GitHubNotificationContext.build(job, run, src,
                        new PullRequestSCMHead("test-pr", "owner", "repo", "branch",
                                1, testBranch, SCMHeadOrigin.DEFAULT, ChangeRequestCheckoutStrategy.HEAD)),
                        new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
        assertNotEquals(notificationsA, notificationsB);
        assertNotEquals(notificationsB, notificationsC);
        assertNotEquals(notificationsA, notificationsC);
    }
}
 
private SCMSourceObserver getObserver(Collection<String> names){
    return new SCMSourceObserver() {
        @NonNull
        @Override
        public SCMSourceOwner getContext() {
            return scmSourceOwner;
        }

        @NonNull
        @Override
        public TaskListener getListener() {
            return new LogTaskListener(Logger.getAnonymousLogger(), Level.INFO);
        }

        @NonNull
        @Override
        public ProjectObserver observe(@NonNull String projectName) throws IllegalArgumentException {
            names.add(projectName);
            return new NoOpProjectObserver();
        }

        @Override
        public void addAttribute(@NonNull String key, @Nullable Object value)
                throws IllegalArgumentException, ClassCastException {

        }
    };
}
 
@Test
public void testPerform() throws IOException, ExecutionException, InterruptedException {
    List<JsonParameterVariables> jsonParameterVariables = new ArrayList<>();
    jsonParameterVariables.add(new JsonParameterVariables("KEY", "$.key2"));
    LambdaInvokeVariables clone = new LambdaInvokeVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, true, jsonParameterVariables);
    LambdaInvokeVariables spy = Mockito.spy(clone);

    when(original.getClone()).thenReturn(spy);
    when(spy.getLambdaClientConfig()).thenReturn(clientConfig);
    when(clientConfig.getClient()).thenReturn(lambdaClient);
    final String logBase64 = "bGFtYmRh";
    final String responsePayload = "{\"key2\": \"value2\"}";

    InvokeResult invokeResult = new InvokeResult()
            .withLogResult(logBase64)
            .withPayload(ByteBuffer.wrap(responsePayload.getBytes()));

    when(lambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(invokeResult);

    FreeStyleProject p = j.createFreeStyleProject();
    p.getPublishersList().add(new LambdaInvokePublisher(Arrays.asList(original, original)));
    FreeStyleBuild build = p.scheduleBuild2(0).get();
    EnvVars environment = build.getEnvironment(new LogTaskListener(LOGGER, Level.INFO));

    assertEquals("value2", environment.get("KEY"));
    assertEquals(Result.SUCCESS, build.getResult());
}
 
@Test
public void testPerformInstanceRole() throws IOException, ExecutionException, InterruptedException {
    List<JsonParameterVariables> jsonParameterVariables = new ArrayList<>();
    jsonParameterVariables.add(new JsonParameterVariables("KEY", "$.key2"));
    LambdaInvokeVariables clone = new LambdaInvokeVariables(true, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, true, jsonParameterVariables);
    LambdaInvokeVariables spy = Mockito.spy(clone);

    when(original.getClone()).thenReturn(spy);
    when(spy.getLambdaClientConfig()).thenReturn(clientConfig);
    when(clientConfig.getClient()).thenReturn(lambdaClient);
    final String logBase64 = "bGFtYmRh";
    final String responsePayload = "{\"key2\": \"value2\"}";

    InvokeResult invokeResult = new InvokeResult()
            .withLogResult(logBase64)
            .withPayload(ByteBuffer.wrap(responsePayload.getBytes()));

    when(lambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(invokeResult);

    FreeStyleProject p = j.createFreeStyleProject();
    p.getPublishersList().add(new LambdaInvokePublisher(Arrays.asList(original, original)));
    FreeStyleBuild build = p.scheduleBuild2(0).get();
    EnvVars environment = build.getEnvironment(new LogTaskListener(LOGGER, Level.INFO));

    assertEquals("value2", environment.get("KEY"));
    assertEquals(Result.SUCCESS, build.getResult());
}
 
@Test
public void testPerform() throws IOException, ExecutionException, InterruptedException {
    List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>();
    jsonParameterVariables.add(new JsonParameterVariables("KEY", "$.key2"));
    LambdaInvokeBuildStepVariables clone = new LambdaInvokeBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, jsonParameterVariables);
    LambdaInvokeBuildStepVariables spy = Mockito.spy(clone);

    when(original.getClone()).thenReturn(spy);
    when(spy.getLambdaClientConfig()).thenReturn(clientConfig);
    when(clientConfig.getClient()).thenReturn(lambdaClient);
    final String logBase64 = "bGFtYmRh";
    final String responsePayload = "{\"key2\": \"value2\"}";

    InvokeResult invokeResult = new InvokeResult()
            .withLogResult(logBase64)
            .withPayload(ByteBuffer.wrap(responsePayload.getBytes()));

    when(lambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(invokeResult);

    FreeStyleProject p = j.createFreeStyleProject();
    p.getBuildersList().add(new LambdaInvokeBuildStep(original));
    FreeStyleBuild build = p.scheduleBuild2(0).get();
    EnvVars environment = build.getEnvironment(new LogTaskListener(LOGGER, Level.INFO));

    assertEquals("value2", environment.get("KEY"));
    assertEquals(Result.SUCCESS, build.getResult());
}
 
@Test
public void testPerformFailure() throws IOException, ExecutionException, InterruptedException {
    List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>();
    jsonParameterVariables.add(new JsonParameterVariables("KEY", "$.key2"));
    LambdaInvokeBuildStepVariables clone = new LambdaInvokeBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, jsonParameterVariables);
    LambdaInvokeBuildStepVariables spy = Mockito.spy(clone);

    when(original.getClone()).thenReturn(spy);
    when(spy.getLambdaClientConfig()).thenReturn(clientConfig);
    when(clientConfig.getClient()).thenReturn(lambdaClient);
    final String logBase64 = "bGFtYmRh";
    final String responsePayload = "{\"errorMessage\":\"event_fail\"}";

    InvokeResult invokeResult = new InvokeResult()
            .withLogResult(logBase64)
            .withPayload(ByteBuffer.wrap(responsePayload.getBytes()))
            .withFunctionError("Unhandled");

    when(lambdaClient.invoke(any(InvokeRequest.class)))
            .thenReturn(invokeResult);

    FreeStyleProject p = j.createFreeStyleProject();
    p.getBuildersList().add(new LambdaInvokeBuildStep(original));
    FreeStyleBuild build = p.scheduleBuild2(0).get();
    EnvVars environment = build.getEnvironment(new LogTaskListener(LOGGER, Level.INFO));

    assertEquals(null, environment.get("KEY"));
    assertEquals(Result.FAILURE, build.getResult());
}
 
@Test
@Issue("JENKINS-50483")
public void roundtrip() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    FreeStyleBuild build = j.buildAndAssertSuccess(p);

    // Here we set a run with all fields which are potentially not allowed in JEP-200
    // TODO: to make the test more robust, it is possible to iterate through fields and use Setters with default constructors. Looks like it's fine for StructuredPojo
    Run awsRun = new Run();
    awsRun.setArn("a:b:c:d:e:f:foo/bar");
    awsRun.setResult(ExecutionResult.SKIPPED);
    awsRun.setNetworkProfile(new NetworkProfile());
    awsRun.setDeviceMinutes(new DeviceMinutes());
    Counters counters = new Counters();
    counters.setPassed(0);
    counters.setFailed(0);
    counters.setSkipped(1);
    counters.setErrored(0);
    counters.setStopped(0);
    counters.setWarned(0);
    counters.setTotal(1);
    awsRun.setCounters(counters);

    // We intentionally use the deprecated constructor to check whether logger is retained
    AWSDeviceFarmTestResult res = new AWSDeviceFarmTestResult(build, awsRun);
    AWSDeviceFarmTestResultAction a = new AWSDeviceFarmTestResultAction(build, res, new LogTaskListener(LOGGER, Level.SEVERE).getLogger());
    build.addAction(a);

    // Check that the action is still there after reload
    build.save();
    build.reload();
    Assert.assertNotNull("AWSDeviceFarmTestResultAction should be retained after the restart", build.getAction(AWSDeviceFarmTestResultAction.class));
}
 
源代码19 项目: git-client-plugin   文件: WarnTempDirValueTest.java
@Before
public void createLogger() {
    Logger logger = Logger.getLogger(this.getClass().getPackage().getName() + "-" + logCount++);
    handler = new LogHandler();
    handler.setLevel(Level.ALL);
    logger.setUseParentHandlers(false);
    logger.addHandler(handler);
    logger.setLevel(Level.ALL);
    listener = new hudson.util.LogTaskListener(logger, Level.ALL);
    listener.getLogger().println(LOGGING_STARTED);
}
 
/**
 * {@inheritDoc}
 */
@Deprecated
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision) {
    return isAutomaticBuild(source,head, currRevision, prevRevision, new LogTaskListener(Logger.getLogger(getClass().getName()), Level.INFO));
}
 
源代码21 项目: blueocean-plugin   文件: GitCloneReadSaveRequest.java
GitClient cloneRepo() throws InterruptedException, IOException {
    EnvVars environment = new EnvVars();
    TaskListener taskListener = new LogTaskListener(Logger.getAnonymousLogger(), Level.ALL);
    String gitExe = gitTool.getGitExe();
    GitClient git = Git.with(taskListener, environment)
            .in(repositoryPath)
            .using(gitExe)
            .getClient();

    git.addCredentials(gitSource.getRemote(), getCredential());

    try {
        git.clone(gitSource.getRemote(), "origin", true, null);

        log.fine("Repository " + gitSource.getRemote() + " cloned to: " + repositoryPath.getCanonicalPath());
    } catch(GitException e) {
        // check if this is an empty repository
        boolean isEmptyRepo = false;
        try {
            if (git.getRemoteReferences(gitSource.getRemote(), null, true, false).isEmpty()) {
                isEmptyRepo = true;
            }
        } catch(GitException ge) {
            // *sigh* @ this necessary hack; {@link org.jenkinsci.plugins.gitclient.CliGitAPIImpl#getRemoteReferences}
            if ("unexpected ls-remote output ".equals(ge.getMessage())) { // blank line, command succeeded
                isEmptyRepo = true;
            }
            // ignore other reasons
        }

        if(isEmptyRepo) {
            git.init();
            git.addRemoteUrl("origin", gitSource.getRemote());

            log.fine("Repository " + gitSource.getRemote() + " not found, created new to: " + repositoryPath.getCanonicalPath());
        } else {
            throw e;
        }
    }

    return git;
}
 
private static List<BitbucketBuildStatusResource> createBuildStatusResources(final SCM scm,
                                                                             final Run<?, ?> build) throws Exception {
    List<BitbucketBuildStatusResource> buildStatusResources = new ArrayList<BitbucketBuildStatusResource>();

    if (scm == null) {
        throw new Exception("Bitbucket build notifier only works with SCM");
    }

    ScmAdapter scmAdapter;
    if (scm instanceof GitSCM) {
        scmAdapter = new GitScmAdapter((GitSCM) scm, build);
    } else if (scm instanceof MercurialSCM) {
        scmAdapter = new MercurialScmAdapter((MercurialSCM) scm, build);
    } else if (scm instanceof MultiSCM) {
        scmAdapter = new MultiScmAdapter((MultiSCM)scm, build);
    } else {
        throw new Exception("Bitbucket build notifier requires a git repo or a mercurial repo as SCM");
    }

    Map<String, URIish> commitRepoMap = scmAdapter.getCommitRepoMap();
    for (Map.Entry<String, URIish> commitRepoPair : commitRepoMap.entrySet()) {

        // if repo is not hosted in bitbucket.org then log it and remove repo from being notified
        URIish repoUri = commitRepoPair.getValue();
        if (!hostValidator.isValid(repoUri.getHost())) {
            logger.log(Level.INFO, hostValidator.renderError());
            continue;
        }

        // expand parameters on repo url
        String repoUrl = build.getEnvironment(new LogTaskListener(logger, Level.INFO)).expand(repoUri.getPath());
        if (repoUrl.endsWith("/")) {
            //fix JENKINS-49902
            repoUrl = repoUrl.substring(0, repoUrl.length() - 1);
        }

        // extract bitbucket user name and repository name from repo URI
        String repoName = repoUrl.substring(
                repoUrl.lastIndexOf("/") + 1,
                repoUrl.contains(".git") ? repoUrl.indexOf(".git") : repoUrl.length()
        );

        if (repoName.isEmpty()) {
            logger.log(Level.INFO, "Bitbucket build notifier could not extract the repository name from the repository URL: " + repoUrl);
            continue;
        }

        String userName = repoUrl.substring(0, repoUrl.lastIndexOf("/" + repoName));
        if (userName.contains("/")) {
            userName = userName.substring(userName.indexOf("/") + 1, userName.length());
        }
        if (userName.isEmpty()) {
            logger.log(Level.INFO, "Bitbucket build notifier could not extract the user name from the repository URL: " + repoUrl + " with repository name: " + repoName);
            continue;
        }

        String commitId = commitRepoPair.getKey();
        if (commitId == null) {
            logger.log(Level.INFO, "Commit ID could not be found!");
            continue;
        }

        buildStatusResources.add(new BitbucketBuildStatusResource(userName, repoName, commitId));
    }

    return buildStatusResources;
}
 
@Test
public void getTrustedRevisionReturnsRevisionIfRepoOwnerAndPullRequestBranchOwnerAreSameWithDifferentCase() throws Exception {
    source.setBuildOriginPRHead(true);
    PullRequestSCMRevision revision = createRevision("CloudBeers");
    assertThat(source.getTrustedRevision(revision, new LogTaskListener(Logger.getAnonymousLogger(), Level.INFO)), sameInstance(revision));
}
 
@Test
public void given__cloud_branch_rev_anon__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId(null);
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("https://github.com/tester/test-repo.git"));

    GitSCM actual = instance.build();
    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("https://github.com/tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is(nullValue()));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("https://github.com/tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}
 
@Test
public void given__cloud_branch_rev_userpass__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId("user-pass");
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is("user-pass"));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("https://github.com/tester/test-repo.git"));

    GitSCM actual = instance.build();
    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("https://github.com/tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is("user-pass"));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("https://github.com/tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}
 
@Test
public void given__cloud_branch_rev_userkey__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId("user-key");
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is("user-key"));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("[email protected]:tester/test-repo.git"));

    GitSCM actual = instance.build();
    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("[email protected]:tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is("user-key"));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("[email protected]:tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}
 
@Test
public void given__cloud_branch_rev_anon_sshtrait_anon__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId(null);
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("https://github.com/tester/test-repo.git"));


    SSHCheckoutTrait sshTrait = new SSHCheckoutTrait(null);
    sshTrait.decorateBuilder(instance);

    GitSCM actual = instance.build();
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.remote(), is("[email protected]:tester/test-repo.git"));

    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("[email protected]:tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is(nullValue()));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("[email protected]:tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}
 
@Test
public void given__cloud_branch_rev_userpass_sshtrait_anon__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId("user-pass");
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is("user-pass"));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("https://github.com/tester/test-repo.git"));

    SSHCheckoutTrait sshTrait = new SSHCheckoutTrait(null);
    sshTrait.decorateBuilder(instance);

    GitSCM actual = instance.build();
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.remote(), is("[email protected]:tester/test-repo.git"));

    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("[email protected]:tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is(nullValue()));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("[email protected]:tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}
 
@Test
public void given__cloud_branch_rev_userkey_sshtrait_anon__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId("user-key");
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is("user-key"));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("[email protected]:tester/test-repo.git"));

    SSHCheckoutTrait sshTrait = new SSHCheckoutTrait(null);
    sshTrait.decorateBuilder(instance);

    GitSCM actual = instance.build();
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.remote(), is("[email protected]:tester/test-repo.git"));

    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("[email protected]:tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is(nullValue()));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("[email protected]:tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}
 
@Test
public void given__cloud_branch_rev_anon_sshtrait_userkey__when__build__then__scmBuilt() throws Exception {
    createGitHubSCMSourceForTest(false, null);
    BranchSCMHead head = new BranchSCMHead("test-branch");
    SCMRevisionImpl revision =
            new SCMRevisionImpl(head, "cafebabedeadbeefcafebabedeadbeefcafebabe");
    source.setCredentialsId(null);
    GitHubSCMBuilder instance = new GitHubSCMBuilder(source, head, revision);
    assertThat(instance.credentialsId(), is(nullValue()));
    assertThat(instance.head(), is(head));
    assertThat(instance.revision(), is(revision));
    assertThat(instance.refSpecs(), contains("+refs/heads/test-branch:refs/remotes/@{remote}/test-branch"));
    assertThat("expecting guess value until withGitHubRemote called",
            instance.remote(), is("https://github.com/tester/test-repo.git"));
    assertThat(instance.browser(), instanceOf(GithubWeb.class));
    assertThat(instance.browser().getRepoUrl(), is("https://github.com/tester/test-repo"));

    instance.withGitHubRemote();
    assertThat(instance.remote(), is("https://github.com/tester/test-repo.git"));

    SSHCheckoutTrait sshTrait = new SSHCheckoutTrait("user-key");
    sshTrait.decorateBuilder(instance);

    GitSCM actual = instance.build();
    assertThat(instance.credentialsId(), is("user-key"));
    assertThat(instance.remote(), is("[email protected]:tester/test-repo.git"));

    assertThat(actual.getBrowser(), instanceOf(GithubWeb.class));
    assertThat(actual.getBrowser().getRepoUrl(), is("https://github.com/tester/test-repo"));
    assertThat(actual.getGitTool(), nullValue());
    assertThat(actual.getUserRemoteConfigs(), hasSize(1));
    UserRemoteConfig config = actual.getUserRemoteConfigs().get(0);
    assertThat(config.getName(), is("origin"));
    assertThat(config.getRefspec(), is("+refs/heads/test-branch:refs/remotes/origin/test-branch"));
    assertThat(config.getUrl(), is("[email protected]:tester/test-repo.git"));
    assertThat(config.getCredentialsId(), is("user-key"));
    RemoteConfig origin = actual.getRepositoryByName("origin");
    assertThat(origin, notNullValue());
    assertThat(origin.getURIs(), hasSize(1));
    assertThat(origin.getURIs().get(0).toString(), is("[email protected]:tester/test-repo.git"));
    assertThat(origin.getFetchRefSpecs(), hasSize(1));
    assertThat(origin.getFetchRefSpecs().get(0).getSource(), is("refs/heads/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).getDestination(), is("refs/remotes/origin/test-branch"));
    assertThat(origin.getFetchRefSpecs().get(0).isForceUpdate(), is(true));
    assertThat(origin.getFetchRefSpecs().get(0).isWildcard(), is(false));
    assertThat(actual.getExtensions(), containsInAnyOrder(
            instanceOf(BuildChooserSetting.class),
            instanceOf(GitSCMSourceDefaults.class))
    );
    BuildChooserSetting chooser = getExtension(actual, BuildChooserSetting.class);
    assertThat(chooser.getBuildChooser(), instanceOf(SpecificRevisionBuildChooser.class));
    SpecificRevisionBuildChooser revChooser =
            (SpecificRevisionBuildChooser) chooser.getBuildChooser();
    Collection<Revision> revisions = revChooser
            .getCandidateRevisions(false, "test-branch", mock(GitClient.class), new LogTaskListener(
                    getAnonymousLogger(), FINEST), null, null);
    assertThat(revisions, hasSize(1));
    assertThat(revisions.iterator().next().getSha1String(), is("cafebabedeadbeefcafebabedeadbeefcafebabe"));
}