类hudson.model.Result源码实例Demo

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

@Nonnull
public Set<Result> getTriggerDownstreamBuildsResultsCriteria() {
    Set<Result> result = new HashSet<>(5);
    if (this.triggerDownstreamUponResultSuccess)
        result.add(Result.SUCCESS);
    if (this.triggerDownstreamUponResultUnstable)
        result.add(Result.UNSTABLE);
    if (this.triggerDownstreamUponResultAborted)
        result.add(Result.ABORTED);
    if (this.triggerDownstreamUponResultNotBuilt)
        result.add(Result.NOT_BUILT);
    if (this.triggerDownstreamUponResultFailure)
        result.add(Result.FAILURE);

    return result;
}
 
@Test
public void readFileAndText() throws Exception {
    String file = writeCSV(getCSV());

    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
            "  def recordsString = \"key,value,attr\\na,b,c\\n1,2,3\\n\"\n" +
            "  List<CSVRecord> records = readCSV text: recordsString, file: '" + file + "'\n" +
            "  assert records.size() == 3\n" +
            "  assert records[0].get(0) == 'key'\n" +
            "  assert records[1].get(1) == 'b'\n" +
            "  assert records[2].get(2) == '3'\n" +
            "}", true));
    WorkflowRun run = p.scheduleBuild2(0).get();
    j.assertBuildStatus(Result.FAILURE, run);
    j.assertLogContains(Messages.ReadCSVStepExecution_tooManyArguments("readCSV"), run);
}
 
源代码3 项目: office-365-connector-plugin   文件: SampleIT.java
@Test
public void validateCompletedRequest_OnMultiplyWebhook_SendsSameData() {

    // given
    mockResult(Result.FAILURE);
    Office365ConnectorWebhookNotifier notifier = new Office365ConnectorWebhookNotifier(run, mockListener());
    mockProperty(run.getParent(), WebhookBuilder.sampleMultiplyWebhookWithAllStatuses());

    // when
    notifier.sendBuildCompletedNotification();

    // then
    assertThat(workerAnswer.getAllData()).hasSize(2);
    assertThat(workerAnswer.getAllData().get(0)).isEqualTo(workerAnswer.getAllData().get(1));
    assertThat(workerAnswer.getTimes()).isEqualTo(2);
}
 
@Test
public void createCompletedCard_OnFirstFailure_ReturnsCard() {

    // given
    Result result = Result.FAILURE;
    when(run.getResult()).thenReturn(result);

    // when
    Card card = cardBuilder.createCompletedCard(Collections.emptyList());

    // then
    assertThat(card.getSections()).hasSize(1);
    assertThat(card.getThemeColor()).isEqualTo(result.color.getHtmlBaseColor());
    Section section = card.getSections().get(0);
    assertThat(section.getActivityTitle()).isEqualTo("Notification from " + JOB_DISPLAY_NAME);
}
 
@Test
public void testConfigAllBlank() throws Exception {
    CodeBuilder test = new CodeBuilder("", "", "", "", "", null, "", "", "", "", "", "", "", "", "", "", "", "",
                                       "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
                                       "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");

    ArgumentCaptor<Result> savedResult = ArgumentCaptor.forClass(Result.class);
    test.perform(build, ws, launcher, listener, mockStepContext);

    verify(build).setResult(savedResult.capture());
    assertEquals(savedResult.getValue(), Result.FAILURE);
    assertEquals("Invalid log contents: " + log.toString(), log.toString().contains(CodeBuilder.configuredImproperlyError), true);
    CodeBuildResult result = test.getCodeBuildResult();
    assertEquals(CodeBuildResult.FAILURE, result.getStatus());
    assertTrue(result.getErrorMessage().contains(CodeBuilder.configuredImproperlyError));
}
 
源代码6 项目: warnings-ng-plugin   文件: EnvInjectPluginITest.java
/**
 * Make sure that a file pattern containing environment variables correctly matches the expected files.
 */
@Test
public void shouldResolveEnvVariablesInPattern() {
    FreeStyleProject project = createJavaWarningsFreestyleProject("**/*.${FILE_EXT}");

    injectEnvironmentVariables(project, "HELLO_WORLD=hello_test", "FILE_EXT=txt");

    createFileWithJavaWarnings("javac.txt", project, 1, 2, 3);
    createFileWithJavaWarnings("javac.csv", project, 1, 2);

    AnalysisResult analysisResult = scheduleBuildAndAssertStatus(project, Result.SUCCESS);

    assertThat(analysisResult).hasTotalSize(3);
    assertThat(analysisResult.getInfoMessages()).contains(String.format(
            "Searching for all files in '%s' that match the pattern '**/*.txt'", getWorkspace(project)));
    assertThat(analysisResult.getInfoMessages()).contains("-> found 1 file");
}
 
@Test
public void testSourceTypeOverrideException() throws Exception {
    CodeBuilder test = new CodeBuilder("keys", "id123", "host", "60", "a", awsSecretKey,
            "", "us-east-1", "existingProject", "sourceVersion", "",
            SourceControlType.ProjectSource.toString(), "", "", GitCloneDepth.One.toString(), BooleanValue.False.toString(),
            "", "", ArtifactsType.NO_ARTIFACTS.toString(), "", "", "", "", "", BooleanValue.False.toString(), BooleanValue.False.toString(), "",
            "[{k, v}]", "[{k, p}]", "buildspec.yml", "5", "invalidSourceType", "https://1.0.0.0.86/my_repo",
            EnvironmentType.LINUX_CONTAINER.toString(), "aws/codebuild/openjdk-8", ComputeType.BUILD_GENERAL1_SMALL.toString(), CacheType.NO_CACHE.toString(), "",
            LogsConfigStatusType.ENABLED.toString(), "group", "stream", LogsConfigStatusType.ENABLED.toString(), "", "location",
            "arn:aws:s3:::my_bucket/certificate.pem", "my_service_role", BooleanValue.False.toString(), BooleanValue.False.toString(), BooleanValue.False.toString(), "", "DISABLED", "");
    ArgumentCaptor<Result> savedResult = ArgumentCaptor.forClass(Result.class);
    test.perform(build, ws, launcher, listener, mockStepContext);

    verify(build).setResult(savedResult.capture());
    assertEquals(savedResult.getValue(), Result.FAILURE);
    assertEquals("Invalid log contents: " + log.toString(), log.toString().contains(CodeBuilderValidation.invalidSourceTypeError), true);
    CodeBuildResult result = test.getCodeBuildResult();
    assertEquals(CodeBuildResult.FAILURE, result.getStatus());
    assertTrue(result.getErrorMessage().contains(CodeBuilderValidation.invalidSourceTypeError));
}
 
源代码8 项目: warnings-ng-plugin   文件: JobActionITest.java
/**
 * Verifies that the aggregation trend chart is visible for a freestyle job at the top, or bottom, or hidden.
 */
@Test
public void shouldShowTrendsAndAggregationFreestyle() {
    FreeStyleProject project = createFreeStyleProjectWithWorkspaceFiles(ECLIPSE_LOG, CHECKSTYLE_XML);
    enableWarnings(project, createEclipse(), createCheckStyle());

    buildWithResult(project, Result.SUCCESS);
    Run<?, ?> build = buildWithResult(project, Result.SUCCESS);
    assertActionProperties(project, build);

    assertThatCheckstyleAndEclipseChartExist(project, true);
    assertThatAggregationChartExists(project, true);

    project = createAggregationJob(TrendChartType.TOOLS_AGGREGATION);
    assertThatCheckstyleAndEclipseChartExist(project, true);
    assertThatAggregationChartExists(project, true);

    project = createAggregationJob(TrendChartType.AGGREGATION_TOOLS);
    assertThatCheckstyleAndEclipseChartExist(project, true);
    assertThatAggregationChartExists(project, true);

    project = createAggregationJob(TrendChartType.TOOLS_ONLY);
    assertThatCheckstyleAndEclipseChartExist(project, true);
    assertThatAggregationChartDoesNotExists(project);
}
 
@Test
public void skipsPutJobResultWhenSkipPutJobFailureFlagIsSetInModel() {
    // given
    when(mockBuild.getResult()).thenReturn(Result.FAILURE);
    model.setActionTypeCategory("Build");
    model.setSkipPutJobResult(true);

    final List<Artifact> outputBuildArtifacts = new ArrayList<>();
    outputBuildArtifacts.add(new Artifact());
    outputBuildArtifacts.add(new Artifact());
    when(mockJobData.getOutputArtifacts()).thenReturn(outputBuildArtifacts);

    // when
    assertFalse(publisher.perform(mockBuild, null, null));

    // then
    final InOrder inOrder = inOrder(mockFactory, mockAWS, mockCodePipelineClient);
    inOrder.verify(mockFactory, never()).getAwsClient(ACCESS_KEY, SECRET_KEY, PROXY_HOST, PROXY_PORT, REGION, PLUGIN_VERSION);
    inOrder.verify(mockAWS, never()).getCodePipelineClient();

    final String expected = String.format(
            "[AWS CodePipeline Plugin] Skipping PutJobFailureResult call for the job with ID %s",
            model.getJob().getId());
    assertContainsIgnoreCase(expected, outContent.toString());
}
 
public PipelineNodeContainerImpl(WorkflowRun run, Link parentLink) {
    this.run = run;
    this.self = parentLink.rel("nodes");

    WorkflowJob job = run.getParent();
    NodeGraphBuilder graphBuilder = NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(run);

    //If build either failed or is in progress then return union with last successful pipeline run
    if (run.getResult() != Result.SUCCESS
        && job.getLastSuccessfulBuild() != null
        && Integer.parseInt(job.getLastSuccessfulBuild().getId()) < Integer.parseInt(run.getId())) {

        NodeGraphBuilder pastBuildGraph = NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(job.getLastSuccessfulBuild());
        this.nodes = graphBuilder.union(pastBuildGraph.getPipelineNodes(), getLink());
    } else {
        this.nodes = graphBuilder.getPipelineNodes(getLink());
    }
    for (BluePipelineNode node : nodes) {
        nodeMap.put(node.getId(), node);
    }
}
 
@Deprecated
@Test
public void listDownstreamJobs_upstream_pom_triggers_downstream_pipelines() {

    dao.getOrCreateBuildPrimaryKey("my-upstream-pom-pipeline-1", 1);
    dao.recordGeneratedArtifact("my-upstream-pom-pipeline-1", 1, "com.mycompany.pom", "parent-pom", "1.0-SNAPSHOT","pom", "1.0-SNAPSHOT", null, false, "pom", null);
    dao.updateBuildOnCompletion("my-upstream-pom-pipeline-1", 1, Result.SUCCESS.ordinal, System.currentTimeMillis() - 1111, 5);

    dao.getOrCreateBuildPrimaryKey("my-downstream-pipeline-1", 2);
    dao.recordParentProject("my-downstream-pipeline-1", 2, "com.mycompany.pom", "parent-pom", "1.0-SNAPSHOT", false);
    dao.updateBuildOnCompletion("my-downstream-pipeline-1", 2, Result.SUCCESS.ordinal, System.currentTimeMillis() - 555, 5);

    SqlTestsUtils.dump("select * from JENKINS_BUILD LEFT OUTER JOIN JENKINS_JOB ON JENKINS_BUILD.JOB_ID = JENKINS_JOB.ID", ds, System.out);
    SqlTestsUtils.dump("select * from MAVEN_ARTIFACT INNER JOIN GENERATED_MAVEN_ARTIFACT ON MAVEN_ARTIFACT.ID = GENERATED_MAVEN_ARTIFACT.ARTIFACT_ID", ds, System.out);
    SqlTestsUtils.dump("select * from MAVEN_ARTIFACT INNER JOIN MAVEN_PARENT_PROJECT ON MAVEN_ARTIFACT.ID = MAVEN_PARENT_PROJECT.ARTIFACT_ID", ds, System.out);

    List<String> downstreamJobs = dao.listDownstreamJobs("my-upstream-pom-pipeline-1", 1);
    assertThat(downstreamJobs, Matchers.containsInAnyOrder("my-downstream-pipeline-1"));
    System.out.println(downstreamJobs);
}
 
@Test
public void testGetCBClientExcepts() throws Exception {
    CodeBuilder test = createDefaultCodeBuilder();
    String error = "failed to instantiate cb client.";
    doThrow(new InvalidInputException(error)).when(mockFactory).getCodeBuildClient();
    ArgumentCaptor<Result> savedResult = ArgumentCaptor.forClass(Result.class);

    test.perform(build, ws, launcher, listener, mockStepContext);

    verify(build).setResult(savedResult.capture());
    assertEquals(savedResult.getValue(), Result.FAILURE);
    assertEquals("Invalid log contents: " + log.toString(), log.toString().contains(error), true);
    CodeBuildResult result = test.getCodeBuildResult();
    assertEquals(CodeBuildResult.FAILURE, result.getStatus());
    assertTrue(result.getErrorMessage().contains(error));
}
 
源代码13 项目: marathon-plugin   文件: MarathonStep.java
@Override
protected Void run() throws Exception {
    if (step.getAppid() != null && !step.getAppid().equals("")) {
        listener.getLogger().println("[Marathon] DEPRECATION WARNING: This configuration is using \"appid\" instead of \"id\". Please update this configuration.");
        step.setId(step.getAppid());
    }

    try {
        MarathonBuilder
                .getBuilder(step)
                .setEnvVars(envVars)
                .setWorkspace(ws)
                .read(step.filename)
                .build()
                .toFile()
                .update();
    } catch (MarathonException | MarathonFileInvalidException | MarathonFileMissingException me) {
        final String errorMsg = String.format("[Marathon] %s", me.getMessage());
        listener.error(errorMsg);
        run.setResult(Result.FAILURE);
    }

    return null;
}
 
@Override
public void perform(
        @Nonnull Run<?, ?> run,
        @Nonnull FilePath filePath,
        @Nonnull Launcher launcher,
        @Nonnull TaskListener taskListener) throws InterruptedException, IOException {

    Result result = run.getResult();

    boolean success  = result == Result.SUCCESS  && whenSuccess;
    boolean unstable = result == Result.UNSTABLE && whenUnstable;
    boolean failed   = result == Result.FAILURE  && whenFailed;
    boolean aborted  = result == Result.ABORTED  && whenAborted;

    boolean neededToSend = success || unstable || failed || aborted;

    if (neededToSend) {
        TelegramBotRunner.getInstance().getBot()
                .sendMessage(getMessage(), run, filePath, taskListener);
    }
}
 
@Test
public void testBuildThenWaitThenSuccess() throws Exception {
    Build inProgress = new Build().withBuildStatus(StatusType.IN_PROGRESS).withStartTime(new Date(1));
    Build succeeded = new Build().withBuildStatus(StatusType.SUCCEEDED.toString().toUpperCase()).withStartTime(new Date(2));
    when(mockClient.batchGetBuilds(any(BatchGetBuildsRequest.class))).thenReturn(
            new BatchGetBuildsResult().withBuilds(inProgress),
            new BatchGetBuildsResult().withBuilds(inProgress),
            new BatchGetBuildsResult().withBuilds(succeeded));
    CodeBuilder test = createDefaultCodeBuilder();
    ArgumentCaptor<Result> savedResult = ArgumentCaptor.forClass(Result.class);

    test.perform(build, ws, launcher, listener, mockStepContext);

    verify(build).setResult(savedResult.capture());
    assertEquals(savedResult.getValue(), Result.SUCCESS);
    CodeBuildResult result = test.getCodeBuildResult();
    assertEquals(CodeBuildResult.SUCCESS, result.getStatus());
}
 
protected void should_connect_agent(DockerTemplate template) throws IOException, ExecutionException, InterruptedException, TimeoutException {

        // FIXME on CI windows nodes don't have Docker4Windows
        Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);

        String dockerHost = SystemUtils.IS_OS_WINDOWS ? "tcp://localhost:2375" : "unix:///var/run/docker.sock";

        DockerCloud cloud = new DockerCloud(cloudName, new DockerAPI(new DockerServerEndpoint(dockerHost, null)),
                Collections.singletonList(template));

        j.jenkins.clouds.replaceBy(Collections.singleton(cloud));

        final FreeStyleProject project = j.createFreeStyleProject("test-docker-ssh");
        project.setAssignedLabel(Label.get(LABEL));
        project.getBuildersList().add(new Shell("whoami"));
        final QueueTaskFuture<FreeStyleBuild> scheduledBuild = project.scheduleBuild2(0);
        try {
            final FreeStyleBuild build = scheduledBuild.get(60L, TimeUnit.SECONDS);
            Assert.assertTrue(build.getResult() == Result.SUCCESS);
            Assert.assertTrue(build.getLog().contains("jenkins"));
        } finally {
            scheduledBuild.cancel(true);
        }
    }
 
源代码17 项目: warnings-ng-plugin   文件: RemoteApiITest.java
/** Verifies that the remote API for the tools aggregation correctly returns the summary. */
@Test
public void shouldReturnAggregation() {
    FreeStyleProject project = createFreeStyleProjectWithWorkspaceFiles("checkstyle1.xml", "checkstyle2.xml");
    enableWarnings(project, createCheckstyle("**/checkstyle1*"),
            configurePattern(new Pmd()), configurePattern(new SpotBugs()));
    Run<?, ?> build = buildWithResult(project, Result.SUCCESS);

    JSONWebResponse json = callJsonRemoteApi(build.getUrl() + "warnings-ng/api/json");
    JSONObject result = json.getJSONObject();

    assertThatJson(result).node("tools").isArray().hasSize(3);
    JSONArray tools = result.getJSONArray("tools");

    assertThatToolsContains(tools, "checkstyle", "CheckStyle Warnings", 3);
    assertThatToolsContains(tools, "pmd", "PMD Warnings", 0);
    assertThatToolsContains(tools, "spotbugs", "SpotBugs Warnings", 0);
}
 
@Test
@Issue({"JENKINS-54346", "JENKINS-55505"})
public void closed() throws Exception {
    rr.then(r -> {
        r.createSlave("remote", null, null);
        WorkflowJob p = r.createProject(WorkflowJob.class, "p");
        p.setDefinition(new CpsFlowDefinition(
                "node('remote') {\n" +
                        "  tee('x.log') {\n" +
                        "    echo 'first message'\n" +
                        "  }\n" +
                        "  if (isUnix()) {sh 'rm x.log'} else {bat 'del x.log'}\n" +
                        "  writeFile file: 'x.log', text: 'second message'\n" +
                        "  echo(/got: ${readFile('x.log').trim().replaceAll('\\\\s+', ' ')}/)\n" +
                        "}", true));
        WorkflowRun b = p.scheduleBuild2(0).waitForStart();
        r.assertBuildStatus(Result.SUCCESS, r.waitForCompletion(b));
        r.assertLogContains("got: second message", b);
    });
}
 
源代码19 项目: appcenter-plugin   文件: ProxyTest.java
@Test
public void should_SendRequestsToProxy_When_ProxyConfigurationFound() throws Exception {
    // Given
    jenkinsRule.jenkins.proxy = new ProxyConfiguration(proxyWebServer.getHostName(), proxyWebServer.getPort());
    MockWebServerUtil.enqueueSuccess(proxyWebServer);

    // When
    final FreeStyleBuild freeStyleBuild = freeStyleProject.scheduleBuild2(0).get();

    // Then
    jenkinsRule.assertBuildStatus(Result.SUCCESS, freeStyleBuild);
    assertThat(proxyWebServer.getRequestCount()).isEqualTo(4);
    assertThat(mockWebServer.getRequestCount()).isEqualTo(0);
}
 
@Test
public void createCompletedCard_OnFirstFailure_SkipsFailingSinceFact() {

    // given
    Result result = Result.FAILURE;
    when(run.getResult()).thenReturn(result);

    AbstractBuild previousBuild = mock(AbstractBuild.class);
    when(previousBuild.getResult()).thenReturn(Result.ABORTED);
    when(run.getPreviousBuild()).thenReturn(previousBuild);

    Run previousNotFailedBuild = mock(Run.class);
    int previousNotFailedBuildNumber = BUILD_NUMBER - 3;
    when(previousNotFailedBuild.getNumber()).thenReturn(previousNotFailedBuildNumber);
    when(previousNotFailedBuild.getNextBuild()).thenReturn(previousNotFailedBuild);
    when(run.getPreviousNotFailedBuild()).thenReturn(previousNotFailedBuild);

    // when
    Card card = cardBuilder.createCompletedCard(Collections.emptyList());

    // then
    assertThat(card.getSections()).hasSize(1);
    assertThat(card.getThemeColor()).isEqualTo(result.color.getHtmlBaseColor());
    Section section = card.getSections().get(0);
    assertThat(section.getActivityTitle()).isEqualTo("Notification from " + JOB_DISPLAY_NAME);
    FactAssertion.assertThatLast(section.getFacts(), 1);
    FactAssertion.assertThat(section.getFacts())
            .hasName(FactsBuilder.NAME_STATUS)
            .hasValue("Build Failed");
}
 
@Test
public void buildWithNullCredentialsIDMustFail() throws Exception {
    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "description: 'All tests are OK', repo: 'acceptance-test-harness', " +
                    "sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', status: 'SUCCESS', " +
                    "targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
@Test
public void isStatusMatched_OnResultNotBuild_ReturnsTrue() {

    // given
    DecisionMaker decisionMaker = buildSampleDecisionMaker(Result.NOT_BUILT);
    Webhook webhook = new Webhook("someUrl");

    // when
    boolean statusMatched = decisionMaker.isStatusMatched(webhook);

    // then
    assertThat(statusMatched).isFalse();
}
 
@Test
public void writeGStringWithoutApproval() throws Exception {
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "gstringjobnoapproval");
    p.setDefinition(new CpsFlowDefinition(
            "node('slaves') {\n" +
                    "  writeYaml file: 'test', data: \"${currentBuild.rawBuild}\" \n" +
                    "  def yml = readYaml file: 'test' \n" +
                    "  assert yml == 'gstringjob#1' \n"+
                    "}",
            true));
    WorkflowRun b = j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
    j.assertLogContains("Scripts not permitted to use method org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper getRawBuild", b);
}
 
源代码24 项目: sonar-quality-gates-plugin   文件: QGPublisherIT.java
@Test
public void testPerformShouldFail() throws Exception {
    setGlobalConfigDataAndJobConfigDataNames(TEST_NAME, TEST_NAME);
    doReturn(globalConfigDataForSonarInstance).when(buildDecision).chooseSonarInstance(globalConfig, jobConfigData);
    when(buildDecision.getStatus(globalConfigDataForSonarInstance, jobConfigData, listener)).thenReturn(true, false);
    jenkinsRule.assertBuildStatus(Result.FAILURE, buildProject(freeStyleProject));
    Run lastRun = freeStyleProject._getRuns().newestValue();
    jenkinsRule.assertLogContains("build passed: FALSE", lastRun);
}
 
源代码25 项目: blueocean-plugin   文件: GraphBuilderTest.java
@Test
@Issue("JENKINS-39203")
public void sillyLongName() throws Exception {
    WorkflowRun run = createAndRunJob("SillyLongName",
                                      "earlyUnstableStatusShouldReportPunStateAsRunningAndResultAsUnknown.jenkinsfile",
                                      Result.UNSTABLE);
    NodeGraphBuilder graph = NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(run);
    List<FlowNodeWrapper> nodes = graph.getPipelineNodes();

    assertStageAndEdges(nodes, "stage 1 marked as unstable", BlueRun.BlueRunState.FINISHED, BlueRun.BlueRunResult.UNSTABLE, "stage 2 wait");
    assertStageAndEdges(nodes, "stage 2 wait", BlueRun.BlueRunState.FINISHED, BlueRun.BlueRunResult.SUCCESS);

    assertEquals("Unexpected stages in graph", 2, nodes.size());
}
 
@Test
public void success_v3() throws IOException, InterruptedException {
    AbstractBuild build = mockBuild(GITLAB_CONNECTION_V3, Result.SUCCESS, "test/project.git");
    HttpRequest[] requests = prepareCheckCommitAndUpdateStatusRequests("v3", build, BuildState.success);

    performAndVerify(build, false, requests);
}
 
源代码27 项目: warnings-ng-plugin   文件: FilesScannerITest.java
/**
 * Runs the {@link FilesScanner} on a workspace with no files: the report should contain an error message.
 */
@Test
public void shouldReportErrorOnEmptyWorkspace() {
    FreeStyleProject project = createFreeStyleProject();
    enableCheckStyleWarnings(project);

    AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS);

    assertThat(result).hasTotalSize(0);
    assertThat(result).hasErrorMessages("No files found for pattern '**/*issues.txt'. Configuration error?");
}
 
源代码28 项目: rocket-chat-notifier   文件: ViewTracker.java
private Result getResult(View view) {
	Result ret = Result.SUCCESS;
	for (TopLevelItem item : view.getAllItems()) {
		for (Job<?,?> job : item.getAllJobs()) {
			Run<?, ?> build = job.getLastCompletedBuild();
			if(build != null) {
				Result result = build.getResult();
				if(result.isBetterOrEqualTo(Result.FAILURE)) 
					ret = ret.combine(result);
			}
		}
	}
	return ret;
}
 
源代码29 项目: warnings-ng-plugin   文件: ReferenceFinderITest.java
/**
 * Checks if the reference only looks at the eclipse result of a build and not the overall success. Should return an
 * success result.
 */
@Test
public void shouldCreateSuccessResultWithOverAllMustNotBeSuccess() {
    // #1 SUCCESS
    FreeStyleProject project = createJob(JOB_NAME, "eclipse2Warnings.txt");
    enableWarnings(project, recorder -> {
        recorder.setIgnoreFailedBuilds(false);
        recorder.setEnabledForFailure(true);
        recorder.addQualityGate(3, QualityGateType.NEW, QualityGateResult.UNSTABLE);
    });
    scheduleBuildAndAssertStatus(project, Result.SUCCESS,
            analysisResult -> assertThat(analysisResult).hasTotalSize(2)
                    .hasNewSize(0)
                    .hasQualityGateStatus(QualityGateStatus.PASSED));

    // #2 FAILURE
    cleanAndCopy(project, "eclipse4Warnings.txt");
    Builder failureStep = addFailureStep(project);
    Run<?, ?> expectedReference = scheduleBuildAndAssertStatus(project, Result.FAILURE,
            analysisResult -> assertThat(analysisResult).hasTotalSize(4)
                    .hasNewSize(2)
                    .hasQualityGateStatus(QualityGateStatus.PASSED)).getOwner();

    // #3 SUCCESS (Reference #2)
    cleanAndCopy(project, "eclipse6Warnings.txt");
    removeBuilder(project, failureStep);
    scheduleBuildAndAssertStatus(project, Result.SUCCESS, analysisResult -> assertThat(analysisResult)
            .hasTotalSize(6)
            .hasNewSize(2)
            .hasQualityGateStatus(QualityGateStatus.PASSED)
            .hasReferenceBuild(Optional.of(expectedReference)));
}
 
@Test
public void shouldRetrieveCorrectCredentialsFromVault() throws Exception {
    final String credentialsId = "cid1";
    final String secret = "S3CR3T";
    final String jobId = "testJob";

    VaultStringCredential up = mock(VaultStringCredential.class);
    when(up.getId()).thenReturn(credentialsId);
    when(up.getSecret()).thenReturn(Secret.fromString(secret));
    CredentialsProvider.lookupStores(jenkins.getInstance()).iterator().next()
        .addCredentials(Domain.global(), up);
    WorkflowJob p = jenkins.createProject(WorkflowJob.class, jobId);
    p.setDefinition(
        new CpsFlowDefinition(""
            + "node {\n"
            + " withCredentials([[$class: 'VaultStringCredentialBinding', credentialsId: '"
            + credentialsId
            + "', variable: 'SECRET']]) { "
            + "      " + getShellString() + " 'echo " + getVariable("SECRET")
            + " > secret.txt'\n"
            + "  }\n"
            + "}", true));
    WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b));
    jenkins.assertLogNotContains(secret, b);
    FilePath script = jenkins.getInstance().getWorkspaceFor(p).child("secret.txt");
    assertEquals(secret, script.readToString().trim());
}
 
 类所在包
 同包方法