/**
  * Akin to {@link JenkinsRule#configRoundtrip(Builder)}.
  *
  * @param <S> step type
  * @param before the incoming step
  * @return the result after displaying in a form and resaving
  */
 @SuppressWarnings("unchecked")
 public <S extends Step> S configRoundTrip(S before) throws Exception {
   FreeStyleProject p = rule.createFreeStyleProject();
   p.getBuildersList().add(new StepBuilder(before));
   // workaround for eclipse compiler Ambiguous method call
   p = (FreeStyleProject) rule.configRoundtrip((Item) p);
   StepBuilder b = p.getBuildersList().get(StepBuilder.class);
   assertNotNull(b);
   Step after = b.s;
   assertNotNull(after);
   assertEquals(before.getClass(), after.getClass());
   return (S) after;
 }
  /**
   * TODO DOCUMENT ME!
   *
   * @throws Exception
   */
  @Test
  public void testSaveConfig() throws Exception {
    FreeStyleProject project = jenkinsRule.createFreeStyleProject();
    JiraExtBuildStep builder =
        new JiraExtBuildStep(
            new MentionedInCommitStrategy(),
            Arrays.asList((JiraOperationExtension) new AddComment(true, "Hello World")));
    project.getBuildersList().add(builder);

    jenkinsRule.submit(
        jenkinsRule.createWebClient().getPage(project, "configure").getFormByName("config"));

    JiraExtBuildStep after = project.getBuildersList().get(JiraExtBuildStep.class);
    jenkinsRule.assertEqualBeans(builder, after, "issueStrategy");
  }
 /** Test copy from workspace instead of artifacts area */
 public void testCopyFromWorkspace() throws Exception {
   FreeStyleProject other = createFreeStyleProject(), p = createFreeStyleProject();
   p.getBuildersList()
       .add(
           new CopyArtifact(
               other.getName(), new WorkspaceSelector(), "**/*.txt", "", true, false));
   // Run a build that places a file in the workspace, but does not archive anything
   other.getBuildersList().add(new ArtifactBuilder());
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()).get());
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertFile(true, "foo.txt", b);
   assertFile(true, "subfoo.txt", b);
   assertFile(false, "c.log", b);
 }
 public static List<AbstractProject<?, ?>> findProjectsWithEVMToolsBuilder(
     String... projectNames) {
   List<AbstractProject<?, ?>> returnList = new ArrayList<AbstractProject<?, ?>>();
   List<TopLevelItem> items = Jenkins.getInstance().getItems();
   for (TopLevelItem item : items) {
     if (item instanceof FreeStyleProject) {
       FreeStyleProject project = (FreeStyleProject) item;
       if (!project.isDisabled()) {
         DescribableList<Builder, Descriptor<Builder>> buildersList = project.getBuildersList();
         EVMToolsBuilder builder = buildersList.get(EVMToolsBuilder.class);
         if (builder != null) {
           if (projectNames.length != 0) {
             for (String projectName : projectNames) {
               if (project.getName().equals(projectName)) {
                 returnList.add(project);
                 break;
               }
             }
           } else {
             returnList.add(project);
           }
         }
       }
     }
   }
   return returnList;
 }
 private FreeStyleProject createJob(Builder builder) throws IOException {
   FreeStyleProject p = createFreeStyleProject();
   p.setAssignedLabel(
       null); // let it roam free, or else it ties itself to the master since we have no slaves
   p.getBuildersList().add(builder);
   return p;
 }
  /**
   * Should not cause a fatal error even for an empty selector.
   *
   * @throws Exception
   */
  @Test
  public void testEmptySelector() throws Exception {
    FreeStyleProject copiee = j.createFreeStyleProject();
    FreeStyleProject copier = j.createFreeStyleProject();

    ParameterizedBuildSelector pbs = new ParameterizedBuildSelector("SELECTOR");
    copier
        .getBuildersList()
        .add(
            CopyArtifactUtil.createCopyArtifact(
                copiee.getFullName(),
                null, // parameters
                pbs,
                "**/*", // filter
                "", // excludes
                false, // flatten
                true, // optional
                false // finterprintArtifacts
                ));
    FreeStyleBuild b =
        (FreeStyleBuild)
            copier
                .scheduleBuild2(0, new ParametersAction(new StringParameterValue("SELECTOR", "")))
                .get();
    j.assertBuildStatusSuccess(b);
  }
  @Test
  public void abortBuild() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("test1");
    p.getBuildersList().add(new Shell("sleep 6000"));

    WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, "foo");
    foo.setDefinition(
        new CpsFlowDefinition(StringUtils.join(Arrays.asList("build('test1');"), "\n")));

    QueueTaskFuture<WorkflowRun> q = foo.scheduleBuild2(0);
    WorkflowRun b = q.getStartCondition().get();

    CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get();
    e.waitForSuspension();

    FreeStyleBuild fb = null;
    while (fb == null) {
      fb = p.getBuildByNumber(1);
      Thread.sleep(10);
    }
    fb.getExecutor().interrupt();

    j.assertBuildStatus(Result.ABORTED, j.waitForCompletion(fb));
    j.assertBuildStatus(Result.FAILURE, q.get());
  }
 @Test
 public void parameters() throws Exception {
   WorkflowJob us = j.jenkins.createProject(WorkflowJob.class, "us");
   FreeStyleProject ds = j.jenkins.createProject(FreeStyleProject.class, "ds");
   ds.addProperty(
       new ParametersDefinitionProperty(
           new StringParameterDefinition("branch", "master"),
           new BooleanParameterDefinition("extra", false, null)));
   ds.getBuildersList().add(new Shell("echo branch=$branch extra=$extra"));
   us.setDefinition(new CpsFlowDefinition("build 'ds'"));
   WorkflowRun us1 = j.assertBuildStatusSuccess(us.scheduleBuild2(0));
   FreeStyleBuild ds1 = ds.getBuildByNumber(1);
   j.assertLogContains("branch=master extra=false", ds1);
   Cause.UpstreamCause cause = ds1.getCause(Cause.UpstreamCause.class);
   assertNotNull(cause);
   assertEquals(us1, cause.getUpstreamRun());
   us.setDefinition(
       new CpsFlowDefinition(
           "build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'branch', value: 'release']]",
           true));
   j.assertBuildStatusSuccess(us.scheduleBuild2(0));
   // TODO JENKINS-13768 proposes automatic filling in of default parameter values; should that be
   // used, or is BuildTriggerStepExecution responsible, or ParameterizedJobMixIn.scheduleBuild2?
   j.assertLogContains("branch=release extra=", ds.getBuildByNumber(2));
   us.setDefinition(
       new CpsFlowDefinition(
           "build job: 'ds', parameters: [[$class: 'StringParameterValue', name: 'branch', value: 'release'], [$class: 'BooleanParameterValue', name: 'extra', value: true]]",
           true));
   j.assertBuildStatusSuccess(us.scheduleBuild2(0));
   j.assertLogContains("branch=release extra=true", ds.getBuildByNumber(3));
 }
  @Bug(22641)
  public void testProcessProperlyKilledUnix() throws Exception {
    ProcessTree.enabled = true;
    if (Functions.isWindows()) return; // This test does not involve windows.

    FreeStyleProject sleepProject = createFreeStyleProject();
    FreeStyleProject processJob = createFreeStyleProject();

    sleepProject.getBuildersList().add(new Shell("nohup sleep 100000 &"));

    assertBuildStatusSuccess(sleepProject.scheduleBuild2(0).get());

    processJob.getBuildersList().add(new Shell("ps -ef | grep sleep"));

    assertLogNotContains("sleep 100000", processJob.scheduleBuild2(0).get());
  }
  /** End-to-end installation test. */
  private void doTestAutoInstallation(String id, String fullversion) throws Exception {
    Assume.assumeTrue(
        "this is a really time consuming test, so only run it when we really want",
        Boolean.getBoolean("jenkins.testJDKInstaller"));

    retrieveUpdateCenterData();

    JDKInstaller installer = new JDKInstaller(id, true);

    JDK jdk =
        new JDK(
            "test",
            tmp.getRoot().getAbsolutePath(),
            Arrays.asList(new InstallSourceProperty(Arrays.<ToolInstaller>asList(installer))));

    j.jenkins.getJDKs().add(jdk);

    FreeStyleProject p = j.createFreeStyleProject();
    p.setJDK(jdk);
    p.getBuildersList().add(new Shell("java -fullversion\necho $JAVA_HOME"));
    FreeStyleBuild b = j.buildAndAssertSuccess(p);
    @SuppressWarnings("deprecation")
    String log = b.getLog();
    System.out.println(log);
    // make sure it runs with the JDK that just got installed
    assertTrue(log.contains(fullversion));
    assertTrue(log.contains(tmp.getRoot().getAbsolutePath()));
  }
 public void testMissingStableBuild() throws Exception {
   FreeStyleProject other = createFreeStyleProject(),
       p = createProject(other.getName(), "", "", true, false, false);
   // Make an unstable build in "other"
   other.getBuildersList().add(new UnstableBuilder());
   assertBuildStatus(Result.UNSTABLE, other.scheduleBuild2(0, new UserCause()).get());
   assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0, new UserCause()).get());
 }
  @Before
  public void setUp() throws Exception {
    project = j.createFreeStyleProject("junit");
    archiver = new JUnitResultArchiver("*.xml");
    project.getPublishersList().add(archiver);

    project.getBuildersList().add(new TouchBuilder());
  }
 /** Test that info about selected builds is added into the environment for later build steps. */
 public void testEnvData() throws Exception {
   // Also test conversion of job name to env var name, only keeping letters:
   FreeStyleProject other = createArtifactProject("My (Test) Job"),
       p = createProject(other.getName(), "", "", false, false, false);
   CaptureEnvironmentBuilder envStep = new CaptureEnvironmentBuilder();
   p.getBuildersList().add(envStep);
   // Bump up the build number a bit:
   for (int i = 0; i < 3; i++) other.assignBuildNumber();
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()).get());
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertEquals("4", envStep.getEnvVars().get("COPYARTIFACT_BUILD_NUMBER_MY_TEST_JOB"));
 }
 /**
  * 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));
 }
  /**
   * Returns the future object for a newly created project.
   *
   * @param blockingJobName the name for the project
   * @param shell the shell command task to add
   * @param label the label to bind to master or slave
   * @return the future object for a newly created project
   * @throws IOException
   */
  private Future<FreeStyleBuild> createBlockingProject(
      String blockingJobName, Shell shell, Label label) throws IOException {
    FreeStyleProject blockingProject = this.createFreeStyleProject(blockingJobName);
    blockingProject.setAssignedLabel(label);

    blockingProject.getBuildersList().add(shell);
    Future<FreeStyleBuild> future = blockingProject.scheduleBuild2(0);

    while (!blockingProject.isBuilding()) {
      // wait until job is started
    }

    return future;
  }
  /**
   * Also accepts variable expression.
   *
   * @throws Exception
   */
  @Test
  public void testVariableExpression() throws Exception {
    // Prepare an artifact to be copied.
    FreeStyleProject copiee = j.createFreeStyleProject();
    copiee.getBuildersList().add(new FileWriteBuilder("artifact.txt", "foobar"));
    copiee.getPublishersList().add(new ArtifactArchiver("artifact.txt"));
    j.assertBuildStatusSuccess(copiee.scheduleBuild2(0));

    FreeStyleProject copier = j.createFreeStyleProject();
    ParameterizedBuildSelector pbs = new ParameterizedBuildSelector("${SELECTOR}");
    copier
        .getBuildersList()
        .add(
            CopyArtifactUtil.createCopyArtifact(
                copiee.getFullName(),
                null, // parameters
                pbs,
                "**/*", // filter
                "", // excludes
                false, // flatten
                false, // optional
                false // finterprintArtifacts
                ));
    FreeStyleBuild b =
        j.assertBuildStatusSuccess(
            (FreeStyleBuild)
                copier
                    .scheduleBuild2(
                        0,
                        new ParametersAction(
                            new StringParameterValue(
                                "SELECTOR",
                                "<StatusBuildSelector><stable>true</stable></StatusBuildSelector>")))
                    .get());

    assertEquals("foobar", b.getWorkspace().child("artifact.txt").readToString());
  }
  /** Verifies the queueing behavior in the presence of the expression. */
  public void testQueueBehavior() throws Exception {
    DumbSlave w32 = createSlave("win 32bit", null);
    DumbSlave w64 = createSlave("win 64bit", null);
    createSlave("linux 32bit", null);

    final SequenceLock seq = new SequenceLock();

    FreeStyleProject p1 = createFreeStyleProject();
    p1.getBuildersList()
        .add(
            new TestBuilder() {
              public boolean perform(
                  AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
                  throws InterruptedException, IOException {
                seq.phase(0); // first, make sure the w32 slave is occupied
                seq.phase(2);
                seq.done();
                return true;
              }
            });
    p1.setAssignedLabel(jenkins.getLabel("win && 32bit"));

    FreeStyleProject p2 = createFreeStyleProject();
    p2.setAssignedLabel(jenkins.getLabel("win && 32bit"));

    FreeStyleProject p3 = createFreeStyleProject();
    p3.setAssignedLabel(jenkins.getLabel("win"));

    Future<FreeStyleBuild> f1 = p1.scheduleBuild2(0);

    seq.phase(1); // we schedule p2 build after w32 slave is occupied
    Future<FreeStyleBuild> f2 = p2.scheduleBuild2(0);

    Thread.sleep(1000); // time window to ensure queue has tried to assign f2 build

    // p3 is tied to 'win', so even though p1 is busy, this should still go ahead and complete
    FreeStyleBuild b3 = assertBuildStatusSuccess(p3.scheduleBuild2(0));
    assertSame(w64, b3.getBuiltOn());

    seq.phase(3); // once we confirm that p3 build is over, we let p1 proceed

    // p1 should have been built on w32
    FreeStyleBuild b1 = assertBuildStatusSuccess(f1);
    assertSame(w32, b1.getBuiltOn());

    // and so is p2
    FreeStyleBuild b2 = assertBuildStatusSuccess(f2);
    assertSame(w32, b2.getBuiltOn());
  }
  @Test
  public void buildParallelTests() throws Exception {
    FreeStyleProject p1 = j.createFreeStyleProject("test1");
    p1.getBuildersList().add(new Shell("echo 'Hello World'"));

    FreeStyleProject p2 = j.createFreeStyleProject("test2");
    p2.getBuildersList().add(new Shell("echo 'Hello World'"));

    WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, "foo");
    foo.setDefinition(
        new CpsFlowDefinition(
            StringUtils.join(
                Arrays.asList(
                    "parallel(test1: {\n"
                        + "          build('test1');\n"
                        + "        }, test2: {\n"
                        + "          build('test2');\n"
                        + "        })"),
                "\n"),
            true));

    QueueTaskFuture<WorkflowRun> q = foo.scheduleBuild2(0);
    j.assertBuildStatusSuccess(q);
  }
  @SuppressWarnings("deprecation")
  @Test
  public void buildFolderProject() throws Exception {
    MockFolder dir1 = j.createFolder("dir1");
    FreeStyleProject downstream = dir1.createProject(FreeStyleProject.class, "downstream");
    downstream.getBuildersList().add(new Shell("echo 'Hello World'"));

    MockFolder dir2 = j.createFolder("dir2");
    WorkflowJob upstream = dir2.createProject(WorkflowJob.class, "upstream");
    upstream.setDefinition(new CpsFlowDefinition("build '../dir1/downstream'"));

    QueueTaskFuture<WorkflowRun> q = upstream.scheduleBuild2(0);
    j.assertBuildStatusSuccess(q);
    assertEquals(1, downstream.getBuilds().size());
  }
 private FreeStyleProject createProject(
     String otherProject,
     String filter,
     String target,
     boolean stable,
     boolean flatten,
     boolean optional)
     throws IOException {
   FreeStyleProject p = createFreeStyleProject();
   p.getBuildersList()
       .add(
           new CopyArtifact(
               otherProject, new StatusBuildSelector(stable), filter, target, flatten, optional));
   return p;
 }
  @Test
  public void injectFromScript() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();

    p.setScm(new SingleFileSCM("vars.groovy", "return ['FILE_VAR': 'fvalue']"));
    EnvInjectBuildWrapper wrapper = new EnvInjectBuildWrapper();
    p.getBuildWrappersList().add(wrapper);
    wrapper.setInfo(
        new EnvInjectJobPropertyInfo(
            null, null, null, null, "return ['GROOVY_VAR': 'gvalue']", false));

    CaptureEnvironmentBuilder capture = new CaptureEnvironmentBuilder();
    p.getBuildersList().add(capture);
    p.scheduleBuild2(0).get();

    assertEquals("gvalue", capture.getEnvVars().get("GROOVY_VAR"));
  }
 /**
  * Same test logic as {@link #testBuildLatestPatchsetOnly()} except the trigger is configured to
  * not cancel the previous build.
  *
  * @throws Exception if so.
  */
 @LocalData
 public void testNotBuildLatestPatchsetOnly() throws Exception {
   ((Config) PluginImpl.getInstance().getConfig()).setGerritBuildCurrentPatchesOnly(false);
   FreeStyleProject project = DuplicatesUtil.createGerritTriggeredJob(this, "projectX");
   project.getBuildersList().add(new SleepBuilder(2000));
   server.waitForCommand(GERRIT_STREAM_EVENTS, 2000);
   PatchsetCreated firstEvent = Setup.createPatchsetCreated();
   PluginImpl.getInstance().triggerEvent(firstEvent);
   AbstractBuild firstBuild = waitForBuildToStart(firstEvent, 2000);
   PatchsetCreated secondEvent = Setup.createPatchsetCreated();
   secondEvent.getPatchSet().setNumber("2");
   PluginImpl.getInstance().triggerEvent(secondEvent);
   RunList<FreeStyleBuild> builds = waitForBuilds(project, 2, 5000);
   assertEquals(2, builds.size());
   assertSame(Result.SUCCESS, firstBuild.getResult());
   assertSame(Result.SUCCESS, builds.getFirstBuild().getResult());
   assertSame(Result.SUCCESS, builds.getLastBuild().getResult());
 }
  @Test
  public void injectText() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();

    p.setScm(new SingleFileSCM("vars.properties", "FILE_VAR=fvalue"));
    EnvInjectBuildWrapper wrapper = new EnvInjectBuildWrapper();
    p.getBuildWrappersList().add(wrapper);
    wrapper.setInfo(
        new EnvInjectJobPropertyInfo(
            "vars.properties", "TEXT_VAR=tvalue", null, null, null, false));

    CaptureEnvironmentBuilder capture = new CaptureEnvironmentBuilder();
    p.getBuildersList().add(capture);
    p.scheduleBuild2(0).get();

    assertEquals("tvalue", capture.getEnvVars().get("TEXT_VAR"));
    assertEquals("fvalue", capture.getEnvVars().get("FILE_VAR"));
  }
 public void testSpecificBuildSelector() throws Exception {
   FreeStyleProject other = createArtifactProject(), p = createFreeStyleProject();
   p.getBuildersList()
       .add(
           new CopyArtifact(
               other.getName(), new SpecificBuildSelector("1"), "*.txt", "", false, false));
   assertBuildStatusSuccess(
       other
           .scheduleBuild2(
               0,
               new UserCause(),
               new ParametersAction(new StringParameterValue("FOO", "buildone")))
           .get());
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()));
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertFile(true, "foo.txt", b);
   assertFile(true, "buildone.txt", b);
   assertFile(false, "subdir/subfoo.txt", b);
 }
  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
 }
  @Test
  public void shouldWriteStatusOnGH() throws Exception {
    config.getConfigs().add(github.serverConfig());
    FreeStyleProject prj = jRule.createFreeStyleProject();

    prj.getBuildersList()
        .add(
            new TestBuilder() {
              @Override
              public boolean perform(
                  AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {
                build.addAction(data);
                return true;
              }
            });

    prj.getPublishersList().add(new GitHubCommitNotifier(Result.SUCCESS.toString()));

    prj.scheduleBuild2(0).get();

    github.service().verify(1, postRequestedFor(urlPathMatching(".*/" + SOME_SHA)));
  }
  /**
   * Should not cause a fatal error even for an undefined variable.
   *
   * @throws Exception
   */
  @Issue("JENKINS-30357")
  @Test
  public void testUndefinedParameter() throws Exception {
    FreeStyleProject copiee = j.createFreeStyleProject();
    FreeStyleProject copier = j.createFreeStyleProject();

    ParameterizedBuildSelector pbs = new ParameterizedBuildSelector("NosuchVariable");
    copier
        .getBuildersList()
        .add(
            CopyArtifactUtil.createCopyArtifact(
                copiee.getFullName(),
                null, // parameters
                pbs,
                "**/*", // filter
                "", // excludes
                false, // flatten
                true, // optional
                false // finterprintArtifacts
                ));
    FreeStyleBuild b = copier.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b);
  }
  public void test1() throws Exception {
    FreeStyleProject p = createFreeStyleProject();
    p.getBuildersList()
        .add(
            new TestBuilder() {
              @Override
              public boolean perform(
                  AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
                  throws InterruptedException, IOException {
                listener.getLogger().println("http://www.sun.com/");
                listener.getLogger().println("<http://www.kohsuke.org/>");
                listener.getLogger().println("<a href='http://www.oracle.com/'>");
                return true;
              }
            });
    FreeStyleBuild b = buildAndAssertSuccess(p);

    HtmlPage c = createWebClient().getPage(b, "console");
    String rsp = c.getWebResponse().getContentAsString();
    assertTrue(rsp, rsp.contains("<a href='http://www.sun.com/'>http://www.sun.com/</a>"));
    assertTrue(rsp, rsp.contains("<a href='http://www.kohsuke.org/'>http://www.kohsuke.org/</a>"));
    assertTrue(rsp, rsp.contains("<a href='http://www.oracle.com/'>http://www.oracle.com/</a>"));
  }
  @Test
  public void cancelBuildQueue() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("test1");
    p.getBuildersList().add(new Shell("sleep 6000"));

    WorkflowJob foo = j.jenkins.createProject(WorkflowJob.class, "foo");
    foo.setDefinition(
        new CpsFlowDefinition(StringUtils.join(Arrays.asList("build('test1');"), "\n")));

    j.jenkins.setNumExecutors(0); // should force freestyle build to remain in the queue?

    QueueTaskFuture<WorkflowRun> q = foo.scheduleBuild2(0);

    WorkflowRun b = q.getStartCondition().get();
    CpsFlowExecution e = (CpsFlowExecution) b.getExecutionPromise().get();
    e.waitForSuspension();

    Queue.Item[] items = j.jenkins.getQueue().getItems();
    assertEquals(1, items.length);
    j.jenkins.getQueue().cancel(items[0]);

    j.assertBuildStatus(Result.FAILURE, q.get());
  }