Java 类hudson.model.FreeStyleBuild 实例源码

项目:cucumber-living-documentation-plugin    文件:CucumberLivingDocumentationIT.java   
@Test
public void shouldGenerateLivingDocumentatation() throws Exception{
    //given
    FreeStyleProject project = jenkins.createFreeStyleProject("test");
    SingleFileSCM scm = new SingleFileSCM("asciidoctor.json",
            CucumberLivingDocumentationIT.class.getResource("/json-output/asciidoctor/asciidoctor.json").toURI().toURL());

    project.setScm(scm);
    CukedoctorPublisher publisher = new CukedoctorPublisher(null, FormatType.HTML, TocType.RIGHT, true, true, "Living Documentation",false,false,false,false,false);
    project.getPublishersList().add(publisher);
    project.save();

    //when
    FreeStyleBuild build = jenkins.buildAndAssertSuccess(project);

    //then
    jenkins.assertLogContains("Format: html" + NEW_LINE + "Toc: right"+NEW_LINE +
            "Title: Living Documentation"+NEW_LINE+"Numbered: true"+NEW_LINE +
            "Section anchors: true", build);
    jenkins.assertLogContains("Found 4 feature(s)...",build);
    jenkins.assertLogContains("Documentation generated successfully!",build);

}
项目:cucumber-living-documentation-plugin    文件:CucumberLivingDocumentationIT.java   
@Test
public void shouldGenerateLivingDocumentatationOnSlaveNode() throws Exception{
    DumbSlave slave = jenkins.createOnlineSlave();
    FreeStyleProject project = jenkins.createFreeStyleProject("test");
    project.setAssignedNode(slave);

    SingleFileSCM scm = new SingleFileSCM("asciidoctor.json",
            CucumberLivingDocumentationIT.class.getResource("/json-output/asciidoctor/asciidoctor.json").toURI().toURL());

    project.setScm(scm);
    CukedoctorPublisher publisher = new CukedoctorPublisher(null, FormatType.HTML, TocType.RIGHT, true, true, "Living Documentation",false,false,false,false,false);
    project.getPublishersList().add(publisher);
    project.save();

    FreeStyleBuild build = jenkins.buildAndAssertSuccess(project);
    jenkins.assertLogContains("Format: html" + NEW_LINE + "Toc: right"+NEW_LINE +
            "Title: Living Documentation"+NEW_LINE+"Numbered: true"+NEW_LINE +
            "Section anchors: true", build);
    jenkins.assertLogContains("Found 4 feature(s)...",build);
    jenkins.assertLogContains("Documentation generated successfully!",build);
    Assert.assertTrue("It should run on slave",build.getBuiltOn().equals(slave));

}
项目:consul-kv-builder-plugin    文件:ConsulKVBuilderTest.java   
@Test
public void consulWrite() throws BuilderException {

    try {
        FreeStyleProject project = jenkinsRule.createFreeStyleProject();
        project.getBuildersList().add(new ConsulKVBuilder(ConsulKVBuilderTest.ACL_ID,
                ConsulKVBuilderTest.HOST, ConsulKVBuilderTest.KEY,
                ConsulKVBuilderTest.VALUE, null, null, RequestMode.WRITE, 30000, 30000, DebugMode.ENABLED, false));
        FreeStyleBuild build = project.scheduleBuild2(0).get();

        String log = FileUtils.readFileToString(build.getLogFile());
        assertThat(log, containsString(ConsulKVBuilderTest.WRITE_TEST_VALUE));
    } catch (IOException ioe) {
        throw new BuilderException(ConsulKVBuilderTest.IO_EXCEPTION_TEXT, ioe);
    } catch (InterruptedException ie) {
        throw new BuilderException(ConsulKVBuilderTest.INTERRUPTED_EXCEPTION_TEXT, ie);
    } catch (ExecutionException ee) {
        throw new BuilderException(ConsulKVBuilderTest.EXECUTION_EXCEPTION_TEXT, ee);
    }
}
项目:consul-kv-builder-plugin    文件:ConsulKVBuilderTest.java   
@Test
public void consulRead() throws BuilderException {
    try {
        FreeStyleProject project = jenkinsRule.createFreeStyleProject();
        project.getBuildersList().add(new ConsulKVBuilder(null, ConsulKVBuilderTest.HOST, ConsulKVBuilderTest
                .KEY, null,
                null, ConsulKVBuilderTest.ENV_KEY, RequestMode.READ, 30000,
                30000, DebugMode.ENABLED, false));
        FreeStyleBuild build = project.scheduleBuild2(0).get();

        String log = FileUtils.readFileToString(build.getLogFile());
        assertThat(log, containsString(ConsulKVBuilderTest.READ_TEST_VALUE_1));
        assertThat(log, containsString(ConsulKVBuilderTest.READ_TEST_VALUE_2));
    } catch (IOException ioe) {
        throw new BuilderException(ConsulKVBuilderTest.IO_EXCEPTION_TEXT, ioe);
    } catch (InterruptedException ie) {
        throw new BuilderException(ConsulKVBuilderTest.INTERRUPTED_EXCEPTION_TEXT, ie);
    } catch (ExecutionException ee) {
        throw new BuilderException(ConsulKVBuilderTest.EXECUTION_EXCEPTION_TEXT, ee);
    }
}
项目:consul-kv-builder-plugin    文件:ConsulKVBuilderTest.java   
@Test
public void consulDelete() throws BuilderException {
    try {
        FreeStyleProject project = jenkinsRule.createFreeStyleProject();
        project.getBuildersList().add(new ConsulKVBuilder(ConsulKVBuilderTest.ACL_ID,
                ConsulKVBuilderTest.HOST, ConsulKVBuilderTest.KEY, null, null, null, RequestMode.DELETE, 30000,
                30000,
                DebugMode.ENABLED, false));
        FreeStyleBuild build = project.scheduleBuild2(0).get();

        String log = FileUtils.readFileToString(build.getLogFile());
        assertThat(log, containsString(ConsulKVBuilderTest.WRITE_TEST_VALUE));
    } catch (IOException ioe) {
        throw new BuilderException(ConsulKVBuilderTest.IO_EXCEPTION_TEXT, ioe);
    } catch (InterruptedException ie) {
        throw new BuilderException(ConsulKVBuilderTest.INTERRUPTED_EXCEPTION_TEXT, ie);
    } catch (ExecutionException ee) {
        throw new BuilderException(ConsulKVBuilderTest.EXECUTION_EXCEPTION_TEXT, ee);
    }
}
项目:browserstack-integration-plugin    文件:AutomateTestActionTest.java   
@Test
public void testAutomateExceptionIsHandled() throws Exception {
    /* =================== Prepare ================= */
    new MockAutomateClientThatThrowsAutomateException();
    addBuildStep();
    project.getBuildersList().add(new TouchBuilder());

    /* =================== Execute ================= */
    FreeStyleBuild build = project.scheduleBuild2(0).get();
    AutomateTestAction automateTestAction = new AutomateTestAction(build, mockedCaseResult, "Random4756SessionId");
    Session automateSession = automateTestAction.getSession();

    /* =================== Verify ================= */
    Assert.assertNull("Automate Session MUST be null.", automateSession);
    Assert.assertNotNull("Exception MUST not be null.", automateTestAction.getLastException());
    Assert.assertTrue("Exception should be of Type AutomateException", automateTestAction.getLastException() instanceof AutomateException);
    Assert.assertTrue("Exception message MUST not be empty", StringUtils.isNotEmpty(automateTestAction.getLastError()));
}
项目:browserstack-integration-plugin    文件:AutomateTestActionTest.java   
@Test
public void testSessionNotFoundExceptionIsHandled() throws Exception {
    /* =================== Prepare ================= */
    new MockAutomateClientThatThrowsSessionNotFoundException();
    addBuildStep();
    project.getBuildersList().add(new TouchBuilder());

    /* =================== Execute ================= */
    FreeStyleBuild build = project.scheduleBuild2(0).get();
    AutomateTestAction automateTestAction = new AutomateTestAction(build, mockedCaseResult, "Random4756SessionId");
    Session automateSession = automateTestAction.getSession();

    /* =================== Verify ================= */
    Assert.assertNull("Automate Session MUST be null.", automateSession);
    Assert.assertNotNull("Exception MUST not be null.", automateTestAction.getLastException());
    Assert.assertTrue("Exception should be of Type SessionNotFound", automateTestAction.getLastException() instanceof SessionNotFound);
    Assert.assertTrue("Exception message MUST not be empty", StringUtils.isNotEmpty(automateTestAction.getLastError()));
}
项目:jenkins-deployment-manager-plugin    文件:GoogleCloudManagerBuildWrapperTest.java   
@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());
}
项目:jenkins-deployment-manager-plugin    文件:GoogleCloudManagerBuildWrapperTest.java   
@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());
}
项目:jenkins-deployment-manager-plugin    文件:GoogleCloudManagerDeployerTest.java   
@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());
}
项目:parameter-pool-plugin    文件:ParameterPoolTest.java   
@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);
}
项目:phabricator-jenkins-plugin    文件:BuildIntegrationTest.java   
protected FreeStyleBuild buildWithConduit(JSONObject queryDiffsResponse, JSONObject postCommentResponse, JSONObject sendMessageResponse, boolean harbormaster) throws Exception {
    Map<String, JSONObject> responses = new HashMap<String, JSONObject>();
    if (queryDiffsResponse != null) {
        responses.put("differential.querydiffs", queryDiffsResponse);
    }
    if (postCommentResponse != null) {
        responses.put("differential.createcomment", postCommentResponse);
    }
    if (sendMessageResponse != null) {
        responses.put("harbormaster.sendmessage", sendMessageResponse);
    }
    responses.put("differential.getcommitmessage", new JSONObject().element("result", "commit message"));
    conduit = new FakeConduit(responses);

    TestUtils.addValidCredentials(conduit);

    addBuildStep();

    TestUtils.setDefaultBuildEnvironment(j, harbormaster);

    return p.scheduleBuild2(0).get();
}
项目:phabricator-jenkins-plugin    文件:PhabricatorNotifierTest.java   
@Test
public void testFailBuildOnDecreasedCoverage() throws Exception {
    TestUtils.addCopyBuildStep(p, TestUtils.COBERTURA_XML, CoberturaXMLParser.class, "go-torch-coverage2.xml");
    UberallsClient uberalls = TestUtils.getDefaultUberallsClient();
    notifier = getDecreasedLineCoverageNotifier(0.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.FAILURE, build.getResult());
    assertLogContains("Sending build result to Harbormaster with PHID PHID-not-real, success: false", build);
}
项目:phabricator-jenkins-plugin    文件:PhabricatorNotifierTest.java   
@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());
}
项目:phabricator-jenkins-plugin    文件:PhabricatorNotifierTest.java   
@Test
public void testPassBuildOnSameCoverage() throws Exception {
    TestUtils.addCopyBuildStep(p, TestUtils.COBERTURA_XML, CoberturaXMLParser.class, "go-torch-coverage2.xml");
    UberallsClient uberalls = TestUtils.getDefaultUberallsClient();
    notifier = getDecreasedLineCoverageNotifier(0.0);
    when(uberalls.getCoverage(any(String.class))).thenReturn("{\n" +
        "  \"sha\": \"deadbeef\",\n" +
        "  \"lineCoverage\": 0.0,\n" +
        "  \"packageCoverage\": 0,\n" +
        "  \"classesCoverage\": 0,\n" +
        "  \"methodCoverage\": 0,\n" +
        "  \"conditionalCoverage\": 0\n" +
        "}");
    notifier.setUberallsClient(uberalls);

    FreeStyleBuild build = buildWithConduit(getFetchDiffResponse(), null, new JSONObject());
    assertEquals(Result.SUCCESS, build.getResult());
}
项目:phabricator-jenkins-plugin    文件:PhabricatorNotifierTest.java   
@Test
public void testPassBuildOnPositiveMaximumCoverageDecrease() throws Exception {
    TestUtils.addCopyBuildStep(p, TestUtils.COBERTURA_XML, CoberturaXMLParser.class, "go-torch-coverage2.xml");
    UberallsClient uberalls = TestUtils.getDefaultUberallsClient();
    notifier = getDecreasedLineCoverageNotifier(0.01);
    when(uberalls.getCoverage(any(String.class))).thenReturn("{\n" +
        "  \"sha\": \"deadbeef\",\n" +
        "  \"lineCoverage\": 95.2391,\n" +
        "  \"filesCoverage\": 0,\n" +
        "  \"packageCoverage\": 0,\n" +
        "  \"classesCoverage\": 0,\n" +
        "  \"methodCoverage\": 0,\n" +
        "  \"conditionalCoverage\": 0\n" +
        "}");
    notifier.setUberallsClient(uberalls);

    FreeStyleBuild build = buildWithConduit(getFetchDiffResponse(), null, new JSONObject());
    assertEquals(Result.SUCCESS, build.getResult());
}
项目:phabricator-jenkins-plugin    文件:PhabricatorNotifierTest.java   
@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);
}
项目:phabricator-jenkins-plugin    文件:CoberturaCoverageProviderTest.java   
@Test
public void testGetMetricsWithBuildActionResult() throws Exception {
    FreeStyleBuild build = getBuild();
    build.addAction(CoberturaBuildAction.load(
            build,
            getMockResult(),
            null,
            null,
            false,
            false,
            false,
            false,
            false
    ));
    provider.setBuild(build);
    assertTrue(provider.hasCoverage());

    CodeCoverageMetrics metrics = provider.getMetrics();
    assertNotNull(metrics);
    assertEquals(75.0f, metrics.getLineCoveragePercent(), 0.0f);
}
项目:phabricator-jenkins-plugin    文件:CoberturaCoverageProviderTest.java   
@Test
public void testGetLineCoverageWithFile() throws Exception {
    FreeStyleBuild build = getExecutedBuild();

    File coverageFile = new File(build.getWorkspace().getRemote(), "coverage0.xml");
    InputStream in = getClass().getResourceAsStream("go-torch-coverage.xml");
    OutputStream out = new BufferedOutputStream(new FileOutputStream(coverageFile));
    IOUtils.copy(in, out);
    out.close();
    provider.setBuild(build);

    Map<String, List<Integer>> coverage = provider.readLineCoverage();

    assertNotNull(coverage);
    assertEquals(1, coverage.get("github.com/uber/go-torch/visualization/visualization.go").get(66).longValue());
}
项目:phabricator-jenkins-plugin    文件:BuildResultProcessorTest.java   
private BuildResultProcessor runProcessLintViolationsTest(String lintFileContent, ConduitAPIClient conduitAPIClient)
        throws Exception {
    final String fileName = ".phabricator-lint";
    project.getBuildersList().add(echoBuilder(fileName, lintFileContent));
    FreeStyleBuild build = getBuild();

    BuildResultProcessor processor = new BuildResultProcessor(
            TestUtils.getDefaultLogger(),
            build,
            mock(Differential.class),
            new DifferentialClient(null, conduitAPIClient),
            TestUtils.TEST_PHID,
            mock(CodeCoverageMetrics.class),
            TestUtils.TEST_BASE_URL,
            true,
            new CoverageCheckSettings(true, 0.0, 100.0)
    );
    processor.processLintResults(fileName, "1000");
    processor.processHarbormaster();
    return processor;
}
项目:phabricator-jenkins-plugin    文件:RemoteFileFetcherTest.java   
@Test
public void testNoCommentConfigured() throws Exception {
    FreeStyleBuild build = getBuild();
    RemoteFileFetcher fetcher = new RemoteFileFetcher(
            build.getWorkspace(),
            logger,
            "",
            "1000"
    );

    assertNull(fetcher.getRemoteFile());

    fetcher = new RemoteFileFetcher(
            build.getWorkspace(),
            logger,
            "non-existent",
            "1000"
    );

    assertNull(fetcher.getRemoteFile());
}
项目:phabricator-jenkins-plugin    文件:RemoteFileFetcherTest.java   
private void testWithContent(String content, String len) throws Exception {
    final String fileName = "just-a-test.txt";
    project.getBuildersList().add(echoBuilder(fileName, content));
    FreeStyleBuild build = getBuild();

    RemoteFileFetcher fetcher = new RemoteFileFetcher(
            build.getWorkspace(),
            logger,
            fileName,
            len
    );

    assertEquals(content, fetcher.getRemoteFile());

    fetcher = new RemoteFileFetcher(
            build.getWorkspace(),
            logger,
            "*.txt",
            len
    );

    assertEquals(content, fetcher.getRemoteFile());
}
项目:sumologic-jenkins-plugin    文件:SumoBuildNotifierTest.java   
@Test
public void testSendBuildData() throws Exception {
  ArgumentCaptor<HttpRequest> captor = ArgumentCaptor.forClass(HttpRequest.class);
  FreeStyleProject project = j.createFreeStyleProject();

  project.getBuildersList().add(new Shell("Echo Hello"));
  project.getBuildersList().add(new Shell("Echo Hello2"));
  project.getBuildersList().add(new Shell("Echo Hello3"));
  project.getBuildersList().add(new Shell("Echo Hello4"));
  project.getPublishersList().add(new SumoBuildNotifier());

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  Mockito.verify(handler, atLeast(1)).handle(
      captor.capture(),
      Mockito.isA(HttpResponse.class),
      Mockito.isA(HttpContext.class));

  HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) captor.getValue();


  Assert.assertTrue("Message too short.", ModelFactory.createBuildModel(build).toJson().length() <= request.getEntity().getContentLength());
}
项目:yet-another-docker-plugin    文件:FreestyleTest.java   
@Override
public Boolean call() throws Throwable {
    final Jenkins jenkins = Jenkins.getInstance();

    // prepare job
    final FreeStyleProject project = jenkins.createProject(FreeStyleProject.class, "freestyle-project");
    final Shell env = new Shell("env");
    project.getBuildersList().add(env);
    project.setAssignedLabel(new LabelAtom(DOCKER_CLOUD_LABEL));
    project.save();

    LOG.trace("trace test.");
    project.scheduleBuild(new TestCause());

    // image pull may take time
    waitUntilNoActivityUpTo(jenkins, 10 * 60 * 1000);

    final FreeStyleBuild lastBuild = project.getLastBuild();
    assertThat(lastBuild, not(nullValue()));
    assertThat(lastBuild.getResult(), is(Result.SUCCESS));

    assertThat(getLog(lastBuild), Matchers.containsString(TEST_VALUE));
    assertThat(getLog(lastBuild), Matchers.containsString(CLOUD_ID + "=" + DOCKER_CLOUD_NAME));

    return true;
}
项目:yet-another-docker-plugin    文件:DockerSimpleBuildWrapperTest.java   
@Ignore("For local experiments")
@Test
public void testWrapper() throws Exception {
    final FreeStyleProject project = jRule.createProject(FreeStyleProject.class, "freestyle");

    final DockerConnector connector = new DockerConnector("tcp://" + ADDRESS + ":2376/");
    connector.setConnectorType(JERSEY);

    final DockerSlaveConfig config = new DockerSlaveConfig();
    config.getDockerContainerLifecycle().setImage("java:8-jdk-alpine");
    config.setLauncher(new NoOpDelegatingComputerLauncher(new DockerComputerSingleJNLPLauncher()));
    config.setRetentionStrategy(new DockerOnceRetentionStrategy(10));

    final DockerSimpleBuildWrapper dockerSimpleBuildWrapper = new DockerSimpleBuildWrapper(connector, config);
    project.getBuildWrappersList().add(dockerSimpleBuildWrapper);
    project.getBuildersList().add(new Shell("sleep 30"));

    final QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);

    jRule.waitUntilNoActivity();
    jRule.pause();
}
项目:docker-commons-plugin    文件:DockerRunFingerprintFacetTest.java   
@Test
public void test_readResolve() throws Exception {
    FreeStyleProject p = rule.createFreeStyleProject("test");
    FreeStyleBuild b = rule.assertBuildStatusSuccess(p.scheduleBuild2(0));

    ContainerRecord r1 = new ContainerRecord("192.168.1.10", "cid", IMAGE_ID, "magic", System.currentTimeMillis(), Collections.<String, String>emptyMap());
    DockerFingerprints.addRunFacet(r1, b);

    Fingerprint fingerprint = DockerFingerprints.of(IMAGE_ID);
    DockerRunFingerprintFacet facet = new DockerRunFingerprintFacet(fingerprint, System.currentTimeMillis(), IMAGE_ID);
    ContainerRecord r2 = new ContainerRecord("192.168.1.10", "cid", null, "magic", System.currentTimeMillis(), Collections.<String, String>emptyMap());
    facet.add(r2);

    Assert.assertNull(r2.getImageId());
    facet.readResolve();
    Assert.assertEquals(IMAGE_ID, r2.getImageId());

    // Check that actions have been automatically added
    DockerFingerprintAction fpAction = b.getAction(DockerFingerprintAction.class);
    Assert.assertNotNull("DockerFingerprintAction should be added automatically", fpAction);
    Assert.assertTrue("Docker image should be referred in the action", 
            fpAction.getImageIDs().contains(IMAGE_ID));
}
项目:dockerhub-notification-plugin    文件:BackCompat102Test.java   
@Test
@LocalData
public void testBuilds() {
    FreeStyleProject job = j.jenkins.getItemByFullName("JenkinsSlaveTrigger", FreeStyleProject.class);
    assertNotNull("The job should be loaded", job);

    RunList<FreeStyleBuild> builds = job.getBuilds();
    FreeStyleBuild two = builds.getLastBuild();
    assertNotNull(two);
    FreeStyleBuild one = two.getPreviousBuild();
    assertNotNull(one);

    assertSame("First build should be failure", Result.FAILURE, one.getResult());
    assertSame("Second build should be success", Result.SUCCESS, two.getResult());

    DockerHubWebHookCause cause = two.getCause(DockerHubWebHookCause.class);
    assertNotNull("The cause should be loaded", cause);
    PushNotification notification = cause.getPushNotification();
    assertNotNull("The cause should have a notification", notification);
    assertEquals("csanchez/jenkins-swarm-slave", notification.getRepoName());
    assertEquals("registry.hub.example.com", notification.getRegistryHost());
}
项目:google-storage-plugin    文件:DownloadStepTest.java   
@Test
public void testBuild() throws Exception {
  MockUploadModule module = new MockUploadModule(executor);
  DownloadStep step = new DownloadStep(CREDENTIALS_ID,
      "gs://bucket/path/to/object.txt",
      "", module);
  FreeStyleProject project = jenkins.createFreeStyleProject("testBuild");

  // Set up mock to retrieve the object
  StorageObject objToGet = new StorageObject();
  objToGet.setBucket("bucket");
  objToGet.setName("path/to/obj.txt");
  executor.when(Storage.Objects.Get.class, objToGet,
      MockUploadModule.checkGetObject("path/to/object.txt"));

  module.addNextMedia(IOUtils.toInputStream("test", "UTF-8"));

  project.getBuildersList().add(step);
  FreeStyleBuild build = jenkins.buildAndAssertSuccess(project);

  FilePath result = build.getWorkspace().withSuffix("/path/to/obj.txt");
  assertTrue(result.exists());
  assertEquals("test", result.readToString());
}
项目:google-storage-plugin    文件:DownloadStepTest.java   
@Test
public void testBuildPrefix() throws Exception {
  MockUploadModule module = new MockUploadModule(executor);
  DownloadStep step = new DownloadStep(CREDENTIALS_ID,
      "gs://bucket/path/to/object.txt",
      "subPath", module);
  step.setPathPrefix("path/to/");
  FreeStyleProject project = jenkins.createFreeStyleProject("testBuild");

  // Set up mock to retrieve the object
  StorageObject objToGet = new StorageObject();
  objToGet.setBucket("bucket");
  objToGet.setName("path/to/obj.txt");
  executor.when(Storage.Objects.Get.class, objToGet,
      MockUploadModule.checkGetObject("path/to/object.txt"));

  module.addNextMedia(IOUtils.toInputStream("test", "UTF-8"));

  project.getBuildersList().add(step);
  FreeStyleBuild build = jenkins.buildAndAssertSuccess(project);

  FilePath result = build.getWorkspace().withSuffix("/subPath/obj.txt");
  assertTrue(result.exists());
  assertEquals("test", result.readToString());
}
项目:google-storage-plugin    文件:DownloadStepTest.java   
@Test
public void testBuildMoreComplex() throws Exception {
  MockUploadModule module = new MockUploadModule(executor);
  DownloadStep step = new DownloadStep(CREDENTIALS_ID,
      "gs://bucket/download/$BUILD_ID/path/$BUILD_ID/test_$BUILD_ID.txt",
      "output", module);
  step.setPathPrefix("download/$BUILD_ID/");
  FreeStyleProject project = jenkins.createFreeStyleProject("testBuild");

  // Set up mock to retrieve the object
  StorageObject objToGet = new StorageObject();
  objToGet.setBucket("bucket");
  objToGet.setName("download/1/path/1/test_1.txt");
  executor.when(Storage.Objects.Get.class, objToGet,
      MockUploadModule.checkGetObject("download/1/path/1/test_1.txt"));

  module.addNextMedia(IOUtils.toInputStream("contents 1", "UTF-8"));

  project.getBuildersList().add(step);
  FreeStyleBuild build = jenkins.buildAndAssertSuccess(project);

  FilePath result = build.getWorkspace()
      .withSuffix("/output/path/1/test_1.txt");
  assertTrue(result.exists());
  assertEquals("contents 1", result.readToString());
}
项目:google-storage-plugin    文件:ClassicUploadStepTest.java   
@Test
public void testBuild() throws Exception {
  ClassicUploadStep step = new ClassicUploadStep(CREDENTIALS_ID, BUCKET_URI,
      new MockUploadModule(executor), "*.$BUILD_ID.txt");
  FreeStyleProject project = jenkins.createFreeStyleProject("testBuild");

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class,
      MockUploadModule.checkBucketName(BUCKET_NAME));
  executor.passThruWhen(Storage.Objects.Insert.class,
      MockUploadModule.checkObjectName("abc.1.txt"));

  project.getBuildersList().add(step);

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  // Put three different files in the workspace. Only one should match if
  // the expansion is done correctly.
  build.getWorkspace().child("abc.7.txt").write("hello", "UTF-8");
  build.getWorkspace().child("abc.1.txt").write("hello", "UTF-8");
  build.getWorkspace().child("abc.$BUILD_ID.txt").write("hello", "UTF-8");
  step.perform(build, build.getWorkspace(),
      build.getWorkspace().createLauncher(TaskListener.NULL),
      TaskListener.NULL);
}
项目:google-storage-plugin    文件:ClassicUploadStepTest.java   
@Test
public void testInvalidCredentials() throws Exception {
  ClassicUploadStep step = new ClassicUploadStep("bad-credentials",
      BUCKET_URI, new MockUploadModule(executor), "*.$BUILD_ID.txt");
  FreeStyleProject project = jenkins.createFreeStyleProject("testBuild");

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class,
      MockUploadModule.checkBucketName(BUCKET_NAME));
  executor.passThruWhen(Storage.Objects.Insert.class,
      MockUploadModule.checkObjectName("abc.1.txt"));

  project.getBuildersList().add(step);
  FreeStyleBuild build = project.scheduleBuild2(0).get();

  try {
    step.perform(build, build.getWorkspace(),
        build.getWorkspace().createLauncher(TaskListener.NULL),
        TaskListener.NULL);
  } catch (AbortException e) {
    assertTrue(e.getMessage().contains("bad-credentials"));
    return;
  }
  // Expected exception to happen.
  assertTrue(false);
}
项目:pretested-integration-plugin    文件:FastForwardSingleCommitsIT.java   
@Test
public void acc_fastForwardSingleCommitFails_SkipsWhenMultipleCommits() throws Exception {
    List<TestCommit> commits = new ArrayList<TestCommit>() {
        {
            add(new TestCommit("master", "README.md", "# Commit 1", "1: added readme"));
            add(new TestCommit("ready/feature_1", "README.md", "# Commit 2", "2: updated readme"));
            add(new TestCommit("ready/feature_1", "README.md", "# Commit 3", "3: updated readme some more"));
        }
    };
    repository = TestUtilsFactory.createRepository("acc_fastForwardsSingleCommits", commits);

    FreeStyleProject project = TestUtilsFactory.configurePretestedIntegrationPlugin(jenkinsRule, TestUtilsFactory.STRATEGY_TYPE.ACCUMULATED, repository);
    TestUtilsFactory.triggerProject(project);
    jenkinsRule.waitUntilNoActivityUpTo(60000);

    FreeStyleBuild build = project.getFirstBuild();
    assertTrue("The result should be SUCCESS, but is : " + build.getResult(),build.getResult().isBetterOrEqualTo(Result.SUCCESS));

    String console = jenkinsRule.createWebClient().getPage(project.getLastBuild(), "console").asText();
    System.out.println(console);
    repository.close();
    assertTrue("FF merge should have been skipped.", console.contains("Skip FF as there are several commits"));
}
项目:google-storage-plugin    文件:GoogleCloudStorageUploaderTest.java   
@Test
public void testFilePlainWithFailureAndUpload() throws Exception {
  forFailedJobs = true;

  underTest = new GoogleCloudStorageUploader(CREDENTIALS_ID,
      ImmutableList.<AbstractUpload>of(setOptionalParams(
          new ClassicUpload(bucket, new MockUploadModule(executor),
              glob, null /* legacy arg */, null /* legacy arg */))));

  project.getBuildersList().add(new Shell("echo foo > bar.txt"));
  // Fail the build to show that the uploader does nothing.
  project.getBuildersList().add(new FailureBuilder());
  project.getPublishersList().add(underTest);

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  assertEquals(Result.FAILURE, build.getResult());
}
项目:google-storage-plugin    文件:GoogleCloudStorageUploaderTest.java   
@Test
public void testFileGlob() throws Exception {
  glob = "*.txt";
  underTest = new GoogleCloudStorageUploader(CREDENTIALS_ID,
      ImmutableList.<AbstractUpload>of(setOptionalParams(
          new ClassicUpload(bucket, new MockUploadModule(executor),
              glob, null /* legacy arg */, null /* legacy arg */))));

  project.getBuildersList().add(new Shell("echo foo > bar.txt"));
  project.getPublishersList().add(underTest);

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  assertEquals(Result.SUCCESS, build.getResult());
}
项目:google-storage-plugin    文件:GoogleCloudStorageUploaderTest.java   
@Test
public void testAbsolutePath() throws Exception {
  String absoluteFilePath = "/tmp/bar.txt";
  glob = absoluteFilePath;
  underTest = new GoogleCloudStorageUploader(CREDENTIALS_ID,
      ImmutableList.<AbstractUpload>of(setOptionalParams(
          new ClassicUpload(bucket, new MockUploadModule(executor),
              glob, null /* legacy arg */, null /* legacy arg */))));

  project.getBuildersList().add(new Shell("echo foo > " +
      absoluteFilePath));
  project.getPublishersList().add(underTest);

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  assertEquals(Result.SUCCESS, build.getResult());
}
项目:google-storage-plugin    文件:GoogleCloudStorageUploaderTest.java   
@Test
public void testAbsoluteGlob() throws Exception {
  String absoluteFilePath1 = "/tmp/bar.1.txt";
  String absoluteFilePath2 = "/tmp/bar.2.txt";
  glob = "/tmp/bar.*.txt";
  underTest = new GoogleCloudStorageUploader(CREDENTIALS_ID,
      ImmutableList.<AbstractUpload>of(setOptionalParams(
          new ClassicUpload(bucket, new MockUploadModule(executor),
              glob, null /* legacy arg */, null /* legacy arg */))));

  project.getBuildersList().add(new Shell("echo foo > " +
      absoluteFilePath1));
  project.getBuildersList().add(new Shell("echo foo > " +
      absoluteFilePath2));
  project.getPublishersList().add(underTest);

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  assertEquals(Result.SUCCESS, build.getResult());
}
项目:pretested-integration-plugin    文件:FastForwardSingleCommitsIT.java   
@Test
public void acc_fastForwardSingleCommitFails_FailsWhenImpossible() throws Exception {
    List<TestCommit> commits = new ArrayList<TestCommit>() {
        {
            add(new TestCommit("master", "README.md", "# Commit 1", "1: added readme"));
            add(new TestCommit("ready/feature_1", "README.md", "# 2", "Commit 2: updated readme"));
            add(new TestCommit("master", "README.md", "# Commit 3", "3: added readme"));
        }
    };
    repository = TestUtilsFactory.createRepository("acc_fastForwardsSingleCommits", commits);

    FreeStyleProject project = TestUtilsFactory.configurePretestedIntegrationPlugin(jenkinsRule, TestUtilsFactory.STRATEGY_TYPE.ACCUMULATED, repository);
    TestUtilsFactory.triggerProject(project);
    jenkinsRule.waitUntilNoActivityUpTo(60000);

    FreeStyleBuild build = project.getFirstBuild();
    jenkinsRule.assertBuildStatus(Result.FAILURE, build);
    String console = jenkinsRule.createWebClient().getPage(project.getLastBuild(), "console").asText();
    System.out.println(console);
    assertTrue("FF merge should have failed.", console.contains("FF merge failed."));
}
项目:google-storage-plugin    文件:GoogleCloudStorageUploaderTest.java   
@Test
public void testFileWithRecursiveGlob() throws Exception {
  glob = "**/*.txt";
  underTest = new GoogleCloudStorageUploader(CREDENTIALS_ID,
      ImmutableList.<AbstractUpload>of(setOptionalParams(
          new ClassicUpload(bucket, new MockUploadModule(executor),
              glob, null /* legacy arg */, null /* legacy arg */))));

  project.getBuildersList().add(
      new Shell("mkdir blah; echo foo > blah/bar.txt"));
  project.getPublishersList().add(underTest);

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  assertEquals(Result.SUCCESS, build.getResult());
}
项目:google-storage-plugin    文件:GoogleCloudStorageUploaderTest.java   
@Test
public void testMultiFileGlob() throws Exception {
  glob = "*.txt";
  underTest = new GoogleCloudStorageUploader(CREDENTIALS_ID,
      ImmutableList.<AbstractUpload>of(setOptionalParams(
          new ClassicUpload(bucket, new MockUploadModule(executor),
              glob, null /* legacy arg */, null /* legacy arg */))));

  project.getBuildersList().add(
      new Shell("echo foo > foo.txt; echo bar > bar.txt"));
  project.getPublishersList().add(underTest);

  executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
  executor.passThruWhen(Storage.Buckets.Insert.class);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);
  executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);

  FreeStyleBuild build = project.scheduleBuild2(0).get();

  assertEquals(Result.SUCCESS, build.getResult());
}