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

The following examples show how to use org.jenkinsci.plugins.workflow.job.WorkflowJob#scheduleBuild2() . 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: AbstractPipelineTestProject.java    From aws-codecommit-trigger-plugin with Apache License 2.0 6 votes vote down vote up
protected void subscribeProject(ProjectFixture fixture) throws Exception {
    String name = UUID.randomUUID().toString();
    WorkflowJob job = jenkinsRule.getInstance().createProject(WorkflowJob.class, name);

    String script = fixture.getPipelineScript().replace("${EmitEvent}", AbstractPipelineTestProject.class.getName() + ".emitBuildEvent()");
    CpsFlowDefinition flowDefinition = new CpsFlowDefinition(script, true);
    job.setDefinition(flowDefinition);

    QueueTaskFuture<WorkflowRun> run = job.scheduleBuild2(0);
    WorkflowRun wfRun = run.get();
    Assertions.assertThat(wfRun.getResult())
        .describedAs("Pipeline unable to start succeed")
        .isEqualTo(Result.SUCCESS);
    jenkinsRule.assertBuildStatusSuccess(wfRun);

    resetPipelineBuildEvent(fixture);

    if (!fixture.isHasTrigger()) {
        return;
    }

    final String uuid = this.sqsQueue.getUuid();
    SQSTrigger trigger = new SQSTrigger(uuid, fixture.isSubscribeInternalScm(), fixture.getScmConfigs());
    job.addTrigger(trigger);
    trigger.start(job, false);
}
 
Example 2
Source File: PipelineApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getPipelineJobRuns() throws Exception {
    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition("" +
        "node {" +
        "   stage ('Build1'); " +
        "   echo ('Building'); " +
        "   stage ('Test1'); " +
        "   sleep 10000      " +
        "   echo ('Testing'); " +
        "}"));

    job1.setConcurrentBuild(false);

    WorkflowRun r = job1.scheduleBuild2(0).waitForStart();
    job1.scheduleBuild2(0);


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

    Assert.assertEquals(2, l.size());
    Assert.assertEquals("io.jenkins.blueocean.service.embedded.rest.QueuedBlueRun", ((Map) l.get(0)).get("_class"));
    Assert.assertEquals("io.jenkins.blueocean.rest.impl.pipeline.PipelineRunImpl", ((Map) l.get(1)).get("_class"));
}
 
Example 3
Source File: MattermostSendStepIntegrationTest.java    From jenkins-mattermost-plugin with MIT License 6 votes vote down vote up
@Test
  public void test_fail_on_error() throws Exception {
    WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow");
    // just define message
	  job.setDefinition(
			  new CpsFlowDefinition(
					  "mattermostSend(message: 'message', endpoint: 'endpoint', icon: 'icon', channel: '#channel', color: 'good', failOnError: true);",
					  true));
	  //noinspection ConstantConditions
	  //job.scheduleBuild(0,new Cause.UserIdCause());
	  QueueTaskFuture<WorkflowRun> workflowRunQueueTaskFuture = job.scheduleBuild2(0);
	  //WorkflowRun workflowRun = workflowRunQueueTaskFuture.getStartCondition().get();
	  //workflowRun.getExecutionPromise().get();
	  WorkflowRun run = jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRunQueueTaskFuture);
	  //jenkinsRule.assertBuildStatusSuccess(workflowRun);
	  // everything should come from step configuration
//	  String log = JenkinsRule.getLog(run);
//	  Assert.assertTrue(log.contains("Warn"));
	  //TODO jenkinsRule.assertLogContains(
	  //   "Mattermost notification failed. See Jenkins logs for details.", run);
  }
 
Example 4
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-49297")
public void submitInputPostBlock() throws Exception {
    WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    URL resource = Resources.getResource(getClass(), "stepsFromPost.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    job.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    QueueTaskFuture<WorkflowRun> buildTask = job.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

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

    assertEquals(1, nodes.size());

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

    assertEquals(3, steps.size());

    assertEquals("7", steps.get(0).get("id"));
    assertEquals("Hello World", steps.get(0).get("displayDescription"));
    assertEquals("12", steps.get(1).get("id"));
    assertEquals("Hello World from post", steps.get(1).get("displayDescription"));
    assertEquals("13", steps.get(2).get("id"));
    assertEquals("Wait for interactive input", steps.get(2).get("displayName"));
}
 
Example 5
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-48884")
public void submitInputPostBlockWithParallelStages() throws Exception {
    WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    URL resource = Resources.getResource(getClass(), "parallelStepsFromPost.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    job.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    QueueTaskFuture<WorkflowRun> buildTask = job.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

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

    assertEquals(6, nodes.size());

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

    assertEquals(4, steps.size());

    assertEquals("15", steps.get(0).get("id"));
    assertEquals("exit 1", steps.get(0).get("displayDescription"));
    assertEquals("17", steps.get(1).get("id"));
    assertEquals("hello stable", steps.get(1).get("displayDescription"));
    assertEquals("47", steps.get(2).get("id"));
    assertEquals("Hello World from post", steps.get(2).get("displayDescription"));
    assertEquals("48", steps.get(3).get("id"));
    assertEquals("Wait for interactive input", steps.get(3).get("displayName"));
}
 
Example 6
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void waitForInputTest() throws Exception {
    String script = "node {\n" +
        "    stage(\"parallelStage\"){\n" +
        "      parallel left : {\n" +
        "            echo \"running\"\n" +
        "            def branchInput = input message: 'Please input branch to test against', parameters: [[$class: 'StringParameterDefinition', defaultValue: 'master', description: '', name: 'branch']]\n" +
        "            echo \"BRANCH NAME: ${branchInput}\"\n" +
        "        }, \n" +
        "        right : {\n" +
        "            sh 'sleep 100000'\n" +
        "        }\n" +
        "    }\n" +
        "}";

    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition(script, false));
    QueueTaskFuture<WorkflowRun> buildTask = job1.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    Map runResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/");

    Assert.assertEquals("PAUSED", runResp.get("state"));

    List<FlowNodeWrapper> nodes = NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(run).getPipelineNodes();

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

    Assert.assertEquals("PAUSED", nodesResp.get(0).get("state"));
    Assert.assertEquals("UNKNOWN", nodesResp.get(0).get("result"));
    Assert.assertEquals("parallelStage", nodesResp.get(0).get("displayName"));

    Assert.assertEquals("PAUSED", nodesResp.get(1).get("state"));
    Assert.assertEquals("UNKNOWN", nodesResp.get(1).get("result"));
    Assert.assertEquals("left", nodesResp.get(1).get("displayName"));

    Assert.assertEquals("RUNNING", nodesResp.get(2).get("state"));
    Assert.assertEquals("UNKNOWN", nodesResp.get(2).get("result"));
    Assert.assertEquals("right", nodesResp.get(2).get("displayName"));

    List<Map> stepsResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/", List.class);

    Assert.assertEquals("RUNNING", stepsResp.get(0).get("state"));
    Assert.assertEquals("UNKNOWN", stepsResp.get(0).get("result"));
    Assert.assertEquals("13", stepsResp.get(0).get("id"));

    Assert.assertEquals("PAUSED", stepsResp.get(2).get("state"));
    Assert.assertEquals("UNKNOWN", stepsResp.get(2).get("result"));
    Assert.assertEquals("12", stepsResp.get(2).get("id"));
}
 
Example 7
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void testBlockedStep() throws Exception {
    String script = "node {\n" +
        "    stage(\"one\"){\n" +
        "        echo '1'\n" +
        "    }\n" +
        "    stage(\"two\") {\n" +
        "            node('blah'){\n" +
        "                sh 'blah'\n" +
        "            }\n" +
        "        }\n" +
        "\n" +
        "}";

    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition(script, false));

    QueueTaskFuture<WorkflowRun> runQueueTaskFuture = job1.scheduleBuild2(0);
    WorkflowRun run = runQueueTaskFuture.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    if (waitForItemToAppearInQueue(1000 * 300)) { //5 min timeout
        List<FlowNode> nodes = getStages(NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(run));
        if (nodes.size() == 2) {
            List<Map> stepsResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/11/steps/", List.class);
            assertEquals(1, stepsResp.size());
            assertEquals("QUEUED", stepsResp.get(0).get("state"));
        }
    } else {
        // Avoid spurious code coverage failures
        final FlowNode node = new FlowNode(null, "fake") {
            @Override
            protected String getTypeDisplayName() {
                return "fake";
            }
        };
        final MemoryFlowChunk chunk = new MemoryFlowChunk() {
            @Override
            public FlowNode getFirstNode() {
                return node;
            }
        };
        new PipelineStepVisitor.LocalAtomNode(chunk, "fake");
    }
}
 
Example 8
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void submitInput() throws Exception {
    String script = "node {\n" +
        "    stage(\"first\"){\n" +
        "            def branchInput = input message: 'Please input branch to test against', parameters: [[$class: 'StringParameterDefinition', defaultValue: 'master', description: '', name: 'branch']]\n" +
        "            echo \"BRANCH NAME: ${branchInput}\"\n" +
        "    }\n" +
        "}";

    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition(script, false));
    QueueTaskFuture<WorkflowRun> buildTask = job1.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }


    List<Map> stepsResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/", List.class);


    Assert.assertEquals("PAUSED", stepsResp.get(0).get("state"));
    Assert.assertEquals("UNKNOWN", stepsResp.get(0).get("result"));
    Assert.assertEquals("7", stepsResp.get(0).get("id"));

    Map<String, Object> input = (Map<String, Object>) stepsResp.get(0).get("input");
    Assert.assertNotNull(input);
    String id = (String) input.get("id");
    Assert.assertNotNull(id);

    List<Map<String, Object>> params = (List<Map<String, Object>>) input.get("parameters");

    post("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/7/",
         ImmutableMap.of("id", id,
                         PARAMETERS_ELEMENT,
                         ImmutableList.of(ImmutableMap.of("name", params.get(0).get("name"), "value", "master"))
         )
        , 200);

    if (waitForBuildCount(job1, 1, Result.SUCCESS)) {
        Map<String, Object> resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/7/");
        Assert.assertEquals("FINISHED", resp.get("state"));
        Assert.assertEquals("SUCCESS", resp.get("result"));
        Assert.assertEquals("7", resp.get("id"));
    }
}
 
Example 9
Source File: PipelineNodeTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void abortInput() throws Exception {
    String script = "node {\n" +
        "    stage(\"thing\"){\n" +
        "            input 'continue'\n" +
        "    }\n" +
        "}";

    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition(script, false));
    QueueTaskFuture<WorkflowRun> buildTask = job1.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    List<Map> stepsResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/", List.class);

    System.out.println(stepsResp);

    Assert.assertEquals("PAUSED", stepsResp.get(0).get("state"));
    Assert.assertEquals("UNKNOWN", stepsResp.get(0).get("result"));
    String stepId = (String) stepsResp.get(0).get("id");
    //Assert.assertEquals("7", stepsResp.get(0).get("id"));

    Map<String, Object> input = (Map<String, Object>) stepsResp.get(0).get("input");
    Assert.assertNotNull(input);
    String id = (String) input.get("id");
    Assert.assertNotNull(id);

    JSONObject req = new JSONObject();
    req.put("id", id);
    req.put("abort", true);

    post("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/" + stepId + "/", req, 200);

    if (waitForBuildCount(job1, 1, Result.ABORTED)) {
        Map<String, Object> resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/" + stepId + "/");
        Assert.assertEquals("FINISHED", resp.get("state"));
        Assert.assertEquals("ABORTED", resp.get("result"));
        Assert.assertEquals(stepId, resp.get("id"));
    }
}
 
Example 10
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test @Ignore
public void getPipelineJobrRuns() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    sampleRepo1.init();
    sampleRepo1.write("Jenkinsfile", "stage 'build'\n "+"node {echo 'Building'}\n"+
        "stage 'test'\nnode { echo 'Testing'}\n" +
        "sleep 10000 \n"+
        "stage 'deploy'\nnode { echo 'Deploying'}\n"
    );
    sampleRepo1.write("file", "initial content");
    sampleRepo1.git("add", "Jenkinsfile");
    sampleRepo1.git("commit", "--all", "--message=flow");

    //create feature branch
    sampleRepo1.git("checkout", "-b", "abc");
    sampleRepo1.write("Jenkinsfile", "echo \"branch=${env.BRANCH_NAME}\"; "+"node {" +
        "   stage ('Build'); " +
        "   echo ('Building'); " +
        "   stage ('Test'); sleep 10000; " +
        "   echo ('Testing'); " +
        "   stage ('Deploy'); " +
        "   echo ('Deploying'); " +
        "}");
    ScriptApproval.get().approveSignature("method java.lang.String toUpperCase");
    sampleRepo1.write("file", "subsequent content1");
    sampleRepo1.git("commit", "--all", "--message=tweaked1");


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

    for(WorkflowJob job : mp.getItems()) {
        Queue.Item item =  job.getQueueItem();
        if(item != null ) {
            item.getFuture().waitForStart();
        }
        job.setConcurrentBuild(false);
        job.scheduleBuild2(0);
        job.scheduleBuild2(0);
    }
    List l = request().get("/organizations/jenkins/pipelines/p/activities").build(List.class);

    Assert.assertEquals(4, l.size());
    Assert.assertEquals("io.jenkins.blueocean.service.embedded.rest.QueueItemImpl", ((Map) l.get(0)).get("_class"));
    Assert.assertEquals("io.jenkins.blueocean.rest.impl.pipeline.PipelineRunImpl", ((Map) l.get(2)).get("_class"));
}
 
Example 11
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void testMultiBranchPipelineQueueContainer() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    sampleRepo1.init();
    sampleRepo1.write("Jenkinsfile", "stage 'build'\n " + "node {echo 'Building'}\n" +
            "stage 'test'\nnode { echo 'Testing'}\n" +
            "sleep 10000 \n" +
            "stage 'deploy'\nnode { echo 'Deploying'}\n"
    );
    sampleRepo1.write("file", "initial content");
    sampleRepo1.git("add", "Jenkinsfile");
    sampleRepo1.git("commit", "--all", "--message=flow");

    //create feature branch
    sampleRepo1.git("checkout", "-b", "abc");
    sampleRepo1.write("Jenkinsfile", "echo \"branch=${env.BRANCH_NAME}\"; " + "node {" +
            "   stage ('Build'); " +
            "   echo ('Building'); " +
            "   stage ('Test'); sleep 10000; " +
            "   echo ('Testing'); " +
            "   stage ('Deploy'); " +
            "   echo ('Deploying'); " +
            "}");
    ScriptApproval.get().approveSignature("method java.lang.String toUpperCase");
    sampleRepo1.write("file", "subsequent content1");
    sampleRepo1.git("commit", "--all", "--message=tweaked1");


    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo1.toString(), "", "*", "", false),
            new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }
    scheduleAndFindBranchProject(mp);
    Resource r = BluePipelineFactory.resolve(mp);
    assertTrue(r instanceof MultiBranchPipelineImpl);

    for (WorkflowJob job : mp.getItems()) {
        Queue.Item item = job.getQueueItem();
        job.setConcurrentBuild(false);
        job.scheduleBuild2(0);
        job.scheduleBuild2(0);
    }
    Queue.Item[] queueItems = Jenkins.getInstance().getQueue().getItems();
    MultiBranchPipelineQueueContainer mbpQueueContainer =
            new MultiBranchPipelineQueueContainer((MultiBranchPipelineImpl) r);
    Iterator<BlueQueueItem> blueQueueItems = mbpQueueContainer.iterator(0,100);
    if (queueItems.length > 0){
        assertTrue(mbpQueueContainer.iterator().hasNext());
        assertEquals("/blue/rest/organizations/jenkins/pipelines/p/queue/", mbpQueueContainer.getLink().getHref());
        BlueQueueItem blueQueueItem = mbpQueueContainer.get(String.valueOf(queueItems[0].getId()));
        assertNotNull(blueQueueItem);
        assertTrue(blueQueueItems.hasNext());
    }
}
 
Example 12
Source File: SseEventTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void pipelineWithInput() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    final OneShotEvent success = new OneShotEvent();

    String script = "node {\n" +
            "  stage(\"build\"){\n" +
            "    echo \"running\"\n" +
            "    input message: 'Please input branch to test against', parameters: [[$class: 'StringParameterDefinition', defaultValue: 'master', description: '', name: 'branch']]\n" +
            "  }\n" +
            "}";

    final boolean[] wasPaused = {false};
    final boolean[] wasUnPaused = {false};
    final AssertionHelper assertionHelper = new AssertionHelper();
    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))) {
                assertionHelper.isEquals("/blue/rest/organizations/jenkins/pipelines/pipeline1/", message.get(blueocean_job_rest_url));
                assertionHelper.isEquals("pipeline1", message.get(blueocean_job_pipeline_name));
                if(message.get(jenkins_event).equals(Events.JobChannel.job_run_queue_left.name())) {
                    assertionHelper.isEquals("1", message.get(blueocean_queue_item_expected_build_number));
                    assertionHelper.isNotNull(message.get(Job.job_run_queueId));
                    assertionHelper.isNotNull(message.get(Job.job_run_status));
                }
                assertionHelper.isEquals("pipeline1", message.get(job_name));
                assertionHelper.isEquals("job", message.get(jenkins_channel));
                assertionHelper.isEquals("jenkins", message.get(jenkins_org));
                assertionHelper.isNull(message.get(job_ismultibranch));
                assertionHelper.isNull(message.get(job_multibranch_indexing_result));
                assertionHelper.isNull(message.get(job_multibranch_indexing_status));

                if("job_run_unpaused".equals(message.get(jenkins_event))){
                    wasUnPaused[0] = true;
                }
            }else if("pipeline".equals(message.get(jenkins_channel))){
                assertionHelper.isEquals("1", message.get(pipeline_run_id));
                if(message.get(jenkins_event).equals(pipeline_stage.name())) {
                    assertionHelper.isEquals("build", message.get(pipeline_step_stage_name));
                }
                if("input".equals(message.get(pipeline_step_name))){
                    wasPaused[0] = true;
                    assertionHelper.isEquals("true", message.get(pipeline_step_is_paused));
                }
            }
            if(wasPaused[0] && wasUnPaused[0]){ // signal finish only when both conditions are met
                success.signal();
            }
        }
    });

    con.subscribe("pipeline");
    con.subscribe("job");

    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition(script, false));
    QueueTaskFuture<WorkflowRun> buildTask = job1.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    //Now that flow is paused, send a signal that it's un-paused
    ExtensionList<PipelineEventListener.InputStepPublisher> inputStepPublisherList =
            ExtensionList.lookup(PipelineEventListener.InputStepPublisher.class);
    assertFalse(inputStepPublisherList.isEmpty());

    InputAction inputAction = run.getAction(InputAction.class);
    List<InputStepExecution> executionList = inputAction.getExecutions();
    assertFalse(executionList.isEmpty());
    InputStep inputStep = executionList.get(0).getInput();
    inputStepPublisherList.get(0).onStepContinue(inputStep,run);

    success.block(5000);
    con.close();
    if(success.isSignaled()){
        assertTrue(wasPaused[0]);
        assertTrue(wasUnPaused[0]);
    }
    if(assertionHelper.totalErrors() > 0){
        fail("There were errors: "+ assertionHelper.totalErrors());
    }
}
 
Example 13
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());

}