Java Code Examples for hudson.model.queue.QueueTaskFuture

The following examples show how to use hudson.model.queue.QueueTaskFuture. These examples are extracted from open source projects. 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 Project: aws-codecommit-trigger-plugin   Author: riboseinc   File: AbstractPipelineTestProject.java    License: Apache License 2.0 6 votes vote down vote up
protected void subscribeProject(ProjectFixture fixture) throws Exception {
    String name = UUID.randomUUID().toString();
    WorkflowJob job = jenkinsRule.getInstance().createProject(WorkflowJob.class, name);

    String script = fixture.getPipelineScript().replace("${EmitEvent}", AbstractPipelineTestProject.class.getName() + ".emitBuildEvent()");
    CpsFlowDefinition flowDefinition = new CpsFlowDefinition(script, true);
    job.setDefinition(flowDefinition);

    QueueTaskFuture<WorkflowRun> run = job.scheduleBuild2(0);
    WorkflowRun wfRun = run.get();
    Assertions.assertThat(wfRun.getResult())
        .describedAs("Pipeline unable to start succeed")
        .isEqualTo(Result.SUCCESS);
    jenkinsRule.assertBuildStatusSuccess(wfRun);

    resetPipelineBuildEvent(fixture);

    if (!fixture.isHasTrigger()) {
        return;
    }

    final String uuid = this.sqsQueue.getUuid();
    SQSTrigger trigger = new SQSTrigger(uuid, fixture.isSubscribeInternalScm(), fixture.getScmConfigs());
    job.addTrigger(trigger);
    trigger.start(job, false);
}
 
Example #2
Source Project: jenkins-mattermost-plugin   Author: kuleuven   File: MattermostSendStepIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
  public void test_fail_on_error() throws Exception {
    WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "workflow");
    // just define message
	  job.setDefinition(
			  new CpsFlowDefinition(
					  "mattermostSend(message: 'message', endpoint: 'endpoint', icon: 'icon', channel: '#channel', color: 'good', failOnError: true);",
					  true));
	  //noinspection ConstantConditions
	  //job.scheduleBuild(0,new Cause.UserIdCause());
	  QueueTaskFuture<WorkflowRun> workflowRunQueueTaskFuture = job.scheduleBuild2(0);
	  //WorkflowRun workflowRun = workflowRunQueueTaskFuture.getStartCondition().get();
	  //workflowRun.getExecutionPromise().get();
	  WorkflowRun run = jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRunQueueTaskFuture);
	  //jenkinsRule.assertBuildStatusSuccess(workflowRun);
	  // everything should come from step configuration
//	  String log = JenkinsRule.getLog(run);
//	  Assert.assertTrue(log.contains("Warn"));
	  //TODO jenkinsRule.assertLogContains(
	  //   "Mattermost notification failed. See Jenkins logs for details.", run);
  }
 
Example #3
Source Project: yet-another-docker-plugin   Author: KostyaSha   File: DockerSimpleBuildWrapperTest.java    License: 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 #4
Source Project: docker-plugin   Author: jenkinsci   File: DockerComputerConnectorTest.java    License: 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 #5
Source Project: jenkins-client-java   Author: jenkins-zh   File: JobsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void getBuildDetails() throws Exception
{

    FreeStyleProject project = j.createFreeStyleProject();
    QueueTaskFuture<FreeStyleBuild> build = project.scheduleBuild2(0);
    assertNotNull(build);
    build.waitForStart();
    j.waitForCompletion(build.get());

    BuildDetail buildDetails = jobs.getBuildDetails(project.getName(), 1);
    assertNotNull(buildDetails);
}
 
Example #6
Source Project: jenkins-client-java   Author: jenkins-zh   File: JobsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void getLastBuildDetails() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject project = j.createFreeStyleProject();
    QueueTaskFuture<FreeStyleBuild> build = project.scheduleBuild2(0);
    assertNotNull(build);
    build.waitForStart();
    j.waitForCompletion(build.get());

    BuildDetail buildDetails = jobs.getLastBuildDetails(project.getName());
    assertNotNull(buildDetails);
}
 
Example #7
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineNodeTest.java    License: MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-49297")
public void submitInputPostBlock() throws Exception {
    WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    URL resource = Resources.getResource(getClass(), "stepsFromPost.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    job.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    QueueTaskFuture<WorkflowRun> buildTask = job.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    List<Map> nodes = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);

    assertEquals(1, nodes.size());

    List<Map> steps = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/" + nodes.get(0).get("id") + "/steps/", List.class);

    assertEquals(3, steps.size());

    assertEquals("7", steps.get(0).get("id"));
    assertEquals("Hello World", steps.get(0).get("displayDescription"));
    assertEquals("12", steps.get(1).get("id"));
    assertEquals("Hello World from post", steps.get(1).get("displayDescription"));
    assertEquals("13", steps.get(2).get("id"));
    assertEquals("Wait for interactive input", steps.get(2).get("displayName"));
}
 
Example #8
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineNodeTest.java    License: MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-48884")
public void submitInputPostBlockWithParallelStages() throws Exception {
    WorkflowJob job = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    URL resource = Resources.getResource(getClass(), "parallelStepsFromPost.jenkinsfile");
    String jenkinsFile = Resources.toString(resource, Charsets.UTF_8);
    job.setDefinition(new CpsFlowDefinition(jenkinsFile, true));
    QueueTaskFuture<WorkflowRun> buildTask = job.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    List<Map> nodes = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);

    assertEquals(6, nodes.size());

    List<Map> steps = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/" + nodes.get(0).get("id") + "/steps/", List.class);

    assertEquals(4, steps.size());

    assertEquals("15", steps.get(0).get("id"));
    assertEquals("exit 1", steps.get(0).get("displayDescription"));
    assertEquals("17", steps.get(1).get("id"));
    assertEquals("hello stable", steps.get(1).get("displayDescription"));
    assertEquals("47", steps.get(2).get("id"));
    assertEquals("Hello World from post", steps.get(2).get("displayDescription"));
    assertEquals("48", steps.get(3).get("id"));
    assertEquals("Wait for interactive input", steps.get(3).get("displayName"));
}
 
Example #9
Source Project: ec2-spot-jenkins-plugin   Author: awslabs   File: IntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
protected List<QueueTaskFuture> getQueueTaskFutures(int count) throws IOException {
    final LabelAtom label = new LabelAtom("momo");

    final List<QueueTaskFuture> rs = new ArrayList<>();
    for (int i = 0; i < count; i++) {
        final FreeStyleProject project = j.createFreeStyleProject();
        project.setAssignedLabel(label);
        project.getBuildersList().add(Functions.isWindows() ? new BatchFile("Ping -n " + JOB_SLEEP_TIME + " 127.0.0.1 > nul") : new Shell("sleep " + JOB_SLEEP_TIME));
        rs.add(project.scheduleBuild2(0));
    }
    return rs;
}
 
Example #10
private static void waitTasksFinish(List<QueueTaskFuture> tasks) {
    for (final QueueTaskFuture<FreeStyleBuild> task : tasks) {
        try {
            task.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #11
Source Project: ec2-spot-jenkins-plugin   Author: awslabs   File: AutoResubmitIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_successfully_resubmit_freestyle_task() throws Exception {
    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
            0, 0, 10, 1, false, false,
            false, 0, 0, false,
            10, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    System.out.println("check if zero nodes!");
    Assert.assertEquals(0, j.jenkins.getNodes().size());

    assertAtLeastOneNode();

    final Node node = j.jenkins.getNodes().get(0);
    assertQueueIsEmpty();

    System.out.println("disconnect node");
    node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));

    // due to test nature job could be failed if started or aborted as we call disconnect
    // in prod code it's not matter
    assertLastBuildResult(Result.FAILURE, Result.ABORTED);

    node.toComputer().connect(true);
    assertNodeIsOnline(node);
    assertQueueAndNodesIdle(node);

    Assert.assertEquals(1, j.jenkins.getProjects().size());
    Assert.assertEquals(Result.SUCCESS, j.jenkins.getProjects().get(0).getLastBuild().getResult());
    Assert.assertEquals(2, j.jenkins.getProjects().get(0).getBuilds().size());

    cancelTasks(rs);
}
 
Example #12
Source Project: ec2-spot-jenkins-plugin   Author: awslabs   File: AutoResubmitIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_resubmit_if_disabled() throws Exception {
    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, new LocalComputerConnector(j), false, false,
            0, 0, 10, 1, false, false,
            true, 0, 0, false, 10, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    System.out.println("check if zero nodes!");
    Assert.assertEquals(0, j.jenkins.getNodes().size());

    assertAtLeastOneNode();

    final Node node = j.jenkins.getNodes().get(0);
    assertQueueIsEmpty();

    System.out.println("disconnect node");
    node.toComputer().disconnect(new OfflineCause.ChannelTermination(new UnsupportedOperationException("Test")));

    assertLastBuildResult(Result.FAILURE, Result.ABORTED);

    node.toComputer().connect(true);
    assertNodeIsOnline(node);
    assertQueueAndNodesIdle(node);

    Assert.assertEquals(1, j.jenkins.getProjects().size());
    Assert.assertEquals(Result.FAILURE, j.jenkins.getProjects().get(0).getLastBuild().getResult());
    Assert.assertEquals(1, j.jenkins.getProjects().get(0).getBuilds().size());

    cancelTasks(rs);
}
 
Example #13
Source Project: ec2-spot-jenkins-plugin   Author: awslabs   File: ProvisionIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_add_planned_if_capacity_required_but_not_described_yet() throws Exception {
    ComputerLauncher computerLauncher = mock(ComputerLauncher.class);
    ComputerConnector computerConnector = mock(ComputerConnector.class);
    when(computerConnector.launch(anyString(), any(TaskListener.class))).thenReturn(computerLauncher);

    mockEc2ApiToDescribeFleetNotInstanceWhenModified();

    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, computerConnector, false, false,
            0, 0, 10, 1, false, false,
            false, 0, 0, false,
            2, false);
    j.jenkins.clouds.add(cloud);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    triggerSuggestReviewNow("momo");

    Assert.assertEquals(0, j.jenkins.getNodes().size());

    tryUntil(new Runnable() {
        @Override
        public void run() {
            Assert.assertEquals(0, j.jenkins.getNodes().size());
            Assert.assertEquals(2, j.jenkins.getLabels().size());
            Assert.assertEquals(1, j.jenkins.getLabelAtom("momo").nodeProvisioner.getPendingLaunches().size());
        }
    });

    cancelTasks(rs);
}
 
Example #14
Source Project: ec2-spot-jenkins-plugin   Author: awslabs   File: ProvisionIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_keep_planned_node_until_node_will_not_be_online_so_jenkins_will_not_request_overprovision() throws Exception {
    ComputerLauncher computerLauncher = mock(ComputerLauncher.class);
    ComputerConnector computerConnector = mock(ComputerConnector.class);
    when(computerConnector.launch(anyString(), any(TaskListener.class))).thenReturn(computerLauncher);

    EC2FleetCloud cloud = spy(new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, computerConnector, false, false,
            0, 0, 10, 1, false, false,
            false, 300, 15, false,
            2, false));

    // provide init state
    cloud.setStats(new FleetStateStats("", 0, "active",
            Collections.<String>emptySet(), Collections.<String, Double>emptyMap()));

    j.jenkins.clouds.add(cloud);

    mockEc2ApiToDescribeInstancesWhenModified(InstanceStateName.Running);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    final String labelString = "momo";
    triggerSuggestReviewNow(labelString);

    Thread.sleep(TimeUnit.MINUTES.toMillis(2));

    verify(cloud, times(1)).provision(any(Label.class), anyInt());

    cancelTasks(rs);
}
 
Example #15
Source Project: ec2-spot-jenkins-plugin   Author: awslabs   File: ProvisionIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_convert_planned_to_node_if_state_is_not_running_and_check_state_enabled() throws Exception {
    ComputerLauncher computerLauncher = mock(ComputerLauncher.class);
    ComputerConnector computerConnector = mock(ComputerConnector.class);
    when(computerConnector.launch(anyString(), any(TaskListener.class))).thenReturn(computerLauncher);

    EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, "region",
            null, "fId", "momo", null, computerConnector, false, false,
            0, 0, 10, 1, true, false,
            false, 0, 0, false,
            2, false);
    j.jenkins.clouds.add(cloud);

    mockEc2ApiToDescribeInstancesWhenModified(InstanceStateName.Pending);

    List<QueueTaskFuture> rs = getQueueTaskFutures(1);

    triggerSuggestReviewNow("momo");

    Assert.assertEquals(0, j.jenkins.getNodes().size());

    tryUntil(new Runnable() {
        @Override
        public void run() {
            Assert.assertEquals(ImmutableSet.of("master", "momo"), labelsToNames(j.jenkins.getLabels()));
            Assert.assertEquals(1, j.jenkins.getLabelAtom("momo").nodeProvisioner.getPendingLaunches().size());
            Assert.assertEquals(0, j.jenkins.getNodes().size());
        }
    });

    cancelTasks(rs);
}
 
Example #16
Source Project: jenkins-test-harness   Author: jenkinsci   File: JenkinsRule.java    License: MIT License 5 votes vote down vote up
/**
 * Runs specified job and asserts that in finished with given build result.
 * @since TODO
 */
@Nonnull
public <J extends Job<J,R> & ParameterizedJobMixIn.ParameterizedJob<J,R>,R extends Run<J,R> & Queue.Executable> R buildAndAssertStatus(@Nonnull Result status, @Nonnull J job) throws Exception {
    final QueueTaskFuture<R> f = new ParameterizedJobMixIn<J, R>() {
        @Override protected J asJob() {
            return job;
        }
    }.scheduleBuild2(0);
    return assertBuildStatus(status, f);
}
 
Example #17
Source Project: github-integration-plugin   Author: KostyaSha   File: GitHubPRRepository.java    License: MIT License 5 votes vote down vote up
@Override
public FormValidation doBuild(StaplerRequest req) throws IOException {
    FormValidation result;

    try {
        if (!job.hasPermission(Item.BUILD)) {
            return FormValidation.error("Forbidden");
        }

        final String prNumberParam = "prNumber";
        int prId = 0;
        if (req.hasParameter(prNumberParam)) {
            prId = Integer.valueOf(req.getParameter(prNumberParam));
        }

        if (prId == 0 || !getPulls().containsKey(prId)) {
            return FormValidation.error("No branch to build");
        }

        final GitHubPRPullRequest localPR = getPulls().get(prId);
        final GitHubPRCause cause = new GitHubPRCause(localPR, null, this, false, "Manual run.");

        final JobRunnerForCause runner = new JobRunnerForCause(getJob(), ghPRTriggerFromJob(getJob()));
        final QueueTaskFuture<?> queueTaskFuture = runner.startJob(cause);

        if (nonNull(queueTaskFuture)) {
            result = FormValidation.ok("Build scheduled");
        } else {
            result = FormValidation.warning("Build not scheduled");
        }
    } catch (Exception e) {
        LOG.error("Can't start build", e.getMessage());
        result = FormValidation.error(e, "Can't start build: " + e.getMessage());
    }

    return result;
}
 
Example #18
Source Project: github-integration-plugin   Author: KostyaSha   File: JobHelper.java    License: MIT License 5 votes vote down vote up
public static boolean rebuild(Run<?, ?> run) {
    final QueueTaskFuture queueTaskFuture = asParameterizedJobMixIn(run.getParent())
            .scheduleBuild2(
                    0,
                    run.getAction(ParametersAction.class),
                    run.getAction(CauseAction.class),
                    run.getAction(BuildBadgeAction.class)
            );
    return queueTaskFuture != null;
}
 
Example #19
Source Project: github-integration-plugin   Author: KostyaSha   File: GitHubBranchRepository.java    License: MIT License 5 votes vote down vote up
@RequirePOST
public FormValidation doBuild(StaplerRequest req) throws IOException {
    FormValidation result;

    try {
        if (!job.hasPermission(Item.BUILD)) {
            return FormValidation.error("Forbidden");
        }

        final String param = "branchName";
        String branchName = null;
        if (req.hasParameter(param)) {
            branchName = req.getParameter(param);
        }
        if (isNull(branchName) || !getBranches().containsKey(branchName)) {
            return FormValidation.error("No branch to build");
        }

        final GitHubBranch localBranch = getBranches().get(branchName);
        final GitHubBranchCause cause = new GitHubBranchCause(localBranch, this, "Manual run.", false);
        final JobRunnerForBranchCause runner = new JobRunnerForBranchCause(getJob(),
                ghBranchTriggerFromJob(job));
        final QueueTaskFuture<?> queueTaskFuture = runner.startJob(cause);

        if (nonNull(queueTaskFuture)) {
            result = FormValidation.ok("Build scheduled");
        } else {
            result = FormValidation.warning("Build not scheduled");
        }
    } catch (Exception e) {
        LOG.error("Can't start build", e.getMessage());
        result = FormValidation.error(e, "Can't start build: " + e.getMessage());
    }

    return result;
}
 
Example #20
Source Project: github-integration-plugin   Author: KostyaSha   File: JobRunnerForBranchCause.java    License: MIT License 5 votes vote down vote up
@Override
public boolean apply(GitHubBranchCause cause) {
    try {
        cause.setPollingLogFile(trigger.getPollingLogAction().getPollingLogFile());

        StringBuilder sb = new StringBuilder();
        sb.append("Jenkins queued the run (").append(cause.getReason()).append(")");

        if (trigger.isCancelQueued() && cancelQueuedBuildByBranchName(cause.getBranchName())) {
            sb.append(". Queued builds aborted");
        }

        QueueTaskFuture<?> queueTaskFuture = startJob(cause);
        if (isNull(queueTaskFuture)) {
            LOGGER.error("{} job didn't start", job.getFullName());
        }

        LOGGER.info(sb.toString());

        // remote connection
        if (trigger.isPreStatus()) {
            trigger.getRemoteRepository()
                    .createCommitStatus(cause.getCommitSha(),
                            GHCommitState.PENDING,
                            null,
                            sb.toString(),
                            job.getFullName());
        }
    } catch (IOException e) {
        LOGGER.error("Can't trigger build ({})", e.getMessage(), e);
        return false;
    }
    return true;
}
 
Example #21
Source Project: github-integration-plugin   Author: KostyaSha   File: JobRunnerForCauseTest.java    License: MIT License 5 votes vote down vote up
public static QueueTaskFuture schedule(Job<?, ?> job, int number, String param, int queuetPeriod) {
    ParameterizedJobMixIn jobMixIn = JobInfoHelpers.asParameterizedJobMixIn(job);
    GitHubPRCause cause = newGitHubPRCause().withNumber(number);
    ParametersAction parametersAction = new ParametersAction(
            Collections.<ParameterValue>singletonList(new StringParameterValue("value", param))
    );
    return jobMixIn.scheduleBuild2(queuetPeriod, new CauseAction(cause), parametersAction);
}
 
Example #22
Source Project: aws-device-farm-jenkins-plugin   Author: awslabs   File: AWSDeviceFarmRecorderTest.java    License: 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 #23
Source Project: gitlab-plugin   Author: jenkinsci   File: BuildPageRedirectActionTest.java    License: 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 #24
Source Project: gitlab-plugin   Author: jenkinsci   File: BuildPageRedirectActionTest.java    License: 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 #25
Source Project: gitlab-plugin   Author: jenkinsci   File: NoteBuildActionTest.java    License: 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 #26
Source Project: gitlab-plugin   Author: jenkinsci   File: NoteBuildActionTest.java    License: 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 #27
Source Project: gitlab-plugin   Author: jenkinsci   File: MergeRequestBuildActionTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void build_acceptedMr() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject testProject = jenkins.createFreeStyleProject();
    trigger.setTriggerOnAcceptedMergeRequest(true);
    trigger.setTriggerOnMergeRequest(false);
    testProject.addTrigger(trigger);
    testProject.setScm(new GitSCM(gitRepoUrl));
    QueueTaskFuture<?> future = testProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("gitlabTargetBranch", "master")));
    future.get();

    executeMergeRequestAction(testProject, getJson("MergeRequestEvent_merged.json"));
    assertTrue(wouldFire);
}
 
Example #28
Source Project: gitlab-plugin   Author: jenkinsci   File: MergeRequestBuildActionTest.java    License: 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.MERGE)
            .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();

    executeMergeRequestAction(testProject, getJson("MergeRequestEvent_alreadyBuiltMR_differentTargetBranch.json"));

    assertTrue(wouldFire);
}
 
Example #29
Source Project: credentials-binding-plugin   Author: jenkinsci   File: DollarSecretPatternFactoryTest.java    License: 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 #30
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineNodeTest.java    License: MIT License 4 votes vote down vote up
@Test
public void waitForInputTest() throws Exception {
    String script = "node {\n" +
        "    stage(\"parallelStage\"){\n" +
        "      parallel left : {\n" +
        "            echo \"running\"\n" +
        "            def branchInput = input message: 'Please input branch to test against', parameters: [[$class: 'StringParameterDefinition', defaultValue: 'master', description: '', name: 'branch']]\n" +
        "            echo \"BRANCH NAME: ${branchInput}\"\n" +
        "        }, \n" +
        "        right : {\n" +
        "            sh 'sleep 100000'\n" +
        "        }\n" +
        "    }\n" +
        "}";

    WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
    job1.setDefinition(new CpsFlowDefinition(script, false));
    QueueTaskFuture<WorkflowRun> buildTask = job1.scheduleBuild2(0);
    WorkflowRun run = buildTask.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) run.getExecutionPromise().get();

    while (run.getAction(InputAction.class) == null) {
        e.waitForSuspension();
    }

    Map runResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/");

    Assert.assertEquals("PAUSED", runResp.get("state"));

    List<FlowNodeWrapper> nodes = NodeGraphBuilder.NodeGraphBuilderFactory.getInstance(run).getPipelineNodes();

    List<Map> nodesResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/nodes/", List.class);

    Assert.assertEquals("PAUSED", nodesResp.get(0).get("state"));
    Assert.assertEquals("UNKNOWN", nodesResp.get(0).get("result"));
    Assert.assertEquals("parallelStage", nodesResp.get(0).get("displayName"));

    Assert.assertEquals("PAUSED", nodesResp.get(1).get("state"));
    Assert.assertEquals("UNKNOWN", nodesResp.get(1).get("result"));
    Assert.assertEquals("left", nodesResp.get(1).get("displayName"));

    Assert.assertEquals("RUNNING", nodesResp.get(2).get("state"));
    Assert.assertEquals("UNKNOWN", nodesResp.get(2).get("result"));
    Assert.assertEquals("right", nodesResp.get(2).get("displayName"));

    List<Map> stepsResp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/steps/", List.class);

    Assert.assertEquals("RUNNING", stepsResp.get(0).get("state"));
    Assert.assertEquals("UNKNOWN", stepsResp.get(0).get("result"));
    Assert.assertEquals("13", stepsResp.get(0).get("id"));

    Assert.assertEquals("PAUSED", stepsResp.get(2).get("state"));
    Assert.assertEquals("UNKNOWN", stepsResp.get(2).get("result"));
    Assert.assertEquals("12", stepsResp.get(2).get("id"));
}