Java Code Examples for hudson.model.FreeStyleProject#scheduleBuild2()

The following examples show how to use hudson.model.FreeStyleProject#scheduleBuild2() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DockerSimpleBuildWrapperTest.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@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();
}
 
Example 2
Source File: DockerComputerConnectorTest.java    From docker-plugin with MIT License 6 votes vote down vote up
protected void should_connect_agent(DockerTemplate template) throws IOException, ExecutionException, InterruptedException, TimeoutException {

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

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

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

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

        final FreeStyleProject project = j.createFreeStyleProject("test-docker-ssh");
        project.setAssignedLabel(Label.get(LABEL));
        project.getBuildersList().add(new Shell("whoami"));
        final QueueTaskFuture<FreeStyleBuild> scheduledBuild = project.scheduleBuild2(0);
        try {
            final FreeStyleBuild build = scheduledBuild.get(60L, TimeUnit.SECONDS);
            Assert.assertTrue(build.getResult() == Result.SUCCESS);
            Assert.assertTrue(build.getLog().contains("jenkins"));
        } finally {
            scheduledBuild.cancel(true);
        }
    }
 
Example 3
Source File: QueuesTest.java    From jenkins-client-java with MIT License 6 votes vote down vote up
@Test
public void getItems() throws IOException
{
    Queue queue = queues.getItems();
    assertNotNull(queue.getItems());
    assertEquals(0, queue.getItems().size());

    j.jenkins.setNumExecutors(0);
    FreeStyleProject project = j.createFreeStyleProject();
    project.scheduleBuild2(0);

    queue = queues.getItems();
    List<QueueItem> items = queue.getItems();
    assertEquals(1, items.size());

    QueueItem firstItem = items.get(0);
    int firstItemId = firstItem.getId();

    assertNotNull(queues.getItem(firstItemId));

    queues.cancelItem(firstItemId);
    assertEquals(0, queues.getItems().getItems().size());
}
 
Example 4
Source File: AWSDeviceFarmRecorderTest.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
@Issue("JENKINS-50483")
public void dataSerializationSmokeTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    AWSDeviceFarmRecorder rec = new AWSDeviceFarmRecorder(
            "TestProjectName", "TestDevicePool", null, null,
            null, null, "APPIUM_JAVA_JUNIT", false, false, null,
            null, null, null, null, null, null,
            null, null, null, null, null, null, null, null,
            null, null, null, null, null, null,
            null, null, null, null, false, false,
            null, null, null, null, null, null,
            false, false, false, 10, false, false,
            false, false, false, null
    );
    p.getPublishersList().add(rec);

    // Try to build it. It is not supposed to work, but we will filter out the JEP-200 exception
    final QueueTaskFuture<FreeStyleBuild> future = p.scheduleBuild2(0);
    final FreeStyleBuild build = future.get();
    j.assertBuildStatus(Result.FAILURE, build);
    // Currently it fails with Either IAM Role ARN or AKID/SKID must be set and does not report the serialization issue after that

    // No matter what, we should be able to save the project even after the failure
    p.save();
    build.save();
}
 
Example 5
Source File: DollarSecretPatternFactoryTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-24805")
@Test
public void maskingFreeStyleSecrets() throws Exception {
    String firstCredentialsId = "creds_1";
    String firstPassword = "a$build";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, firstCredentialsId, "sample1", Secret.fromString(firstPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    String secondCredentialsId = "creds_2";
    String secondPassword = "a$$b";
    StringCredentialsImpl secondCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, secondCredentialsId, "sample2", Secret.fromString(secondPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), secondCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding("PASS_1", firstCredentialsId),
            new StringBinding("PASS_2", secondCredentialsId)));

    FreeStyleProject project = r.createFreeStyleProject();

    project.setConcurrentBuild(true);
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo \"$PASS_1\""));
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_2%") : new Shell("echo \"$PASS_2\""));
    project.getBuildersList().add(new Maven("$PASS_1 $PASS_2", "default"));
    project.getBuildWrappersList().add(wrapper);

    r.configRoundtrip((Item)project);

    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    FreeStyleBuild build = future.get();
    r.assertLogNotContains(firstPassword, build);
    r.assertLogNotContains(firstPassword.replace("$", "$$"), build);
    r.assertLogNotContains(secondPassword, build);
    r.assertLogNotContains(secondPassword.replace("$", "$$"), build);
    r.assertLogContains("****", build);
}
 
Example 6
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_differentTargetBranch() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new GitLabWebHookCause(causeData()
            .withActionType(CauseData.ActionType.NOTE)
            .withSourceProjectId(1)
            .withTargetProjectId(1)
            .withBranch("feature")
            .withSourceBranch("feature")
            .withUserName("")
            .withSourceRepoHomepage("https://gitlab.org/test")
            .withSourceRepoName("test")
            .withSourceNamespace("test-namespace")
            .withSourceRepoUrl("[email protected]:test.git")
            .withSourceRepoSshUrl("[email protected]:test.git")
            .withSourceRepoHttpUrl("https://gitlab.org/test.git")
            .withMergeRequestTitle("Test")
            .withMergeRequestId(1)
            .withMergeRequestIid(1)
            .withTargetBranch("master")
            .withTargetRepoName("test")
            .withTargetNamespace("test-namespace")
            .withTargetRepoSshUrl("[email protected]:test.git")
            .withTargetRepoHttpUrl("https://gitlab.org/test.git")
            .withTriggeredByUser("test")
            .withLastCommit("123")
            .withTargetProjectUrl("https://gitlab.org/test")
            .build()));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example 7
Source File: NoteBuildActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_alreadyBuiltMR_alreadyBuiltMR() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master")));
    future.get();

    exception.expect(HttpResponses.HttpResponseException.class);
    new NoteBuildAction(testProject, getJson("NoteEvent_alreadyBuiltMR.json"), null).execute(response);

    verify(trigger).onPost(any(NoteHook.class));
}
 
Example 8
Source File: BuildPageRedirectActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void redirectToBuildStatusUrl() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.setScm(new GitSCM(gitRepoUrl));
    testProject.setQuietPeriod(0);
    QueueTaskFuture<FreeStyleBuild> future = testProject.scheduleBuild2(0);
    FreeStyleBuild build = future.get(15, TimeUnit.SECONDS);

    doThrow(IOException.class).when(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getUrl());
    getBuildPageRedirectAction(testProject).execute(response);

    verify(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getBuildStatusUrl());
}
 
Example 9
Source File: BuildPageRedirectActionTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void redirectToBuildUrl() throws IOException, ExecutionException, InterruptedException, TimeoutException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    testProject.setScm(new GitSCM(gitRepoUrl));
    testProject.setQuietPeriod(0);
    QueueTaskFuture<FreeStyleBuild> future = testProject.scheduleBuild2(0);
    FreeStyleBuild build = future.get(15, TimeUnit.SECONDS);

    getBuildPageRedirectAction(testProject).execute(response);

    verify(response).sendRedirect2(jenkins.getInstance().getRootUrl() + build.getUrl());
}
 
Example 10
Source File: WorkSpaceZipperTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@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());
}
 
Example 11
Source File: WorkSpaceZipperTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetZipFolder() 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").child("index.js").copyFrom(new FileInputStream(testUtil.getResource("echo/index.js")));
            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);
    assertNotNull(zipFile.getEntry("index.js"));
}
 
Example 12
Source File: WorkSpaceZipperTest.java    From aws-lambda-jenkins-plugin with MIT License 5 votes vote down vote up
@Test
public void testGetZipWithZip() 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.zip").copyFrom(new FileInputStream(testUtil.getResource("echo.zip")));
            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.zip");

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

    ZipFile zipFile = new ZipFile(zip);
    assertNotNull(zipFile);
    assertNotNull(zipFile.getEntry("index.js"));
}
 
Example 13
Source File: DockerBuildImageStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Test
    public void testBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"))
                ;
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setNoCache(true);

        DockerBuildImageStep dockerBuildImageStep = new DockerBuildImageStep(dockerConnector, buildImage);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(dockerBuildImageStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 14
Source File: DockerImageComboStepTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Ignore
    @Test
    public void testComboBuild() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
        String dockerfilePath = dumbSlave.getChannel().call(new StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"));
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerBuildImage buildImage = new DockerBuildImage();
        buildImage.setBaseDirectory(dockerfilePath);
        buildImage.setPull(true);
        buildImage.setTags(Collections.singletonList("localhost:5000/myfirstimage"));

        DockerImageComboStep comboStep = new DockerImageComboStep(dockerConnector, buildImage);
        comboStep.setClean(true);
        comboStep.setCleanupDangling(true);
        comboStep.setPush(true);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(comboStep);

        project.save();

        QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);
        FreeStyleBuild freeStyleBuild = taskFuture.get();
        jRule.waitForCompletion(freeStyleBuild);
        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 15
Source File: DockerShellStepIT.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Test
    public void testDockerShellStep() throws Throwable {
        jRule.getInstance().setNumExecutors(0);
//        jRule.createSlave();
//        jRule.createSlave("my-slave", "remote-slave", new EnvVars());
        final UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
                null, "description", "vagrant", "vagrant");

        CredentialsStore store = CredentialsProvider.lookupStores(jRule.getInstance()).iterator().next();
        store.addCredentials(Domain.global(), credentials);

        final SSHLauncher sshLauncher = new SSHLauncher("192.168.33.10", 22, credentials.getId(),
                "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", //jvmopts
                "", //      String javaPath,
                "",  //      String prefixStartSlaveCmd,
                "", //      String suffixStartSlaveCmd,
                20, //      Integer launchTimeoutSeconds,
                1, //      Integer maxNumRetries,
                3,//      Integer retryWaitTime
                new NonVerifyingKeyVerificationStrategy()
        );
        final DumbSlave dumbSlave = new DumbSlave("docker-daemon", "/home/vagrant/jenkins2", sshLauncher);
        jRule.getInstance().addNode(dumbSlave);
        await().timeout(60, SECONDS).until(() -> assertThat(dumbSlave.getChannel(), notNullValue()));
//        String dockerfilePath = dumbSlave.getChannel().call(new DockerBuildImageStepTest.StringThrowableCallable());


        final CredentialsYADockerConnector dockerConnector = new CredentialsYADockerConnector()
                .withConnectorType(JERSEY)
                .withServerUrl("tcp://127.0.0.1:2376")
                .withSslConfig(new LocalDirectorySSLConfig("/home/vagrant/keys"));
//                .withCredentials(new DockerDaemonFileCredentials(null, "docker-cert", "",
//                        "/home/vagrant/keys"));

        DockerShellStep dockerShellStep = new DockerShellStep();
        dockerShellStep.setShellScript("env && pwd");
        dockerShellStep.setConnector(dockerConnector);

        FreeStyleProject project = jRule.createFreeStyleProject("test");
        project.getBuildersList().add(dockerShellStep);

        project.save();

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

        jRule.waitForCompletion(freeStyleBuild);

        jRule.assertBuildStatusSuccess(freeStyleBuild);
    }
 
Example 16
Source File: FreeStyleProjectTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void migrateToScript() throws Exception {
  LockableResourcesManager.get().createResource("resource1");

  FreeStyleProject p = j.createFreeStyleProject("p");
  p.addProperty(
      new RequiredResourcesProperty(
          null, null, null, "groovy:resourceName == 'resource1'", null));

  p.save();

  j.jenkins.reload();

  FreeStyleProject p2 = j.jenkins.getItemByFullName("p", FreeStyleProject.class);
  RequiredResourcesProperty newProp = p2.getProperty(RequiredResourcesProperty.class);
  assertNull(newProp.getLabelName());
  assertNotNull(newProp.getResourceMatchScript());
  assertEquals("resourceName == 'resource1'", newProp.getResourceMatchScript().getScript());

  SemaphoreBuilder p2Builder = new SemaphoreBuilder();
  p2.getBuildersList().add(p2Builder);

  FreeStyleProject p3 = j.createFreeStyleProject("p3");
  p3.addProperty(new RequiredResourcesProperty("resource1", null, "1", null, null));
  SemaphoreBuilder p3Builder = new SemaphoreBuilder();
  p3.getBuildersList().add(p3Builder);

  final QueueTaskFuture<FreeStyleBuild> taskA =
      p3.scheduleBuild2(0, new TimerTrigger.TimerTriggerCause());
  TestHelpers.waitForQueue(j.jenkins, p3);
  final QueueTaskFuture<FreeStyleBuild> taskB =
      p2.scheduleBuild2(0, new TimerTrigger.TimerTriggerCause());

  p3Builder.release();
  final FreeStyleBuild buildA = taskA.get(60, TimeUnit.SECONDS);
  p2Builder.release();
  final FreeStyleBuild buildB = taskB.get(60, TimeUnit.SECONDS);

  long buildAEndTime = buildA.getStartTimeInMillis() + buildA.getDuration();
  assertTrue(
      "Project A build should be finished before the build of project B starts. "
          + "A finished at "
          + buildAEndTime
          + ", B started at "
          + buildB.getStartTimeInMillis(),
      buildB.getStartTimeInMillis() >= buildAEndTime);
}
 
Example 17
Source File: FreeStyleProjectTest.java    From lockable-resources-plugin with MIT License 4 votes vote down vote up
@Test
public void approvalRequired() throws Exception {
  LockableResourcesManager.get().createResource(LockableResourcesRootAction.ICON);

  j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

  j.jenkins.setAuthorizationStrategy(
      new MockAuthorizationStrategy()
          .grant(Jenkins.READ, Item.READ)
          .everywhere()
          .toAuthenticated()
          .grant(Jenkins.ADMINISTER)
          .everywhere()
          .to("bob")
          .grant(Item.CONFIGURE, Item.BUILD)
          .everywhere()
          .to("alice"));

  final String SCRIPT =
      "resourceName == org.jenkins.plugins.lockableresources.actions.LockableResourcesRootAction.ICON;";

  FreeStyleProject p = j.createFreeStyleProject();
  SecureGroovyScript groovyScript =
      new SecureGroovyScript(SCRIPT, true, null).configuring(ApprovalContext.create());

  p.addProperty(new RequiredResourcesProperty(null, null, null, null, groovyScript));

  User.getOrCreateByIdOrFullName("alice");
  JenkinsRule.WebClient wc = j.createWebClient();
  wc.login("alice");

  QueueTaskFuture<FreeStyleBuild> futureBuild = p.scheduleBuild2(0);
  TestHelpers.waitForQueue(j.jenkins, p, Queue.BlockedItem.class);

  Queue.BlockedItem blockedItem = (Queue.BlockedItem) j.jenkins.getQueue().getItem(p);
  assertThat(
      blockedItem.getCauseOfBlockage(),
      is(instanceOf(LockableResourcesQueueTaskDispatcher.BecauseResourcesQueueFailed.class)));

  ScriptApproval approval = ScriptApproval.get();
  List<ScriptApproval.PendingSignature> pending = new ArrayList<>();
  pending.addAll(approval.getPendingSignatures());

  assertFalse(pending.isEmpty());
  assertEquals(1, pending.size());
  ScriptApproval.PendingSignature firstPending = pending.get(0);

  assertEquals(
      "staticField org.jenkins.plugins.lockableresources.actions.LockableResourcesRootAction ICON",
      firstPending.signature);
  approval.approveSignature(firstPending.signature);

  j.assertBuildStatusSuccess(futureBuild);
}
 
Example 18
Source File: HudsonTestCaseShutdownSlaveTest.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
public void testShutdownSlave() throws Exception {
    DumbSlave slave1 = createOnlineSlave(); // online, and a build finished.
    DumbSlave slave2 = createOnlineSlave(); // online, and a build finished, and disconnected.
    DumbSlave slave3 = createOnlineSlave(); // online, and a build still running.
    DumbSlave slave4 = createOnlineSlave(); // online, and not used.
    DumbSlave slave5 = createSlave();   // offline.
    
    assertNotNull(slave1);
    assertNotNull(slave2);
    assertNotNull(slave3);
    assertNotNull(slave4);
    assertNotNull(slave5);
    
    // A build runs on slave1 and finishes.
    {
        FreeStyleProject project1 = createFreeStyleProject();
        project1.setAssignedLabel(LabelExpression.parseExpression(slave1.getNodeName()));
        project1.getBuildersList().add(new SleepBuilder(1 * 1000));
        assertBuildStatusSuccess(project1.scheduleBuild2(0));
    }
    
    // A build runs on slave2 and finishes, then disconnect slave2 
    {
        FreeStyleProject project2 = createFreeStyleProject();
        project2.setAssignedLabel(LabelExpression.parseExpression(slave2.getNodeName()));
        project2.getBuildersList().add(new SleepBuilder(1 * 1000));
        assertBuildStatusSuccess(project2.scheduleBuild2(0));
        
        SlaveComputer computer2 = slave2.getComputer();
        computer2.disconnect(null);
        computer2.waitUntilOffline();
    }
    
    // A build runs on slave3 and does not finish.
    // This build will be interrupted in tearDown().
    {
        FreeStyleProject project3 = createFreeStyleProject();
        project3.setAssignedLabel(LabelExpression.parseExpression(slave3.getNodeName()));
        project3.getBuildersList().add(new SleepBuilder(10 * 60 * 1000));
        project3.scheduleBuild2(0);
        FreeStyleBuild build;
        while((build = project3.getLastBuild()) == null) {
            Thread.sleep(500);
        }
        assertTrue(build.isBuilding());
    }
}