public void testTakeBlockedByProperty() throws Exception {
    Slave slave = createSlave();
    FreeStyleProject project = createFreeStyleProject();

    // First, attempt to run our project before adding the property
    Future<FreeStyleBuild> build = project.scheduleBuild2(0);
    assertBuildStatus(Result.SUCCESS, build.get(20, TimeUnit.SECONDS));

    // Add the build-blocker property and try again
    slave.getNodeProperties().add(new RejectAllTasksProperty());

    build = project.scheduleBuild2(0);
    try {
      build.get(10, TimeUnit.SECONDS);
      fail("Expected timeout exception");
    } catch (TimeoutException e) {
      List<BuildableItem> buildables = jenkins.getQueue().getBuildableItems();
      assertNotNull(buildables);
      assertEquals(1, buildables.size());

      BuildableItem item = buildables.get(0);
      assertEquals(project, item.task);
      assertNotNull(item.getCauseOfBlockage());
      assertEquals(
          Messages.Queue_WaitingForNextAvailableExecutor(),
          item.getCauseOfBlockage().getShortDescription());
    }
  }
  @Test
  public void shouldPopulatePropertiesContentWithCustomWorkspace() throws Exception {
    final String customWorkspaceValue = tmp.newFolder().getAbsolutePath();
    String customEnvVarName = "materialize_workspace_path";
    String customEnvVarValue = "${WORKSPACE}/materialize_workspace";

    FreeStyleProject project = j.createFreeStyleProject();
    project.setCustomWorkspace(customWorkspaceValue);

    EnvVars.masterEnvVars.remove("WORKSPACE"); // ensure build node don't have such var already

    EnvInjectBuildWrapper envInjectBuildWrapper = new EnvInjectBuildWrapper();
    envInjectBuildWrapper.setInfo(withPropContent(customEnvVarName + "=" + customEnvVarValue));
    project.getBuildWrappersList().add(envInjectBuildWrapper);

    FreeStyleBuild build = j.buildAndAssertSuccess(project);

    // Retrieve build workspace
    String buildWorkspaceValue = build.getWorkspace().getRemote();
    assertThat(
        "1. Should see actual ws equal to custom",
        buildWorkspaceValue,
        equalTo(customWorkspaceValue));

    // Compute value with workspace
    String expectedCustomEnvVarValue =
        replaceMacro(customEnvVarValue, of("WORKSPACE", buildWorkspaceValue));

    assertThat(
        "2. Property should be resolved with custom ws in build",
        build,
        withEnvInjectAction(map(hasEntry(customEnvVarName, expectedCustomEnvVarValue))));
  }
  /** 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()));
  }
  @Test
  @LocalData
  public void testLoadOnStart() throws Exception {
    // verify that SpecificUserAuthorizationStrategy is loaded correctly from the disk on startup.
    {
      FreeStyleProject p = j.jenkins.getItemByFullName("test", FreeStyleProject.class);
      assertNotNull(p);
      AuthorizeProjectProperty prop = p.getProperty(AuthorizeProjectProperty.class);
      assertNotNull(prop);
      assertEquals(SpecificUsersAuthorizationStrategy.class, prop.getStrategy().getClass());
      SpecificUsersAuthorizationStrategy strategy =
          (SpecificUsersAuthorizationStrategy) prop.getStrategy();
      assertEquals("test1", strategy.getUserid());
    }

    j.jenkins.reload();

    // verify that SpecificUserAuthorizationStrategy is reloaded correctly from the disk.
    {
      FreeStyleProject p = j.jenkins.getItemByFullName("test", FreeStyleProject.class);
      assertNotNull(p);
      AuthorizeProjectProperty prop = p.getProperty(AuthorizeProjectProperty.class);
      assertNotNull(prop);
      assertEquals(SpecificUsersAuthorizationStrategy.class, prop.getStrategy().getClass());
      SpecificUsersAuthorizationStrategy strategy =
          (SpecificUsersAuthorizationStrategy) prop.getStrategy();
      assertEquals("test1", strategy.getUserid());
    }
  }
  /**
   * 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);
  }
 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;
 }
  public void testSelfExcludingJobs() throws Exception {

    BuildBlockerProperty theProperty = new BuildBlockerProperty();
    theProperty.setBlockingJobs("SelfExcluding_.*");

    FreeStyleProject theJob1 = createFreeStyleProject("SelfExcluding_Job1");
    theJob1.addProperty(theProperty);
    assertTrue(theJob1.getBuilds().isEmpty());

    FreeStyleProject theJob2 = createFreeStyleProject("SelfExcluding_Job2");
    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);

    long theStartTime = System.currentTimeMillis();
    long theEndTime = theStartTime;
    while ((!theFuture1.isDone() || !theFuture2.isDone()) && theEndTime < theStartTime + 5000) {
      theEndTime = System.currentTimeMillis();
    }

    // if more then five seconds have passed, we assume its a deadlock.
    assertTrue(theEndTime < theStartTime + 5000);

    // restore changed settings
    Hudson.getInstance().setNumExecutors(theOldNumExecutors);
    theJob2.delete();
    theJob1.delete();
  }
  @Test
  public void testParameterisedJobShouldSaveAllParameters() throws Exception {
    final FreeStyleProject project = createFreeStyleProject("ParameterisedJob");

    // set parameters
    final ParameterDefinition param1 =
        new StringParameterDefinition("myStringParam", "myStringValue", "My String Parameter");
    final ParameterDefinition param2 =
        new BooleanParameterDefinition("myBooleanParam", false, "My Boolean Parameter");
    project.addProperty(new ParametersDefinitionProperty(param1, param2));

    // enable audit2db plugin
    final DbAuditPublisher plugin = getPlugin();
    project.getPublishersList().add((Publisher) plugin);

    // build now
    final Future<FreeStyleBuild> futureBuild = project.scheduleBuild2(0);
    final FreeStyleBuild build = futureBuild.get();
    Assert.assertNotNull(build);
    Assert.assertEquals("Unexpected build result", Result.SUCCESS, build.getResult());

    // check data persistence
    final BuildDetailsRepository repository = plugin.getRepository();
    final BuildDetails actual = repository.getBuildDetailsForBuild(build);
    final BuildDetails expected = new BuildDetailsImpl(build);
    Assert.assertEquals("Unexpected build details", expected, actual);
    Assert.assertNotNull("Unexpected null end date", actual.getEndDate());
    Assert.assertTrue("Unexpected duration", actual.getDuration() > 0L);
    Assert.assertEquals("Unexpected number of params", 2, actual.getParameters().size());
  }
  @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());
  }
 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;
 }
  @Override
  public Iterable<Edge> getEdgesIncidentWith(AbstractProject<?, ?> project) {
    Set<Edge> artifactEdges = Sets.newHashSet();

    if (copyartifactIsInstalled) {
      if (project instanceof FreeStyleProject) {

        FreeStyleProject proj = (FreeStyleProject) project;
        List<Builder> builders = proj.getBuilders();

        for (Builder builder : builders) {

          if (builder instanceof CopyArtifact) {

            CopyArtifact caBuilder = (CopyArtifact) builder;
            String projectName = caBuilder.getProjectName();
            Jenkins jenkins = Jenkins.getInstance();
            AbstractProject<?, ?> projectFromName =
                jenkins.getItem(projectName, project.getParent(), AbstractProject.class);

            if (projectFromName != null) {
              artifactEdges.add(new CopyArtifactEdge(node(projectFromName), node(project)));
            }
          }
        }
      }
    }
    return artifactEdges;
  }
  public void testDataCompatibilityWithHostNameWithWhitespace() throws Exception {
    DumbSlave slave =
        new DumbSlave(
            "abc def (xyz) : test",
            "dummy",
            createTmpDir().getPath(),
            "1",
            Mode.NORMAL,
            "",
            createComputerLauncher(null),
            RetentionStrategy.NOOP,
            Collections.EMPTY_LIST);
    jenkins.addNode(slave);

    FreeStyleProject p = createFreeStyleProject();
    p.setAssignedLabel(jenkins.getLabel("abc def"));
    assertEquals("abc def", p.getAssignedLabel().getName());
    assertEquals("\"abc def\"", p.getAssignedLabel().getExpression());

    // expression should be persisted, not the name
    Field f = AbstractProject.class.getDeclaredField("assignedNode");
    f.setAccessible(true);
    assertEquals("\"abc def\"", f.get(p));

    // but if the name is set, we'd still like to parse it
    f.set(p, "a:b c");
    assertEquals("a:b c", p.getAssignedLabel().getName());
  }
  public void testShouldHaveNextCommit() throws Exception {

    setup();
    File dir = createTempDirectory();
    MercurialBridge plugin = new MercurialBridge(false, "test", "");
    plugin.setWorkingDirectory(new FilePath(dir));

    System.out.println("Creating test repository at repository: " + dir.getAbsolutePath());

    // Setup the repository
    hg(dir, "init");
    shell(dir, "touch", "foo");
    hg(dir, "add", "foo");
    hg(dir, "commit", "-m", "\"added foo\"");
    hg(dir, "branch", "test");
    shell(dir, "touch", "bar");
    hg(dir, "add", "bar");
    hg(dir, "commit", "-m", "\"added bar\"");
    shell(dir, "touch", "bar3");
    hg(dir, "add", "bar3");
    hg(dir, "commit", "-m", "\"added bar3\"");

    MercurialSCM scm = new MercurialSCM(null, dir.getAbsolutePath(), null, null, null, null, true);
    FreeStyleProject project =
        Hudson.getInstance().createProject(FreeStyleProject.class, "testproject");
    project.setScm(scm);

    // Setup build and listener
    OutputStream out = new ByteArrayOutputStream();
    BuildListener blistener = new StreamBuildListener(out);
    FreeStyleBuild build = new FreeStyleBuild(project);

    assertNotNull(plugin.nextCommit(build, launcher, blistener, new Commit<String>("0")));
    cleanup(dir);
  }
  public void testShouldNotHaveNextCommit() throws Exception {

    setup();
    File dir = createTempDirectory();
    MercurialBridge plugin = new MercurialBridge(false, "devtest", "");
    plugin.setWorkingDirectory(new FilePath(dir));

    System.out.println("Creating test repository at repository: " + dir.getAbsolutePath());

    // Setup the repository
    hg(dir, "init");
    hg(dir, "branch", "devtest");
    shell(dir, "touch", "foo");
    hg(dir, "add", "foo");
    hg(dir, "commit", "-m", "\"added foo\"");
    String revision = hg(dir, "log", "-l1", "--template", "{node}").toString();
    // shell(dir, "echo",revision,">",".hg/currentBuildFile");

    MercurialSCM scm = new MercurialSCM(null, dir.getAbsolutePath(), null, null, null, null, true);
    FreeStyleProject project =
        Hudson.getInstance().createProject(FreeStyleProject.class, "testproject");
    project.setScm(scm);

    // Setup build and listener
    OutputStream out = new ByteArrayOutputStream();
    BuildListener blistener = new StreamBuildListener(out);
    FreeStyleBuild build = new FreeStyleBuild(project);

    Commit<String> result =
        plugin.nextCommit(build, launcher, blistener, new Commit<String>(revision));

    assertNull(result);
    cleanup(dir);
  }
  /** Scenario: loads on one label shouldn't translate to load on another label. */
  public void testLabels() throws Exception {
    BulkChange bc = new BulkChange(hudson);
    try {
      DummyCloudImpl cloud = initHudson(0);
      Label blue = hudson.getLabel("blue");
      Label red = hudson.getLabel("red");
      cloud.label = red;

      // red jobs
      List<FreeStyleProject> redJobs = create5SlowJobs(new Latch(5));
      for (FreeStyleProject p : redJobs) p.setAssignedLabel(red);

      // blue jobs
      List<FreeStyleProject> blueJobs = create5SlowJobs(new Latch(5));
      for (FreeStyleProject p : blueJobs) p.setAssignedLabel(blue);

      // build all
      List<Future<FreeStyleBuild>> blueBuilds = buildAll(blueJobs);
      verifySuccessfulCompletion(buildAll(redJobs));

      // cloud should only give us 5 nodes for 5 red jobs
      assertEquals(5, cloud.numProvisioned);

      // and all blue jobs should be still stuck in the queue
      for (Future<FreeStyleBuild> bb : blueBuilds) assertFalse(bb.isDone());
    } finally {
      bc.abort();
    }
  }
 protected FreeStyleProject setupProject() throws Exception {
   IntegritySCM scm = new IntegritySCM("server1", configPath, "devjob");
   FreeStyleProject project = jenkinsRule.createFreeStyleProject();
   project.setScm(scm);
   project.save();
   return project;
 }
  @Before
  public void setUp() throws Exception {
    project = j.createFreeStyleProject("junit");
    archiver = new JUnitResultArchiver("*.xml");
    project.getPublishersList().add(archiver);

    project.getBuildersList().add(new TouchBuilder());
  }
 @Test
 @Issue("JENKINS-25312")
 public void testMarkSuccessOnCommitNotifierFailure() throws Exception {
   FreeStyleProject prj = jRule.createFreeStyleProject();
   prj.getPublishersList().add(new GitHubCommitNotifier(Result.SUCCESS.toString()));
   Build b = prj.scheduleBuild2(0).get();
   jRule.assertBuildStatus(Result.SUCCESS, b);
 }
 @Test
 @Issue("JENKINS-23641")
 public void testNoBuildData() throws Exception {
   FreeStyleProject prj = jRule.createFreeStyleProject("23641_noBuildData");
   prj.getPublishersList().add(new GitHubCommitNotifier());
   Build b = prj.scheduleBuild2(0).get();
   jRule.assertBuildStatus(Result.FAILURE, b);
   jRule.assertLogContains(BuildDataHelper_NoBuildDataError(), b);
 }
  /**
   * Creates a new freestyle project and checks if the rebuild action is available on the project
   * level.
   *
   * @throws Exception Exception
   */
  public void testWhenProjectWithoutParamsThenRebuildProjectAvailable() throws Exception {
    FreeStyleProject project = createFreeStyleProject();

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

    RebuildLastCompletedBuildAction action =
        build.getProject().getAction(RebuildLastCompletedBuildAction.class);
    assertNotNull(action);
  }
 public void testFlatten() throws Exception {
   FreeStyleProject other = createArtifactProject(),
       p = createProject(other.getName(), "", "newdir", false, true, false);
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()).get());
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertFile(true, "newdir/foo.txt", b);
   assertFile(true, "newdir/subfoo.txt", b);
   assertFile(true, "newdir/c.log", b);
 }
 public void testCopyToTarget() throws Exception {
   FreeStyleProject other = createArtifactProject(),
       p = createProject(other.getName(), "deep*/**", "new/deep/dir", true, false, false);
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()).get());
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertFile(false, "foo.txt", b);
   assertFile(false, "new/deep/dir/foo.txt", b);
   assertFile(true, "new/deep/dir/deepfoo/a/b/c.log", b);
 }
 public void testCopyWithFilter() throws Exception {
   FreeStyleProject other = createArtifactProject(),
       p = createProject(other.getName(), "**/bogus*, **/sub*, bogus/**", "", false, false, false);
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()).get());
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertFile(false, "foo.txt", b);
   assertFile(true, "subdir/subfoo.txt", b);
   assertFile(false, "deepfoo/a/b/c.log", b);
 }
  public void testShouldCauseMergeConflict() throws Exception {
    setup();
    File dir = createTempDirectory();
    MercurialBridge plugin = new MercurialBridge(false, "test", "");
    plugin.setWorkingDirectory(new FilePath(dir));

    System.out.println("Creating test repository at repository: " + dir.getAbsolutePath());

    hg(dir, "init");
    File hello = new File(dir, "hello");

    PrintWriter writer = new PrintWriter(hello, "UTF-8");
    writer.println("hello");
    writer.close();
    writer = null;

    hg(dir, "add", "hello");
    hg(dir, "commit", "-m", "Added hello");
    hg(dir, "branch", "test");

    writer = new PrintWriter(hello, "UTF-8");
    writer.println("hello, world");
    writer.close();
    writer = null;

    hg(dir, "commit", "-m", "Changed contents of hello in test branch");
    String revision = hg(dir, "tip", "--template", "{node}").toString();
    hg(dir, "update", "-C", "default");

    writer = new PrintWriter(hello, "UTF-8");
    writer.println("hello, jenkins");
    writer.close();
    writer = null;

    hg(dir, "commit", "-m", "Changed contents of hello in default branch");

    MercurialSCM scm = new MercurialSCM(null, dir.getAbsolutePath(), null, null, null, null, true);
    FreeStyleProject project =
        Hudson.getInstance().createProject(FreeStyleProject.class, "testproject");
    project.setScm(scm);

    // Setup build and listener
    OutputStream out = new ByteArrayOutputStream();
    BuildListener blistener = new StreamBuildListener(out);
    FreeStyleBuild build = new FreeStyleBuild(project);

    boolean exceptionThrown = false;
    try {
      plugin.prepareWorkspace(build, launcher, blistener, new Commit<String>(revision));
    } catch (AbortException e) {
      exceptionThrown = true;
    }

    assertTrue(exceptionThrown);
  }
 /** Test copying artifacts from a particular configuration of a matrix job */
 public void testMatrixJob() throws Exception {
   MatrixProject other = createMatrixArtifactProject();
   FreeStyleProject p = createProject(other.getName() + "/FOO=two", "", "", true, false, false);
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()).get());
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertFile(true, "foo.txt", b);
   assertFile(true, "two.txt", b);
   assertFile(true, "subdir/subfoo.txt", b);
   assertFile(true, "deepfoo/a/b/c.log", b);
 }
 @Test
 @Issue("JENKINS-23641")
 public void testNoBuildRevision() throws Exception {
   FreeStyleProject prj = jRule.createFreeStyleProject();
   prj.setScm(new GitSCM("http://non.existent.git.repo.nowhere/repo.git"));
   prj.getPublishersList().add(new GitHubCommitNotifier());
   // Git plugin 2.4.1 + does not include BuildData if checkout fails, so we add it if needed
   Build b = safelyGenerateBuild(prj);
   jRule.assertBuildStatus(Result.FAILURE, b);
   jRule.assertLogContains(BuildDataHelper_NoLastRevisionError(), b);
 }
  @LocalData
  @Test
  public void persistence() throws Exception {
    project.scheduleBuild2(0).get(60, TimeUnit.SECONDS);

    reloadJenkins();

    FreeStyleBuild build = project.getBuildByNumber(1);

    assertTestResults(build);
  }
 /**
  * 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;
 }
 private Build safelyGenerateBuild(FreeStyleProject prj)
     throws InterruptedException, java.util.concurrent.ExecutionException {
   Build b;
   if (jRule
       .getPluginManager()
       .getPlugin("git")
       .getVersionNumber()
       .isNewerThan(new VersionNumber("2.4.0"))) {
     b = prj.scheduleBuild2(0, new Cause.UserIdCause(), new BuildData()).get();
   } else {
     b = prj.scheduleBuild2(0).get();
   }
   return b;
 }
  @Test
  public void testNoInfiniteRecursion() throws Exception {
    final String proj1 = "Project1";
    final String proj2 = "Project2";
    final FreeStyleProject project1 = createFreeStyleProject(proj1);
    final FreeStyleProject project2 = createFreeStyleProject(proj2);
    project1.getPublishersList().add(new BuildTrigger(proj2, false));
    project2.getPublishersList().add(new BuildTrigger(proj1, false));
    hudson.rebuildDependencyGraph();

    final BuildForm form1 = new BuildForm(jenkins, new PipelineBuild(null, project1, null));
    assertThat(form1.getDependencies(), hasSize(1));
    assertThat(form1.getDependencies().get(0).getDependencies(), hasSize(0));
  }