类hudson.model.AbstractBuild源码实例Demo

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

源代码1 项目: credentials-binding-plugin   文件: BindingStep.java
@Override public OutputStream decorateLogger(AbstractBuild _ignore, final OutputStream logger) throws IOException, InterruptedException {
    final Pattern p = Pattern.compile(pattern.getPlainText());
    return new LineTransformationOutputStream() {
        @Override protected void eol(byte[] b, int len) throws IOException {
            if (!p.toString().isEmpty()) {
                Matcher m = p.matcher(new String(b, 0, len, charsetName));
                if (m.find()) {
                    logger.write(m.replaceAll("****").getBytes(charsetName));
                } else {
                    // Avoid byte → char → byte conversion unless we are actually doing something.
                    logger.write(b, 0, len);
                }
            } else {
                // Avoid byte → char → byte conversion unless we are actually doing something.
                logger.write(b, 0, len);
            }
        }
        @Override public void flush() throws IOException {
            logger.flush();
        }
        @Override public void close() throws IOException {
            super.close();
            logger.close();
        }
    };
}
 
源代码2 项目: zaproxy-plugin   文件: ZAProxy.java
/**
 * Return the ZAProxy program name with separator prefix (\zap.bat or /zap.sh) depending of the build node and the OS.
 * 
 * @param build
 * @return the ZAProxy program name with separator prefix (\zap.bat or /zap.sh)
 * @throws IOException
 * @throws InterruptedException
 */
private String getZAPProgramNameWithSeparator(AbstractBuild<?, ?> build) throws IOException, InterruptedException {
	Node node = build.getBuiltOn();
	String zapProgramName = "";
	
	// Append zap program following Master/Slave and Windows/Unix
	if( "".equals(node.getNodeName())) { // Master
		if( File.pathSeparatorChar == ':' ) { // UNIX
			zapProgramName = "/" + ZAP_PROG_NAME_SH;
		} else { // Windows (pathSeparatorChar == ';')
			zapProgramName = "\\" + ZAP_PROG_NAME_BAT;
		}
	} 
	else { // Slave
		if( "Unix".equals(((SlaveComputer)node.toComputer()).getOSDescription()) ) {
			zapProgramName = "/" + ZAP_PROG_NAME_SH;
		} else {
			zapProgramName = "\\" + ZAP_PROG_NAME_BAT;
		}
	}
	return zapProgramName;
}
 
/**
 * We'll use this from the <tt>config.jelly</tt>.
 */

@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
    DeployJobVariables jobVariables = extractDeployJobVariables(build);

    String message = region + " Tagging ENVIRONMENT [" + jobVariables.getEnvironment() + "] with VERSION [" + jobVariables.getVersion() + "]";
    listener.getLogger().println(message);

    EC2Connector connector = EC2Connector.getEC2Connector(getCredentials());
    boolean taggingSuccessful = connector.tagEnvironmentWithVersion(Region.getRegion(Regions.fromName(region)), jobVariables);
    if (!taggingSuccessful) {
        String failedMessage = "ERROR: Could not tag ENVIRONMENT [" + jobVariables.getEnvironment() + "] with VERSION [" + jobVariables.getVersion() + "]";
        listener.getLogger().println(failedMessage);
    }

    return taggingSuccessful;
}
 
/**
 * Verifies onNewHead adds the build action for an atom node if there's an error (used for sending errors that occur
 * out of a stage
 */
@Test
public void testAtomNodeAddsAction() throws IOException {
    ErrorAction error = mock(ErrorAction.class);
    CpsFlowExecution execution = mock(CpsFlowExecution.class);
    StepAtomNode stageNode = new StepAtomNode(execution, null, mock(FlowNode.class));
    stageNode.addAction(error);

    FlowExecutionOwner owner = mock(FlowExecutionOwner.class);
    when(execution.getOwner()).thenReturn(owner);
    AbstractBuild build = mock(AbstractBuild.class);
    when(owner.getExecutable()).thenReturn(build);
    when(build.getAction(ExecutionModelAction.class)).thenReturn(null); // not declarative

    GithubBuildStatusGraphListener instance = new GithubBuildStatusGraphListener();
    instance.onNewHead(stageNode);
    verify(build).addAction(any(BuildStatusAction.class));
}
 
@Before
public void setUp() throws Exception {
    ItemGroup itemGroup = mock(ItemGroup.class);
    when(itemGroup.getFullDisplayName()).thenReturn(StringUtils.EMPTY);

    Job job = mock(Job.class);
    when(job.getDisplayName()).thenReturn(JOB_DISPLAY_NAME);
    when(job.getParent()).thenReturn(itemGroup);

    run = mock(AbstractBuild.class);
    when(run.getNumber()).thenReturn(BUILD_NUMBER);
    when(run.getParent()).thenReturn(job);

    mockDisplayURLProvider(JOB_DISPLAY_NAME, BUILD_NUMBER);
    TaskListener taskListener = mock(TaskListener.class);
    cardBuilder = new CardBuilder(run, taskListener);
}
 
@Test
public void getEscapedDisplayName_OnNameWithSpecialCharacters_EscapesSpecialCharacters() {

    // given
    final String specialDisplayName = "this_is_my-very#special *job*";
    ItemGroup itemGroup = mock(ItemGroup.class);
    when(itemGroup.getFullDisplayName()).thenReturn(StringUtils.EMPTY);

    Job job = mock(Job.class);
    when(job.getDisplayName()).thenReturn(specialDisplayName);
    when(job.getParent()).thenReturn(itemGroup);

    run = mock(AbstractBuild.class);
    when(run.getParent()).thenReturn(job);
    TaskListener taskListener = mock(TaskListener.class);

    mockDisplayURLProvider(JOB_DISPLAY_NAME, BUILD_NUMBER);
    cardBuilder = new CardBuilder(run, taskListener);

    // when
    String displayName = Deencapsulation.invoke(cardBuilder, "getEscapedDisplayName");

    // then
    assertThat(displayName).isEqualTo("this\\_is\\_my\\-very\\#special \\*job\\*");
}
 
@Test
@Ignore("build.getWorkspace() cannot be mocked")
public void should_handle_private_key_credentials() throws Exception {
    // Given
    Inventory inventory = new InventoryPath("/tmp/hosts");
    SSHUserPrivateKey pkey = mock(SSHUserPrivateKey.class);
    when(pkey.getUsername()).thenReturn("mylogin");
    BuildListener listener = mock(BuildListener.class);
    CLIRunner runner = mock(CLIRunner.class);
    AbstractBuild<?,?> build = mock(AbstractBuild.class);
    when(build.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    AnsibleAdHocCommandInvocation invocation = new AnsibleAdHocCommandInvocation("/usr/local/bin/ansible", build, listener);
    invocation.setHostPattern("localhost");
    invocation.setInventory(inventory);
    invocation.setModule("ping");
    invocation.setCredentials(pkey);
    invocation.setForks(5);
    // When
    invocation.execute(runner);
    // Then
    ArgumentCaptor<ArgumentListBuilder> argument = ArgumentCaptor.forClass(ArgumentListBuilder.class);
    verify(runner).execute(argument.capture(), anyMap());
    assertThat(argument.getValue().toString())
            .matches("/usr/local/bin/ansible localhost -i /tmp/hosts -m ping -f 5 --private-key .+ -u mylogin");
}
 
@Override
public boolean checkout(AbstractBuild<?,?> build, Launcher launcher, FilePath workspace, BuildListener listener, File changeLogFile) throws IOException, InterruptedException {
    if (workspace.exists()) {
        listener.getLogger().println("Deleting existing workspace " + workspace.getRemote());
        workspace.deleteRecursive();
    }
    listener.getLogger().println("Staging first zip: " + firstZip);
    workspace.unzipFrom(firstZip.openStream());
    listener.getLogger().println("Staging second zip: " + secondZip);
    workspace.unzipFrom(secondZip.openStream());

    // Get list of files changed in secondZip.
    ExtractChangeLogParser.ExtractChangeLogEntry changeLog = new ExtractChangeLogParser.ExtractChangeLogEntry(secondZip.toString());

    try (ZipInputStream zip = new ZipInputStream(secondZip.openStream())) {
        ZipEntry e;
        while ((e = zip.getNextEntry()) != null) {
            if (!e.isDirectory())
                changeLog.addFile(new ExtractChangeLogParser.FileInZip(e.getName()));
        }
    }
    saveToChangeLog(changeLogFile, changeLog);

    return true;
}
 
源代码9 项目: jira-ext-plugin   文件: AddFixVersion.java
@Override
public void perform(List<JiraCommit> commits, AbstractBuild build, Launcher launcher, BuildListener listener)
{
    for (JiraCommit commit : JiraCommit.filterDuplicateIssues(commits))
    {
        try
        {
            String expandedFixVersion = build.getEnvironment(listener).expand(fixVersion);
            getJiraClientSvc().addFixVersion(commit.getJiraTicket(), expandedFixVersion);
        }
        catch (Throwable t)
        {
            listener.getLogger().println("ERROR Updating fix versions, skipping");
            t.printStackTrace(listener.getLogger());
        }
    }
}
 
源代码10 项目: jira-ext-plugin   文件: AddFixVersionTest.java
@Test
public void testExpandValues()
        throws Exception
{
    AddFixVersion addFixVersion = new AddFixVersion("Beta Release $FOO");
    addFixVersion.setJiraClientSvc(jiraClientSvc);
    AbstractBuild mockBuild = mock(AbstractBuild.class);
    EnvVars envVars = new EnvVars();
    envVars.put("FOO", "BAR");
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(envVars);
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101"));
    jiraCommits.add(new JiraCommit("SSD-101"));

    addFixVersion.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).addFixVersion(eq("SSD-101"), eq("Beta Release BAR"));

}
 
源代码11 项目: jira-ext-plugin   文件: TransitionTest.java
/**
 * An exception adding the first label add should not disrupt the next label
 */
@Test
public void testResiliency()
        throws Exception
{
    Transition transition = new Transition("Resolve");
    transition.setJiraClientSvc(jiraClientSvc);

    AbstractBuild mockBuild = mock(AbstractBuild.class);
    when(mockBuild.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars());
    List<JiraCommit> jiraCommits = new ArrayList<>();
    jiraCommits.add(new JiraCommit("SSD-101", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    jiraCommits.add(new JiraCommit("SSD-102", MockChangeLogUtil.mockChangeLogSetEntry("Test Comment")));
    doThrow(new RuntimeException("Issue is invalid"))
            .when(jiraClientSvc).changeWorkflowOfTicket("SSD-101", "Test Comment");
    transition.perform(jiraCommits, mockBuild, mock(Launcher.class), new StreamBuildListener(System.out, Charset.defaultCharset()));
    verify(jiraClientSvc, times(1)).changeWorkflowOfTicket(eq("SSD-101"), eq("Resolve"));
    verify(jiraClientSvc, times(1)).changeWorkflowOfTicket(eq("SSD-102"), eq("Resolve"));
}
 
@Override
@SuppressWarnings("unchecked")
public Job<?, ?> get() {
    AbstractBuild earlierBuild, earliestBuild;

    // link "previous" builds ...
    while (buildHistory.size() > 1) {
        earliestBuild = buildHistory.pop();
        earlierBuild  = buildHistory.peek();

        when(earlierBuild.getPreviousBuild()).thenReturn(earliestBuild);
    }

    // pick the first build from the build history and make it the "last build"
    if (buildHistory.size() == 1) {
    	doReturn(buildHistory.pop()).when(job).getLastBuild();
    }
    
    // mock the necessary methods to get the currentBuilds
    // it will return the full list so make sure it contains only building builds
    doReturn(runList).when(job).getNewBuilds();
    doReturn(runList).when(runList).filter(any(Predicate.class));
    doReturn(allBuilds.iterator()).when(runList).iterator();

    return job;
}
 
/**
 * Construct a FlakyTestResultAction object with Run and BuildListener
 *
 * @param build this build
 * @param listener listener of this build
 */
public FlakyTestResultAction(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
  this.build = build;
  // TODO consider the possibility that there is >1 such action
  AbstractTestResultAction action = build.getAction(AbstractTestResultAction.class);
  if (action != null) {
    Object latestResult = action.getResult();
    if (latestResult != null && latestResult instanceof TestResult) {
      VirtualChannel channel = launcher.getChannel();
      if(channel == null) {
        throw new InterruptedException("Could not get channel to run a program remotely.");
      }
      FlakyTestResult flakyTestResult = channel.call(new FlakyTestResultCollector((TestResult) latestResult));

      flakyTestResult.freeze(action, build);
      FlakyRunStats stats = new FlakyRunStats(flakyTestResult.getTestFlakyStatsMap());
      setFlakyRunStats(stats, listener);
    }
  } else {
    logger.log(Level.WARNING, "No test result found, please publish junit report first");
  }
}
 
/**
 * @return the most recent AWS Device Farm test action from the previous build
 */
@Override
public AWSDeviceFarmTestResultAction getPreviousResult() {
    AbstractBuild<?, ?> build = getOwner();
    if (owner == null) {
        return null;
    }
    return AWSDeviceFarmUtils.previousAWSDeviceFarmBuildAction(build.getProject());
}
 
源代码15 项目: gitlab-plugin   文件: GitLabMessagePublisherTest.java
private AbstractBuild mockBuild(String gitLabConnection, Result result, String... remoteUrls) {
    AbstractBuild build = mock(AbstractBuild.class);
    BuildData buildData = mock(BuildData.class);
    when(buildData.getRemoteUrls()).thenReturn(new HashSet<>(Arrays.asList(remoteUrls)));
    when(build.getAction(BuildData.class)).thenReturn(buildData);
    when(build.getResult()).thenReturn(result);
    when(build.getUrl()).thenReturn(BUILD_URL);
    when(build.getResult()).thenReturn(result);
    when(build.getNumber()).thenReturn(BUILD_NUMBER);

    AbstractProject<?, ?> project = mock(AbstractProject.class);
    when(project.getProperty(GitLabConnectionProperty.class)).thenReturn(new GitLabConnectionProperty(gitLabConnection));
    when(build.getProject()).thenReturn(project);
    EnvVars environment = mock(EnvVars.class);
    when(environment.expand(anyString())).thenAnswer(new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return (String) invocation.getArguments()[0];
        }
    });
    try {
        when(build.getEnvironment(any(TaskListener.class))).thenReturn(environment);
    } catch (IOException | InterruptedException e) {
        throw new RuntimeException(e);
    }
    return build;
}
 
源代码16 项目: gitlab-plugin   文件: GitLabMessagePublisherTest.java
@Test
public void failed_v4() throws IOException, InterruptedException {
    AbstractBuild build = mockBuild(GITLAB_CONNECTION_V4, Result.FAILURE);
    String defaultNote = formatNote(build, ":negative_squared_cross_mark: Jenkins Build {0}\n\nResults available at: [Jenkins [{1} #{2}]]({3})");

    performAndVerify(
        build, defaultNote, false, false, false, false, false,
        prepareSendMessageWithSuccessResponse("v4", MERGE_REQUEST_IID, defaultNote));
}
 
源代码17 项目: jenkins-client-plugin   文件: CreateStep.java
@Override
public boolean perform(final AbstractBuild build, Launcher launcher,
        final BuildListener listener) throws IOException,
        InterruptedException {
    final Map<String, String> overrides = consolidateEnvVars(listener, build, launcher);
    return withTempInput("markup", getJsonyaml(overrides), new WithTempInputRunnable() {
        @Override
        public boolean perform(String markupFilename) throws IOException,
                InterruptedException {
            return standardRunOcCommand(build, listener, "create",
                    toList("-f", markupFilename), toList(), toList());
        }
    });
}
 
源代码18 项目: sonar-quality-gates-plugin   文件: QGBuilder.java
@Override
public boolean prebuild(AbstractBuild<?, ?> build, BuildListener listener) {

    globalConfigDataForSonarInstance = buildDecision.chooseSonarInstance(jobExecutionService.getGlobalConfigData(), jobConfigData);

    if (globalConfigDataForSonarInstance == null) {
        listener.error(JobExecutionService.GLOBAL_CONFIG_NO_LONGER_EXISTS_ERROR, jobConfigData.getSonarInstanceName());
        return false;
    }

    return true;
}
 
源代码19 项目: zaproxy-plugin   文件: ZAProxy.java
/**
 * Set the JDK to use to start ZAP.
 * 
 * @param build
 * @param listener the listener to display log during the job execution in jenkins
 * @param env list of environment variables. Used to set the path to the JDK
 * @throws IOException
 * @throws InterruptedException
 */
private void computeJdkToUse(AbstractBuild<?, ?> build,
		BuildListener listener, EnvVars env) throws IOException, InterruptedException {
	JDK jdkToUse = getJdkToUse(build.getProject());
	if (jdkToUse != null) {
		Computer computer = Computer.currentComputer();
		// just in case we are not in a build
		if (computer != null) {
			jdkToUse = jdkToUse.forNode(computer.getNode(), listener);
		}
		jdkToUse.buildEnvVars(env);
	}
}
 
源代码20 项目: phabricator-jenkins-plugin   文件: TestUtils.java
public static void addCopyBuildStep(
        FreeStyleProject p,
        final String fileName,
        final Class resourceClass,
        final String resourceName) {
    p.getBuildersList().add(new TestBuilder() {
        @Override
        public boolean perform(AbstractBuild build, Launcher launcher, BuildListener buildListener) throws
                InterruptedException, IOException {
            build.getWorkspace().child(fileName).copyFrom(resourceClass.getResourceAsStream(resourceName));
            return true;
        }
    });
}
 
@Before
public void setUp() {
    suppress(method(BuildStatusConfig.class, "load"));
    suppress(method(BuildStatusConfig.class, "save"));

    repository = mock(GHRepository.class);
    when(repository.getName()).thenReturn(repoName);

    PowerMockito.mockStatic(GithubNotificationConfig.class);
    githubConfig = mock(GithubNotificationConfig.class);
    when(githubConfig.getRepo()).thenReturn(repository);
    when(githubConfig.getShaString()).thenReturn(sha);
    when(githubConfig.getBranchName()).thenReturn(branchName);
    when(GithubNotificationConfig.fromRun(anyObject())).thenReturn(githubConfig);

    PowerMockito.mockStatic(InfluxDbNotifierConfig.class);
    when(InfluxDbNotifierConfig.fromGlobalConfig((String)isNull(), (String)isNull(), any())).thenReturn(mock(InfluxDbNotifierConfig.class));

    statsdNotifierConfig = mock(StatsdNotifierConfig.class);
    PowerMockito.mockStatic(StatsdNotifierConfig.class);
    when(StatsdNotifierConfig.fromGlobalConfig(any())).thenReturn(statsdNotifierConfig);

    PowerMockito.mockStatic(StatsdClient.class);
    when(StatsdClient.getInstance(any(), any(), anyInt())).thenReturn(null);

    PowerMockito.mockStatic(HttpNotifierConfig.class);
    when(HttpNotifierConfig.fromGlobalConfig((String)isNull(), (String)isNull(), any())).thenReturn(mock(HttpNotifierConfig.class));

    mockRun = mock(AbstractBuild.class);
    when(mockRun.getExternalizableId()).thenReturn(jobName);
}
 
@Test
public void testFromCobertura(){
  CoberturaBuildAction action = PowerMockito.mock(CoberturaBuildAction.class);
  AbstractBuild build = mock(AbstractBuild.class);
  when(action.getOwner()).thenReturn(build);
  File file = mock(File.class);
  when(build.getRootDir()).thenReturn(file);
  Map<CoverageMetric, Ratio> results = new HashMap<>();
  results.put(CoverageMetric.CONDITIONAL, Ratio.create(1, 10));
  results.put(CoverageMetric.CLASSES, Ratio.create(2, 10));
  results.put(CoverageMetric.FILES, Ratio.create(3, 10));
  results.put(CoverageMetric.LINE, Ratio.create(4, 10));
  results.put(CoverageMetric.METHOD, Ratio.create(5, 10));
  results.put(CoverageMetric.PACKAGES, Ratio.create(6, 10));
  
  when(action.getResults()).thenReturn(results);
  
  CodeCoverage coverage = CodeCoverage.fromCobertura(action);
  assertNotNull(coverage);
  assertEquals(10, coverage.getConditionals(), 0);
  assertEquals(20, coverage.getClasses(), 0);
  assertEquals(30, coverage.getFiles(), 0);
  assertEquals(40, coverage.getLines(), 0);
  assertEquals(50, coverage.getMethods(), 0);
  assertEquals(60, coverage.getPackages(), 0);
  assertEquals(-1f, coverage.getInstructions(), 0);

}
 
/**
 * Generate a results (pass/warn/fail) trend graph for recent results.
 *
 * @param owner       The build which owns the latest result.
 * @param isCompleted The flag to denote if the result is completed which determines our caching.
 * @param results     The list of previous to latest results which generate the trend.
 * @return The result trend graph.
 */
public static Graph createResultTrendGraph(AbstractBuild<?, ?> owner, Boolean isCompleted, List<AWSDeviceFarmTestResult> results) {
    List<String> rows = new ArrayList<String>();
    List<Number> vals = new ArrayList<Number>();
    List<NumberOnlyBuildLabel> cols = new ArrayList<NumberOnlyBuildLabel>();

    for (AWSDeviceFarmTestResult result : results) {
        Run<?, ?> build = result.getOwner();

        // Create label for this result using its Jenkins build number.
        NumberOnlyBuildLabel label = new NumberOnlyBuildLabel(build);

        // Add 'pass' results
        rows.add("Pass");
        cols.add(label);
        vals.add(result.getPassCount());

        // Add 'warn' results
        rows.add("Warn");
        cols.add(label);
        vals.add(result.getWarnCount());

        // Add 'fail' results.
        rows.add("Fail");
        cols.add(label);
        vals.add(result.getFailCount());
    }

    CategoryDataset dataset = createDataset(vals, rows, cols);
    Color[] colors = new Color[]{AWSDeviceFarmGraph.PassColor, AWSDeviceFarmGraph.WarnColor, AWSDeviceFarmGraph.FailColor};
    return new AWSDeviceFarmGraph(owner, isCompleted, getGraphSize(), dataset, "Build #", "# of tests", colors);
}
 
源代码24 项目: gitlab-plugin   文件: GitLabVotePublisherTest.java
@Test
public void removePreviousVote() throws IOException, InterruptedException {
    // GIVEN
    AbstractBuild build = mockSimpleBuild(GITLAB_CONNECTION_V4, Result.FAILURE);
    mockAward("v4", MERGE_REQUEST_IID, 1, "thumbsdown");

    // WHEN
    performAndVerify(build, "v4", MERGE_REQUEST_IID, "thumbsdown");

    // THEN
    mockServerClient.verify(prepareSendMessageWithSuccessResponse(build, "v4", MERGE_REQUEST_IID, "thumbsdown"));
    mockServerClient.verify(awardEmojiRequest("v4", MERGE_REQUEST_IID, "POST")
        .withQueryStringParameter("name", "thumbsdown"));
}
 
源代码25 项目: junit-plugin   文件: CaseResultTest.java
private FreeStyleBuild configureTestBuild(String projectName) throws Exception {
    FreeStyleProject p = projectName == null ? rule.createFreeStyleProject() : rule.createFreeStyleProject(projectName);
    p.getBuildersList().add(new TestBuilder() {
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            build.getWorkspace().child("junit.xml").copyFrom(
                getClass().getResource("junit-report-20090516.xml"));
            return true;
        }
    });
    p.getPublishersList().add(new JUnitResultArchiver("*.xml"));
    return rule.assertBuildStatus(Result.UNSTABLE, p.scheduleBuild2(0).get());
}
 
源代码26 项目: blueocean-plugin   文件: ArtifactsSecurity564.java
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
    FilePath f = new FilePath(build.getWorkspace(), path);
    f.mkdirs();
    for (int i = 0; i < numberOfFiles; i++) {
        new FilePath(f, i + ".txt").touch(System.currentTimeMillis());
    }

    return true;
}
 
@Test
public void testGetZipFolderEmpty() throws Exception {
    final OneShotEvent buildEnded = new OneShotEvent();

    FreeStyleProject p = j.createFreeStyleProject();
    p.getBuildersList().add(new TestBuilder() {
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher,
                               BuildListener listener) throws InterruptedException, IOException {
            build.getWorkspace().child("echo").mkdirs();
            buildEnded.signal();
            return true;
        }
    });

    p.scheduleBuild2(0);
    buildEnded.block();

    JenkinsLogger logger = new JenkinsLogger(System.out);
    WorkSpaceZipper workSpaceZipper = new WorkSpaceZipper(p.getSomeWorkspace(), logger);
    File zip = workSpaceZipper.getZip("echo");

    assertTrue(zip.exists());
    assertTrue(zip.getAbsolutePath().contains("awslambda-"));

    ZipFile zipFile = new ZipFile(zip);
    assertNotNull(zipFile);
    assertFalse(zipFile.entries().hasMoreElements());
}
 
源代码28 项目: ec2-spot-jenkins-plugin   文件: IntegrationTest.java
protected void assertLastBuildResult(final Result... lastBuildResults) {
    tryUntil(new Runnable() {
        @Override
        public void run() {
            final AbstractBuild lastBuild = j.jenkins.getProjects().get(0).getLastBuild();
            System.out.println("wait until " + Arrays.toString(lastBuildResults) + " current state "
                    + (lastBuild == null ? "<none>" : lastBuild.getResult()));
            Assert.assertNotNull(lastBuild);
            Assert.assertTrue(
                    lastBuild.getResult() + " should be in " + Arrays.toString(lastBuildResults),
                    Arrays.asList(lastBuildResults).contains(lastBuild.getResult()));
        }
    });
}
 
源代码29 项目: jira-ext-plugin   文件: SingleTicketStrategyTest.java
@Test
public void testExpansion()
        throws Exception
{
    AbstractBuild mockBuild = mock(AbstractBuild.class);
    EnvVars envVars = new EnvVars();
    envVars.put("FOO", "BAR");
    when(mockBuild.getEnvironment(any(BuildListener.class))).thenReturn(envVars);
    SingleTicketStrategy strategy = new SingleTicketStrategy("$FOO");
    List<JiraCommit> commits = strategy.getJiraCommits(mockBuild, mock(BuildListener.class));
    assertEquals(1, commits.size());
    assertEquals("BAR", commits.get(0).getJiraTicket());
}
 
源代码30 项目: credentials-binding-plugin   文件: Binding.java
@Deprecated
@SuppressWarnings("rawtypes")
public Environment bind(@Nonnull final AbstractBuild build, final Launcher launcher, final BuildListener listener) throws IOException, InterruptedException {
    final SingleEnvironment e = bindSingle(build, build.getWorkspace(), launcher, listener);
    return new Environment() {
        @Override public String value() {
            return e.value;
        }
        @Override public void unbind() throws IOException, InterruptedException {
            e.unbinder.unbind(build, build.getWorkspace(), launcher, listener);
        }
    };
}
 
 类所在包
 同包方法