Java Code Examples for org.jenkinsci.plugins.workflow.job.WorkflowJob#setDefinition()

The following examples show how to use org.jenkinsci.plugins.workflow.job.WorkflowJob#setDefinition() . 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: PipelineNodeTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void BlockStageNodesFailureTest1() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition("node{\n" +
                                                 "    stage ('Build') {\n" +
                                                 "            sh 'echo1 \"Building\"'\n" +
                                                 "    }\n" +
                                                 "    stage ('Test') {\n" +
                                                 "            sh 'echo testing'\n" +
                                                 "    }\n" +
                                                 "    stage ('Deploy') {\n" +
                                                 "            sh 'echo deploy'\n" +
                                                 "    }\n" +
                                                 "}", false));

    WorkflowRun b1 = job1.scheduleBuild2(0).get();
    j.assertBuildStatus(Result.FAILURE, b1);
    List<Map> nodes = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);
    Assert.assertEquals(1, nodes.size());
    Assert.assertEquals("FAILURE", nodes.get(0).get("result"));
    Assert.assertEquals("FINISHED", nodes.get(0).get("state"));

}
 
Example 2
Source File: ReadCSVStepTest.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Test
public void readFileWithFormat() throws Exception {
    String file = writeCSV(getCSV());

    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
            "  def format = CSVFormat.EXCEL.withHeader('key', 'value', 'attr').withSkipHeaderRecord(true)\n" +
            "  List<CSVRecord> records = readCSV file: '" + file + "', format: format\n" +
            "  assert records.size() == 2\n" +
            "  assert records[0].get('key') == 'a'\n" +
            "  assert records[0].get('value') == 'b'\n" +
            "  assert records[0].get('attr') == 'c'\n" +
            "  assert records[1].get('key') == '1'\n" +
            "  assert records[1].get('value') == '2'\n" +
            "  assert records[1].get('attr') == '3'\n" +
            "}", true));
    j.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
 
Example 3
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void maven_build_on_master_with_specified_maven_installation_succeeds() throws Exception {
    loadMavenJarProjectInGitRepo(this.gitRepoRule);

    String pipelineScript = "node('master') {\n" +
            "    git($/" + gitRepoRule.toString() + "/$)\n" +
            "    withMaven(maven: 'apache-maven-3.5.0') {\n" +
            "        sh 'mvn package'\n" +
            "    }\n" +
            "}";

    WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master-with-tool-provided-maven");
    pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
    WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0));

    // verify provided Maven is used
    jenkinsRule.assertLogContains("using Maven installation 'apache-maven-3.5.0'", build);

    // verify .pom is archived and fingerprinted
    // "[withMaven] Archive ... under jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.pom"
    jenkinsRule.assertLogContains("under jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.pom", build);

    // verify .jar is archived and fingerprinted
    jenkinsRule.assertLogContains("under jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.jar", build);
}
 
Example 4
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
@Test
public void skipIfLocked() throws Exception {
  LockableResourcesManager lm = LockableResourcesManager.get();
  lm.createResourceWithLabel("resource1", "label1");
  lm.reserve(Arrays.asList(lm.fromName("resource1")), "test");

  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(resource: 'resource1', skipIfLocked: true) {\n" + "  echo 'Running body'\n" + "}",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  j.waitForCompletion(b1);
  j.assertBuildStatus(Result.SUCCESS, b1);
  j.assertLogContains("[resource1] is locked, skipping execution...", b1);
  j.assertLogNotContains("Running body", b1);
}
 
Example 5
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getPipelineWihoutNodesAllStepsTest() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");


    job1.setDefinition(new CpsFlowDefinition("node {\n" +
                                                 "    sh \"echo Building...\"\n" +
                                                 "}\n" +
                                                 "    node{\n" +
                                                 "        echo \"Unit testing...\"\n" +
                                                 "        sh \"echo Tests running\"\n" +
                                                 "        sh \"echo Tests completed\"\n" +
                                                 "    }", false
    ));
    WorkflowRun b1 = job1.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b1);

    List<Map> resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/", List.class);
    Assert.assertEquals(4, resp.size());
    String log = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/" + resp.get(0).get("id") + "/log/", String.class);
    assertNotNull(log);
}
 
Example 6
Source File: ZipFileBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-30941")
@Test
public void cleanUpSucceeds() throws Exception {
    /** Issue was just present on Linux not windows - but the test will run on both */

    final String credentialsId = "zipfile";

    FileCredentialsImpl fc = new FileCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "Just a zip file", "a.zip", SecretBytes.fromBytes(IOUtils.toByteArray(ZipFileBindingTest.class.getResource("a.zip"))));
    CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), fc);

    final String contents = "Test of ZipFileBinding\n";
    
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(""
                                          + "node {\n"
                                          + "  withCredentials([[$class: 'ZipFileBinding', credentialsId: '"+ credentialsId +"', variable: 'ziploc']]) {\n"
                                          + "    echo readFile(encoding: 'UTF-8', file: \"${env.ziploc}/dir/testfile.txt\")\n"
                                          + "  }\n"
                                          + "}\n"
                                          , true));

    WorkflowRun run = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(run);
    j.assertLogContains(contents, run);
}
 
Example 7
Source File: LockStepTest.java    From lockable-resources-plugin with MIT License 6 votes vote down vote up
@Test
public void lockWithLabel() throws Exception {
  LockableResourcesManager.get().createResourceWithLabel("resource1", "label1");
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          "lock(label: 'label1', variable: 'var') {\n"
              + "	echo \"Resource locked: ${env.var}\"\n"
              + "}\n"
              + "echo 'Finish'",
          true));
  WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
  j.waitForCompletion(b1);
  j.assertBuildStatus(Result.SUCCESS, b1);
  j.assertLogContains("Lock released on resource [Label: label1]", b1);
  j.assertLogContains("Resource locked: resource1", b1);
  isPaused(b1, 1, 0);

  assertNotNull(LockableResourcesManager.get().fromName("resource1"));
}
 
Example 8
Source File: PipelineApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void pipelineJobCapabilityTest() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");

    job1.setDefinition(new CpsFlowDefinition("" +
        "node {" +
        "   stage ('Build1'); " +
        "   sleep(60); " +
        "   stage ('Test1'); " +
        "   echo ('Testing'); " +
        "}"));

    Map response = get("/organizations/jenkins/pipelines/pipeline1/");

    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("hudson.model.Job")
        && classes.contains("org.jenkinsci.plugins.workflow.job.WorkflowJob")
        && classes.contains("io.jenkins.blueocean.rest.model.BluePipeline")
        && !classes.contains("io.jenkins.blueocean.rest.model.BlueBranch")
    );
}
 
Example 9
Source File: CFNCreateChangeSetTests.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void createChangeSetWithRawTemplate() throws Exception {
	WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(this.stack.exists()).thenReturn(true);
	Mockito.when(this.stack.describeChangeSet("bar")).thenReturn(new DescribeChangeSetResult()
			.withChanges(new Change())
			.withStatus(ChangeSetStatus.CREATE_COMPLETE)
	);
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  def changes = cfnCreateChangeSet(stack: 'foo', changeSet: 'bar', template: 'foobaz')\n"
			+ "  echo \"changesCount=${changes.size()}\"\n"
			+ "}\n", true)
	);
	Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
	this.jenkinsRule.assertLogContains("changesCount=1", run);

	PowerMockito.verifyNew(CloudFormationStack.class, Mockito.atLeastOnce()).withArguments(Mockito.any(AmazonCloudFormation.class), Mockito.eq("foo"), Mockito.any(TaskListener.class));
	Mockito.verify(this.stack).createChangeSet(Mockito.eq("bar"), Mockito.eq("foobaz"), Mockito.anyString(), Mockito.anyCollectionOf(Parameter.class), Mockito.anyCollectionOf(Tag.class),
											   Mockito.anyCollectionOf(String.class), Mockito.any(PollConfiguration.class), Mockito.eq(ChangeSetType.UPDATE), Mockito.anyString(), Mockito.any());
}
 
Example 10
Source File: WriteYamlStepTest.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
@Test
public void writeExistingFile() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "list");
    p.setDefinition(new CpsFlowDefinition(
            "node('slaves') {\n" +
                    "  touch 'test.yml' \n" +
                    "  writeYaml file: 'test.yml', data: ['a', 'b', 'c'] \n" +
                    "}",
            true));
    WorkflowRun b = j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
    j.assertLogContains("FileAlreadyExistsException", b);
}
 
Example 11
Source File: S3UploadStepTransferManagerIntegrationTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void useFileListUploaderWhenIncludePathPatternDefined() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "S3UploadStepTest");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  writeFile file: 'work/subdir/test.txt', text: 'Hello!'\n"
			+ "  s3Upload(bucket: 'test-bucket', includePathPattern: '**/*.txt', workingDir: 'work')"
			+ "}\n", true)
	);

	MultipleFileUpload upload = Mockito.mock(MultipleFileUpload.class);
	Mockito.when(transferManager.uploadFileList(Mockito.eq("test-bucket"), Mockito.eq(""), Mockito.any(File.class), Mockito.any(List.class), Mockito.any(ObjectMetadataProvider.class), Mockito.any(ObjectTaggingProvider.class)))
			.thenReturn(upload);
	Mockito.when(upload.getSubTransfers()).thenReturn(Collections.emptyList());

	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
	ArgumentCaptor<File> captorDirectory = ArgumentCaptor.forClass(File.class);

	Mockito.verify(transferManager).uploadFileList(
			Mockito.eq("test-bucket"),
			Mockito.eq(""),
			captorDirectory.capture(),
			captor.capture(),
			Mockito.any(ObjectMetadataProvider.class),
			Mockito.any(ObjectTaggingProvider.class));
	Mockito.verify(upload).getSubTransfers();
	Mockito.verify(upload).waitForCompletion();
	Mockito.verify(transferManager).shutdownNow();
	Mockito.verifyNoMoreInteractions(transferManager, upload);

	Assert.assertEquals(1, captor.getValue().size());
	Assert.assertEquals("test.txt", ((File)captor.getValue().get(0)).getName());
	Assertions.assertThat(((File)captor.getValue().get(0)).getPath()).matches("^.*subdir.test.txt$");
	Assertions.assertThat(captorDirectory.getValue().getPath()).endsWith("work");
	Assertions.assertThat(captorDirectory.getValue().getPath()).doesNotContain("subdir");
}
 
Example 12
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Test
public void maven_build_maven_hpi_project_on_master_succeeds() throws Exception {
    loadJenkinsPluginProjectInGitRepo(this.gitRepoRule);

    String pipelineScript = "node('master') {\n" +
            "    git($/" + gitRepoRule.toString() + "/$)\n" +
            "    withMaven() {\n" +
            "        sh 'mvn package'\n" +
            "    }\n" +
            "}";

    WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master");
    pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
    WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0));

    // verify Maven installation provided by the build agent is used
    // can be either "by the build agent with executable..." or "by the build agent with the environment variable MAVEN_HOME=..."
    jenkinsRule.assertLogContains("[withMaven] using Maven installation provided by the build agent with", build);

    // verify .pom is archived and fingerprinted
    jenkinsRule.assertLogContains("under jenkins/mvn/test/test-jenkins-hpi/0.1-SNAPSHOT/test-jenkins-hpi-0.1-SNAPSHOT.pom", build);

    // verify .jar and .hpi is archived and fingerprinted
    jenkinsRule.assertLogContains("under jenkins/mvn/test/test-jenkins-hpi/0.1-SNAPSHOT/test-jenkins-hpi-0.1-SNAPSHOT.hpi", build);
    jenkinsRule.assertLogContains("under jenkins/mvn/test/test-jenkins-hpi/0.1-SNAPSHOT/test-jenkins-hpi-0.1-SNAPSHOT.jar", build);

    Collection<String> artifactsFileNames = TestUtils.artifactsToArtifactsFileNames(build.getArtifacts());
    assertThat(artifactsFileNames, hasItems("test-jenkins-hpi-0.1-SNAPSHOT.pom", "test-jenkins-hpi-0.1-SNAPSHOT.jar", "test-jenkins-hpi-0.1-SNAPSHOT.hpi"));

    verifyFileIsFingerPrinted(pipeline, build, "jenkins/mvn/test/test-jenkins-hpi/0.1-SNAPSHOT/test-jenkins-hpi-0.1-SNAPSHOT.hpi");
    verifyFileIsFingerPrinted(pipeline, build, "jenkins/mvn/test/test-jenkins-hpi/0.1-SNAPSHOT/test-jenkins-hpi-0.1-SNAPSHOT.jar");
    verifyFileIsFingerPrinted(pipeline, build, "jenkins/mvn/test/test-jenkins-hpi/0.1-SNAPSHOT/test-jenkins-hpi-0.1-SNAPSHOT.pom");

    //  verify Junit Archiver is called for jenkins.mvn.test:test-jenkins-hpi
    jenkinsRule.assertLogContains("[withMaven] junitPublisher - Archive test results for Maven artifact jenkins.mvn.test:test-jenkins-hpi:hpi:0.1-SNAPSHOT generated by", build);

    // verify Task Scanner is called for jenkins.mvn.test:test-jenkins-hpi
    jenkinsRule.assertLogContains("[withMaven] openTasksPublisher - Scan Tasks for Maven artifact jenkins.mvn.test:test-jenkins-hpi:hpi:0.1-SNAPSHOT in source directory", build);
}
 
Example 13
Source File: JobActionITest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Verifies that the aggregation trend chart is visible for a pipeline job at the top, or bottom, or hidden.
 */
@Test
public void shouldShowTrendsAndAggregationPipeline() {
    WorkflowJob job = createPipelineWithWorkspaceFiles(ECLIPSE_LOG, CHECKSTYLE_XML);
    job.setDefinition(
            asStage("def checkstyle = scanForIssues tool: checkStyle(pattern:'**/checkstyle.xml', reportEncoding:'UTF-8')",
                    "publishIssues issues:[checkstyle], trendChartType: 'TOOLS_AGGREGATION'",
                    "def eclipse = scanForIssues tool: eclipse(pattern:'**/eclipse.txt', reportEncoding:'UTF-8')",
                    "publishIssues issues:[eclipse], trendChartType: 'TOOLS_AGGREGATION'"
            ));

    buildSuccessfully(job);
    buildSuccessfully(job);

    assertThatAggregationChartExists(job, true);
    assertThatCheckstyleAndEclipseChartExist(job, true);

    job.setDefinition(asStage("recordIssues tools: ["
            + "checkStyle(pattern:'**/checkstyle.xml', reportEncoding:'UTF-8'),"
            + "eclipse(pattern:'**/eclipse.txt', reportEncoding:'UTF-8')], trendChartType: 'TOOLS_ONLY'"
    ));

    buildSuccessfully(job);
    buildSuccessfully(job);
    assertThatAggregationChartDoesNotExists(job);
    assertThatCheckstyleAndEclipseChartExist(job, true);

    job.setDefinition(asStage("recordIssues tools: ["
            + "checkStyle(pattern:'**/checkstyle.xml', reportEncoding:'UTF-8'),"
            + "eclipse(pattern:'**/eclipse.txt', reportEncoding:'UTF-8')], trendChartType: 'NONE'"
    ));

    buildSuccessfully(job);
    buildSuccessfully(job);
    assertThatCheckstyleAndEclipseChartExist(job, false);
}
 
Example 14
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Test
public void maven_build_on_master_with_missing_specified_maven_installation_fails() throws Exception {
    loadMavenJarProjectInGitRepo(this.gitRepoRule);

    String pipelineScript = "node('master') {\n" +
            "    git($/" + gitRepoRule.toString() + "/$)\n" +
            "    withMaven(maven: 'install-does-not-exist') {\n" +
            "        sh 'mvn package'\n" +
            "    }\n" +
            "}";

    WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master-with-tool-provided-maven");
    pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
    WorkflowRun build = jenkinsRule.assertBuildStatus(Result.FAILURE, pipeline.scheduleBuild2(0));
}
 
Example 15
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-38339")
public void downstreamBuildLinks() throws Exception {
    FreeStyleProject downstream1 = j.createFreeStyleProject("downstream1");
    FreeStyleProject downstream2 = j.createFreeStyleProject("downstream2");

    WorkflowJob upstream = j.createProject(WorkflowJob.class, "upstream");

    URL resource = Resources.getResource(getClass(), "downstreamBuildLinks.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    upstream.setDefinition(new CpsFlowDefinition(jenkinsFile, true));

    j.assertBuildStatus(Result.SUCCESS, upstream.scheduleBuild2(0));

    WorkflowRun r = upstream.getLastBuild();

    List<Map> resp = get("/organizations/jenkins/pipelines/upstream/runs/" + r.getId() + "/nodes/", List.class);

    assertEquals("number of nodes", 5, resp.size());

    Matcher actionMatcher1 = new NodeDownstreamBuildActionMatcher("downstream1");
    Matcher actionMatcher2 = new NodeDownstreamBuildActionMatcher("downstream2");

    List<Map> actions = (List<Map>) resp.get(2).get("actions");
    assertThat("node #2 contains a link to downstream1", actions, hasItem(actionMatcher1));

    actions = (List<Map>) resp.get(3).get("actions");
    assertThat("node #3 contains a link to downstream2", actions, hasItem(actionMatcher2));

    actions = (List<Map>) resp.get(4).get("actions");
    assertThat("node #4 contains a link to downstream1", actions, hasItem(actionMatcher1));
    assertThat("node #4 contains a link to downstream1", actions, hasItem(actionMatcher2));
}
 
Example 16
Source File: PodTemplateStepExecutionTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadLabel() throws Exception {
    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "bad_label");
    p.setDefinition(new CpsFlowDefinition(loadPipelineScript("badlabel.groovy"), true));
    WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    assertNotNull(b);
    r.assertBuildStatus(Result.FAILURE, r.waitForCompletion(b));
    r.waitForMessage(Messages.label_error("mypod!123"), b);
}
 
Example 17
Source File: ReadPropertiesStepTest.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
@Test
public void readNone() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node('slaves') {\n" +
                    "  def props = readProperties()\n" +
                    "}", true));
    WorkflowRun run = j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
    j.assertLogContains(Messages.AbstractFileOrTextStepDescriptorImpl_missingRequiredArgument("readProperties"), run);
}
 
Example 18
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void testTestsInStage() throws Exception {
    String pipeline = "" +
        "node {\n" +
        "  stage ('dev') {\n" +
        "    junit('*.xml')\n" +
        "  }\n" +
        "  stage ('prod') {\n" +
        "    junit('*.xml')\n" +
        "  }\n" +
        "  stage ('testing') {\n" +
        "    parallel(first: {\n" +
        "        junit('*.xml')\n" +
        "      },\n" +
        "      second: {\n" +
        "        junit('*.xml')\n" +
        "      })\n" +
        "  }\n" +
        "}\n";

    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");

    job1.setDefinition(new CpsFlowDefinition(pipeline, true));
    FilePath ws = j.jenkins.getWorkspaceFor(job1);
    FilePath testFile = ws.child("test-result.xml");
    testFile.copyFrom(PipelineNodeTest.class.getResource("testResult.xml"));

    WorkflowRun b1 = job1.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b1);

    NodeGraphBuilder builder = NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(b1);
    List<FlowNode> stages = getStages(builder);

    Assert.assertEquals(3, stages.size());

    List<Map> resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);
    Assert.assertEquals(5, resp.size());

    resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/tests/", List.class);
    Assert.assertEquals(4, resp.size());

    Assert.assertEquals("dev / testDummyMethod – DummyTest", resp.get(0).get("name"));
    Assert.assertEquals("prod / testDummyMethod – DummyTest", resp.get(1).get("name"));
    Assert.assertEquals("testing / first / testDummyMethod – DummyTest", resp.get(2).get("name"));
    Assert.assertEquals("testing / second / testDummyMethod – DummyTest", resp.get(3).get("name"));
}
 
Example 19
Source File: CFNUpdateStackSetStepTest.java    From pipeline-aws-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void updateWithRegionBatches() throws Exception {
	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
	Mockito.when(stackSet.exists()).thenReturn(true);
	String operationId = UUID.randomUUID().toString();
	Mockito.when(stackSet.update(Mockito.anyString(), Mockito.anyString(), Mockito.any(UpdateStackSetRequest.class)))
			.thenReturn(new UpdateStackSetResult()
					.withOperationId(operationId)
			);
	Mockito.when(stackSet.findStackSetInstances()).thenReturn(asList(
			new StackInstanceSummary().withAccount("a1").withRegion("r1"),
			new StackInstanceSummary().withAccount("a2").withRegion("r1"),
			new StackInstanceSummary().withAccount("a2").withRegion("r2"),
			new StackInstanceSummary().withAccount("a3").withRegion("r3")
	));
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  cfnUpdateStackSet(stackSet: 'foo'," +
			"       pollInterval: 27," +
			"       batchingOptions: [" +
			"         regions: true" +
			"       ]" +
			"    )"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

	PowerMockito.verifyNew(CloudFormationStackSet.class, Mockito.atLeastOnce())
			.withArguments(
					Mockito.any(AmazonCloudFormation.class),
					Mockito.eq("foo"),
					Mockito.any(TaskListener.class),
					Mockito.eq(SleepStrategy.EXPONENTIAL_BACKOFF_STRATEGY)
			);
	ArgumentCaptor<UpdateStackSetRequest> requestCapture = ArgumentCaptor.forClass(UpdateStackSetRequest.class);
	Mockito.verify(stackSet, Mockito.times(3)).update(Mockito.anyString(), Mockito.anyString(), requestCapture.capture());
	Map<String, List<String>> capturedRegionAccounts = requestCapture.getAllValues()
			.stream()
			.flatMap(summary -> summary.getRegions()
					.stream()
					.flatMap(region -> summary.getAccounts().stream()
							.map(accountId -> RegionAccountIdTuple.builder().accountId(accountId).region(region).build())
					))
			.collect(Collectors.groupingBy(RegionAccountIdTuple::getRegion, Collectors.mapping(RegionAccountIdTuple::getAccountId, Collectors.toList())));
	Assertions.assertThat(capturedRegionAccounts).containsAllEntriesOf(new HashMap<String, List<String>>() {
		{
			put("r1", asList("a1", "a2"));
			put("r2", singletonList("a2"));
			put("r3", singletonList("a3"));
		}
	});

	Mockito.verify(stackSet, Mockito.times(3)).waitForOperationToComplete(Mockito.any(), Mockito.any());
}
 
Example 20
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void nodesWithPartialParallels() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition("node {\n" +
                                                 "    stage (\"hey\") {\n" +
                                                 "        sh \"echo yeah\"\n" +
                                                 "    }\n" +
                                                 "    stage (\"par\") {\n" +
                                                 "    \n" +
                                                 "        parallel left : {\n" +
                                                 "            sh \"echo OMG BS\"\n" +
                                                 "            sh \"echo yeah\"\n" +
                                                 "        }, \n" +
                                                 "        \n" +
                                                 "        right : {\n" +
                                                 "            sh \"echo wozzle\"\n" +
                                                 "        }\n" +
                                                 "    }\n" +
                                                 "    stage (\"ho\") {\n" +
                                                 "        sh \"echo done\"\n" +
                                                 "    }\n" +
                                                 "}", false));

    j.buildAndAssertSuccess(job1);
    List<Map> resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);
    Assert.assertEquals(5, resp.size());

    job1.setDefinition(new CpsFlowDefinition("node {\n" +
                                                 "    stage (\"hey\") {\n" +
                                                 "        sh \"echo yeah\"\n" +
                                                 "    }\n" +
                                                 "    stage (\"par\") {\n" +
                                                 "    \n" +
                                                 "        parallel left : {\n" +
                                                 "            sh \"echo OMG BS\"\n" +
                                                 "            echo \"running\"\n" +
                                                 "            semaphore('left')\n" +
                                                 "            echo \"BRANCH NAME left\"\n" +
                                                 "            sh \"echo yeah\"\n" +
                                                 "        }, \n" +
                                                 "        \n" +
                                                 "        right : {\n" +
                                                 "            sh \"echo wozzle\"\n" +
                                                 "            semaphore('right')\n" +
                                                 "            echo \"BRANCH NAME right\"\n" +
                                                 "        }\n" +
                                                 "    }\n" +
                                                 "    stage (\"ho\") {\n" +
                                                 "        sh \"echo done\"\n" +
                                                 "    }\n" +
                                                 "}", false));

    WorkflowRun b2 = job1.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("left/1", b2);
    SemaphoreStep.waitForStart("right/1", b2);

    resp = get("/organizations/jenkins/pipelines/pipeline1/runs/2/nodes/", List.class);

    Assert.assertEquals(5, resp.size());

    Map leftNode = resp.get(2);
    Assert.assertEquals("left", leftNode.get("displayName"));

    Map rightNode = resp.get(3);
    Assert.assertEquals("right", rightNode.get("displayName"));

    List<Map> leftSteps = get("/organizations/jenkins/pipelines/pipeline1/runs/2/nodes/" + leftNode.get("id") + "/steps/", List.class);

    Assert.assertEquals(3, leftSteps.size());

    List<Map> rightSteps = get("/organizations/jenkins/pipelines/pipeline1/runs/2/nodes/" + rightNode.get("id") + "/steps/", List.class);

    Assert.assertEquals(2, rightSteps.size());
}