@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));
  }
  public void testRoundTripConfig() throws Exception {
    FreeStyleProject p = createFreeStyleProject();
    RobotPublisher before =
        new RobotPublisher("a", "b", "c", "d", 11, 27, true, "dir1/*.jpg, dir2/*.png");
    p.getPublishersList().add(before);

    submit(getWebClient().getPage(p, "configure").getFormByName("config"));

    RobotPublisher after = p.getPublishersList().get(RobotPublisher.class);

    assertEqualBeans(
        before,
        after,
        "outputPath,outputFileName,reportFileName,logFileName,passThreshold,unstableThreshold,onlyCritical,otherFiles");
  }
  @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());
  }
  @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);
 }
 @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);
 }
        @Override
        protected void before() throws Throwable {
          super.before();
          publisher = new ExtendedEmailPublisher();
          publisher.defaultSubject = "%DEFAULT_SUBJECT";
          publisher.defaultContent = "%DEFAULT_CONTENT";
          publisher.attachmentsPattern = "";
          publisher.recipientList = "%DEFAULT_RECIPIENTS";
          publisher.presendScript = "";

          project = createFreeStyleProject();
          project.getPublishersList().add(publisher);
        }
  @Test
  public void testConstructor() throws Exception {
    final String proj1 = "Project1";
    final String proj2 = "Project2";
    final FreeStyleProject project1 = createFreeStyleProject(proj1);
    project1.getPublishersList().add(new BuildTrigger(proj2, false));
    hudson.rebuildDependencyGraph();
    final FreeStyleBuild build1 = buildAndAssertSuccess(project1);
    waitUntilNoActivity();

    final PipelineBuild pb = new PipelineBuild(build1, project1, null);
    final BuildForm bf = new BuildForm(jenkins, pb);

    assertThat(bf.getStatus(), is(pb.getCurrentBuildResult()));
  }
  @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)));
  }
  @Test
  public void testPlainJobShouldSaveNoParameters() throws Exception {
    final FreeStyleProject project = createFreeStyleProject("PlainJob");

    // 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", 0, actual.getParameters().size());
  }
  /**
   * Also applicable for workflow jobs.
   *
   * @throws Exception
   */
  @Issue("JENKINS-30357")
  @Test
  public void testWorkflow() 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));

    WorkflowJob copier = createWorkflowJob();
    copier.setDefinition(
        new CpsFlowDefinition(
            String.format(
                "node {"
                    + "step([$class: 'CopyArtifact',"
                    + "projectName: '%1$s',"
                    + "filter: '**/*',"
                    + "selector: [$class: 'ParameterizedBuildSelector', parameterName: 'SELECTOR'],"
                    + "]);"
                    + "step([$class: 'ArtifactArchiver', artifacts: '**/*']);"
                    + "}",
                copiee.getFullName()),
            true));

    WorkflowRun b =
        j.assertBuildStatusSuccess(
            copier.scheduleBuild2(
                0,
                null,
                new ParametersAction(
                    new StringParameterValue(
                        "SELECTOR",
                        "<StatusBuildSelector><stable>true</stable></StatusBuildSelector>"))));

    VirtualFile vf = b.getArtifactManager().root().child("artifact.txt");
    assertEquals("foobar", IOUtils.toString(vf.open()));
  }
  /**
   * 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());
  }
 public void testConfigView() throws Exception {
   FreeStyleProject p = createFreeStyleProject();
   RobotPublisher before =
       new RobotPublisher("a", "b", "c", "d", 11, 27, true, "dir1/*.jpg, dir2/*.png");
   p.getPublishersList().add(before);
   HtmlPage page = getWebClient().getPage(p, "configure");
   WebAssert.assertTextPresent(page, "Publish Robot Framework");
   WebAssert.assertInputPresent(page, "_.outputPath");
   WebAssert.assertInputContainsValue(page, "_.outputPath", "a");
   WebAssert.assertInputPresent(page, "_.outputFileName");
   WebAssert.assertInputContainsValue(page, "_.outputFileName", "b");
   WebAssert.assertInputPresent(page, "_.reportFileName");
   WebAssert.assertInputContainsValue(page, "_.reportFileName", "c");
   WebAssert.assertInputPresent(page, "_.logFileName");
   WebAssert.assertInputContainsValue(page, "_.logFileName", "d");
   WebAssert.assertInputPresent(page, "_.unstableThreshold");
   WebAssert.assertInputContainsValue(page, "_.unstableThreshold", "27.0");
   WebAssert.assertInputPresent(page, "_.passThreshold");
   WebAssert.assertInputContainsValue(page, "_.passThreshold", "11.0");
   WebAssert.assertInputPresent(page, "_.onlyCritical");
   WebAssert.assertInputContainsValue(page, "_.onlyCritical", "on");
   WebAssert.assertInputPresent(page, "_.otherFiles");
   WebAssert.assertInputContainsValue(page, "_.otherFiles", "dir1/*.jpg,dir2/*.png");
 }
  @Test
  public void testGetParameterList() throws Exception {
    final String proj1 = "Project1";
    final String proj2 = "Project2";
    final FreeStyleProject project1 = createFreeStyleProject(proj1);
    project1.getPublishersList().add(new BuildTrigger(proj2, false));

    final List<ParameterDefinition> pds = new ArrayList<ParameterDefinition>();
    pds.add(new StringParameterDefinition("tag", ""));
    pds.add(new StringParameterDefinition("branch", ""));

    project1.addProperty(new ParametersDefinitionProperty(pds));
    hudson.rebuildDependencyGraph();
    final FreeStyleBuild build1 = buildAndAssertSuccess(project1);
    waitUntilNoActivity();
    final ArrayList<String> paramList = new ArrayList<String>();
    paramList.add("tag");
    paramList.add("branch");

    final PipelineBuild pb = new PipelineBuild(build1, project1, null);
    final BuildForm bf = new BuildForm(jenkins, pb);

    assertEquals(paramList, bf.getParameterList());
  }
 private FreeStyleProject createArtifactProject(String name) throws IOException {
   FreeStyleProject p = name != null ? createFreeStyleProject(name) : createFreeStyleProject();
   p.getBuildersList().add(new ArtifactBuilder());
   p.getPublishersList().add(new ArtifactArchiver("**", "", false));
   return p;
 }
  @Test
  public void testIntegration() throws Exception {
    final JSch mockJsch = mock(JSch.class);
    final Session mockSession = mock(Session.class);
    final ChannelSftp mockSftp = mock(ChannelSftp.class);
    final int port = 28;
    final int timeout = 3000;
    final BapSshHostConfiguration testHostConfig =
        new BapSshHostConfiguration(
            "testConfig",
            "testHostname",
            "testUsername",
            "",
            "/testRemoteRoot",
            port,
            timeout,
            false,
            "",
            "",
            false) {
          @Override
          public JSch createJSch() {
            return mockJsch;
          }
        };
    final BapSshCommonConfiguration commonConfig =
        new BapSshCommonConfiguration("passphrase", "key", "", false);
    new JenkinsTestHelper().setGlobalConfig(commonConfig, testHostConfig);
    final String dirToIgnore = "target";
    final int execTimeout = 10000;
    final BapSshTransfer transfer =
        new BapSshTransfer(
            "**/*",
            null,
            "sub-home",
            dirToIgnore,
            false,
            false,
            "",
            execTimeout,
            false,
            false,
            false,
            null);
    final BapSshPublisher publisher =
        new BapSshPublisher(
            testHostConfig.getName(),
            false,
            new ArrayList<BapSshTransfer>(Collections.singletonList(transfer)),
            false,
            false,
            null,
            null,
            null);
    final BapSshPublisherPlugin plugin =
        new BapSshPublisherPlugin(
            new ArrayList<BapSshPublisher>(Collections.singletonList(publisher)),
            false,
            false,
            false,
            "master",
            null);

    final FreeStyleProject project = createFreeStyleProject();
    project.getPublishersList().add(plugin);
    final String buildDirectory = "build-dir";
    final String buildFileName = "file.txt";
    project
        .getBuildersList()
        .add(
            new TestBuilder() {
              @Override
              public boolean perform(
                  final AbstractBuild<?, ?> build,
                  final Launcher launcher,
                  final BuildListener listener)
                  throws InterruptedException, IOException {
                final FilePath dir = build.getWorkspace().child(dirToIgnore).child(buildDirectory);
                dir.mkdirs();
                dir.child(buildFileName).write("Helloooooo", "UTF-8");
                build.setResult(Result.SUCCESS);
                return true;
              }
            });

    when(mockJsch.getSession(
            testHostConfig.getUsername(), testHostConfig.getHostname(), testHostConfig.getPort()))
        .thenReturn(mockSession);
    when(mockSession.openChannel("sftp")).thenReturn(mockSftp);
    final SftpATTRS mockAttrs = mock(SftpATTRS.class);
    when(mockAttrs.isDir()).thenReturn(true);
    when(mockSftp.stat(anyString())).thenReturn(mockAttrs);

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

    verify(mockJsch)
        .addIdentity("TheKey", BapSshUtil.toBytes("key"), null, BapSshUtil.toBytes("passphrase"));
    verify(mockSession).connect(timeout);
    verify(mockSftp).connect(timeout);
    verify(mockSftp).cd(transfer.getRemoteDirectory());
    verify(mockSftp).cd("build-dir");
    verify(mockSftp).put((InputStream) anyObject(), eq(buildFileName));
  }