Java Code Examples for org.jenkinsci.plugins.workflow.job.WorkflowRun#getAction()

The following examples show how to use org.jenkinsci.plugins.workflow.job.WorkflowRun#getAction() . 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: PipelineNodeGraphVisitor.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public PipelineNodeGraphVisitor(WorkflowRun run) {
    this.run = run;
    this.inputAction = run.getAction(InputAction.class);
    this.pipelineActions = new HashSet<>();
    this.pendingActionsForBranches = new HashMap<>();
    declarative = run.getAction(ExecutionModelAction.class) != null;
    FlowExecution execution = run.getExecution();
    if (execution != null) {
        try {
            ForkScanner.visitSimpleChunks(execution.getCurrentHeads(), this, new StageChunkFinder());
        } catch (final Throwable t) {
            // Log run ID, because the eventual exception handler (probably Stapler) isn't specific enough to do so
            logger.error("Caught a " + t.getClass().getSimpleName() +
                             " traversing the graph for run " + run.getExternalizableId());
            throw t;
        }
    } else {
        logger.debug("Could not find execution for run " + run.getExternalizableId());
    }
}
 
Example 2
Source File: BranchNameIssueKeyExtractor.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> extractIssueKeys(final WorkflowRun build) {
    // The action is only injected for Multibranch Pipeline jobs
    // The action is not injected for Pipeline (single branch) jobs
    final SCMRevisionAction scmAction = build.getAction(SCMRevisionAction.class);

    if (scmAction == null) {
        logger.debug("SCMRevisionAction is null");
        return Collections.emptySet();
    }

    final SCMRevision revision = scmAction.getRevision();
    final ScmRevision scmRevision = new ScmRevision(revision.getHead().getName());

    return extractIssueKeys(scmRevision);
}
 
Example 3
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 6 votes vote down vote up
@Test
public void singleStep() throws Exception {
    WorkflowJob j = rule.jenkins.createProject(WorkflowJob.class, "singleStep");
    j.setDefinition(new CpsFlowDefinition("stage('first') {\n" +
            "  node {\n" +
            "    def results = junit(testResults: '*.xml')\n" + // node id 7
            "    assert results.totalCount == 6\n" +
            "  }\n" +
            "}\n", true));
    FilePath ws = rule.jenkins.getWorkspaceFor(j);
    FilePath testFile = ws.child("test-result.xml");
    testFile.copyFrom(TestResultTest.class.getResource("junit-report-1463.xml"));

    WorkflowRun r = rule.buildAndAssertSuccess(j);
    TestResultAction action = r.getAction(TestResultAction.class);
    assertNotNull(action);
    assertEquals(1, action.getResult().getSuites().size());
    assertEquals(6, action.getTotalCount());

    assertExpectedResults(r, 1, 6, "7");

    // Case result display names shouldn't include stage, since there's only one stage.
    for (CaseResult c : action.getPassedTests()) {
        assertEquals(c.getTransformedTestName(), c.getDisplayName());
    }
}
 
Example 4
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 5 votes vote down vote up
private static TestResult assertBlockResults(WorkflowRun run, int suiteCount, int testCount, int failCount, BlockStartNode blockNode) {
    assertNotNull(blockNode);

    TestResultAction action = run.getAction(TestResultAction.class);
    assertNotNull(action);

    TestResult aResult = action.getResult().getResultForPipelineBlock(blockNode.getId());
    assertNotNull(aResult);

    assertEquals(suiteCount, aResult.getSuites().size());
    assertEquals(testCount, aResult.getTotalCount());
    assertEquals(failCount, aResult.getFailCount());
    if (failCount > 0) {
        assertThat(findJUnitSteps(blockNode), CoreMatchers.hasItem(hasWarningAction()));
    } else {
        assertThat(findJUnitSteps(blockNode), CoreMatchers.not(CoreMatchers.hasItem(hasWarningAction())));
    }

    PipelineBlockWithTests aBlock = action.getResult().getPipelineBlockWithTests(blockNode.getId());

    assertNotNull(aBlock);
    List<String> aTestNodes = new ArrayList<>(aBlock.nodesWithTests());
    TestResult aFromNodes = action.getResult().getResultByNodes(aTestNodes);
    assertNotNull(aFromNodes);
    assertEquals(aResult.getSuites().size(), aFromNodes.getSuites().size());
    assertEquals(aResult.getFailCount(), aFromNodes.getFailCount());
    assertEquals(aResult.getSkipCount(), aFromNodes.getSkipCount());
    assertEquals(aResult.getPassCount(), aFromNodes.getPassCount());

    return aResult;
}
 
Example 5
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-48196")
@Test
public void stageInParallel() throws Exception {
    WorkflowJob j = rule.jenkins.createProject(WorkflowJob.class, "stageInParallel");
    FilePath ws = rule.jenkins.getWorkspaceFor(j);
    FilePath testFile = ws.child("first-result.xml");
    testFile.copyFrom(TestResultTest.class.getResource("junit-report-1463.xml"));
    FilePath secondTestFile = ws.child("second-result.xml");
    secondTestFile.copyFrom(TestResultTest.class.getResource("junit-report-2874.xml"));
    FilePath thirdTestFile = ws.child("third-result.xml");
    thirdTestFile.copyFrom(TestResultTest.class.getResource("junit-report-nested-testsuites.xml"));

    j.setDefinition(new CpsFlowDefinition("stage('outer') {\n" +
            "  node {\n" +
            "    parallel(a: { stage('a') { def first = junit(testResults: 'first-result.xml'); assert first.totalCount == 6 }  },\n" +
            "             b: { stage('b') { def second = junit(testResults: 'second-result.xml'); assert second.totalCount == 1 } },\n" +
            "             c: { stage('d') { def third = junit(testResults: 'third-result.xml'); assert third.totalCount == 3 } })\n" +
            "  }\n" +
            "}\n", true
    ));
    WorkflowRun r = rule.assertBuildStatus(Result.UNSTABLE,
            rule.waitForCompletion(j.scheduleBuild2(0).waitForStart()));
    TestResultAction action = r.getAction(TestResultAction.class);
    assertNotNull(action);
    assertEquals(5, action.getResult().getSuites().size());
    assertEquals(10, action.getTotalCount());

    // assertBranchResults looks to make sure the display names for tests are "(stageName) / (branchName) / (testName)"
    // That should still effectively be the case here, even though there's a stage inside each branch, because the
    // branch and nested stage have the same name.
    assertBranchResults(r, 1, 6, 0, "a", "outer", null);
    assertBranchResults(r, 1, 1, 0, "b", "outer", null);
    // ...except for branch c. That contains a stage named 'd', so its test should have display names like
    // "outer / c / d / (testName)"
    assertBranchResults(r, 3, 3, 1, "c", "outer", "d");
}
 
Example 6
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@Test
public void parallelInStage() throws Exception {
    WorkflowJob j = rule.jenkins.createProject(WorkflowJob.class, "parallelInStage");
    FilePath ws = rule.jenkins.getWorkspaceFor(j);
    FilePath testFile = ws.child("first-result.xml");
    testFile.copyFrom(TestResultTest.class.getResource("junit-report-1463.xml"));
    FilePath secondTestFile = ws.child("second-result.xml");
    secondTestFile.copyFrom(TestResultTest.class.getResource("junit-report-2874.xml"));
    FilePath thirdTestFile = ws.child("third-result.xml");
    thirdTestFile.copyFrom(TestResultTest.class.getResource("junit-report-nested-testsuites.xml"));

    j.setDefinition(new CpsFlowDefinition("stage('first') {\n" +
            "  node {\n" +
            "    parallel(a: { def first = junit(testResults: 'first-result.xml'); assert first.totalCount == 6 },\n" +
            "             b: { def second = junit(testResults: 'second-result.xml'); assert second.totalCount == 1 },\n" +
            "             c: { def third = junit(testResults: 'third-result.xml'); assert third.totalCount == 3 })\n" +
            "  }\n" +
            "}\n", true
    ));
    WorkflowRun r = rule.assertBuildStatus(Result.UNSTABLE,
            rule.waitForCompletion(j.scheduleBuild2(0).waitForStart()));
    TestResultAction action = r.getAction(TestResultAction.class);
    assertNotNull(action);
    assertEquals(5, action.getResult().getSuites().size());
    assertEquals(10, action.getTotalCount());

    assertBranchResults(r, 1, 6, 0, "a", "first", null);
    assertBranchResults(r, 1, 1, 0, "b", "first", null);
    assertBranchResults(r, 3, 3, 1, "c", "first", null);
    assertStageResults(r, 5, 10, 1, "first");
}
 
Example 7
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 8
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 9
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 5 votes vote down vote up
@Test
public void twoSteps() throws Exception {
    WorkflowJob j = rule.jenkins.createProject(WorkflowJob.class, "twoSteps");
    j.setDefinition(new CpsFlowDefinition("stage('first') {\n" +
            "  node {\n" +
            "    def first = junit(testResults: 'first-result.xml')\n" +    // node id 7
            "    def second = junit(testResults: 'second-result.xml')\n" +  // node id 8
            "    assert first.totalCount == 6\n" +
            "    assert second.totalCount == 1\n" +
            "  }\n" +
            "}\n", true));
    FilePath ws = rule.jenkins.getWorkspaceFor(j);
    FilePath testFile = ws.child("first-result.xml");
    testFile.copyFrom(TestResultTest.class.getResource("junit-report-1463.xml"));
    FilePath secondTestFile = ws.child("second-result.xml");
    secondTestFile.copyFrom(TestResultTest.class.getResource("junit-report-2874.xml"));

    WorkflowRun r = rule.buildAndAssertSuccess(j);
    TestResultAction action = r.getAction(TestResultAction.class);
    assertNotNull(action);
    assertEquals(2, action.getResult().getSuites().size());
    assertEquals(7, action.getTotalCount());

    // First call
    assertExpectedResults(r, 1, 6, "7");

    // Second call
    assertExpectedResults(r, 1, 1, "8");

    // Combined calls
    assertExpectedResults(r, 2, 7, "7", "8");

    // Case result display names shouldn't include stage, since there's only one stage.
    for (CaseResult c : action.getPassedTests()) {
        assertEquals(c.getTransformedTestName(), c.getDisplayName());
    }
}
 
Example 10
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
private void verifyFileIsFingerPrinted(WorkflowJob pipeline, WorkflowRun build, String fileName) throws java.io.IOException {
    System.out.println(getClass() + " verifyFileIsFingerPrinted(" + build + ", " + fileName + ")");
    Fingerprinter.FingerprintAction fingerprintAction = build.getAction(Fingerprinter.FingerprintAction.class);
    Map<String, String> records = fingerprintAction.getRecords();
    System.out.println(getClass() + " records: " + records);
    String jarFileMd5sum = records.get(fileName);
    assertThat(jarFileMd5sum, not(nullValue()));

    Fingerprint jarFileFingerPrint = jenkinsRule.getInstance().getFingerprintMap().get(jarFileMd5sum);
    assertThat(jarFileFingerPrint.getFileName(), is(fileName));
    assertThat(jarFileFingerPrint.getOriginal().getJob().getName(), is(pipeline.getName()));
    assertThat(jarFileFingerPrint.getOriginal().getNumber(), is(build.getNumber()));
}
 
Example 11
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-27395")
@Test
public void maven_build_test_results_by_stage_and_branch() throws Exception {
    loadMavenJarProjectInGitRepo(this.gitRepoRule);

    String pipelineScript = "stage('first') {\n" +
            "    parallel(a: {\n" +
            "        node('master') {\n" +
            "            git($/" + gitRepoRule.toString() + "/$)\n" +
            "            withMaven() {\n" +
            "                sh 'mvn package verify'\n" +
            "            }\n" +
            "        }\n" +
            "    },\n" +
            "    b: {\n" +
            "        node('master') {\n" +
            "            git($/" + gitRepoRule.toString() + "/$)\n" +
            "            withMaven() {\n" +
            "                sh 'mvn package verify'\n" +
            "            }\n" +
            "        }\n" +
            "    })\n" +
            "}";

    WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master");
    pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
    WorkflowRun build = jenkinsRule.buildAndAssertSuccess(pipeline);

    TestResultAction testResultAction = build.getAction(TestResultAction.class);
    assertThat(testResultAction.getTotalCount(), is(4));
    assertThat(testResultAction.getFailCount(), is(0));

    /*
    TODO enable test below when we can bump the junit-plugin to version 1.23+
    JUnitResultsStepTest.assertStageResults(build, 4, 6, "first");

    JUnitResultsStepTest.assertBranchResults(build, 2, 3, "a", "first");
    JUnitResultsStepTest.assertBranchResults(build, 2, 3, "b", "first");
    */
}
 
Example 12
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
@Test
public void maven_build_jar_project_on_master_succeeds() throws Exception {
    loadMavenJarProjectInGitRepo(this.gitRepoRule);

    String pipelineScript = "node('master') {\n" +
            "    git($/" + gitRepoRule.toString() + "/$)\n" +
            "    withMaven() {\n" +
            "        sh 'mvn package verify'\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
    // "[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);

    Collection<String> artifactsFileNames = TestUtils.artifactsToArtifactsFileNames(build.getArtifacts());
    assertThat(artifactsFileNames, hasItems("mono-module-maven-app-0.1-SNAPSHOT.pom", "mono-module-maven-app-0.1-SNAPSHOT.jar"));

    verifyFileIsFingerPrinted(pipeline, build, "jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.jar");
    verifyFileIsFingerPrinted(pipeline, build, "jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.pom");

    //  verify Junit Archiver is called for maven-surefire-plugin
    jenkinsRule.assertLogContains("[withMaven] junitPublisher - Archive test results for Maven artifact jenkins.mvn.test:mono-module-maven-app:jar:0.1-SNAPSHOT " +
            "generated by maven-surefire-plugin:test", build);

    TestResultAction testResultAction = build.getAction(TestResultAction.class);
    assertThat(testResultAction.getTotalCount(), is(2));
    assertThat(testResultAction.getFailCount(), is(0));

    //  verify Junit Archiver is called for maven-failsafe-plugin
    jenkinsRule.assertLogContains("[withMaven] junitPublisher - Archive test results for Maven artifact jenkins.mvn.test:mono-module-maven-app:jar:0.1-SNAPSHOT " +
            "generated by maven-failsafe-plugin:integration-test", build);

    // verify Task Scanner is called for jenkins.mvn.test:mono-module-maven-app
    jenkinsRule.assertLogContains("[withMaven] openTasksPublisher - Scan Tasks for Maven artifact jenkins.mvn.test:mono-module-maven-app:jar:0.1-SNAPSHOT", build);
    TasksResultAction tasksResultAction = build.getAction(TasksResultAction.class);
    assertThat(tasksResultAction.getProjectActions().size(), is(1));
}
 
Example 13
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 4 votes vote down vote up
@Test
public void testTrends() throws Exception {
    WorkflowJob j = rule.jenkins.createProject(WorkflowJob.class, "testTrends");
    j.setDefinition(new CpsFlowDefinition("node {\n" +
            "  stage('first') {\n" +
            "    def first = junit(testResults: \"junit-report-testTrends-first.xml\")\n" +
            "  }\n" +
            "  stage('second') {\n" +
            "    def second = junit(testResults: \"junit-report-testTrends-second.xml\")\n" +
            "  }\n" +
            "}\n", true));
    FilePath ws = rule.jenkins.getWorkspaceFor(j);
    FilePath firstFile = ws.child("junit-report-testTrends-first.xml");
    FilePath secondFile = ws.child("junit-report-testTrends-second.xml");

    // Populate first run's tests.
    firstFile.copyFrom(JUnitResultsStepTest.class.getResource("junit-report-testTrends-first-1.xml"));
    secondFile.copyFrom(JUnitResultsStepTest.class.getResource("junit-report-testTrends-second-1.xml"));

    WorkflowRun firstRun = rule.buildAndAssertSuccess(j);
    assertStageResults(firstRun, 1, 8, 0, "first");
    assertStageResults(firstRun, 1, 1, 0, "second");

    // Populate second run's tests.
    firstFile.copyFrom(JUnitResultsStepTest.class.getResource("junit-report-testTrends-first-2.xml"));
    secondFile.copyFrom(JUnitResultsStepTest.class.getResource("junit-report-testTrends-second-2.xml"));

    WorkflowRun secondRun = rule.assertBuildStatus(Result.UNSTABLE, rule.waitForCompletion(j.scheduleBuild2(0).waitForStart()));
    assertStageResults(secondRun, 1, 8, 3, "first");
    assertStageResults(secondRun, 1, 1, 0, "second");

    // Populate third run's tests
    firstFile.copyFrom(JUnitResultsStepTest.class.getResource("junit-report-testTrends-first-3.xml"));
    secondFile.copyFrom(JUnitResultsStepTest.class.getResource("junit-report-testTrends-second-3.xml"));

    WorkflowRun thirdRun = rule.assertBuildStatus(Result.UNSTABLE, rule.waitForCompletion(j.scheduleBuild2(0).waitForStart()));
    assertStageResults(thirdRun, 1, 8, 3, "first");
    assertStageResults(thirdRun, 1, 1, 0, "second");
    TestResultAction thirdAction = thirdRun.getAction(TestResultAction.class);
    assertNotNull(thirdAction);

    for (CaseResult failed : thirdAction.getFailedTests()) {
        if (failed.getDisplayName() != null) {
            if (failed.getDisplayName().equals("first / testGetVendorFirmKeyForVendorRep")) {
                assertEquals("first / org.twia.vendor.VendorManagerTest.testGetVendorFirmKeyForVendorRep",
                        failed.getFullDisplayName());
                assertEquals(2, failed.getFailedSince());
            } else if (failed.getDisplayName().equals("first / testCreateAdjustingFirm")) {
                assertEquals("first / org.twia.vendor.VendorManagerTest.testCreateAdjustingFirm",
                        failed.getFullDisplayName());
                assertEquals(2, failed.getFailedSince());
            } else if (failed.getDisplayName().equals("first / testCreateVendorFirm")) {
                assertEquals("first / org.twia.vendor.VendorManagerTest.testCreateVendorFirm",
                        failed.getFullDisplayName());
                assertEquals(3, failed.getFailedSince());
            } else {
                fail("Failed test displayName " + failed.getDisplayName() + " is unexpected.");
            }
        }
    }
}
 
Example 14
Source File: JUnitResultsStepTest.java    From junit-plugin with MIT License 4 votes vote down vote up
@Test
public void threeSteps() throws Exception {
    WorkflowJob j = rule.jenkins.createProject(WorkflowJob.class, "threeSteps");
    j.setDefinition(new CpsFlowDefinition("stage('first') {\n" +
            "  node {\n" +
            "    def first = junit(testResults: 'first-result.xml')\n" +    // node id 7
            "    def second = junit(testResults: 'second-result.xml')\n" +  // node id 8
            "    def third = junit(testResults: 'third-result.xml')\n" +    // node id 9
            "    assert first.totalCount == 6\n" +
            "    assert second.totalCount == 1\n" +
            "  }\n" +
            "}\n", true));
    FilePath ws = rule.jenkins.getWorkspaceFor(j);
    FilePath testFile = ws.child("first-result.xml");
    testFile.copyFrom(TestResultTest.class.getResource("junit-report-1463.xml"));
    FilePath secondTestFile = ws.child("second-result.xml");
    secondTestFile.copyFrom(TestResultTest.class.getResource("junit-report-2874.xml"));
    FilePath thirdTestFile = ws.child("third-result.xml");
    thirdTestFile.copyFrom(TestResultTest.class.getResource("junit-report-nested-testsuites.xml"));

    WorkflowRun r = rule.assertBuildStatus(Result.UNSTABLE,
            rule.waitForCompletion(j.scheduleBuild2(0).waitForStart()));
    TestResultAction action = r.getAction(TestResultAction.class);
    assertNotNull(action);
    assertEquals(5, action.getResult().getSuites().size());
    assertEquals(10, action.getTotalCount());

    // First call
    assertExpectedResults(r, 1, 6, "7");

    // Second call
    assertExpectedResults(r, 1, 1, "8");

    // Third call
    assertExpectedResults(r, 3, 3, "9");

    // Combined first and second calls
    assertExpectedResults(r, 2, 7, "7", "8");

    // Combined first and third calls
    assertExpectedResults(r, 4, 9, "7", "9");

    // Case result display names shouldn't include stage, since there's only one stage.
    for (CaseResult c : action.getPassedTests()) {
        assertEquals(c.getTransformedTestName(), c.getDisplayName());
    }
}
 
Example 15
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 16
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void getMultiBranchPipelineActivityRuns() 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());
    }
    scheduleAndFindBranchProject(mp);
    j.waitUntilNoActivity();

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

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

    //execute feature/ux-1 branch build
    p = findBranchProject(mp, "feature%2Fux-1");
    WorkflowRun b2 = p.getLastBuild();
    assertEquals(1, b2.getNumber());


    //execute feature 2 branch build
    p = findBranchProject(mp, "feature2");
    WorkflowRun b3 = p.getLastBuild();
    assertEquals(1, b3.getNumber());


    List<Map> resp = get("/organizations/jenkins/pipelines/p/runs", List.class);
    Assert.assertEquals(3, resp.size());
    Date d1 = new SimpleDateFormat(DATE_FORMAT_STRING).parse((String)resp.get(0).get("startTime"));
    Date d2 = new SimpleDateFormat(DATE_FORMAT_STRING).parse((String)resp.get(1).get("startTime"));
    Date d3 = new SimpleDateFormat(DATE_FORMAT_STRING).parse((String)resp.get(2).get("startTime"));

    Assert.assertTrue(d1.compareTo(d2) >= 0);
    Assert.assertTrue(d2.compareTo(d3) >= 0);

    for(Map m: resp){
        BuildData d;
        WorkflowRun r;
        if(m.get("pipeline").equals("master")){
            r = b1;
            d = b1.getAction(BuildData.class);
        } else if(m.get("pipeline").equals("feature2")){
            r = b3;
            d = b3.getAction(BuildData.class);
        } else{
            r = b2;
            d = b2.getAction(BuildData.class);
        }
        validateRun(r,m);
        String commitId = "";
        if(d != null) {
            commitId = d.getLastBuiltRevision().getSha1String();
            Assert.assertEquals(commitId, m.get("commitId"));
        }
    }
}
 
Example 17
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 18
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 19
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 20
Source File: PipelineStepVisitor.java    From blueocean-plugin with MIT License 4 votes vote down vote up
public PipelineStepVisitor(WorkflowRun run, @Nullable final FlowNode node) {
    this.node = node;
    this.run = run;
    this.inputAction = run.getAction(InputAction.class);
}