@Test
  public void testRebuild() throws Exception {
    // job with promotion process
    FreeStyleProject p1 = j.createFreeStyleProject("promojob");

    // setup promotion process
    JobPropertyImpl promotion = new JobPropertyImpl(p1);
    p1.addProperty(promotion);
    PromotionProcess proc = promotion.addProcess("promo");
    proc.conditions.add(new SelfPromotionCondition(false));

    // build it
    FreeStyleBuild b1 = j.assertBuildStatusSuccess(p1.scheduleBuild2(0));
    j.waitUntilNoActivity();

    // verify that promotion happened
    Assert.assertSame(proc.getBuilds().getLastBuild().getTarget(), b1);

    // job with parameter
    FreeStyleProject p2 = j.createFreeStyleProject("paramjob");

    // add promoted build param
    p2.addProperty(
        new ParametersDefinitionProperty(
            new PromotedBuildParameterDefinition(
                "var", "promojob", "promo", "promoted build param to test rebuild")));

    // build with parameter
    FreeStyleBuild b2 = j.assertBuildStatusSuccess(p2.scheduleBuild2(0));

    // validate presence of parameter
    ParametersAction a1 = b2.getAction(ParametersAction.class);
    Assert.assertNotNull(a1);
    Assert.assertFalse(a1.getParameters().isEmpty());
    ParameterValue v1 = a1.getParameter("var");
    Assert.assertTrue(v1 instanceof PromotedBuildParameterValue);
    PromotedBuildParameterValue pbpv1 = (PromotedBuildParameterValue) v1;
    Assert.assertEquals(b1.getNumber(), pbpv1.getRun().getNumber());

    // rebuild it
    JenkinsRule.WebClient wc = j.createWebClient();
    HtmlPage page = wc.getPage(b2, "rebuild");
    HtmlForm form = page.getFormByName("config");
    j.submit(form);
    j.waitUntilNoActivity();

    // validate presence of parameter
    FreeStyleBuild rebuild = p2.getLastBuild();
    j.assertBuildStatusSuccess(rebuild);
    Assert.assertNotEquals(b2.getNumber(), rebuild.getNumber());
    ParametersAction a2 = rebuild.getAction(ParametersAction.class);
    Assert.assertNotNull(a2);
    Assert.assertFalse(a2.getParameters().isEmpty());
    ParameterValue v2 = a2.getParameter("var");
    Assert.assertTrue(v2 instanceof PromotedBuildParameterValue);
    PromotedBuildParameterValue pbpv2 = (PromotedBuildParameterValue) v2;
    Assert.assertEquals(b1.getNumber(), pbpv2.getRun().getNumber());
  }
 /**
  * Interrupting the flow ought to interrupt its downstream builds too, even across nested parallel
  * branches.
  */
 @Test
 public void interruptFlow() throws Exception {
   FreeStyleProject ds1 = j.createFreeStyleProject("ds1");
   ds1.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
   FreeStyleProject ds2 = j.createFreeStyleProject("ds2");
   ds2.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
   FreeStyleProject ds3 = j.createFreeStyleProject("ds3");
   ds3.getBuildersList().add(new SleepBuilder(Long.MAX_VALUE));
   WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, "us");
   us.setDefinition(
       new CpsFlowDefinition(
           "parallel ds1: {build 'ds1'}, ds23: {parallel ds2: {build 'ds2'}, ds3: {build 'ds3'}}",
           true));
   j.jenkins.setNumExecutors(3);
   j.jenkins.setNodes(
       j.jenkins.getNodes()); // TODO https://github.com/jenkinsci/jenkins/pull/1596 renders this
   // workaround unnecessary
   WorkflowRun usb = us.scheduleBuild2(0).getStartCondition().get();
   assertEquals(1, usb.getNumber());
   FreeStyleBuild ds1b, ds2b, ds3b;
   while ((ds1b = ds1.getLastBuild()) == null
       || (ds2b = ds2.getLastBuild()) == null
       || (ds3b = ds3.getLastBuild()) == null) {
     Thread.sleep(100);
   }
   assertEquals(1, ds1b.getNumber());
   assertEquals(1, ds2b.getNumber());
   assertEquals(1, ds3b.getNumber());
   // Same as X button in UI.
   // Should be the same as, e.g., GerritTrigger.RunningJobs.cancelJob, which calls
   // Executor.interrupt directly.
   // (Not if the Executor.currentExecutable is an AfterRestartTask.Body, though in that case
   // probably the FreeStyleBuild would have been killed by restart anyway!)
   usb.doStop();
   j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(usb));
   j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds1b));
   j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds2b));
   j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(ds3b));
 }
  /** This test unit is for testing a commit hook using the UUID */
  @Bug(399165)
  @Test
  public void testPrebuiltCommitTrigger() throws Exception {
    hudson.setCrumbIssuer(null);

    // First create repository with 1 file and commit information
    SVNCommitInfo info = createSVNRepository();
    assertNull(info.getErrorMessage());
    assertEquals("Failed to create 1 revision.", 1, info.getNewRevision());

    // Create freestyle project with SVN SCM.
    FreeStyleProject project = createFreeStyleProject();
    project.setScm(new SubversionSCM("file:///tmp/399165"));
    SCMTrigger trigger = new SCMTrigger("0 */6 * * *");
    project.addTrigger(trigger);
    trigger.start(project, true);

    // Execute build (This is critical for fixing eclipse bug: 399165)
    assertBuildStatusSuccess(project.scheduleBuild2(0));

    // Commit a file again.
    info = createSecondCommit();
    assertNull(info.getErrorMessage());
    assertEquals("Failed to create second commit.", 2, info.getNewRevision());

    // Create post-commit hook
    WebClient wc = new WebClient();
    WebRequestSettings wr =
        new WebRequestSettings(
            new URL(
                getURL() + "subversion/" + repository.getRepositoryUUID(false) + "/notifyCommit"),
            HttpMethod.POST);
    wr.setRequestBody("A   dirB/file2.txt");
    wr.setAdditionalHeader("Content-Type", "text/plain;charset=UTF-8");

    wr.setAdditionalHeader("X-Hudson-Subversion-Revision", "2");

    WebConnection conn = wc.getWebConnection();
    System.out.println(wr);
    WebResponse resp = conn.getResponse(wr);
    assertTrue(isGoodHttpStatus(resp.getStatusCode()));

    waitUntilNoActivity();
    FreeStyleBuild b = project.getLastBuild();
    assertNotNull(b);

    assertBuildStatus(Result.SUCCESS, b);

    assertEquals("Failed to execute a buid.", 2, b.getNumber());
  }
  public void testMultipleExecutors() throws Exception {

    // Job1 runs for 1 second, no dependencies
    FreeStyleProject theJob1 = createFreeStyleProject("MultipleExecutor_Job1");
    theJob1.getBuildersList().add(new Shell("sleep 1; exit 0"));
    assertTrue(theJob1.getBuilds().isEmpty());

    // Job2 returns immediatly but can't run while Job1 is running.
    FreeStyleProject theJob2 = createFreeStyleProject("MultipleExecutor_Job2");
    {
      BuildBlockerProperty theProperty = new BuildBlockerProperty();
      theProperty.setBlockingJobs("MultipleExecutor_Job1");
      theJob2.addProperty(theProperty);
    }
    assertTrue(theJob1.getBuilds().isEmpty());

    // allow executing two simultanious jobs
    int theOldNumExecutors = Hudson.getInstance().getNumExecutors();
    Hudson.getInstance().setNumExecutors(2);

    Future<FreeStyleBuild> theFuture1 = theJob1.scheduleBuild2(0);
    Future<FreeStyleBuild> theFuture2 = theJob2.scheduleBuild2(0);
    while (!theFuture1.isDone() || !theFuture2.isDone()) {
      // let the jobs process
    }

    // check if job2 was not started before job1 was finished
    Run theRun1 = theJob1.getLastBuild();
    Run theRun2 = theJob2.getLastBuild();
    assertTrue(theRun1.getTimeInMillis() + theRun1.getDuration() <= theRun2.getTimeInMillis());

    // restore changed settings
    Hudson.getInstance().setNumExecutors(theOldNumExecutors);
    theJob2.delete();
    theJob1.delete();
  }
  @Test
  public void testPostCommitTrigger() throws Exception {
    // Disable crumbs because HTMLUnit refuses to mix request bodies with
    // request parameters
    hudson.setCrumbIssuer(null);

    FreeStyleProject p = createFreeStyleProject();
    String url = "https://tsethudsonsvn.googlecode.com/svn/trunk";
    SCMTrigger trigger = new SCMTrigger("0 */6 * * *");

    p.setScm(new SubversionSCM(url));
    p.addTrigger(trigger);
    trigger.start(p, true);

    String repoUUID = "b703df53-fdd9-0691-3d8c-58db40123d9f";

    WebClient wc = new WebClient();
    WebRequestSettings wr =
        new WebRequestSettings(
            new URL(getURL() + "subversion/" + repoUUID + "/notifyCommit"), HttpMethod.POST);
    wr.setRequestBody("A   trunk/testcommit.txt");
    wr.setAdditionalHeader("Content-Type", "text/plain;charset=UTF-8");

    wr.setAdditionalHeader("X-Hudson-Subversion-Revision", "16");

    WebConnection conn = wc.getWebConnection();
    WebResponse resp = conn.getResponse(wr);
    assertTrue(isGoodHttpStatus(resp.getStatusCode()));

    waitUntilNoActivity();
    FreeStyleBuild b = p.getLastBuild();
    assertNotNull(b);
    assertBuildStatus(Result.SUCCESS, b);

    SVNRevisionState revisionState = b.getAction(SVNRevisionState.class);

    assertNotNull("Failed to find revision", revisionState);

    assertNotNull("Failed to find revision", revisionState.revisions.get(url));

    assertEquals(16, revisionState.revisions.get(url).longValue());
  }
  public void testManualAbortProcess() throws Exception {
    ProcessTree.enabled = true;
    FreeStyleProject project = createFreeStyleProject();

    // this contains a maven project with a single test that sleeps 5s.
    project.setScm(
        new ExtractResourceSCM(getClass().getResource("ProcessTreeKiller-test-project.jar")));
    project.getBuildersList().add(new Maven("install", "maven"));

    // build the project, wait until tests are running, then cancel.
    project.scheduleBuild2(0).waitForStart();

    FreeStyleBuild b = project.getLastBuild();
    b.doStop();

    Thread.sleep(1000);

    // will fail (at least on windows) if test process is still running
    b.getWorkspace().deleteRecursive();
  }
 @Issue("JENKINS-28063")
 @Test
 public void coalescedQueue() throws Exception {
   FreeStyleProject ds = j.createFreeStyleProject("ds");
   ds.setConcurrentBuild(true);
   ds.getBuildersList().add(new SleepBuilder(3000));
   WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, "us");
   us.setDefinition(new CpsFlowDefinition("echo \"triggered #${build('ds').number}\"", true));
   QueueTaskFuture<WorkflowRun> us1F = us.scheduleBuild2(0);
   us1F.waitForStart(); // make sure we do not coalesce the us `Queue.Item`s
   QueueTaskFuture<WorkflowRun> us2F = us.scheduleBuild2(0);
   WorkflowRun us1 = us1F.get();
   assertEquals(1, us1.getNumber());
   j.assertLogContains("triggered #1", us1);
   WorkflowRun us2 = us2F.get();
   assertEquals(2, us2.getNumber());
   j.assertLogContains("triggered #1", us2);
   FreeStyleBuild ds1 = ds.getLastBuild();
   assertEquals(1, ds1.getNumber());
   assertEquals(2, ds1.getCauses().size()); // 2× UpstreamCause
 }