jenkins.plugins.git.GitSCMSource Java Examples

The following examples show how to use jenkins.plugins.git.GitSCMSource. 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: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void startMultiBranchPipelineRuns() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }
    WorkflowJob p = scheduleAndFindBranchProject(mp, "feature%2Fux-1");
    j.waitUntilNoActivity();

    Map resp = post("/organizations/jenkins/pipelines/p/branches/"+ Util.rawEncode("feature%2Fux-1")+"/runs/",
        Collections.EMPTY_MAP);
    String id = (String) resp.get("id");
    String link = getHrefFromLinks(resp, "self");
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature%252Fux-1/runs/"+id+"/", link);
}
 
Example #2
Source File: PushBuildAction.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    for (SCMSource scmSource : ((SCMSourceOwner) project).getSCMSources()) {
        if (scmSource instanceof GitSCMSource) {
            GitSCMSource gitSCMSource = (GitSCMSource) scmSource;
            try {
                if (new URIish(gitSCMSource.getRemote()).equals(new URIish(gitSCMSource.getRemote()))) {
                    if (!gitSCMSource.isIgnoreOnPushNotifications()) {
                        LOGGER.log(Level.FINE, "Notify scmSourceOwner {0} about changes for {1}",
                                   toArray(project.getName(), gitSCMSource.getRemote()));
                        ((SCMSourceOwner) project).onSCMSourceUpdated(scmSource);
                    } else {
                        LOGGER.log(Level.FINE, "Ignore on push notification for scmSourceOwner {0} about changes for {1}",
                                   toArray(project.getName(), gitSCMSource.getRemote()));
                    }
                }
            } catch (URISyntaxException e) {
                // nothing to do
            }
        }
    }
}
 
Example #3
Source File: DefaultsBinderTest.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Test
public void testDefaultJenkinsFileLoadFromWorkspace() throws Exception {
    GlobalConfigFiles globalConfigFiles = r.jenkins.getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class);
    ConfigFileStore store = globalConfigFiles.get();
    Config config = new GroovyScript("Jenkinsfile", "Jenkinsfile", "",
        "semaphore 'wait'; node {checkout scm; load 'Jenkinsfile'}");
    store.save(config);


    sampleGitRepo.init();
    sampleGitRepo.write("Jenkinsfile", "echo readFile('file')");
    sampleGitRepo.git("add", "Jenkinsfile");
    sampleGitRepo.write("file", "initial content");
    sampleGitRepo.git("commit", "--all", "--message=flow");
    WorkflowMultiBranchProject mp = r.jenkins.createProject(PipelineMultiBranchDefaultsProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleGitRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    WorkflowJob p = PipelineMultiBranchDefaultsProjectTest.scheduleAndFindBranchProject(mp, "master");
    SemaphoreStep.waitForStart("wait/1", null);
    WorkflowRun b1 = p.getLastBuild();
    assertNotNull(b1);
    assertEquals(1, b1.getNumber());
    SemaphoreStep.success("wait/1", null);
    r.assertLogContains("initial content", r.waitForCompletion(b1));
}
 
Example #4
Source File: DefaultsBinderTest.java    From pipeline-multibranch-defaults-plugin with MIT License 6 votes vote down vote up
@Test
public void testDefaultJenkinsFile() throws Exception {
    GlobalConfigFiles globalConfigFiles = r.jenkins.getExtensionList(GlobalConfigFiles.class).get(GlobalConfigFiles.class);
    ConfigFileStore store = globalConfigFiles.get();

    Config config = new GroovyScript("Jenkinsfile", "Jenkinsfile", "",
        "semaphore 'wait'; node {checkout scm; echo readFile('file')}");
    store.save(config);

    sampleGitRepo.init();
    sampleGitRepo.write("file", "initial content");
    sampleGitRepo.git("commit", "--all", "--message=flow");
    WorkflowMultiBranchProject mp = r.jenkins.createProject(PipelineMultiBranchDefaultsProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleGitRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    WorkflowJob p = PipelineMultiBranchDefaultsProjectTest.scheduleAndFindBranchProject(mp, "master");
    SemaphoreStep.waitForStart("wait/1", null);
    WorkflowRun b1 = p.getLastBuild();
    assertNotNull(b1);
    assertEquals(1, b1.getNumber());
    SemaphoreStep.success("wait/1", null);
    r.assertLogContains("initial content", r.waitForCompletion(b1));
}
 
Example #5
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getPipelinesTest() throws Exception {

    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    WorkflowJob p = scheduleAndFindBranchProject(mp, "master");


    j.waitUntilNoActivity();

    List<Map> responses = get("/search/?q=type:pipeline;excludedFromFlattening:jenkins.branch.MultiBranchProject", List.class);
    Assert.assertEquals(1, responses.size());
}
 
Example #6
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getMultiBranchPipelineRunStages() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    WorkflowJob p = scheduleAndFindBranchProject(mp, "master");


    j.waitUntilNoActivity();
    WorkflowRun b1 = p.getLastBuild();
    assertEquals(1, b1.getNumber());
    assertEquals(3, mp.getItems().size());

    j.waitForCompletion(b1);

    List<Map> nodes = get("/organizations/jenkins/pipelines/p/branches/master/runs/1/nodes", List.class);

    Assert.assertEquals(3, nodes.size());
}
 
Example #7
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void multiBranchPipelineIndex() throws Exception {
    User user = login();
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
            new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    Map map = new RequestBuilder(baseUrl)
            .post("/organizations/jenkins/pipelines/p/runs/")
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( getCrumb( j.jenkins ) )
            .data(ImmutableMap.of())
            .status(200)
            .build(Map.class);

    assertNotNull(map);
}
 
Example #8
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getMultiBranchPipelinesWithNonMasterBranch() throws Exception {
    sampleRepo.git("checkout", "feature2");
    sampleRepo.git("branch","-D", "master");
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");

    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();

    List<Map> resp = get("/organizations/jenkins/pipelines/", List.class);
    Assert.assertEquals(1, resp.size());
    validateMultiBranchPipeline(mp, resp.get(0), 2);
    assertNull(mp.getBranch("master"));
}
 
Example #9
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getMultiBranchPipelineInsideFolder() throws IOException, ExecutionException, InterruptedException {
    MockFolder folder1 = j.createFolder("folder1");
    WorkflowMultiBranchProject mp = folder1.createProject(WorkflowMultiBranchProject.class, "p");
    mp.setDisplayName("My MBP");

    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();

    Map r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/");

    validateMultiBranchPipeline(mp, r, 3);
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/p/",
        ((Map)((Map)r.get("_links")).get("self")).get("href"));
    Assert.assertEquals("folder1/My%20MBP", r.get("fullDisplayName"));
    r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/master/");
    Assert.assertEquals("folder1/My%20MBP/master", r.get("fullDisplayName"));
}
 
Example #10
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getMultiBranchPipelines() throws IOException, ExecutionException, InterruptedException {
    Assume.assumeTrue(runAllTests());
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    FreeStyleProject f = j.jenkins.createProject(FreeStyleProject.class, "f");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();

    List<Map> resp = get("/organizations/jenkins/pipelines/", List.class);
    Assert.assertEquals(2, resp.size());
    validatePipeline(f, resp.get(0));
    validateMultiBranchPipeline(mp, resp.get(1), 3);
    Assert.assertEquals(mp.getBranch("master").getBuildHealth().getScore(), resp.get(0).get("weatherScore"));
}
 
Example #11
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void resolveMbpLink() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    FreeStyleProject f = j.jenkins.createProject(FreeStyleProject.class, "f");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();

    j.waitUntilNoActivity();

    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/",LinkResolver.resolveLink(mp).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/master/",LinkResolver.resolveLink(mp.getBranch("master")).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature%252Fux-1/",LinkResolver.resolveLink(mp.getBranch("feature%2Fux-1")).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature2/",LinkResolver.resolveLink(mp.getBranch("feature2")).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/f/",LinkResolver.resolveLink(f).getHref());
}
 
Example #12
Source File: GitPipelineCreateRequestTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void createPipeline() throws UnirestException, IOException {
    User user = login("vivek", "Vivek Pandey", "[email protected]");
    Map r = new PipelineBaseTest.RequestBuilder(baseUrl)
        .status(201)
        .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
        .crumb( crumb )
        .post("/organizations/jenkins/pipelines/")
        .data(ImmutableMap.of("name", "pipeline1",
            "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
            "scmConfig", ImmutableMap.of("id", GitScm.ID, "uri", sampleRepo.toString())))
        .build(Map.class);
    assertNotNull(r);
    assertEquals("pipeline1", r.get("name"));

    MultiBranchProject mbp = (MultiBranchProject) j.getInstance().getItem("pipeline1");
    GitSCMSource source = (GitSCMSource) mbp.getSCMSources().get(0);
    List<SCMSourceTrait> traits = source.getTraits();

    Assert.assertNotNull(SCMTrait.find(traits, BranchDiscoveryTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanAfterCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanBeforeCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, LocalBranchTrait.class));
}
 
Example #13
Source File: GithubIssueTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void changeSetEntryIsNotGithub() throws Exception {
    MultiBranchProject project = mock(MultiBranchProject.class);
    Job job = mock(MockJob.class);
    Run run = mock(Run.class);
    ChangeLogSet logSet = mock(ChangeLogSet.class);
    ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);

    when(project.getProperties()).thenReturn(new DescribableList(project));
    when(entry.getParent()).thenReturn(logSet);
    when(logSet.getRun()).thenReturn(run);
    when(run.getParent()).thenReturn(job);
    when(job.getParent()).thenReturn(project);

    when(entry.getMsg()).thenReturn("Closed #123 #124");
    when(project.getSCMSources()).thenReturn(Lists.newArrayList(new GitSCMSource("http://example.com/repo.git")));

    Collection<BlueIssue> resolved = BlueIssueFactory.resolve(entry);
    Assert.assertEquals(0, resolved.size());
}
 
Example #14
Source File: WorkflowCpsGlobalLibTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("workflow-cps-global-lib/README.md")
public void configure_global_library() throws Exception {
    assertEquals(1, GlobalLibraries.get().getLibraries().size());
    final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0);
    assertEquals("awesome-lib", library.getName());
    final SCMSourceRetriever retriever = (SCMSourceRetriever) library.getRetriever();
    final GitSCMSource scm = (GitSCMSource) retriever.getScm();
    assertEquals("https://github.com/jenkins-infra/pipeline-library.git", scm.getRemote());
}
 
Example #15
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getPipelineJobRunsNoBranches() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo1.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));

    List l = request().get("/organizations/jenkins/pipelines/p/runs").build(List.class);

    Assert.assertEquals(0, l.size());

    List branches = request().get("/organizations/jenkins/pipelines/p/runs").build(List.class);
    Assert.assertEquals(0, branches.size());

}
 
Example #16
Source File: BlueOceanWebURLBuilderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getMultiBranchPipelineInsideFolder() throws Exception {
    MockFolder folder1 = jenkinsRule.createFolder("folder1");
    MockFolder folder2 = folder1.createProject(MockFolder.class, "folder two with spaces");
    WorkflowMultiBranchProject mp = folder2.createProject(WorkflowMultiBranchProject.class, "p");

    String blueOceanURL;

    blueOceanURL = urlMapper.getUrl(mp);
    assertURL("blue/organizations/jenkins/folder1%2Ffolder%20two%20with%20spaces%2Fp/branches/", blueOceanURL);

    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false), new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();
    jenkinsRule.waitUntilNoActivity();

    // All branch jobs should just resolve back to the same top level branches
    // page for the multibranch job in Blue Ocean.
    WorkflowJob masterJob = findBranchProject(mp, "master");
    blueOceanURL = urlMapper.getUrl(masterJob);
    assertURL("blue/organizations/jenkins/folder1%2Ffolder%20two%20with%20spaces%2Fp/branches/", blueOceanURL);
    WorkflowJob featureUx1Job = findBranchProject(mp, "feature/ux-1");
    blueOceanURL = urlMapper.getUrl(featureUx1Job);
    assertURL("blue/organizations/jenkins/folder1%2Ffolder%20two%20with%20spaces%2Fp/branches/", blueOceanURL);
    WorkflowJob feature2Job = findBranchProject(mp, "feature2");
    blueOceanURL = urlMapper.getUrl(feature2Job);
    assertURL("blue/organizations/jenkins/folder1%2Ffolder%20two%20with%20spaces%2Fp/branches/", blueOceanURL);

    // Runs on the jobs
    blueOceanURL = urlMapper.getUrl(masterJob.getFirstBuild());
    assertURL("blue/organizations/jenkins/folder1%2Ffolder%20two%20with%20spaces%2Fp/detail/master/1/", blueOceanURL);
    blueOceanURL = urlMapper.getUrl(featureUx1Job.getFirstBuild());
    assertURL("blue/organizations/jenkins/folder1%2Ffolder%20two%20with%20spaces%2Fp/detail/feature%2Fux-1/1/", blueOceanURL);
}
 
Example #17
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void parameterizedBranchTest() throws Exception{
    setupParameterizedScm();

    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo2.toString(), "", "*", "", false)));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    WorkflowJob p = scheduleAndFindBranchProject(mp, branches[1]);
    j.waitUntilNoActivity();

    Map resp = get("/organizations/jenkins/pipelines/p/branches/"+Util.rawEncode(branches[1])+"/", Map.class);
    List<Map<String,Object>> parameters = (List<Map<String, Object>>) resp.get("parameters");
    Assert.assertEquals(1, parameters.size());
    Assert.assertEquals("param1", parameters.get(0).get("name"));
    Assert.assertEquals("StringParameterDefinition", parameters.get(0).get("type"));
    Assert.assertEquals("string param", parameters.get(0).get("description"));
    Assert.assertEquals("xyz", ((Map)parameters.get(0).get("defaultParameterValue")).get("value"));

    resp = post("/organizations/jenkins/pipelines/p/branches/"+Util.rawEncode(branches[1])+"/runs/",
            ImmutableMap.of("parameters",
                    ImmutableList.of(ImmutableMap.of("name", "param1", "value", "abc"))
            ), 200);
    Assert.assertEquals(branches[1], resp.get("pipeline"));
    Thread.sleep(5000);
    resp = get("/organizations/jenkins/pipelines/p/branches/"+Util.rawEncode(branches[1])+"/runs/2/");
    Assert.assertEquals("Response should be SUCCESS: " + resp.toString(), "SUCCESS", resp.get("result"));
    Assert.assertEquals("Response should be FINISHED: " + resp.toString(), "FINISHED", resp.get("state"));
}
 
Example #18
Source File: JobAnalyticsTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private void createMultiBranch(GitSampleRepoRule rule) throws Exception {
    WorkflowMultiBranchProject mp = j.createProject(WorkflowMultiBranchProject.class, UUID.randomUUID().toString());
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, rule.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    mp.save();
    mp.scheduleBuild2(0).getFuture().get();
    mp.getIndexing().getLogText().writeLogTo(0, System.out);
    j.waitUntilNoActivity();
    WorkflowJob master = mp.getItemByBranchName("master");
    assertNotNull(master);
    WorkflowRun lastBuild = master.getLastBuild();
    assertNotNull(lastBuild);
    assertEquals(Result.SUCCESS, lastBuild.getResult());
}
 
Example #19
Source File: PipelineBranchDefaultsProjectFactoryTest.java    From pipeline-multibranch-defaults-plugin with MIT License 5 votes vote down vote up
@Test
public void allBranches() throws Exception {
    sampleRepo.init();
    sampleRepo.git("checkout", "-b", "dev/main");
    sampleRepo.write("file", "initial content");
    sampleRepo.git("add", "file");
    sampleRepo.git("commit", "--all", "--message=flow");
    WorkflowMultiBranchProject mp = r.jenkins.createProject(PipelineMultiBranchDefaultsProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false)));
    WorkflowJob p = PipelineMultiBranchDefaultsProjectTest.scheduleAndFindBranchProject(mp, "dev%2Fmain");
    assertEquals(2, mp.getItems().size());
}
 
Example #20
Source File: GitPipelineCreateRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
protected SCMSource createSource(@Nonnull MultiBranchProject project, @Nonnull BlueScmConfig scmConfig) {
    GitSCMSource gitSource = new GitSCMSource(StringUtils.defaultString(scmConfig.getUri()));
    gitSource.setCredentialsId(computeCredentialId(scmConfig));
    List<SCMSourceTrait> traits = gitSource.getTraits();
    traits.add(new BranchDiscoveryTrait());
    traits.add(new CleanBeforeCheckoutTrait());
    traits.add(new CleanAfterCheckoutTrait());
    traits.add(new LocalBranchTrait());
    return gitSource;
}
 
Example #21
Source File: BranchNameIssueKeyExtractorTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractIssueKeys_whenScmRevisionActionNotNull() {
    // given
    final WorkflowRun mockWorkflowRun = mock(WorkflowRun.class);
    final GitBranchSCMHead head = new GitBranchSCMHead(BRANCH_NAME);
    final SCMRevisionAction scmRevisionAction =
            new SCMRevisionAction(new GitSCMSource(""), new GitBranchSCMRevision(head, ""));
    when(mockWorkflowRun.getAction(SCMRevisionAction.class)).thenReturn(scmRevisionAction);

    // when
    final Set<String> issueKeys = classUnderTest.extractIssueKeys(mockWorkflowRun);

    // then
    assertThat(issueKeys).containsExactlyInAnyOrder("TEST-123");
}
 
Example #22
Source File: CachesTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testBranchCacheLoaderNoMetadata() throws Exception {
    sampleRepo1.init();
    sampleRepo1.write("Jenkinsfile", "node { echo 'hi'; }");
    sampleRepo1.git("add", "Jenkinsfile");
    sampleRepo1.git("commit", "--all", "--message=buildable");

    WorkflowMultiBranchProject project = r.jenkins.createProject(WorkflowMultiBranchProject.class, "Repo");
    GitSCMSource source = new GitSCMSource(sampleRepo1.toString());
    source.setTraits(new ArrayList<>(Arrays.asList(new BranchDiscoveryTrait())));

    BranchSource branchSource = new BranchSource(source);
    branchSource.setStrategy(new DefaultBranchPropertyStrategy(null));

    TaskListener listener = StreamTaskListener.fromStderr();
    assertEquals("[SCMHead{'master'}]", source.fetch(listener).toString());
    project.setSourcesList(new ArrayList<>(Arrays.asList(branchSource)));

    project.scheduleBuild2(0).getFuture().get();

    Caches.BranchCacheLoader loader = new Caches.BranchCacheLoader(r.jenkins);
    BranchImpl.Branch branch = loader.load(project.getFullName() + "/master").orNull();

    // if branch is defined, it'll be sorted by branch
    assertNotNull(branch);
    assertTrue(branch.isPrimary());
    assertEquals("master", branch.getUrl());
}
 
Example #23
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getMultiBranchPipeline() throws IOException, ExecutionException, InterruptedException {
    Assume.assumeTrue(runAllTests());
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();


    Map resp = get("/organizations/jenkins/pipelines/p/");
    validateMultiBranchPipeline(mp, resp, 3);

    List<String> names = (List<String>) resp.get("branchNames");

    IsArrayContainingInAnyOrder.arrayContainingInAnyOrder(names, branches);

    List<Map> br = get("/organizations/jenkins/pipelines/p/branches", List.class);

    List<String> branchNames = new ArrayList<>();
    List<Integer> weather = new ArrayList<>();
    for (Map b : br) {
        branchNames.add((String) b.get("name"));
        weather.add((int) b.get("weatherScore"));
    }

    for (String n : branches) {
        assertTrue(branchNames.contains(n));
    }

    for (int s : weather) {
        assertEquals(100, s);
    }
}
 
Example #24
Source File: GitReadSaveService.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public String getApiUrl(@Nonnull Item item) {
    if (item instanceof org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) {
        MultiBranchProject<?,?> mbp = (MultiBranchProject<?,?>)item;
        return mbp.getSCMSources().stream()
                .filter(s->s instanceof GitSCMSource)
                .map(s -> ((GitSCMSource)s).getRemote())
                .findFirst()
                .orElse(null);
    }
    return null;
}
 
Example #25
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testMultiBranchPipelineBranchSecurePermissions() throws IOException, ExecutionException, InterruptedException {
    j.jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false));
    j.jenkins.setAuthorizationStrategy(new LegacyAuthorizationStrategy());

    MockFolder folder1 = j.createFolder("folder1");
    WorkflowMultiBranchProject mp = folder1.createProject(WorkflowMultiBranchProject.class, "p");

    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();


    Map r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/");


    Map<String,Boolean> permissions = (Map<String, Boolean>) r.get("permissions");
    Assert.assertFalse(permissions.get("create"));
    Assert.assertTrue(permissions.get("read"));
    Assert.assertFalse(permissions.get("start"));
    Assert.assertFalse(permissions.get("stop"));



    r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/branches/master/");

    permissions = (Map<String, Boolean>) r.get("permissions");
    Assert.assertFalse(permissions.get("create"));
    Assert.assertFalse(permissions.get("start"));
    Assert.assertFalse(permissions.get("stop"));
    Assert.assertTrue(permissions.get("read"));
}
 
Example #26
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testMultiBranchPipelineBranchUnsecurePermissions() throws IOException, ExecutionException, InterruptedException {
    MockFolder folder1 = j.createFolder("folder1");
    WorkflowMultiBranchProject mp = folder1.createProject(WorkflowMultiBranchProject.class, "p");

    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();


    Map r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/");


    Map<String,Boolean> permissions = (Map<String, Boolean>) r.get("permissions");
    Assert.assertTrue(permissions.get("create"));
    Assert.assertTrue(permissions.get("read"));
    Assert.assertTrue(permissions.get("start"));
    Assert.assertTrue(permissions.get("stop"));



    r = get("/organizations/jenkins/pipelines/folder1/pipelines/p/branches/master/");

    permissions = (Map<String, Boolean>) r.get("permissions");
    Assert.assertTrue(permissions.get("create"));
    Assert.assertTrue(permissions.get("start"));
    Assert.assertTrue(permissions.get("stop"));
    Assert.assertTrue(permissions.get("read"));
}
 
Example #27
Source File: GitHubSCMSourceTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-48035")
public void testGitHubRepositoryNameContributor_When_not_GitHub() throws IOException {
    WorkflowMultiBranchProject job = r.createProject(WorkflowMultiBranchProject.class);
    job.setSourcesList(Arrays.asList(new BranchSource(new GitSCMSource("file://tmp/something"))));
    Collection<GitHubRepositoryName> names = GitHubRepositoryNameContributor.parseAssociatedNames(job);
    assertThat(names, Matchers.empty());
    //And specifically...
    names = new ArrayList<>();
    ExtensionList.lookup(GitHubRepositoryNameContributor.class).get(GitHubSCMSourceRepositoryNameContributor.class).parseAssociatedNames(job, names);
    assertThat(names, Matchers.empty());
}
 
Example #28
Source File: DependencyGraphTest.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
/**
 * The maven-war-app has a dependency on the maven-jar-app
 */
@Test
public void verify_downstream_multi_branch_pipeline_trigger() throws Exception {
    System.out.println("gitRepoRule: " + gitRepoRule);
    loadMavenJarProjectInGitRepo(this.gitRepoRule);
    System.out.println("downstreamArtifactRepoRule: " + downstreamArtifactRepoRule);
    loadMavenWarProjectInGitRepo(this.downstreamArtifactRepoRule);

    String script = "node('master') {\n" +
            "    checkout scm\n" +
            "    withMaven() {\n" +
            "        sh 'mvn install'\n" +
            "    }\n" +
            "}";
    gitRepoRule.write("Jenkinsfile", script);
    gitRepoRule.git("add", "Jenkinsfile");
    gitRepoRule.git("commit", "--message=jenkinsfile");


    downstreamArtifactRepoRule.write("Jenkinsfile", script);
    downstreamArtifactRepoRule.git("add", "Jenkinsfile");
    downstreamArtifactRepoRule.git("commit", "--message=jenkinsfile");

    // TRIGGER maven-jar#1 to record that "build-maven-jar" generates this jar and install this maven jar in the local maven repo
    WorkflowMultiBranchProject mavenJarPipeline = jenkinsRule.createProject(WorkflowMultiBranchProject.class, "build-maven-jar");
    mavenJarPipeline.addTrigger(new WorkflowJobDependencyTrigger());
    mavenJarPipeline.getSourcesList().add(new BranchSource(new GitSCMSource(null, gitRepoRule.toString(), "", "*", "", false)));
    System.out.println("trigger maven-jar#1...");
    WorkflowJob mavenJarPipelineMasterPipeline = WorkflowMultibranchProjectTestsUtils.scheduleAndFindBranchProject(mavenJarPipeline, "master");
    assertEquals(1, mavenJarPipeline.getItems().size());
    System.out.println("wait for maven-jar#1...");
    jenkinsRule.waitUntilNoActivity();

    assertThat(mavenJarPipelineMasterPipeline.getLastBuild().getNumber(), is(1));
    // TODO check in DB that the generated artifact is recorded

    // TRIGGER maven-war#1 to record that "build-maven-war" has a dependency on "build-maven-jar"
    WorkflowMultiBranchProject mavenWarPipeline = jenkinsRule.createProject(WorkflowMultiBranchProject.class, "build-maven-war");
    mavenWarPipeline.addTrigger(new WorkflowJobDependencyTrigger());
    mavenWarPipeline.getSourcesList().add(new BranchSource(new GitSCMSource(null, downstreamArtifactRepoRule.toString(), "", "*", "", false)));
    System.out.println("trigger maven-war#1...");
    WorkflowJob mavenWarPipelineMasterPipeline = WorkflowMultibranchProjectTestsUtils.scheduleAndFindBranchProject(mavenWarPipeline, "master");
    assertEquals(1, mavenWarPipeline.getItems().size());
    System.out.println("wait for maven-war#1...");
    jenkinsRule.waitUntilNoActivity();
    WorkflowRun mavenWarPipelineFirstRun = mavenWarPipelineMasterPipeline.getLastBuild();

    // TODO check in DB that the dependency on the war project is recorded


    // TRIGGER maven-jar#2 so that it triggers "maven-war" and creates maven-war#2
    System.out.println("trigger maven-jar#2...");
    Future<WorkflowRun> mavenJarPipelineMasterPipelineSecondRunFuture = mavenJarPipelineMasterPipeline.scheduleBuild2(0, new CauseAction(new Cause.RemoteCause("127.0.0.1", "junit test")));
    System.out.println("wait for maven-jar#2...");
    mavenJarPipelineMasterPipelineSecondRunFuture.get();
    jenkinsRule.waitUntilNoActivity();


    WorkflowRun mavenWarPipelineLastRun = mavenWarPipelineMasterPipeline.getLastBuild();

    System.out.println("mavenWarPipelineLastBuild: " + mavenWarPipelineLastRun + " caused by " + mavenWarPipelineLastRun.getCauses());

    assertThat(mavenWarPipelineLastRun.getNumber(), is(mavenWarPipelineFirstRun.getNumber() + 1));
    Cause.UpstreamCause upstreamCause = mavenWarPipelineLastRun.getCause(Cause.UpstreamCause.class);
    assertThat(upstreamCause, notNullValue());

}
 
Example #29
Source File: SseEventTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void multiBranchJobEventsWithCustomOrg() throws Exception {
    MockFolder folder = j.createFolder("TestOrgFolderName");
    assertNotNull(folder);

    setupScm();

    final OneShotEvent success = new OneShotEvent();

    final Boolean[] pipelineNameMatched = {null};
    final Boolean[] mbpPipelineNameMatched = {null};

    SSEConnection con = new SSEConnection(j.getURL(), "me", new ChannelSubscriber() {
        @Override
        public void onMessage(@Nonnull Message message) {
            System.out.println(message);
            if("job".equals(message.get(jenkins_channel))) {
                if ("org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject".equals(message.get(jenkins_object_type))) {
                    if("pipeline1".equals(message.get(blueocean_job_pipeline_name))) {
                        mbpPipelineNameMatched[0] = true;
                    }else{
                        mbpPipelineNameMatched[0] = false;
                    }
                } else if ("org.jenkinsci.plugins.workflow.job.WorkflowJob".equals(message.get(jenkins_object_type))) {
                    if("pipeline1".equals(message.get(blueocean_job_pipeline_name))) {
                        pipelineNameMatched[0] = true;
                    }else {
                        pipelineNameMatched[0] = false;
                    }
                }
            }
            if(pipelineNameMatched[0] != null && mbpPipelineNameMatched[0] != null){
                success.signal();
            }
        }
    });
    con.subscribe("pipeline");
    con.subscribe("job");

    final WorkflowMultiBranchProject mp = folder.createProject(WorkflowMultiBranchProject.class, "pipeline1");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
            new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();

    WorkflowJob p = mp.getItem("master");
    if (p == null) {
        mp.getIndexing().writeWholeLogTo(System.out);
        fail("master project not found");
    }
    j.waitUntilNoActivity();
    WorkflowRun b1 = p.getLastBuild();
    assertEquals(1, b1.getNumber());
    assertEquals(2, mp.getItems().size());

    success.block(5000);
    con.close();
    if(success.isSignaled()) {
        assertTrue(pipelineNameMatched[0]);
        assertTrue(mbpPipelineNameMatched[0]);
    }
}
 
Example #30
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void branchCapabilityTest() throws Exception {

    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    WorkflowJob p = scheduleAndFindBranchProject(mp, "master");


    j.waitUntilNoActivity();

    //check MBP capabilities
    Map<String,Object> response = get("/organizations/jenkins/pipelines/p/");
    String clazz = (String) response.get("_class");

    response = get("/classes/"+clazz+"/");
    Assert.assertNotNull(response);

    List<String> classes = (List<String>) response.get("classes");
    Assert.assertTrue(classes.contains(BLUE_SCM)
            && classes.contains(JENKINS_MULTI_BRANCH_PROJECT)
            && classes.contains(BLUE_MULTI_BRANCH_PIPELINE)
            && classes.contains(BLUE_PIPELINE_FOLDER)
            && classes.contains(JENKINS_ABSTRACT_FOLDER)
            && classes.contains(BLUE_PIPELINE));

    response = get("/organizations/jenkins/pipelines/p/branches/master/", Map.class);
    clazz = (String) response.get("_class");

    response = get("/classes/"+clazz+"/");
    Assert.assertNotNull(response);

    classes = (List<String>) response.get("classes");
    Assert.assertTrue(classes.contains(JENKINS_JOB)
        && classes.contains(JENKINS_WORKFLOW_JOB)
        && classes.contains(BLUE_BRANCH)
        && classes.contains(BLUE_PIPELINE)
        && classes.contains(PULL_REQUEST));
}