@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 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));
 }
  @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());
  }
  @LocalData
  @Test
  public void setDescription() throws Exception {
    FreeStyleBuild build = project.scheduleBuild2(0).get(10, TimeUnit.SECONDS);

    CaseResult caseResult = build.getAction(TestResultAction.class).getFailedTests().get(0);
    String url =
        build.getUrl()
            + "/testReport/"
            + caseResult.getRelativePathFrom(caseResult.getTestResult());

    testSetDescription(url, caseResult);

    ClassResult classResult = caseResult.getParent();
    url =
        build.getUrl()
            + "/testReport/"
            + classResult.getParent().getSafeName()
            + "/"
            + classResult.getSafeName();
    testSetDescription(url, classResult);

    PackageResult packageResult = classResult.getParent();
    url = build.getUrl() + "/testReport/" + classResult.getParent().getSafeName();
    testSetDescription(url, packageResult);
  }
  /**
   * When a build is marked as NOT_BUILD And more builds are started And there are no changes Then
   * all following builds should also be marked NOT_BUILD
   */
  public void testShouldMarkBuildsAsNotBuilt() throws Exception {
    setup();
    File dir = createTempDirectory();
    MercurialBridge plugin = new MercurialBridge(false, "test", "default");
    plugin.setWorkingDirectory(new FilePath(dir));

    hg(dir, "init");
    shell(dir, "touch", "foo");
    hg(dir, "add", "foo");
    hg(dir, "commit", "-m", "\"added foo\"");
    // String rev = hg(dir,"tip","--template","{node}").toString();
    hg(dir, "branch", "test");
    shell(dir, "touch", "bar");
    hg(dir, "add", "bar");
    hg(dir, "commit", "-m", "\"added bar\"");

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

    Future<FreeStyleBuild> f = project.scheduleBuild2(0);
    FreeStyleBuild build = f.get();
    assertEquals(Result.SUCCESS, build.getResult());
    f = project.scheduleBuild2(0);
    build = f.get();
    assertEquals(Result.NOT_BUILT, build.getResult());
    f = project.scheduleBuild2(0);
    build = f.get();
    assertEquals(Result.NOT_BUILT, build.getResult());
    cleanup(dir);
  }
  @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))));
  }
  @Test
  public void testTriggerName() throws Exception {
    List<RecipientProvider> recProviders = Collections.emptyList();
    PreBuildTrigger trigger =
        new PreBuildTrigger(
            recProviders,
            "$DEFAULT_RECIPIENTS",
            "$DEFAULT_REPLYTO",
            "$DEFAULT_SUBJECT",
            "$DEFAULT_CONTENT",
            "",
            0,
            "project");
    addEmailType(trigger);
    publisher.getConfiguredTriggers().add(trigger);

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

    assertThat(
        "Email should have been triggered, so we should see it in the logs.",
        build.getLog(100),
        hasItems("Email was triggered for: " + PreBuildTrigger.TRIGGER_NAME));
    assertEquals(1, Mailbox.get("*****@*****.**").size());
    Message message = Mailbox.get("*****@*****.**").get(0);
    assertEquals(PreBuildTrigger.TRIGGER_NAME, message.getSubject());
  }
  /**
   * Tests to trigger a build with the same patch set twice, one is a manual event and the other a
   * normal. Expecting one build to be scheduled with two causes of different type..
   *
   * @throws Exception if so.
   */
  @LocalData
  public void testDoubleTriggeredBuildOfDifferentType() throws Exception {
    FreeStyleProject project = DuplicatesUtil.createGerritTriggeredJob(this, "projectX");
    server.waitForCommand(GERRIT_STREAM_EVENTS, 2000);
    PatchsetCreated patchsetCreated = Setup.createPatchsetCreated();
    ManualPatchsetCreated mpc = new ManualPatchsetCreated();
    mpc.setChange(patchsetCreated.getChange());
    mpc.setPatchset(patchsetCreated.getPatchSet());
    mpc.setUploader(patchsetCreated.getUploader());
    mpc.setUserName("bobby");
    PluginImpl.getInstance().triggerEvent(Setup.createPatchsetCreated());
    PluginImpl.getInstance().triggerEvent(mpc);

    RunList<FreeStyleBuild> builds = waitForBuilds(project, 1, 5000);
    FreeStyleBuild build = builds.get(0);
    assertSame(Result.SUCCESS, build.getResult());
    assertEquals(1, builds.size());

    int count = 0;
    for (Cause cause : build.getCauses()) {
      if (cause instanceof GerritCause) {
        count++;
        assertNotNull(((GerritCause) cause).getContext());
        assertNotNull(((GerritCause) cause).getContext().getThisBuild());
        assertNotNull(((GerritCause) cause).getEvent());
      }
    }
    assertEquals(2, count);
  }
Пример #9
0
  /** 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()));
  }
Пример #10
0
  /**
   * 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);
  }
 protected FreeStyleBuild build(
     final FreeStyleProject project,
     final Result expectedResult,
     final String... expectedNewlyCommittedFiles)
     throws Exception {
   final FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause()).get();
   System.out.println(build.getLog(50));
   return build;
 }
  @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());
  }
  /** 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());
  }
  /**
   * Given that there are uncomitted changes in the integration branch And that the build is marked
   * successful When handlePostBuild has been invoked Then there should be no more changes on the
   * integration branch And the integration branch has a new commit with the changes
   *
   * @throws Exception
   */
  public void testShouldCommitChanges() throws Exception {
    setup();
    File dir = createTempDirectory();
    System.out.println("Creating test repository at repository: " + dir.getAbsolutePath());

    MercurialBridge plugin = new MercurialBridge(false, "test", "default");
    plugin.setWorkingDirectory(new FilePath(dir));

    hg(dir, "init");
    shell(dir, "touch", "foo");
    hg(dir, "add", "foo");
    hg(dir, "commit", "-m", "added foo");
    hg(dir, "branch", "test");
    String revision = hg(dir, "tip", "--template", "{node}").toString();
    shell(dir, "touch", "bar");
    hg(dir, "add", "bar");
    hg(dir, "commit", "-m", "added bar");
    hg(dir, "update", "default");
    hg(dir, "merge", "test");

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

    Future<FreeStyleBuild> b = project.scheduleBuild2(0);
    FreeStyleBuild build = spy(b.get());
    when(build.getResult()).thenReturn(Result.SUCCESS);

    OutputStream out = new ByteArrayOutputStream();
    BuildListener bListener = new StreamBuildListener(out);
    assertTrue(hg(dir, "branch").toString().startsWith("default"));
    assertTrue(hg(dir, "status").toString().startsWith("M bar"));
    assertNotNull(build.getResult());

    plugin.nextCommit(build, launcher, bListener, null);

    plugin.handlePostBuild(build, launcher, bListener);

    assertTrue(hg(dir, "branch").toString().startsWith("default"));
    assertTrue(hg(dir, "status").toString().isEmpty());

    assertTrue(
        hg(dir, "log", "-rtip", "--template", "{desc}").toString().startsWith("Merge of revision"));

    cleanup(dir);
  }
  @Test
  public void doNothingIfItWillNotShortenThePath() throws Exception {
    DumbSlave s = j.createOnlineSlave();

    // Would be turned into 'short_project...XXXXXXXX' which is in fact longer than the original
    FreeStyleProject p = j.createFreeStyleProject("short_project_name");
    p.setAssignedNode(s);

    // Not enough for anything
    setMaxPathLength(s, 1);

    FreeStyleBuild b = p.scheduleBuild2(0).get();
    assertThat(
        b.getWorkspace().getRemote(),
        equalTo(s.getRootPath() + DS + "workspace" + DS + p.getFullName().replace("/", DS)));
  }
  @Test
  public void doNothingIfThereIsEnoughRoom() throws Exception {
    DumbSlave s = j.createOnlineSlave();

    MockFolder f = j.createFolder("this_is_my_folder_alright");
    FreeStyleProject p = f.createProject(FreeStyleProject.class, "and_a_project_in_it");
    p.setAssignedNode(s);

    // Enough for the test - even on windows
    setMaxPathLength(s, 4096);

    FreeStyleBuild b = p.scheduleBuild2(0).get();
    assertThat(
        b.getWorkspace().getRemote(),
        equalTo(s.getRootPath() + DS + "workspace" + DS + p.getFullName().replace("/", DS)));
  }
 public void testCopyToSlave() throws Exception {
   DumbSlave node = createSlave();
   SlaveComputer c = node.getComputer();
   c.connect(false).get(); // wait until it's connected
   if (c.isOffline()) fail("Slave failed to go online: " + c.getLog());
   FreeStyleProject other = createArtifactProject(),
       p = createProject(other.getName(), "", "", false, false, false);
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()).get());
   p.setAssignedLabel(node.getSelfLabel());
   FreeStyleBuild b = p.scheduleBuild2(0, new UserCause()).get();
   assertBuildStatusSuccess(b);
   assertSame(node, b.getBuiltOn());
   assertFile(true, "foo.txt", b);
   assertFile(true, "subdir/subfoo.txt", b);
   assertFile(true, "deepfoo/a/b/c.log", b);
 }
  /**
   * Push the build around to different nodes via the assignment to make sure it gets where we need
   * it to.
   */
  public void testQueueBehavior2() throws Exception {
    DumbSlave s = createSlave("win", null);

    FreeStyleProject p = createFreeStyleProject();

    p.setAssignedLabel(jenkins.getLabel("!win"));
    FreeStyleBuild b = assertBuildStatusSuccess(p.scheduleBuild2(0));
    assertSame(jenkins, b.getBuiltOn());

    p.setAssignedLabel(jenkins.getLabel("win"));
    b = assertBuildStatusSuccess(p.scheduleBuild2(0));
    assertSame(s, b.getBuiltOn());

    p.setAssignedLabel(jenkins.getLabel("!win"));
    b = assertBuildStatusSuccess(p.scheduleBuild2(0));
    assertSame(jenkins, b.getBuiltOn());
  }
  @Test
  public void unwrapFolders() throws Exception {
    DumbSlave s = j.createOnlineSlave();

    MockFolder f = j.createFolder("this_is_my_folder_alright");
    FreeStyleProject p = f.createProject(FreeStyleProject.class, "and_a_project_in_it");
    p.setAssignedNode(s);

    // Not enough for anything
    setMaxPathLength(s, 1);

    FreeStyleBuild b = p.scheduleBuild2(0).get();
    String buildWs = b.getWorkspace().getRemote();
    String wsDir = s.getRootPath() + DS + "workspace" + DS;
    assertThat(buildWs, startsWith(wsDir + "and_a_pro"));
    assertThat(buildWs, buildWs.length(), equalTo(wsDir.length() + 24));
  }
 /**
  * Tests that a legacy FoundFailureCause can be loaded by the annotator.
  *
  * @throws Exception if so.
  */
 @LocalData
 public void testLoadOldFailureCauseWithOnlyLineNumbers() throws Exception {
   FreeStyleProject job = (FreeStyleProject) Jenkins.getInstance().getItem("MyProject");
   assertNotNull(job);
   FreeStyleBuild build = job.getBuilds().getFirstBuild();
   OldDataConverter.getInstance().waitForInitialCompletion();
   FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class);
   List<FoundFailureCause> foundFailureCauses =
       Whitebox.getInternalState(action, "foundFailureCauses");
   FoundFailureCause foundFailureCause = foundFailureCauses.get(0);
   FoundIndication indication = foundFailureCause.getIndications().get(0);
   assertTrue(indication.getMatchingString().matches(indication.getPattern()));
   IndicationAnnotator annotator = new IndicationAnnotator(foundFailureCauses);
   Map<String, AnnotationHelper> helperMap = Whitebox.getInternalState(annotator, "helperMap");
   // since the old FoundIndication doesn't contain a matchingString from the start, we check it.
   AnnotationHelper annotationHelper = helperMap.get(indication.getMatchingString());
   assertNotNull(annotationHelper);
 }
  @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());
  }
Пример #22
0
  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
 }
 public void testSavedBuildSelector() throws Exception {
   FreeStyleProject other = createArtifactProject(), p = createFreeStyleProject();
   p.getBuildersList()
       .add(
           new CopyArtifact(other.getName(), new SavedBuildSelector(), "*.txt", "", false, false));
   FreeStyleBuild b =
       other
           .scheduleBuild2(
               0,
               new UserCause(),
               new ParametersAction(new StringParameterValue("FOO", "buildone")))
           .get();
   assertBuildStatusSuccess(b);
   assertBuildStatusSuccess(other.scheduleBuild2(0, new UserCause()));
   b.keepLog(true);
   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);
 }
Пример #25
0
  protected void setUp() throws Exception {
    super.setUp();

    RobotParser.RobotParserCallable remoteOperation =
        new RobotParser.RobotParserCallable("output.xml", null, null);
    RobotResult result =
        remoteOperation.invoke(
            new File(new RobotGraphHelperTest().getClass().getResource("output.xml").toURI())
                .getParentFile(),
            null);
    result.tally(null);

    // Mocked builds to play as owners of test results
    FreeStyleBuild mockBuild1 = mock(FreeStyleBuild.class);
    FreeStyleBuild mockBuild2 = mock(FreeStyleBuild.class);
    when(mockBuild2.compareTo(mockBuild1)).thenReturn(1);
    when(mockBuild1.compareTo(mockBuild2)).thenReturn(-1);

    // This is to pass hudson.util.Graph constructor
    GregorianCalendar c = new GregorianCalendar();
    c.setTimeInMillis(0L);
    when(mockBuild1.getTimestamp()).thenReturn(c);
    when(mockBuild2.getTimestamp()).thenReturn(c);

    // set up some results chains
    mockResult1 = spy(result);
    doReturn(null).when(mockResult1).getPreviousResult();
    doReturn(mockBuild1).when(mockResult1).getOwner();

    mockResult2 = spy(result);
    doReturn(mockResult1).when(mockResult2).getPreviousResult();
    doReturn(mockBuild2).when(mockResult2).getOwner();
  }
  private void assertTestResults(FreeStyleBuild build) {
    TestResultAction testResultAction = build.getAction(TestResultAction.class);
    assertNotNull("no TestResultAction", testResultAction);

    TestResult result = testResultAction.getResult();
    assertNotNull("no TestResult", result);

    assertEquals("should have 1 failing test", 1, testResultAction.getFailCount());
    assertEquals("should have 1 failing test", 1, result.getFailCount());

    assertEquals("should have 132 total tests", 132, testResultAction.getTotalCount());
    assertEquals("should have 132 total tests", 132, result.getTotalCount());
  }
  /**
   * Tests to trigger a build with the same patch set twice. Expecting one build to be scheduled
   * with one cause.
   *
   * @throws Exception if so.
   */
  @LocalData
  public void testDoubleTriggeredBuild() throws Exception {
    FreeStyleProject project = DuplicatesUtil.createGerritTriggeredJob(this, "projectX");
    server.waitForCommand(GERRIT_STREAM_EVENTS, 2000);
    PluginImpl.getInstance().triggerEvent(Setup.createPatchsetCreated());
    PluginImpl.getInstance().triggerEvent(Setup.createPatchsetCreated());

    RunList<FreeStyleBuild> builds = waitForBuilds(project, 1, 5000);
    FreeStyleBuild build = builds.get(0);
    assertSame(Result.SUCCESS, build.getResult());
    assertEquals(1, project.getBuilds().size());

    int count = 0;
    for (Cause cause : build.getCauses()) {
      if (cause instanceof GerritCause) {
        count++;
        assertNotNull(((GerritCause) cause).getContext());
        assertNotNull(((GerritCause) cause).getEvent());
      }
    }
    assertEquals(1, count);
  }
  @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 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());
  }