@Test public void junitResultArchiver() throws Exception { WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " writeFile text: '''<testsuite name='a'><testcase name='a1'/><testcase name='a2'><error>a2 failed</error></testcase></testsuite>''', file: 'a.xml'\n" + " writeFile text: '''<testsuite name='b'><testcase name='b1'/><testcase name='b2'/></testsuite>''', file: 'b.xml'\n" + " junit '*.xml'\n" + "}", true)); WorkflowRun b = r.assertBuildStatus(Result.UNSTABLE, p.scheduleBuild2(0).get()); TestResultAction a = b.getAction(TestResultAction.class); assertNotNull(a); assertEquals(4, a.getTotalCount()); assertEquals(1, a.getFailCount()); List<FlowNode> coreStepNodes = new DepthFirstScanner().filteredNodes(b.getExecution(), new NodeStepTypePredicate("step")); assertThat(coreStepNodes, Matchers.hasSize(1)); assertEquals("*.xml", ArgumentsAction.getStepArgumentsAsString(coreStepNodes.get(0))); }
public static boolean isRelevant(OTCNotifier notifier, String phase, Result result){ boolean onStarted; boolean onCompleted; boolean onFinalized; boolean failureOnly; //Make sure OTC Notifier was found in the publisherList if(notifier != null){ onStarted = notifier.getOnStarted(); onCompleted = notifier.getOnCompleted(); onFinalized = notifier.getOnFinalized(); failureOnly = notifier.getFailureOnly(); if(onStarted && "STARTED".equals(phase) || onCompleted && "COMPLETED".equals(phase) || onFinalized && "FINALIZED".equals(phase)){//check selections if(failureOnly && result != null && result.equals(Result.FAILURE) || !failureOnly){//check failureOnly return true; } } } return false; }
@Override public void onFailure(StepContext context, Throwable t) { try { TaskListener listener = context.get(TaskListener.class); Result r = Result.FAILURE; if (t instanceof AbortException) { listener.error(t.getMessage()); } else if (t instanceof FlowInterruptedException) { FlowInterruptedException fie = (FlowInterruptedException) t; fie.handle(context.get(Run.class), listener); r = fie.getResult(); } else { listener.getLogger().println(Functions.printThrowable(t).trim()); // TODO 2.43+ use Functions.printStackTrace } context.get(Run.class).setResult(r); context.onSuccess(null); } catch (Exception x) { context.onFailure(x); } }
@Test public void failure() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("waitUntil {semaphore 'wait'}", true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); SemaphoreStep.waitForStart("wait/1", b); SemaphoreStep.success("wait/1", false); SemaphoreStep.waitForStart("wait/2", b); String message = "broken condition"; SemaphoreStep.failure("wait/2", new AbortException(message)); // TODO the following fails (missing message) when run as part of whole suite, but not standalone: story.j.assertLogContains(message, story.j.assertBuildStatus(Result.FAILURE, story.j.waitForCompletion(b))); story.j.waitForCompletion(b); story.j.assertBuildStatus(Result.FAILURE, b); story.j.assertLogContains(message, b); // TODO observed to flake on windows-8-2.32.3: see two `semaphore`s and a “Will try again after 0.25 sec” but no such message } }); }
@Issue("JENKINS-41276") @Test public void abortShouldNotRetry() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "int count = 0; retry(3) { echo 'trying '+(count++); semaphore 'start'; echo 'NotHere' } echo 'NotHere'", true)); final WorkflowRun b = p.scheduleBuild2(0).waitForStart(); SemaphoreStep.waitForStart("start/1", b); ACL.impersonate(User.get("dev").impersonate(), new Runnable() { @Override public void run() { b.getExecutor().doStop(); } }); r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b)); r.assertLogContains("trying 0", b); r.assertLogContains("Aborted by dev", b); r.assertLogNotContains("trying 1", b); r.assertLogNotContains("trying 2", b); r.assertLogNotContains("NotHere", b); }
@Test public void toolWithoutSymbol() throws Exception { File toolHome = folder.newFolder("mockTools"); MockToolWithoutSymbol tool = new MockToolWithoutSymbol("mock-tool-without-symbol", toolHome.getAbsolutePath(), JenkinsRule.NO_PROPERTIES); Jenkins.getInstance().getDescriptorByType(MockToolWithoutSymbol.MockToolWithoutSymbolDescriptor.class).setInstallations(tool); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("node {def home = tool name: '" + tool.getName() + "', type: 'mockToolWithoutSymbol'}", true)); r.assertLogContains("No mockToolWithoutSymbol named mock-tool-without-symbol found", r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0))); p.setDefinition(new CpsFlowDefinition("node {def home = tool name: '" + tool.getName() + "', type: '" + MockToolWithoutSymbol.class.getName() + "'\n" + "echo \"${home}\"}", true)); r.assertLogContains(toolHome.getAbsolutePath(), r.assertBuildStatusSuccess(p.scheduleBuild2(0))); }
@Test public void specialStatus() throws Exception { User.get("smrt"); WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "catchError {\n" + " semaphore 'specialStatus'\n" + "}", true)); SemaphoreStep.failure("specialStatus/1", new FlowInterruptedException(Result.UNSTABLE, new CauseOfInterruption.UserInterruption("smrt"))); WorkflowRun b = p.scheduleBuild2(0).get(); r.assertLogContains("smrt", r.assertBuildStatus(Result.UNSTABLE, b)); /* TODO fixing this is trickier since CpsFlowExecution.setResult does not implement a public method, and anyway CatchErrorStep in its current location could not refer to FlowExecution: List<FlowNode> heads = b.getExecution().getCurrentHeads(); assertEquals(1, heads.size()); assertEquals(Result.UNSTABLE, ((FlowEndNode) heads.get(0)).getResult()); */ }
@Test public void downstreamJobTriggerByRestrictedUser() throws Exception { String allowedUsername = "foo"; UserSelector selector = new UserSelector(allowedUsername); JobRestriction restriction = new StartedByUserRestriction(singletonList(selector), false, false, false); setUpDiskPoolRestriction(restriction); authenticate(allowedUsername); WorkflowRun upstreamRun = createWorkflowJobAndRun(); j.assertBuildStatusSuccess(upstreamRun); j.assertLogContains(format("Selected Disk ID '%s' from the Disk Pool ID '%s'", DISK_ID_ONE, DISK_POOL_ID), upstreamRun); String notAllowedUsername = "bar"; authenticate(notAllowedUsername); WorkflowJob downstreamJob = j.jenkins.createProject(WorkflowJob.class, randomAlphanumeric(7)); downstreamJob.setDefinition(new CpsFlowDefinition(format("" + "def run = selectRun '%s' \n" + "exwsAllocate selectedRun: run", upstreamRun.getParent().getFullName()))); WorkflowRun downstreamRun = downstreamJob.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause())).get(); j.assertBuildStatus(Result.FAILURE, downstreamRun); j.assertLogContains(format("Disk Pool identified by '%s' is not accessible due to the applied Disk Pool restriction: Started By User", DISK_POOL_ID), downstreamRun); }
@Test public void notAllowedGroup() throws Exception { String username = "foobar"; String group = "allowed"; GroupSelector groupSelector = new GroupSelector("not-allowed-group"); JobRestriction restriction = new StartedByMemberOfGroupRestriction(singletonList(groupSelector), false); setUpDiskPoolRestriction(restriction); JenkinsRule.DummySecurityRealm securityRealm = j.createDummySecurityRealm(); securityRealm.addGroups(username, group); j.jenkins.setSecurityRealm(securityRealm); authenticate(username); WorkflowRun run = createWorkflowJobAndRun(); j.assertBuildStatus(Result.FAILURE, run); j.assertLogContains(format("Disk Pool identified by '%s' is not accessible due to the applied Disk Pool restriction: Started By member of group", DISK_POOL_ID), run); }
@Test @Parameters({"fastestWriteSpeed(estimatedWorkspaceSize: 300)", "[$class: 'FastestWriteSpeedStrategy'\\, estimatedWorkspaceSize: 300]"}) public void diskHasNotEnoughUsableSpace(String strategy) throws Exception { // The Disk mounting point parameter isn't an actual mount. // Therefore, the disk's usable space will be 0, and the job will fail as expected Disk disk = new Disk("disk", null, "not-an-actual-mounting-point", null, null); DiskPool diskPool = TestUtil.createDiskPool(disk); TestUtil.setUpDiskPools(j.jenkins, diskPool); long estimatedWorkspaceSize = 300; WorkflowRun run = TestUtil.createWorkflowJobAndRun(j.jenkins, format("" + "exwsAllocate diskPoolId: '%s', " + " strategy: %s", diskPool.getDiskPoolId(), strategy)); j.assertBuildStatus(Result.FAILURE, run); j.assertLogContains(format("Using Disk allocation strategy: '%s'", new FastestWriteSpeedStrategy().getDescriptor().getDisplayName()), run); j.assertLogContains(format("Couldn't find any Disk with at least %s MB usable space", estimatedWorkspaceSize), run); }
private String runToBuildPhase(Run run) { if (run != null && !run.hasntStartedYet()) { if (run.isBuilding()) { return BuildPhases.RUNNING; } else { Result result = run.getResult(); if (result != null) { if (result.equals(Result.SUCCESS)) { return BuildPhases.COMPLETE; } else if (result.equals(Result.ABORTED)) { return BuildPhases.CANCELLED; } else if (result.equals(Result.FAILURE)) { return BuildPhases.FAILED; } else if (result.equals(Result.UNSTABLE)) { return BuildPhases.FAILED; } else { return BuildPhases.PENDING; } } } } return BuildPhases.NEW; }
@Test public void testBuildThenWaitThenSuccess() throws Exception { setUpBuildEnvironment(); 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); verify(build).setResult(savedResult.capture()); assertEquals(savedResult.getValue(), Result.SUCCESS); }
@Test public void testBuildThenWaitThenFails() throws Exception { setUpBuildEnvironment(); Build inProgress = new Build().withBuildStatus(StatusType.IN_PROGRESS).withStartTime(new Date(1)); Build failed = new Build().withBuildStatus(StatusType.FAILED).withStartTime(new Date(2)); when(mockClient.batchGetBuilds(any(BatchGetBuildsRequest.class))).thenReturn( new BatchGetBuildsResult().withBuilds(inProgress), new BatchGetBuildsResult().withBuilds(inProgress), new BatchGetBuildsResult().withBuilds(failed)); CodeBuilder test = createDefaultCodeBuilder(); ArgumentCaptor<Result> savedResult = ArgumentCaptor.forClass(Result.class); test.perform(build, ws, launcher, listener); verify(build).setResult(savedResult.capture()); assertEquals(savedResult.getValue(), Result.FAILURE); }
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { try { GoogleRobotCredentials credentials = GoogleRobotCredentials.getById(getCredentialsId()); GoogleDriveManager driveManager = new GoogleDriveManager(authorize(credentials)); String pattern = Util.replaceMacro(getPattern(), build.getEnvironment(listener)); String workspace = build.getWorkspace().getRemote(); String[] filesToUpload = listFiles(workspace, pattern); for (String file : filesToUpload) { listener.getLogger().println("Uploading file: " + file); driveManager.store(file, getDriveLocation()); } } catch (GeneralSecurityException e) { build.setResult(Result.FAILURE); return false; } return true; }
@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; }
@Test public void performDeployTest() throws Exception { configFilePath.write(CONFIG_FILE_CONTENTS, "UTF-8"); importPaths.get(0).write(TEMPLATE1_CONTENTS, "UTF-8"); importPaths.get(1).write(TEMPLATE2_CONTENTS, "UTF-8"); // Hand the deployer a special builder that will intercept executions { executor.when(DeploymentManager.Deployments.Insert.class, newRunningOperation()); executor.when(DeploymentManager.Operations.Get.class, newRunningOperation()); executor.when(DeploymentManager.Operations.Get.class, newDoneOperation()); executor.when(DeploymentManager.Deployments.Delete.class, newDoneOperation()); } String remoteImportPaths = PathUtils.toRemotePaths(importPaths); GoogleCloudManagerBuildWrapper deployer = new GoogleCloudManagerBuildWrapper( getNewTestingTemplatedCloudDeployment(credentials.getId(), DEPLOYMENT_NAME, configFilePath.getRemote(), remoteImportPaths, new MockPluginModule(executor))); project.getBuildWrappersList().add(deployer); FreeStyleBuild build = project.scheduleBuild2(0).get(); dumpLog(build); assertEquals(Result.SUCCESS, build.getResult()); }
@Test public void performDeployWithIOExceptionDuringDeleteTest() throws Exception { configFilePath.write(CONFIG_FILE_CONTENTS, "UTF-8"); importPaths.get(0).write(TEMPLATE1_CONTENTS, "UTF-8"); importPaths.get(1).write(TEMPLATE2_CONTENTS, "UTF-8"); // Hand the deployer a special builder that will intercept executions { executor.when(DeploymentManager.Deployments.Insert.class, newDoneOperation()); executor.throwWhen(DeploymentManager.Deployments.Delete.class, new IOException("test")); } GoogleCloudManagerBuildWrapper deployer = new GoogleCloudManagerBuildWrapper(getNewTestingTemplatedCloudDeployment( credentials.getId(), DEPLOYMENT_NAME, configFilePath.getRemote(), PathUtils.toRemotePaths(importPaths), new MockPluginModule(executor))); project.getBuildWrappersList().add(deployer); FreeStyleBuild build = project.scheduleBuild2(0).get(); dumpLog(build); assertEquals(Result.FAILURE, build.getResult()); }
@Test public void performDeployTest() throws Exception { configFilePath.write(CONFIG_FILE_CONTENTS, "UTF-8"); importPaths.get(0).write(TEMPLATE1_CONTENTS, "UTF-8"); importPaths.get(1).write(TEMPLATE2_CONTENTS, "UTF-8"); // Hand the deployer a special builder that will intercept executions executor.when(DeploymentManager.Deployments.Insert.class, newRunningOperation()); executor.when(DeploymentManager.Operations.Get.class, newRunningOperation()); executor.when(DeploymentManager.Operations.Get.class, newDoneOperation()); GoogleCloudManagerDeployer deployer = new GoogleCloudManagerDeployer(getNewTestingTemplatedCloudDeployment(credentials.getId(), DEPLOYMENT_NAME, configFilePath.getRemote(), PathUtils.toRemotePaths(importPaths), new MockPluginModule(executor))); project.getPublishersList().add(deployer); FreeStyleBuild build = project.scheduleBuild2(0).get(); assertEquals(Result.SUCCESS, build.getResult()); }
@Test public void getEnvironmentExceptionTest() throws Exception { GoogleCloudManagerDeployer deployer = new GoogleCloudManagerDeployer(getNewTestingTemplatedCloudDeployment(credentials.getId(), DEPLOYMENT_NAME, CONFIG_FILE, PathUtils.toRemotePaths(importPaths), null)); BuildListener listener = mock(BuildListener.class); PrintStream printStream = new PrintStream(new ByteArrayOutputStream()); when(listener.getLogger()).thenReturn(printStream); when(listener.error(any(String.class))).thenReturn(new PrintWriter(printStream)); AbstractBuild build = mock(AbstractBuild.class); when(build.getResult()).thenReturn(Result.SUCCESS); when(build.getEnvironment(listener)).thenThrow(new IOException("test")); // Check that we failed the build step due to a failure to retrieve // the environment. assertFalse(deployer.perform(build, null, listener)); }
@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 maven_build_on_master_with_specified_maven_installation_succeeds() throws Exception { loadMavenJarProjectInGitRepo(this.gitRepoRule); String pipelineScript = "node('master') {\n" + " git($/" + gitRepoRule.toString() + "/$)\n" + " withMaven(maven: 'apache-maven-3.5.0') {\n" + " sh 'mvn package'\n" + " }\n" + "}"; WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "build-on-master-with-tool-provided-maven"); pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true)); WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0)); // verify provided Maven is used jenkinsRule.assertLogContains("use Maven installation 'apache-maven-3.5.0'", build); // verify .pom is archived and fingerprinted // "[withMaven] Archive ... under jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.pom" jenkinsRule.assertLogContains("under jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.pom", build); // verify .jar is archived and fingerprinted jenkinsRule.assertLogContains("under jenkins/mvn/test/mono-module-maven-app/0.1-SNAPSHOT/mono-module-maven-app-0.1-SNAPSHOT.jar", build); }
/** * JENKINS-43678 */ @Test public void maven_build_on_master_with_no_generated_jar_succeeds() throws Exception { loadMavenJarProjectInGitRepo(this.gitRepoRule); String pipelineScript = "node('master') {\n" + " git($/" + gitRepoRule.toString() + "/$)\n" + " withMaven() {\n" + " sh 'mvn test'\n" + " }\n" + "}"; WorkflowJob pipeline = jenkinsRule.createProject(WorkflowJob.class, "test-on-master"); pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true)); WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0)); // don't try to archive the artifact as it has not been generated jenkinsRule.assertLogNotContains("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")); assertThat(build.getArtifacts().toString(), build.getArtifacts().size(), is(1)); }
public void testGetProjectActionHavingLastBuildGivesStarWarsAction() { AbstractProject mockProject = mock(AbstractProject.class); Build mockBuild = mock(Build.class); Quote expectedQuote = generateQuote(StarWarsResult.SUCCESS); when(mockProject.getLastBuild()).thenReturn(mockBuild); when(mockBuild.getResult()).thenReturn(Result.SUCCESS); when(mockQuotesGenerator.generate(StarWarsResult.SUCCESS)).thenReturn(expectedQuote); Action action = recorder.getProjectAction(mockProject); assertTrue(action instanceof StarWarsAction); assertEquals(StarWarsResult.SUCCESS, ((StarWarsAction) action).getResult()); assertNotNull(((StarWarsAction) action).getQuote()); }
public void testPerformWithFailureResultAddsStarWarsActionWithFailResultAndExpectedQuote() throws Exception { List<Action> actions = new ArrayList<Action>(); Quote expectedQuote = generateQuote(StarWarsResult.FAIL); AbstractBuild mockBuild = mock(AbstractBuild.class); when(mockBuild.getResult()).thenReturn(Result.FAILURE); when(mockBuild.getActions()).thenReturn(actions); mockQuotesGenerator.add(expectedQuote); when(mockQuotesGenerator.generate(StarWarsResult.FAIL)).thenReturn(expectedQuote); assertEquals(0, actions.size()); Launcher mockLauncher = mock(Launcher.class); BuildListener mockBuildListener = mock(BuildListener.class); recorder.perform(mockBuild, mockLauncher, mockBuildListener); assertEquals(1, actions.size()); assertTrue(actions.get(0) instanceof StarWarsAction); StarWarsAction action = (StarWarsAction) actions.get(0); assertEquals(StarWarsResult.FAIL, action.getResult()); assertEquals(expectedQuote, action.getQuote()); }
@Override public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { // return early if label not required if (onlyOnSuccess && run.getResult() != Result.SUCCESS) { return; } try { // Expand label name and description EnvVars env = run.getEnvironment(listener); Expand expand = new Expand(env); String name = expand.format(rawLabelName, false); String description = expand.format(rawLabelDesc, false); // Get TagAction and check for promoted builds TagAction tagAction = getTagAction(env, run); // Label with TagAction tagAction.labelBuild(listener, name, description, workspace); } catch (Exception e) { final String err = "P4: Could not label: " + e; log(err); throw new AbortException(err); } }
private String getRunStatus(AbstractBuild<?, ?> theBuild) { Result result = theBuild.getResult(); if (result != null) { if (result.isBetterOrEqualTo(Result.SUCCESS)) { return "PASSED"; } else if (result.isBetterOrEqualTo(Result.UNSTABLE)) { return "WARNING"; } else if (result.equals(Result.ABORTED)) { return "INTERRUPTED"; } else { return "FAILED"; } } else { return "FAILED"; } }
private String generateCustomizedMessage(AbstractBuild<?, ?> build) { GhprcTrigger trigger = Ghprc.extractTrigger(build); if (trigger == null) { return ""; } JobConfiguration jobConfiguration = JobConfiguration.builder() .printStackTrace(trigger.isDisplayBuildErrorsOnDownstreamBuilds()).build(); GhprcBuildManager buildManager = GhprcBuildManagerFactoryUtil.getBuildManager(build, jobConfiguration); StringBuilder sb = new StringBuilder(); sb.append(buildManager.calculateBuildUrl(publishedURL)); if (build.getResult() != Result.SUCCESS) { sb.append(buildManager.getTestResults()); } return sb.toString(); }
@Test public void testPostUnitWithFailure() throws Exception { TestUtils.addCopyBuildStep(p, TestUtils.JUNIT_XML, JUnitTestProvider.class, "go-torch-junit-fail.xml"); p.getPublishersList().add(TestUtils.getDefaultXUnitPublisher()); FreeStyleBuild build = buildWithConduit(getFetchDiffResponse(), null, new JSONObject()); assertEquals(Result.UNSTABLE, build.getResult()); assertLogContains("Publishing unit results to Harbormaster for 8 tests", build); FakeConduit conduitTestClient = getConduitClient(); // There are two requests, first it fetches the diff info, secondly it posts the unit result to harbormaster assertEquals(2, conduitTestClient.getRequestBodies().size()); String actualUnitResultWithFailureRequestBody = conduitTestClient.getRequestBodies().get(1); assertConduitRequest(getUnitResultWithFailureRequest(), actualUnitResultWithFailureRequestBody); }
@Test public void pickFirstErrorBuildIfPreferringErrors() throws Exception { FreeStyleProject project = createProject(0, true); Shell exitShell = new Shell("exit 1"); project.getBuildersList().add(exitShell); project.scheduleBuild2(0).waitForStart().run(); project.scheduleBuild2(0).waitForStart().run(); project.getBuildersList().remove(exitShell); FreeStyleBuild successfulBuildAfterFailures = project.scheduleBuild2(0).get(); String logText = FileUtils.readFileToString(successfulBuildAfterFailures.getLogFile()); assertEquals(logText, Result.SUCCESS, successfulBuildAfterFailures.getResult()); FreeStyleBuild completedBuild = project.scheduleBuild2(0).get(); logText = FileUtils.readFileToString(completedBuild.getLogFile()); assertThatVmIsInText(completedBuild.getNumber(), 2, logText); }
/** * Publishes JSON payload to notify URL. */ @SuppressWarnings({ "MethodWithMultipleReturnPoints", "SuppressionAnnotation" }) @Override public boolean perform ( AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener ) throws InterruptedException, IOException { this.listener = notNull( listener, "Build listener" ); boolean isIntermediateStep = build.getUrl().contains( "$" ); boolean isSuccessResult = build.getResult().isBetterOrEqualTo( Result.SUCCESS ); if ( isIntermediateStep || TextUtils.isBlank ( notifyUrl ) || ( ! isSuccessResult )) { return true; } listener.getLogger().println( String.format( "Building notify JSON payload" )); String notifyJson = buildNotifyJson( build, build.getEnvironment( listener )); listener.getLogger().println( String.format( "Publishing notify JSON payload to %s", notifyUrl )); // noinspection ConstantConditions sendNotifyRequest( notifyUrl, notifyJson ); return true; }
/** * Return a Jenkins build result which matches the result status from AWS Device Farm. * * @return */ public Result getBuildResult(Boolean ignoreRunError) { if (ignoreRunError != null && ignoreRunError && ExecutionResult.ERRORED.equals(result)) { if (totalCount == skipCount) { result = ExecutionResult.SKIPPED; } else if (stopCount > 0) { result = ExecutionResult.STOPPED; } else if (errorCount > 0) { result = ExecutionResult.ERRORED; } else if (failCount > 0) { result = ExecutionResult.FAILED; } else if (warnCount > 0) { result = ExecutionResult.WARNED; } else { result = ExecutionResult.PASSED; } } return resultMap.get(result); }
public void perform(LambdaEventSourceBuildStepVariables lambdaEventSourceBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaEventSourceBuildStepVariables executionVariables = lambdaEventSourceBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); EventSourceConfig eventSourceConfig = executionVariables.getEventSourceConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig(); EventSourceCallable eventSourceCallable = new EventSourceCallable(listener, eventSourceConfig, clientConfig); Boolean lambdaSuccess = launcher.getChannel().call(eventSourceCallable); if(!lambdaSuccess){ run.setResult(Result.FAILURE); } run.addAction(new LambdaEventSourceAction(executionVariables.getFunctionName(), lambdaSuccess)); } catch(Exception exc) { throw new RuntimeException(exc); } }
public void perform(LambdaPublishBuildStepVariables lambdaPublishBuildStepVariables, Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaPublishBuildStepVariables executionVariables = lambdaPublishBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); PublishConfig publishConfig = executionVariables.getPublishConfig(); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig(); PublishCallable publishCallable = new PublishCallable(listener, publishConfig, clientConfig); LambdaPublishServiceResponse lambdaSuccess = launcher.getChannel().call(publishCallable); if(!lambdaSuccess.getSuccess()){ run.setResult(Result.FAILURE); } run.addAction(new LambdaPublishAction(lambdaSuccess.getFunctionVersion(), lambdaSuccess.getFunctionAlias(), lambdaSuccess.getSuccess())); } catch(Exception exc) { throw new RuntimeException(exc); } }
@Override @RequirePOST public FormValidation doRebuildAllFailed() throws IOException { FormValidation result; try { Jenkins instance = GitHubWebHook.getJenkinsInstance(); if (instance.hasPermission(Item.BUILD)) { Map<String, List<Run<?, ?>>> builds = getAllBranchBuilds(); for (List<Run<?, ?>> buildList : builds.values()) { if (!buildList.isEmpty() && Result.FAILURE.equals(buildList.get(0).getResult())) { Run<?, ?> lastBuild = buildList.get(0); rebuild(lastBuild); } } result = FormValidation.ok("Rebuild scheduled"); } else { result = FormValidation.error("Forbidden"); } } catch (Exception e) { LOG.error("Can't start rebuild", e.getMessage()); result = FormValidation.error(e, "Can't start rebuild: %s", e.getMessage()); } return result; }
@Test public void testPerform() throws Exception { String script = "from pyjenkins import *\n" + "class Foo(PyJenkinsBuild):\n" + " def run(self):\n" + " return Result.SUCCESS\n" + "register_pybuild( Foo() )"; FileUtils.writeStringToFile(new File(workingDir, "the-build.py"), script); MockBuild build = newMockBuild(jenkins, workingDir); BuildListener listener = newListener(); PyJenkinsRunner runner = new PyJenkinsRunner("the-build.py"); boolean result = runner.perform(build, newLauncher(), listener); // should not have gotten any errors verify(listener, never()).fatalError(anyString()); verify(listener, never()).error(anyString()); assertTrue("it should return true", result); assertEquals(Result.SUCCESS, build.getResult()); }
@Test public void testExecuteFailure() throws Exception { String script = "from pyjenkins import *\n" + "class Foo(PyJenkinsBuild):\n" + " def run(self):\n" + " if execute(['foo']):\n" + " return Result.SUCCESS\n" + " else:\n" + " return Result.FAILURE\n" + "register_pybuild( Foo() )"; FileUtils.writeStringToFile(new File(workingDir, "the-build.py"), script); MockBuild build = newMockBuild(jenkins, workingDir); BuildListener listener = newListener(); Launcher launcher = new Launcher.LocalLauncher(listener); PyJenkinsRunner runner = new PyJenkinsRunner("the-build.py"); boolean result = runner.perform(build, launcher, listener); assertFalse("it should return false", result); assertEquals(Result.FAILURE, build.getResult()); }
@Test public void testPassBuildOnDecreasedCoverageButGreaterThanMinPercent() throws Exception { TestUtils.addCopyBuildStep(p, TestUtils.COBERTURA_XML, CoberturaXMLParser.class, "go-torch-coverage2.xml"); UberallsClient uberalls = TestUtils.getDefaultUberallsClient(); notifier = getNotifierWithCoverageCheck(0.0, 90.0); when(uberalls.getCoverage(any(String.class))).thenReturn("{\n" + " \"sha\": \"deadbeef\",\n" + " \"lineCoverage\": 100,\n" + " \"filesCoverage\": 100,\n" + " \"packageCoverage\": 100,\n" + " \"classesCoverage\": 100,\n" + " \"methodCoverage\": 100,\n" + " \"conditionalCoverage\": 100\n" + "}"); notifier.getDescriptor().setUberallsURL("http://uber.alls"); notifier.setUberallsClient(uberalls); FreeStyleBuild build = buildWithConduit(getFetchDiffResponse(), null, new JSONObject()); assertEquals(Result.SUCCESS, build.getResult()); }
public void perform(LambdaInvokeBuildStepVariables lambdaInvokeBuildStepVariables,Run<?, ?> run, Launcher launcher, TaskListener listener) { try { LambdaInvokeBuildStepVariables executionVariables = lambdaInvokeBuildStepVariables.getClone(); executionVariables.expandVariables(run.getEnvironment(listener)); LambdaClientConfig clientConfig = executionVariables.getLambdaClientConfig(); InvokeConfig invokeConfig = executionVariables.getInvokeConfig(); InvokeCallable invokeCallable = new InvokeCallable(listener, invokeConfig, clientConfig); LambdaInvocationResult invocationResult = launcher.getChannel().call(invokeCallable); if(!invocationResult.isSuccess()){ run.setResult(Result.FAILURE); } for (Map.Entry<String,String> entry : invocationResult.getInjectables().entrySet()) { run.addAction(new LambdaOutputInjectionAction(entry.getKey(), entry.getValue())); } run.getEnvironment(listener); run.addAction(new LambdaInvokeAction(executionVariables.getFunctionName(), invocationResult.isSuccess())); } catch (Exception exc) { throw new RuntimeException(exc); } }
@Override public boolean perform(AbstractBuild build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { if (build.getResult() != null && build.getResult() == Result.FAILURE) { return false; } listener.getLogger().println("TestFairy Advanced Uploader (Android)... v " + Utils.getVersion(getClass()) + ", run on " + getHostName()); try { EnvVars vars = build.getEnvironment(listener); String changeLog = Utils.extractChangeLog(vars, build.getChangeSet(), listener.getLogger()); AndroidBuildEnvironment environment = getDescriptor().getEnvironment(launcher); try { launcher.getChannel().call(new AndroidRemoteRecorder(listener, this, vars, environment, changeLog)); } catch (Throwable ue) { throw new TestFairyException(ue.getMessage(), ue); } return true; } catch (TestFairyException e) { listener.error(e.getMessage() + "\n"); e.printStackTrace(listener.getLogger()); return false; } }
@Test public void pythonExceptionsShouldBeCaught() throws Exception { String script = "from pyjenkins import *\n" + "class Foo(PyJenkinsBuild):\n" + " def run(self):\n" + " raise Exception('it broke')\n" + " return Result.SUCCESS\n" + "register_pybuild( Foo() )"; FileUtils.writeStringToFile(new File(workingDir, "the-build.py"), script); MockBuild build = newMockBuild(jenkins, workingDir); BuildListener listener = newListener(); Launcher launcher = new Launcher.LocalLauncher(listener); PyJenkinsRunner runner = new PyJenkinsRunner("the-build.py"); boolean result = runner.perform(build, launcher, listener); assertFalse("it should return false", result); assertEquals("it should fail the build", Result.FAILURE, build.getResult()); // make sure python line numbers and error message is in the exception verify(listener).fatalError(matches("(?s).*line 4.*it broke.*")); }