下面列出了怎么用hudson.model.Run的API类实例代码及写法,或者点击链接到github查看源代码。
public static boolean isWorkflowRun(Run<?, ?> build, StaticJenkinsAPIs staticJenkinsAPIs) {
//Cache class lookup
if (hasWorkflowClass == null) {
if (!staticJenkinsAPIs.hasPlugin(PIPELINE_PLUGIN)) {
hasWorkflowClass = false;
return false;
}
try {
workflowRunClass = Class.forName(WORKFLOW_RUN_CLASS_NAME);
hasWorkflowClass = true;
} catch (ClassNotFoundException e) {
hasWorkflowClass = false;
return false;
}
}
if (hasWorkflowClass) {
return workflowRunClass.isInstance(build);
}
return false;
}
private void executePullOnDocker(Run<?, ?> build, PrintStream llog, String xImage, DockerClient client)
throws DockerException {
PullImageResultCallback resultCallback = new PullImageResultCallback() {
@Override
public void onNext(PullResponseItem item) {
if (item.getStatus() != null && item.getProgress() == null) {
llog.print(item.getId() + ":" + item.getStatus());
LOG.info("{} : {}", item.getId(), item.getStatus());
}
super.onNext(item);
}
};
PullImageCmd cmd = client.pullImageCmd(xImage);
DockerCloud.setRegistryAuthentication(cmd, getRegistry(), build.getParent().getParent());
try {
cmd.exec(resultCallback).awaitCompletion();
} catch (InterruptedException e) {
throw new DockerClientException("Interrupted while pulling image", e);
}
}
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
@Nonnull TaskListener listener) throws InterruptedException, IOException {
PrintStream llog = listener.getLogger();
try {
llog.println("Executing remote build image...");
List<String> buildImages = workspace.act(newDockerBuildImageStepCallable()
.withBuildImage(buildImage)
.withConnector(connector)
.withTaskListener(listener)
);
llog.println(buildImages);
} catch (Throwable ex) {
LOG.error("Can't build image", ex);
throw ex;
}
}
/**
* Gets a list of stages in a declarative pipeline.
*
* @param run a particular run of a job
* @return a list of stage names
*/
protected static List<BuildStage> getDeclarativeStages(Run<?, ?> run) {
ExecutionModelAction executionModelAction = run.getAction(ExecutionModelAction.class);
if (null == executionModelAction) {
return null;
}
ModelASTStages stages = executionModelAction.getStages();
if (null == stages) {
return null;
}
List<ModelASTStage> stageList = stages.getStages();
if (null == stageList) {
return null;
}
return convertList(stageList);
}
private String notifyTestCase(String jobName, String suiteName, TestCase testCase, Run<?, ?> run) {
String buildUrl = run.getUrl();
int buildNumber = run.getNumber();
Cause cause = run.getCause(Cause.class);
String buildCause = cause == null ? BuildNotifierConstants.DEFAULT_STRING : cause.getShortDescription();
String data = config.getSchema().formatTestCase(jobName,
repoOwner,
repoName,
branchName,
suiteName,
testCase.getName(),
testCase.getPassedCount(),
testCase.getSkippedCount(),
testCase.getFailedCount(),
buildUrl,
buildNumber,
buildCause);
return data;
}
public AbstractTestResultAction getLastTestResultAction() {
final Run<?,?> tb = job.getLastSuccessfulBuild();
Run<?,?> b = job.getLastBuild();
while(b!=null) {
AbstractTestResultAction a = b.getAction(AbstractTestResultAction.class);
if(a!=null && (!b.isBuilding())) return a;
if(b==tb)
// if even the last successful build didn't produce the test result,
// that means we just don't have any tests configured.
return null;
b = b.getPreviousBuild();
}
return null;
}
public void sendMessage(
Long chatId, String message, Run<?, ?> run, FilePath filePath, TaskListener taskListener)
throws IOException, InterruptedException {
final String expandedMessage = expandMessage(message, run, filePath, taskListener);
try {
if (chatId == null) {
SUBSCRIBERS.getApprovedUsers()
.forEach(user -> this.sendMessage(user.getId(), expandedMessage));
} else {
sendMessage(chatId, expandedMessage);
}
} catch (Exception e) {
LOG.log(Level.SEVERE, "Error while sending the message", e);
}
if (CONFIG.isShouldLogToConsole()) taskListener.getLogger().println(expandedMessage);
}
@Before
public void setup() throws IOException, InterruptedException {
// Prepare site.
when(envVarsMock.get("JIRA_SITE")).thenReturn("LOCAL");
when(envVarsMock.get("BUILD_URL")).thenReturn("http://localhost:8080/jira-testing/job/01");
PowerMockito.mockStatic(Site.class);
Mockito.when(Site.get(any())).thenReturn(siteMock);
when(siteMock.getService()).thenReturn(jiraServiceMock);
when(runMock.getCauses()).thenReturn(null);
when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
doNothing().when(printStreamMock).println();
final ResponseDataBuilder<Object> builder = ResponseData.builder();
when(jiraServiceMock.getAttachment(anyString()))
.thenReturn(builder.successful(true).code(200).message("Success").build());
when(contextMock.get(Run.class)).thenReturn(runMock);
when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
}
public static void addComment(final int id, final String comment, final Run<?, ?> run, final TaskListener listener) {
if (comment == null || comment.trim().isEmpty()) {
return;
}
String finalComment = comment;
if (nonNull(run) && nonNull(listener)) {
try {
finalComment = run.getEnvironment(listener).expand(comment);
} catch (Exception e) {
LOG.error("Error", e);
}
}
try {
if (nonNull(run)) {
final GitHubPRTrigger trigger = ghPRTriggerFromRun(run);
GHRepository ghRepository = trigger.getRemoteRepository();
ghRepository.getPullRequest(id).comment(finalComment);
}
} catch (IOException ex) {
LOG.error("Couldn't add comment to pull request #{}: '{}'", id, finalComment, ex);
}
}
@Override
public void process(@Nonnull StepContext context, @Nonnull Element mavenSpyLogsElt) throws IOException, InterruptedException {
Run run = context.get(Run.class);
TaskListener listener = context.get(TaskListener.class);
PipelineMavenPluginDao dao = GlobalPipelineMavenConfig.get().getDao();
List<MavenArtifact> parentProjects = listParentProjects(mavenSpyLogsElt, LOGGER);
List<MavenDependency> dependencies = listDependencies(mavenSpyLogsElt, LOGGER);
List<MavenArtifact> generatedArtifacts = XmlUtils.listGeneratedArtifacts(mavenSpyLogsElt, true);
List<String> executedLifecyclePhases = XmlUtils.getExecutedLifecyclePhases(mavenSpyLogsElt);
recordParentProject(parentProjects, run,listener, dao);
recordDependencies(dependencies, generatedArtifacts, run, listener, dao);
recordGeneratedArtifacts(generatedArtifacts, executedLifecyclePhases, run, listener, dao);
}
@Override
public Report scan(final Run<?, ?> run, final FilePath workspace, final Charset sourceCodeEncoding,
final LogHandler logger) {
String actualPattern = getActualPattern();
if (StringUtils.isBlank(actualPattern)) {
return scanInConsoleLog(workspace, run, logger);
}
else {
if (StringUtils.isBlank(getPattern())) {
logger.log("Using default pattern '%s' since user defined pattern is not set",
getDescriptor().getPattern());
}
return scanInWorkspace(workspace, expandPattern(run, actualPattern), logger);
}
}
@Before
public void setup() throws IOException, InterruptedException {
// Prepare site.
when(envVarsMock.get("JIRA_SITE")).thenReturn("LOCAL");
when(envVarsMock.get("BUILD_URL")).thenReturn("http://localhost:8080/jira-testing/job/01");
PowerMockito.mockStatic(Site.class);
Mockito.when(Site.get(any())).thenReturn(siteMock);
when(siteMock.getService()).thenReturn(jiraServiceMock);
when(runMock.getCauses()).thenReturn(null);
when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
doNothing().when(printStreamMock).println();
final ResponseDataBuilder<Void> builder = ResponseData.builder();
when(jiraServiceMock.updateVersion(anyString(), any()))
.thenReturn(builder.successful(true).code(200).message("Success").build());
when(contextMock.get(Run.class)).thenReturn(runMock);
when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
}
@Override
public void onCompleted(Run run, TaskListener listener) {
// TODO consider the possibility that there is >1 such action
TestResultAction testResultAction = run.getAction(TestResultAction.class);
HistoryAggregatedFlakyTestResultAction historyAction = run.getParent()
.getAction(HistoryAggregatedFlakyTestResultAction.class);
// Aggregate test running results
if (historyAction != null) {
historyAction.aggregateOneBuild(run);
}
if (testResultAction != null && testResultAction.getFailCount() > 0) {
// Only add deflake action if there are test failures
run.addAction(
new DeflakeAction(getFailingTestClassMethodMap(testResultAction.getFailedTests())));
}
}
private static void publishJobEvent(@Nonnull Run<?,?> run, @Nonnull Events.JobChannel event) {
try {
// TODO: What's the actual event we should send here?
PubsubBus.getBus().publish(new RunMessage(run)
.setEventName(event)
);
} catch (MessageException e) {
LOGGER.log(Level.WARNING, "Error publishing Job event.", e);
}
}
@Override
public BuildResult<AnalysisBuildResult> next() {
if (cursor.isPresent()) {
Run<?, ?> run = cursor.get();
Optional<ResultAction> resultAction = selector.get(run);
cursor = getRunWithResult(run.getPreviousBuild(), selector, IGNORE_QUALITY_GATE, IGNORE_JOB_RESULT);
if (resultAction.isPresent()) {
return new BuildResult<>(new JenkinsBuild(run), resultAction.get().getResult());
}
}
throw new NoSuchElementException("No more runs with an analysis result available: " + cursor);
}
public DecisionMaker(Run run, TaskListener listener) {
this.run = run;
this.taskListener = listener;
Run previousBuild = run.getPreviousBuild();
previousResult = previousBuild != null ? previousBuild.getResult() : Result.SUCCESS;
}
private static List<BlueRun> collectRuns(Iterator<? extends Run> runIterator, final Link parent, int start, int limit){
if (COLLECT_THREADS > 1) {
LOGGER.debug( "collectRunsParallel {}", COLLECT_THREADS );
return collectRunsParallel( runIterator, parent, start, limit );
}
return collectRunsSingleThread( runIterator, parent, start, limit );
}
private boolean isVisible(final Job<?, ?> job) {
if (!hideCleanJobs) {
return true;
}
Run<?, ?> lastCompletedBuild = job.getLastCompletedBuild();
if (lastCompletedBuild == null) {
return true;
}
return lastCompletedBuild.getActions(ResultAction.class)
.stream()
.filter(createToolFilter(selectTools, tools))
.anyMatch(resultAction -> resultAction.getResult().getTotalSize() > 0);
}
protected void mockResult(Result lastResult) {
when(run.getResult()).thenReturn(lastResult);
AbstractBuild previousBuild = mock(AbstractBuild.class);
when(run.getPreviousBuild()).thenReturn(previousBuild);
when(previousBuild.getResult()).thenReturn(Result.FAILURE);
Run failingSinceBuild = mock(Run.class);
when(failingSinceBuild.getNumber()).thenReturn(10);
Run lastNotFailedBuild = mock(Run.class);
when(lastNotFailedBuild.getNextBuild()).thenReturn(failingSinceBuild);
when(run.getPreviousNotFailedBuild()).thenReturn(lastNotFailedBuild);
}
@Test
public void testPerformShouldSucceedWithNoWarning() throws Exception {
setGlobalConfigDataAndJobConfigDataNames(TEST_NAME, TEST_NAME);
jobConfigData.setProjectKey("projectKey");
doReturn(globalConfigDataForSonarInstance).when(buildDecision).chooseSonarInstance(globalConfig, jobConfigData);
doReturn(true).when(buildDecision).getStatus(any(GlobalConfigDataForSonarInstance.class), any(JobConfigData.class), any(BuildListener.class));
jenkinsRule.buildAndAssertSuccess(freeStyleProject);
Run lastRun = freeStyleProject._getRuns().newestValue();
jenkinsRule.assertLogContains("build passed: TRUE", lastRun);
}
private static String getRootUrl(Run<?, ?> build) {
try {
return DisplayURLProvider.get().getRunURL(build);
} catch (IllegalStateException e) {
return "";
}
}
public static GHCommitState getCommitState(final Run<?, ?> run, final GHCommitState unstableAs) {
GHCommitState state;
Result result = run.getResult();
if (isNull(result)) {
LOG.error("{} result is null.", run);
state = GHCommitState.ERROR;
} else if (result.isBetterOrEqualTo(SUCCESS)) {
state = GHCommitState.SUCCESS;
} else if (result.isBetterOrEqualTo(UNSTABLE)) {
state = unstableAs;
} else {
state = GHCommitState.FAILURE;
}
return state;
}
@Test
public void listExports() throws Exception {
WorkflowJob job = this.jenkinsRule.jenkins.createProject(WorkflowJob.class, "cfnTest");
Mockito.when(this.cloudFormation.listExports(new ListExportsRequest()))
.thenReturn(new ListExportsResult()
.withNextToken("foo1")
.withExports(new Export()
.withName("foo")
.withValue("bar")
)
);
Mockito.when(this.cloudFormation.listExports(new ListExportsRequest().withNextToken("foo1")))
.thenReturn(new ListExportsResult()
.withExports(new Export()
.withName("baz")
.withValue("foo")
)
);
job.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " def exports = cfnExports()\n"
+ " echo \"exportsCount=${exports.size()}\"\n"
+ " echo \"foo=${exports['foo']}\"\n"
+ " echo \"baz=${exports['baz']}\"\n"
+ "}\n", true)
);
Run run = this.jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
this.jenkinsRule.assertLogContains("exportsCount=2", run);
this.jenkinsRule.assertLogContains("foo=bar", run);
this.jenkinsRule.assertLogContains("baz=foo", run);
}
@Override
public void perform(
@Nonnull Run<?, ?> run,
@Nonnull FilePath filePath,
@Nonnull Launcher launcher,
@Nonnull TaskListener taskListener) throws InterruptedException, IOException {
TelegramBotRunner.getInstance().getBot().
sendMessage(getChatId(), getMessage(), run, filePath, taskListener);
}
@VisibleForTesting
static Run<?, ?> getUpstreamRun(AbstractBuild build) {
CauseAction action = build.getAction(hudson.model.CauseAction.class);
if (action != null) {
Cause.UpstreamCause upstreamCause = action.findCause(hudson.model.Cause.UpstreamCause.class);
if (upstreamCause != null) {
return upstreamCause.getUpstreamRun();
}
}
return null;
}
@Deprecated
public TestResult parse(String testResultLocations,
AbstractBuild build, Launcher launcher,
TaskListener listener)
throws InterruptedException, IOException {
if (Util.isOverridden(TestResultParser.class, getClass(), "parseResult", String.class, Run.class, FilePath.class, Launcher.class, TaskListener.class)) {
FilePath workspace = build.getWorkspace();
if (workspace == null) {
throw new AbortException("no workspace in " + build);
}
return parseResult(testResultLocations, build, workspace, launcher, listener);
} else {
throw new AbstractMethodError("you must override parseResult");
}
}
private String getNameWithEnclosingBlocks(String rawName) {
// Only prepend the enclosing flow node names if there are any and the run this is in has multiple blocks directly containing
// test results.
if (!getEnclosingFlowNodeNames().isEmpty()) {
Run<?, ?> r = getRun();
if (r != null) {
TestResultAction action = r.getAction(TestResultAction.class);
if (action != null && action.getResult().hasMultipleBlocks()) {
return StringUtils.join(new ReverseListIterator(getEnclosingFlowNodeNames()), " / ") + " / " + rawName;
}
}
}
return rawName;
}
@Test
public void named_simple_pipeline_builds_as_LString() throws Exception {
WorkflowJob project = j.createProject(WorkflowJob.class);
String pipelineText = IOUtils.toString(getClass().getResourceAsStream(
"pipeline/named-simple-pipeline-builds-as-LString.groovy"));
project.setDefinition(new CpsFlowDefinition(pipelineText, false));
Run build = j.buildAndAssertSuccess(project);
j.assertLogContains("this is pre-build stage", build);
}
/**
* Checks if the reference only looks at the eclipse result of a build and not the overall success. Should return an
* unstable result. Uses a different freestyle project for the reference.
*/
@Test
public void shouldCreateUnstableResultWithOverAllMustNotBeSuccessWithReferenceBuild() {
// #1 SUCCESS
FreeStyleProject reference = createJob(REFERENCE_JOB_NAME, "eclipse4Warnings.txt");
IssuesRecorder issuesRecorder = enableWarnings(reference, recorder -> {
recorder.setIgnoreFailedBuilds(false);
recorder.setEnabledForFailure(true);
});
scheduleBuildAndAssertStatus(reference, Result.SUCCESS,
analysisResult -> assertThat(analysisResult).hasTotalSize(4)
.hasNewSize(0)
.hasQualityGateStatus(QualityGateStatus.INACTIVE));
// #2 FAILURE
cleanAndCopy(reference, "eclipse2Warnings.txt");
issuesRecorder.addQualityGate(3, QualityGateType.NEW, QualityGateResult.UNSTABLE);
Builder failureStep = addFailureStep(reference);
Run<?, ?> expectedReference = scheduleBuildAndAssertStatus(reference, Result.FAILURE,
analysisResult -> assertThat(analysisResult).hasTotalSize(2)
.hasNewSize(0)
.hasQualityGateStatus(QualityGateStatus.PASSED)).getOwner();
removeBuilder(reference, failureStep);
// #1 UNSTABLE (Reference #2)
FreeStyleProject project = createJob(JOB_NAME, "eclipse6Warnings.txt");
enableWarnings(project, recorder -> {
recorder.addQualityGate(3, QualityGateType.NEW, QualityGateResult.UNSTABLE);
recorder.setReferenceJobName(REFERENCE_JOB_NAME);
recorder.setIgnoreFailedBuilds(false);
recorder.setEnabledForFailure(true);
});
scheduleBuildAndAssertStatus(project, Result.UNSTABLE,
analysisResult -> assertThat(analysisResult).hasTotalSize(6)
.hasNewSize(4)
.hasQualityGateStatus(QualityGateStatus.WARNING)
.hasReferenceBuild(Optional.of(expectedReference)));
}
@Test
public void findUniqueArtifactsWithSameName() throws IllegalAccessException {
//mock artifacts
Run.Artifact artifact1 = mock(Run.Artifact.class);
Run.Artifact artifact2 = mock(Run.Artifact.class);
//artifact1 mocks
when(artifact1.getFileName()).thenReturn("test-suite.log");
MemberModifier.field(Run.Artifact.class, "relativePath").set(artifact1, "path1/test-suite.log");
when(artifact1.getHref()).thenReturn("path1/test-suite.log");
//artifact2 mocks
when(artifact2.getFileName()).thenReturn("test-suite.log");
MemberModifier.field(Run.Artifact.class, "relativePath").set(artifact2, "path2/test-suite.log");
when(artifact2.getHref()).thenReturn("path2/test-suite.log");
//list of artifacts
ArrayList artifactList = new ArrayList();
artifactList.add(artifact1);
artifactList.add(artifact2);
//mock run
Run run = mock(Run.class);
when(run.getUrl()).thenReturn("job/myfolder/job/myjob/1/");
when(run.getArtifacts()).thenReturn(artifactList);
Link parentLink = mock(Link.class);
ArtifactImpl a1 = new ArtifactImpl(run, artifact1, parentLink);
ArtifactImpl a2 = new ArtifactImpl(run, artifact2, parentLink);
assertThat(a1.getId(), is(not(a2.getId())));
}