Java Examples for hudson.model.FreeStyleProject

The following java examples will help you to understand the usage of hudson.model.FreeStyleProject. These source code samples are taken from different open source projects.

Example 1
Project: hudson_plugins-master  File: SubversionSCMTest.java View source code
@PresetData(ANONYMOUS_READONLY)
@Bug(2380)
public void testTaggingPermission() throws Exception {
    // create a build
    FreeStyleProject p = createFreeStyleProject();
    p.setScm(loadSvnRepo());
    FreeStyleBuild b = p.scheduleBuild2(0, new Cause.UserCause()).get();
    System.out.println(b.getLog(LOG_LIMIT));
    assertBuildStatus(Result.SUCCESS, b);
    SubversionTagAction action = b.getAction(SubversionTagAction.class);
    assertFalse(b.hasPermission(action.getPermission()));
    WebClient wc = new WebClient();
    HtmlPage html = wc.getPage(b);
    // make sure there's no link to the 'tag this build'
    Document dom = new DOMReader().read(html);
    assertNull(dom.selectSingleNode("//A[text()='Tag this build']"));
    for (HtmlAnchor a : html.getAnchors()) assertFalse(a.getHrefAttribute().contains("/tagBuild/"));
    // and no tag form on tagBuild page
    html = wc.getPage(b, "tagBuild/");
    try {
        html.getFormByName("tag");
        fail("should not have been found");
    } catch (ElementNotFoundException e) {
    }
    // and that tagging would fail
    try {
        wc.getPage(b, "tagBuild/submit?name0=test&Submit=Tag");
        fail("should have been denied");
    } catch (FailingHttpStatusCodeException e) {
        assertEquals(e.getResponse().getStatusCode(), 403);
    }
    // now login as alice and make sure that the tagging would succeed
    wc = new WebClient();
    wc.login("alice", "alice");
    html = wc.getPage(b, "tagBuild/");
    HtmlForm form = html.getFormByName("tag");
    submit(form);
}
Example 2
Project: hudson-main-master  File: CaseResultTest.java View source code
private FreeStyleBuild configureTestBuild(String projectName) throws Exception {
    FreeStyleProject p = projectName == null ? createFreeStyleProject() : createFreeStyleProject(projectName);
    p.getBuildersList().add(new TestBuilder() {

        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            build.getWorkspace().child("junit.xml").copyFrom(getClass().getResource("junit-report-20090516.xml"));
            return true;
        }
    });
    p.getPublishersList().add(new JUnitResultArchiver("*.xml"));
    return assertBuildStatus(Result.UNSTABLE, p.scheduleBuild2(0).get());
}
Example 3
Project: hudson-test-harness-master  File: CaseResultTest.java View source code
private FreeStyleBuild configureTestBuild(String projectName) throws Exception {
    FreeStyleProject p = projectName == null ? createFreeStyleProject() : createFreeStyleProject(projectName);
    p.getBuildersList().add(new TestBuilder() {

        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            build.getWorkspace().child("junit.xml").copyFrom(getClass().getResource("junit-report-20090516.xml"));
            return true;
        }
    });
    p.addPublisher(new JUnitResultArchiver("*.xml"));
    return assertBuildStatus(Result.UNSTABLE, p.scheduleBuild2(0).get());
}
Example 4
Project: java-client-api-master  File: JenkinsServerIT.java View source code
@Test
public void shouldReturnBuildsForJob() throws Exception {
    FreeStyleProject trunk = jenkinsRule.getInstance().createProject(FreeStyleProject.class, JENKINS_TEST_JOB);
    for (int i = 0; i < 5; i++) trunk.scheduleBuild(0, new Cause.UserIdCause(), new ParametersAction(new StringParameterValue("BUILD NUMBER", "" + i)));
    while (trunk.isInQueue() || trunk.isBuilding()) {
    }
    JobWithDetails job = server.getJobs().get(JENKINS_TEST_JOB).details();
    assertEquals(5, job.getBuilds().get(0).getNumber());
}
Example 5
Project: jenkins-master  File: AbstractBuildRangeCommandTest.java View source code
@BeforeClass
public static void setUpClass() throws Exception {
    command = new CLICommandInvoker(j, new DummyRangeCommand());
    project = j.createFreeStyleProject(PROJECT_NAME);
    for (int i = 0; i < BUILDS; i++) {
        assertThat(project.scheduleBuild2(0).get(), not(equalTo(null)));
    }
    assertThat(((FreeStyleProject) j.jenkins.getItem("aProject")).getBuilds().size(), equalTo(BUILDS));
    for (int i : deleted) {
        project.getBuildByNumber(i).delete();
        assertThat(project.getBuildByNumber(i), equalTo(null));
    }
}
Example 6
Project: email-ext-plugin-master  File: ExtendedEmailPublisherTest.java View source code
@Issue("JENKINS-20524")
@Test
public void testMultipleTriggersOfSameType() throws Exception {
    FreeStyleProject prj = j.createFreeStyleProject("JENKINS-20524");
    prj.getPublishersList().add(publisher);
    publisher.recipientList = "mickey@disney.com";
    publisher.configuredTriggers.add(new SuccessTrigger(recProviders, "$DEFAULT_RECIPIENTS", "$DEFAULT_REPLYTO", "$DEFAULT_SUBJECT", "$DEFAULT_CONTENT", "", 0, "project"));
    publisher.configuredTriggers.add(new SuccessTrigger(recProviders, "$DEFAULT_RECIPIENTS", "$DEFAULT_REPLYTO", "$DEFAULT_SUBJECT", "$DEFAULT_CONTENT", "", 0, "project"));
    for (EmailTrigger trigger : publisher.configuredTriggers) {
        trigger.getEmail().addRecipientProvider(new ListRecipientProvider());
    }
    FreeStyleBuild build = prj.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(build);
    assertEquals(2, Mailbox.get("mickey@disney.com").size());
}
Example 7
Project: jenkins-plugins-master  File: ExtendedEmailPublisherTest.java View source code
@Issue("JENKINS-20524")
@Test
public void testMultipleTriggersOfSameType() throws Exception {
    FreeStyleProject prj = j.createFreeStyleProject("JENKINS-20524");
    prj.getPublishersList().add(publisher);
    publisher.recipientList = "mickey@disney.com";
    publisher.configuredTriggers.add(new SuccessTrigger(recProviders, "$DEFAULT_RECIPIENTS", "$DEFAULT_REPLYTO", "$DEFAULT_SUBJECT", "$DEFAULT_CONTENT", "", 0, "project"));
    publisher.configuredTriggers.add(new SuccessTrigger(recProviders, "$DEFAULT_RECIPIENTS", "$DEFAULT_REPLYTO", "$DEFAULT_SUBJECT", "$DEFAULT_CONTENT", "", 0, "project"));
    for (EmailTrigger trigger : publisher.configuredTriggers) {
        trigger.getEmail().addRecipientProvider(new ListRecipientProvider());
    }
    FreeStyleBuild build = prj.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(build);
    assertEquals(2, Mailbox.get("mickey@disney.com").size());
}
Example 8
Project: jira-jenkins-plugin-master  File: UpdaterTest.java View source code
@Test
@WithoutJenkins
public void testGetScmCommentsFromPreviousBuilds() throws Exception {
    final FreeStyleProject project = mock(FreeStyleProject.class);
    final FreeStyleBuild build1 = mock(FreeStyleBuild.class);
    final MockEntry entry1 = new MockEntry("FOOBAR-1: The first build");
    {
        ChangeLogSet changeLogSet = mock(ChangeLogSet.class);
        when(build1.getChangeSet()).thenReturn(changeLogSet);
        List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = new ArrayList<ChangeLogSet<? extends Entry>>();
        changeSets.add(changeLogSet);
        when(build1.getChangeSets()).thenReturn(changeSets);
        when(build1.getResult()).thenReturn(Result.FAILURE);
        doReturn(project).when(build1).getProject();
        doReturn(new JiraCarryOverAction(Sets.newHashSet(new JiraIssue("FOOBAR-1", null)))).when(build1).getAction(JiraCarryOverAction.class);
        final Set<? extends Entry> entries = Sets.newHashSet(entry1);
        when(changeLogSet.iterator()).thenAnswer(new Answer<Object>() {

            public Object answer(final InvocationOnMock invocation) throws Throwable {
                return entries.iterator();
            }
        });
    }
    final FreeStyleBuild build2 = mock(FreeStyleBuild.class);
    final MockEntry entry2 = new MockEntry("FOOBAR-2: The next build");
    {
        ChangeLogSet changeLogSet = mock(ChangeLogSet.class);
        when(build2.getChangeSet()).thenReturn(changeLogSet);
        List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = new ArrayList<ChangeLogSet<? extends Entry>>();
        changeSets.add(changeLogSet);
        when(build2.getChangeSets()).thenReturn(changeSets);
        when(build2.getPreviousBuild()).thenReturn(build1);
        when(build2.getResult()).thenReturn(Result.SUCCESS);
        doReturn(project).when(build2).getProject();
        final Set<? extends Entry> entries = Sets.newHashSet(entry2);
        when(changeLogSet.iterator()).thenAnswer(new Answer<Object>() {

            public Object answer(final InvocationOnMock invocation) throws Throwable {
                return entries.iterator();
            }
        });
    }
    final List<Comment> comments = Lists.newArrayList();
    final JiraSession session = mock(JiraSession.class);
    doAnswer(new Answer<Object>() {

        public Object answer(final InvocationOnMock invocation) throws Throwable {
            Comment rc = Comment.createWithGroupLevel((String) invocation.getArguments()[1], (String) invocation.getArguments()[2]);
            comments.add(rc);
            return null;
        }
    }).when(session).addComment(anyString(), anyString(), anyString(), anyString());
    this.updater = new Updater(build2.getProject().getScm());
    final Set<JiraIssue> ids = Sets.newHashSet(new JiraIssue("FOOBAR-1", null), new JiraIssue("FOOBAR-2", null));
    updater.submitComments(build2, System.out, "http://jenkins", ids, session, false, false, "", "");
    Assert.assertEquals(2, comments.size());
    Assert.assertThat(comments.get(0).getBody(), Matchers.containsString(entry1.getMsg()));
    Assert.assertThat(comments.get(1).getBody(), Matchers.containsString(entry2.getMsg()));
}
Example 9
Project: jira-plugin-master  File: UpdaterTest.java View source code
@Test
@WithoutJenkins
public void testGetScmCommentsFromPreviousBuilds() throws Exception {
    final FreeStyleProject project = mock(FreeStyleProject.class);
    final FreeStyleBuild build1 = mock(FreeStyleBuild.class);
    final MockEntry entry1 = new MockEntry("FOOBAR-1: The first build");
    {
        ChangeLogSet changeLogSet = mock(ChangeLogSet.class);
        when(build1.getChangeSet()).thenReturn(changeLogSet);
        List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = new ArrayList<ChangeLogSet<? extends Entry>>();
        changeSets.add(changeLogSet);
        when(build1.getChangeSets()).thenReturn(changeSets);
        when(build1.getResult()).thenReturn(Result.FAILURE);
        doReturn(project).when(build1).getProject();
        doReturn(new JiraCarryOverAction(Sets.newHashSet(new JiraIssue("FOOBAR-1", null)))).when(build1).getAction(JiraCarryOverAction.class);
        final Set<? extends Entry> entries = Sets.newHashSet(entry1);
        when(changeLogSet.iterator()).thenAnswer(new Answer<Object>() {

            public Object answer(final InvocationOnMock invocation) throws Throwable {
                return entries.iterator();
            }
        });
    }
    final FreeStyleBuild build2 = mock(FreeStyleBuild.class);
    final MockEntry entry2 = new MockEntry("FOOBAR-2: The next build");
    {
        ChangeLogSet changeLogSet = mock(ChangeLogSet.class);
        when(build2.getChangeSet()).thenReturn(changeLogSet);
        List<ChangeLogSet<? extends ChangeLogSet.Entry>> changeSets = new ArrayList<ChangeLogSet<? extends Entry>>();
        changeSets.add(changeLogSet);
        when(build2.getChangeSets()).thenReturn(changeSets);
        when(build2.getPreviousBuild()).thenReturn(build1);
        when(build2.getResult()).thenReturn(Result.SUCCESS);
        doReturn(project).when(build2).getProject();
        final Set<? extends Entry> entries = Sets.newHashSet(entry2);
        when(changeLogSet.iterator()).thenAnswer(new Answer<Object>() {

            public Object answer(final InvocationOnMock invocation) throws Throwable {
                return entries.iterator();
            }
        });
    }
    final List<Comment> comments = Lists.newArrayList();
    final JiraSession session = mock(JiraSession.class);
    doAnswer(new Answer<Object>() {

        public Object answer(final InvocationOnMock invocation) throws Throwable {
            Comment rc = Comment.createWithGroupLevel((String) invocation.getArguments()[1], (String) invocation.getArguments()[2]);
            comments.add(rc);
            return null;
        }
    }).when(session).addComment(anyString(), anyString(), anyString(), anyString());
    this.updater = new Updater(build2.getProject().getScm());
    final Set<JiraIssue> ids = Sets.newHashSet(new JiraIssue("FOOBAR-1", null), new JiraIssue("FOOBAR-2", null));
    updater.submitComments(build2, System.out, "http://jenkins", ids, session, false, false, "", "");
    Assert.assertEquals(2, comments.size());
    Assert.assertThat(comments.get(0).getBody(), Matchers.containsString(entry1.getMsg()));
    Assert.assertThat(comments.get(1).getBody(), Matchers.containsString(entry2.getMsg()));
}
Example 10
Project: matrix-project-plugin-master  File: MatrixProjectDependencyTest.java View source code
/**
	 * Checks if the MatrixProject adds and Triggers downstream Projects via
	 * the DependencyGraph 
	 */
@Test
public void matrixProjectTriggersDependencies() throws Exception {
    MatrixProject matrixProject = j.createProject(MatrixProject.class);
    FreeStyleProject freestyleProject = j.createFreeStyleProject();
    matrixProject.getPublishersList().add(new BuildTrigger(freestyleProject.getName(), false));
    j.jenkins.rebuildDependencyGraph();
    j.buildAndAssertSuccess(matrixProject);
    j.waitUntilNoActivity();
    RunList<FreeStyleBuild> builds = freestyleProject.getBuilds();
    assertEquals("There should only be one FreestyleBuild", 1, builds.size());
    FreeStyleBuild build = builds.iterator().next();
    assertEquals(Result.SUCCESS, build.getResult());
    List<AbstractProject> downstream = j.jenkins.getDependencyGraph().getDownstream(matrixProject);
    assertTrue(downstream.contains(freestyleProject));
}
Example 11
Project: performance-plugin-master  File: PerformancePublisherTest.java View source code
@Test
public void testBuild() throws Exception {
    FreeStyleProject p = createFreeStyleProject();
    p.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            build.getWorkspace().child("test.jtl").copyFrom(getClass().getResource("/JMeterResults.jtl"));
            return true;
        }
    });
    p.getPublishersList().add(new PerformancePublisher("", 0, 0, "", 0, 0, 0, 0, 0, false, "", false, false, false, false, null));
    FreeStyleBuild b = assertBuildStatusSuccess(p.scheduleBuild2(0).get());
    PerformanceBuildAction a = b.getAction(PerformanceBuildAction.class);
    try {
        //assertNotNull(a);
        // poke a few random pages to verify rendering
        WebClient wc = createWebClient();
        wc.getPage(b, "performance");
        wc.getPage(b, "performance/uriReport/test.jtl:Home.endperformanceparameter/");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 12
Project: promoted-builds-plugin-master  File: ItemPathResolverTest.java View source code
@Before
public void setUpFolders() throws Exception {
    folderA = rule.createFolder("a");
    folderB = folderA.createProject(MockFolder.class, "b");
    folderC = folderB.createProject(MockFolder.class, "c");
    projectInTop = rule.createFreeStyleProject("prj");
    projectInC1 = folderC.createProject(FreeStyleProject.class, "prjInC1");
    projectInC2 = folderC.createProject(FreeStyleProject.class, "prjInC2");
}
Example 13
Project: subversion-plugin-master  File: SVNWorkingCopyTest.java View source code
private int checkoutWithFormat(int format) throws Exception {
    super.configureSvnWorkspaceFormat(format);
    FreeStyleProject project = jenkins.createProject(FreeStyleProject.class, "svntest" + format);
    SubversionSCM subversionSCM = new SubversionSCM("https://svn.jenkins-ci.org/trunk/hudson/test-projects/trivial-ant");
    project.setScm(subversionSCM);
    assertBuildStatusSuccess(project.scheduleBuild2(0));
    // Create a status client and get the working copy format.
    SVNClientManager testWCVerseion = SVNClientManager.newInstance(null, "testWCVerseion", null);
    File path = new File(project.getWorkspace().getRemote());
    return testWCVerseion.getStatusClient().doStatus(path, true).getWorkingCopyFormat();
}
Example 14
Project: ansible-plugin-master  File: DslJobRule.java View source code
private void before(Description description) throws Exception {
    FreeStyleProject job = jRule.createFreeStyleProject();
    String script = description.getAnnotation(WithJobDsl.class).value();
    String scriptText = Resources.toString(Resources.getResource(script), Charsets.UTF_8);
    job.getBuildersList().add(new ExecuteDslScripts(new ExecuteDslScripts.ScriptLocation(null, null, scriptText), false, RemovedJobAction.DELETE, RemovedViewAction.DELETE, LookupStrategy.JENKINS_ROOT));
    jRule.buildAndAssertSuccess(job);
    assertThat(jRule.getInstance().getJobNames(), hasItem(is(JOB_NAME_IN_DSL_SCRIPT)));
    generated = jRule.getInstance().getItemByFullName(JOB_NAME_IN_DSL_SCRIPT, FreeStyleProject.class);
}
Example 15
Project: delivery-pipeline-plugin-master  File: PipelineTest.java View source code
@Test
public void testExtractPipelineEmptyPropertyAndNullProperty() throws Exception {
    FreeStyleProject job = jenkins.createFreeStyleProject("job");
    Pipeline pipeline = Pipeline.extractPipeline("Pipeline", job);
    assertEquals(1, pipeline.getStages().size());
    assertEquals("job", pipeline.getStages().get(0).getName());
    assertEquals("job", pipeline.getStages().get(0).getTasks().get(0).getName());
    job.addProperty(new PipelineProperty("", "", ""));
    pipeline = Pipeline.extractPipeline("Pipeline", job);
    assertEquals(1, pipeline.getStages().size());
    assertEquals("job", pipeline.getStages().get(0).getName());
    assertEquals("job", pipeline.getStages().get(0).getTasks().get(0).getName());
}
Example 16
Project: deploy-plugin-master  File: GlassFish3xAdapterTest.java View source code
@Test
public void testConfigure() throws IOException, InterruptedException, ExecutionException {
    Assert.assertEquals(adapter.home, home);
    //    Assert.assertEquals(adapter.adminPort, port);
    Assert.assertEquals(adapter.userName, username);
    Assert.assertEquals(adapter.getPassword(), password);
    ConfigurationFactory configFactory = new DefaultConfigurationFactory();
    ContainerFactory containerFactory = new DefaultContainerFactory();
    FreeStyleProject project = jenkinsRule.createFreeStyleProject();
    FreeStyleBuild build = project.scheduleBuild2(0).get();
    BuildListener listener = new StreamBuildListener(new ByteArrayOutputStream());
    Container container = adapter.getContainer(configFactory, containerFactory, adapter.getContainerId(), build.getEnvironment(listener), build.getBuildVariableResolver());
    Assert.assertNotNull(container);
}
Example 17
Project: disk-usage-plugin-master  File: DiskUsagePropertyTest.java View source code
@Test
public void testGetAllDiskUsageWithoutBuilds() throws Exception {
    FreeStyleProject project = j.jenkins.createProject(FreeStyleProject.class, "project1");
    MatrixProject matrixProject = j.jenkins.createProject(MatrixProject.class, "project2");
    TextAxis axis1 = new TextAxis("axis", "axisA");
    TextAxis axis2 = new TextAxis("axis2", "Aaxis");
    AxisList list = new AxisList();
    list.add(axis1);
    list.add(axis2);
    matrixProject.setAxes(list);
    Long sizeOfProject = 7546l;
    Long sizeOfMatrixProject = 6800l;
    DiskUsageProperty projectProperty = project.getProperty(DiskUsageProperty.class);
    //project.addProperty(projectProperty);
    projectProperty.setDiskUsageWithoutBuilds(sizeOfProject);
    DiskUsageProperty matrixProjectProperty = matrixProject.getProperty(DiskUsageProperty.class);
    matrixProjectProperty.setDiskUsageWithoutBuilds(sizeOfMatrixProject);
    long size1 = 5390;
    int count = 1;
    Long matrixProjectTotalSize = sizeOfMatrixProject;
    for (MatrixConfiguration c : matrixProject.getItems()) {
        DiskUsageProperty configurationProperty = c.getProperty(DiskUsageProperty.class);
        if (configurationProperty == null) {
            configurationProperty = new DiskUsageProperty();
            c.addProperty(configurationProperty);
        }
        configurationProperty.setDiskUsageWithoutBuilds(count * size1);
        matrixProjectTotalSize += count * size1;
        count++;
    }
    matrixProject.getAction(ProjectDiskUsageAction.class).actualizeCashedJobWithoutBuildsData();
    project.getAction(ProjectDiskUsageAction.class).actualizeCashedJobWithoutBuildsData();
    assertEquals("DiskUsageProperty for FreeStyleProject " + project.getDisplayName() + " returns wrong value its size without builds and including sub-projects.", sizeOfProject, project.getProperty(DiskUsageProperty.class).getAllDiskUsageWithoutBuilds());
    assertEquals("DiskUsageProperty for MatrixProject " + matrixProject.getDisplayName() + " returns wrong value for its size without builds and including sub-projects.", matrixProjectTotalSize, matrixProject.getProperty(DiskUsageProperty.class).getAllDiskUsageWithoutBuilds());
}
Example 18
Project: fogbugz-plugin-master  File: FogbugzEventListenerTests.java View source code
@Test
public void testFogbugzEventListener() throws Exception {
    given(notifier.getFogbugzManager()).willReturn(manager);
    given(manager.getCaseById(1)).willThrow(new NoSuchCaseException("1"));
    FogbugzCase expected = new FogbugzCase(7, "HALLO!", 2, 2, "merged", true, "maikelwever/repo1#c7", "r1336", "r1336", "1336", "myproject", "some revision");
    given(manager.getCaseById(7)).willReturn(expected);
    String response = new FogbugzEventListener().scheduleJob(notifier, 0, "some job", null, null, false);
    assertEquals("<html><body>No case found</body></html>", response);
    response = new FogbugzEventListener().scheduleJob(notifier, 1, "some job", null, null, false);
    assertEquals("<html><body>No case found</body></html>", response);
    FreeStyleProject project = j.createFreeStyleProject("myproject_mergekeepers");
    JobProperty property = new ParametersDefinitionProperty(new StringParameterDefinition("CASE_ID", ""));
    project.addProperty(property);
    response = new FogbugzEventListener().scheduleJob(notifier, 7, null, "_mergekeepers", "cixproject", false);
    assertEquals("<html><body>Scheduled ok</body></html>", response);
    assertEquals("CASE_ID=7", project.getQueueItem().getParams().trim());
}
Example 19
Project: jenkins-unity3d-plugin-master  File: IntegrationTests.java View source code
/*@Rule
    public JenkinsRule rule = new JenkinsRule();*/
@Test
@LocalData
public void testEditorException() throws Exception {
    ensureUnityHomeExists();
    FreeStyleProject job = (FreeStyleProject) jenkins.getItem("test_unity3d");
    assertNotNull(job);
    FreeStyleBuild build = job.scheduleBuild2(0).get();
    String log = FileUtils.readFileToString(build.getLogFile());
    //System.out.println(log);
    assertTrue("Found cause for failure in console", log.contains("Exception: Simulated Exception"));
}
Example 20
Project: lyo.server-master  File: ScheduleBuildTest.java View source code
public void testScheduleParameterizedBuild() throws Exception {
    final OneShotEvent buildStarted = new OneShotEvent();
    FreeStyleProject project = createFreeStyleProject("MyProject");
    project.setQuietPeriod(1);
    project.getBuildersList().add(new TestBuilder() {

        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            buildStarted.signal();
            return true;
        }
    });
    ArrayList<ParameterDefinition> parameterDefinitions = new ArrayList<ParameterDefinition>();
    parameterDefinitions.add(new StringParameterDefinition("string", "foo"));
    parameterDefinitions.add(new BooleanParameterDefinition("bool", true, "A boolean parameter."));
    ParametersDefinitionProperty params = new ParametersDefinitionProperty(parameterDefinitions);
    project.addProperty(params);
    AutomationPlan plan = getEntity("/job/MyProject", OSLCConstants.CT_RDF, AutomationPlan.class);
    assertEquals("Expected two parameter definitions", 2, plan.getParameterDefinitions().length);
    AutomationRequest request = new AutomationRequest();
    request.setExecutesAutomationPlan(new Link(plan.getAbout()));
    ParameterInstance stringParameter = new ParameterInstance();
    stringParameter.setName("string");
    stringParameter.setValue("bar");
    request.addInputParameter(stringParameter);
    // TODO: Test other types.
    ClientResponse response = createAutomationRequest(request, OSLCConstants.CT_RDF);
    assertEquals(HttpServletResponse.SC_CREATED, response.getStatusCode());
    String location = response.getHeaders().getFirst("Location");
    assertNotNull(location);
    // Wait for the build.
    buildStarted.block(10000);
    // FIXME: Should be able to get the automation request before the build starts!
    OslcClient client = new OslcClient();
    response = client.getResource(location, OSLCConstants.CT_RDF);
    assertEquals(HttpServletResponse.SC_OK, response.getStatusCode());
    AutomationRequest fetchedRequest = response.getEntity(AutomationRequest.class);
    assertEquals(location, fetchedRequest.getAbout().toString());
    assertEquals(plan.getAbout(), fetchedRequest.getExecutesAutomationPlan().getValue());
    RunList<FreeStyleBuild> runs = project.getBuilds();
    assertEquals(1, runs.size());
    FreeStyleBuild build = runs.iterator().next();
    Map<String, String> actualParameters = build.getBuildVariables();
    assertEquals("bar", actualParameters.get("string"));
}
Example 21
Project: maven-repository-server-plugin-master  File: Jobs.java View source code
@Override
protected void loadChildren() {
    Hudson hudson = Hudson.getInstance();
    List<FreeStyleProject> freeStyleProjects = hudson.getItems(FreeStyleProject.class);
    for (FreeStyleProject freeStyleProject : freeStyleProjects) {
        if (freeStyleProject.getLastStableBuild() != null) {
            Job project = new Job(freeStyleProject, this);
            children.put(freeStyleProject.getName(), project);
        }
    }
}
Example 22
Project: mercurial-plugin-master  File: SCMTestBase.java View source code
@Bug(13329)
@Test
public void basicOps() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new MercurialSCM(hgInstallation(), repo.getPath(), null, null, null, null, false));
    m.hg(repo, "init");
    m.touchAndCommit(repo, "a");
    String log = m.buildAndCheck(p, "a");
    assertClone(log, true);
    m.touchAndCommit(repo, "b");
    log = m.buildAndCheck(p, "b");
    assertClone(log, false);
}
Example 23
Project: metadata-plugin-master  File: CliUtilsTest.java View source code
/**
     * Tests {@link CliUtils#getContainer(String, String, Integer, boolean)}  with a job.
     *
     * @throws Exception if so.
     */
@Test
public void testGetContainerJob() throws Exception {
    Hudson hudson = MockUtils.mockHudson();
    FreeStyleProject project = mock(FreeStyleProject.class);
    when(hudson.getItem("fake")).thenReturn(project);
    MetadataJobProperty property = mock(MetadataJobProperty.class);
    when(project.getProperty(MetadataJobProperty.class)).thenReturn(property);
    MetadataParent<MetadataValue> container = CliUtils.getContainer(null, "fake", null, false);
    assertNotNull(container);
    assertSame(property, container);
}
Example 24
Project: openshift-deployer-plugin-master  File: DeployApplicationTest.java View source code
@Test
public void deployBinary() throws Exception {
    String deployment = ClassLoader.getSystemResource(BINARY_DEPLOYMENT).getFile();
    FreeStyleProject project = jenkins.createFreeStyleProject();
    DeployApplication deployBuildStep = newDeployAppBuildStep(APP_NAME, deployment, DeploymentType.BINARY);
    project.getBuildersList().add(deployBuildStep);
    FreeStyleBuild build = project.scheduleBuild2(0).get();
    assertDeploySucceeded(build);
    removeApp(APP_NAME);
}
Example 25
Project: parameterized-trigger-plugin-master  File: FileBuildTriggerConfigTest.java View source code
@Test
public void testUtf8File() throws Exception {
    FreeStyleProject projectA = r.createFreeStyleProject("projectA");
    String properties = // "hello" in Japanese.
    "KEY=ã?“ã‚“ã?«ã?¡ã?¯\n" + // "KEY" in multibytes.
    "KEY=value";
    projectA.setScm(new SingleFileSCM("properties.txt", properties.getBytes("UTF-8")));
    projectA.getPublishersList().add(new BuildTrigger(new BuildTriggerConfig("projectB", ResultCondition.SUCCESS, new FileBuildParameters("properties.txt", "UTF-8", true))));
    CaptureEnvironmentBuilder builder = new CaptureEnvironmentBuilder();
    FreeStyleProject projectB = r.createFreeStyleProject("projectB");
    projectB.getBuildersList().add(builder);
    projectB.setQuietPeriod(1);
    r.jenkins.rebuildDependencyGraph();
    // SECURITY-170: need to allow multibyte params that can't be traditionally declared.
    try {
        //System.setProperty(ParametersAction.KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME, "true");
        System.setProperty("hudson.model.ParametersAction.keepUndefinedParameters", "true");
        projectA.scheduleBuild2(0).get();
        r.jenkins.getQueue().getItem(projectB).getFuture().get();
        assertNotNull("builder should record environment", builder.getEnvVars());
        assertEquals("ã?“ã‚“ã?«ã?¡ã?¯", builder.getEnvVars().get("KEY"));
        assertEquals("value", builder.getEnvVars().get("KEY"));
    } finally {
        //System.clearProperty(ParametersAction.KEEP_UNDEFINED_PARAMETERS_SYSTEM_PROPERTY_NAME);
        System.clearProperty("hudson.model.ParametersAction.keepUndefinedParameters");
    }
}
Example 26
Project: tap-plugin-master  File: TestFlattenTapResult.java View source code
private void _test(final String tap, int expectedTotal, String[] expectedDescriptions, boolean printDescriptions) throws IOException, InterruptedException, ExecutionException {
    FreeStyleProject project = this.hudson.createProject(FreeStyleProject.class, "flatten-the-file");
    project.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher arg1, BuildListener arg2) throws InterruptedException, IOException {
            build.getWorkspace().child("result.tap").write(tap, "UTF-8");
            return true;
        }
    });
    TapPublisher publisher = new TapPublisher(// test results
    "result.tap", // failIfNoResults
    true, // failedTestsMarkBuildAsFailure
    true, // outputTapToConsole
    false, // enableSubtests
    true, // discardOldReports
    true, // todoIsFailure
    true, // includeCommentDiagnostics
    true, // validateNumberOfTests
    true, // planRequired
    true, // verbose
    false, // showOnlyFailures
    true, // stripSingleParents
    false, // flattenTapResult
    true, //skipIfBuildNotOk
    false);
    project.getPublishersList().add(publisher);
    project.save();
    FreeStyleBuild build = (FreeStyleBuild) project.scheduleBuild2(0).get();
    TapTestResultAction action = build.getAction(TapTestResultAction.class);
    TapResult testResult = action.getTapResult();
    assertEquals(expectedTotal, testResult.getTotal());
    final TestSet testSet = testResult.getTestSets().get(0).getTestSet();
    int testIndex = 0;
    for (TestResult result : testSet.getTestResults()) {
        final String description = result.getDescription();
        final int testNumber = result.getTestNumber();
        int expectedTestNumber = testIndex + 1;
        if (printDescriptions) {
            System.out.printf("%d: %s\n", testNumber, description);
        }
        assertEquals(expectedTestNumber, testNumber);
        if (expectedDescriptions != null) {
            assertEquals(expectedDescriptions[testIndex], description);
        }
        testIndex++;
    }
}
Example 27
Project: dumpling-master  File: DeadlocksTest.java View source code
private void assertListing(String out) {
    assertThat(out, startsWith(Util.multiline("", "Monitor Deadlock #1:", "\"Handling POST /hudson/job/some_other_job/doRename : ajp-127.0.0.1-8009-24\" daemon prio=10 tid=0x5851b800 nid=27336", "\tWaiting to <0x40dce6960> (a hudson.model.ListView)", "\tAcquired   <0x40dce0d68> (a hudson.plugins.nested_view.NestedView)", "\tAcquired   <0x49c5f7990> (a hudson.model.FreeStyleProject)", "\tAcquired * <0x404325338> (a hudson.model.Hudson)", "\"Handling POST /hudson/view/some_view/configSubmit : ajp-127.0.0.1-8009-107\" daemon prio=10 tid=0x2ad440c4e000 nid=17982", "\tWaiting to <0x404325338> (a hudson.model.Hudson)", "\tAcquired * <0x40dce6960> (a hudson.model.ListView)")));
    assertThat(out, containsString("%nDeadlocks: 1%n"));
}
Example 28
Project: accelerated-build-now-plugin-master  File: CantAbortHumanBuildTest.java View source code
@Test
@LocalData
public void test_dont_abort_build_if_started_by_user() throws Exception {
    System.out.println("I have : " + Jenkins.getInstance().getNumExecutors() + " executor(s) available");
    FreeStyleProject job1 = Jenkins.getInstance().getAllItems(FreeStyleProject.class).get(0);
    assertThat(job1.getName(), equalTo("simpleJobWithParameters"));
    job1.getBuildersList().add(new SleepBuilder(3000));
    httpPostBuildToJenkins("job/simpleJobWithParameters/buildWithParameters", "stringParameterName=Value&.crumb=test");
    FreeStyleProject acceleratedJob = createFreeStyleProject("acceleratedJob");
    acceleratedJob.getBuildersList().add(new SleepBuilder(3000));
    AcceleratedBuildNowAction acceleratedBuildNowAction = new AcceleratedBuildNowAction(acceleratedJob);
    StaplerRequest request = mock(StaplerRequest.class);
    when(request.getContextPath()).thenReturn("");
    StaplerResponse response = mock(StaplerResponse.class);
    doNothing().when(response).sendRedirect(anyString());
    acceleratedBuildNowAction.doBuild(request, response);
    while (!Jenkins.getInstance().getQueue().isEmpty()) {
        Thread.sleep(1000);
        System.out.println("Waiting for the queue to empty");
    }
    assertEquals(3, job1.getBuilds().size());
    FreeStyleBuild job1FirstBuild = job1.getBuilds().get(1);
    assertBuildStatus(Result.SUCCESS, job1FirstBuild);
    job1FirstBuild.getCauses();
    for (Cause cause : job1FirstBuild.getCauses()) {
        System.out.println("the cause is : " + cause.getShortDescription());
        System.out.println("the cause class is : " + cause.getClass().getName());
    }
    assertEquals(1, acceleratedJob.getBuilds().size());
    FreeStyleBuild acceleratedJobOnlyBuild = acceleratedJob.getBuilds().getLastBuild();
    assertBuildStatus(Result.SUCCESS, acceleratedJobOnlyBuild);
    // job1firstBuild started before acceleratedJobOnlyBuild
    assertTrue(job1FirstBuild.getStartTimeInMillis() < acceleratedJobOnlyBuild.getStartTimeInMillis());
}
Example 29
Project: build-failure-analyzer-plugin-master  File: BuildFailureScannerHudsonTest.java View source code
/**
     * Happy test that should find one failure indication in the build.
     *
     * @throws Exception if so.
     */
@Test
public void testOneIndicationFound() throws Exception {
    FreeStyleProject project = createProject();
    FailureCause failureCause = configureCauseAndIndication();
    Future<FreeStyleBuild> future = project.scheduleBuild2(0, new Cause.UserIdCause());
    FreeStyleBuild build = future.get(10, TimeUnit.SECONDS);
    jenkins.assertBuildStatus(Result.FAILURE, build);
    FailureCauseBuildAction action = build.getAction(FailureCauseBuildAction.class);
    assertNotNull(action);
    List<FoundFailureCause> causeListFromAction = action.getFoundFailureCauses();
    assertTrue(findCauseInList(causeListFromAction, failureCause));
    HtmlPage page = jenkins.createWebClient().goTo(build.getUrl() + "console");
    HtmlElement document = page.getDocumentElement();
    FoundFailureCause foundFailureCause = causeListFromAction.get(0);
    assertEquals(FORMATTED_DESCRIPTION, foundFailureCause.getDescription());
    FoundIndication foundIndication = foundFailureCause.getIndications().get(0);
    String id = foundIndication.getMatchingHash() + foundFailureCause.getId();
    HtmlElement focus = document.getElementById(id);
    assertNotNull(focus);
    List<HtmlElement> errorElements = document.getElementsByAttribute("span", "title", foundFailureCause.getName());
    assertNotNull(errorElements);
    HtmlElement error = errorElements.get(0);
    assertNotNull(error);
    assertEquals("Error message not found: ", BUILD_LOG_FIRST_LINE, error.getTextContent().trim());
}
Example 30
Project: build-timeout-plugin-master  File: BuildTimeoutWrapperIntegrationTest.java View source code
/*
	 * Method to get environment variables when no timeout env variable is declared
	 */
public EnvVars getEnvVars() throws Exception {
    BuildTimeoutWrapper.MINIMUM_TIMEOUT_MILLISECONDS = 0;
    FreeStyleProject project = createFreeStyleProject();
    project.getBuildWrappersList().add(new BuildTimeoutWrapper(new QuickBuildTimeOutStrategy(300000), false, false));
    CaptureEnvironmentBuilder captureEnvBuilder = new CaptureEnvironmentBuilder();
    project.getBuildersList().add(captureEnvBuilder);
    project.scheduleBuild2(0).get();
    return captureEnvBuilder.getEnvVars();
}
Example 31
Project: copyartifact-plugin-master  File: TriggeredBuildSelectorTest.java View source code
/**
     * Tests that web configuration page works correct.
     * @throws Exception
     */
@Test
public void testWebConfiguration() throws Exception {
    WebClient wc = j.createWebClient();
    {
        FreeStyleProject p = j.createFreeStyleProject();
        p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact("${upstream}", "", new TriggeredBuildSelector(true, TriggeredBuildSelector.UpstreamFilterStrategy.UseOldest, false), "", "", false, false, false));
        p.save();
        j.submit(wc.getPage(p, "configure").getFormByName("config"));
        p = j.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class);
        assertNotNull(p);
        CopyArtifact copyArtifact = p.getBuildersList().get(CopyArtifact.class);
        assertNotNull(p);
        assertNotNull(copyArtifact.getBuildSelector());
        assertEquals(TriggeredBuildSelector.class, copyArtifact.getBuildSelector().getClass());
        TriggeredBuildSelector selector = (TriggeredBuildSelector) copyArtifact.getBuildSelector();
        assertTrue(selector.isFallbackToLastSuccessful());
        assertEquals(TriggeredBuildSelector.UpstreamFilterStrategy.UseOldest, selector.getUpstreamFilterStrategy());
    }
    {
        FreeStyleProject p = j.createFreeStyleProject();
        p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact("${upstream}", "", new TriggeredBuildSelector(false, TriggeredBuildSelector.UpstreamFilterStrategy.UseNewest, false), "", "", false, false, false));
        p.save();
        j.submit(wc.getPage(p, "configure").getFormByName("config"));
        p = j.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class);
        assertNotNull(p);
        CopyArtifact copyArtifact = p.getBuildersList().get(CopyArtifact.class);
        assertNotNull(p);
        assertNotNull(copyArtifact.getBuildSelector());
        assertEquals(TriggeredBuildSelector.class, copyArtifact.getBuildSelector().getClass());
        TriggeredBuildSelector selector = (TriggeredBuildSelector) copyArtifact.getBuildSelector();
        assertFalse(selector.isFallbackToLastSuccessful());
        assertEquals(TriggeredBuildSelector.UpstreamFilterStrategy.UseNewest, selector.getUpstreamFilterStrategy());
    }
    {
        FreeStyleProject p = j.createFreeStyleProject();
        p.getBuildersList().add(CopyArtifactUtil.createCopyArtifact("${upstream}", "", new TriggeredBuildSelector(true, TriggeredBuildSelector.UpstreamFilterStrategy.UseGlobalSetting, false), "", "", false, false, false));
        p.save();
        j.submit(wc.getPage(p, "configure").getFormByName("config"));
        p = j.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class);
        assertNotNull(p);
        CopyArtifact copyArtifact = p.getBuildersList().get(CopyArtifact.class);
        assertNotNull(p);
        assertNotNull(copyArtifact.getBuildSelector());
        assertEquals(TriggeredBuildSelector.class, copyArtifact.getBuildSelector().getClass());
        TriggeredBuildSelector selector = (TriggeredBuildSelector) copyArtifact.getBuildSelector();
        assertTrue(selector.isFallbackToLastSuccessful());
        assertEquals(TriggeredBuildSelector.UpstreamFilterStrategy.UseGlobalSetting, selector.getUpstreamFilterStrategy());
    }
}
Example 32
Project: gerrit-trigger-plugin-master  File: SpecGerritTriggerHudsonTest.java View source code
/**
     * Tests that a triggered build in silent start mode does not emit any build started messages.
     * @throws Exception if so.
     */
@Test
@LocalData
public void testTriggeredSilentStartModeBuild() throws Exception {
    FreeStyleProject project = new TestUtils.JobBuilder(j).silentStartMode(true).build();
    serverMock.waitForCommand(GERRIT_STREAM_EVENTS, 2000);
    gerritServer.triggerEvent(Setup.createPatchsetCreated());
    TestUtils.waitForBuilds(project, 1, 20000);
    List<SshdServerMock.CommandMock> commands = serverMock.getCommandHistory();
    for (int i = 0; i < commands.size(); i++) {
        String command = commands.get(i).getCommand();
        assertFalse(command.toLowerCase().contains("build started"));
    }
}
Example 33
Project: instant-messaging-plugin-master  File: BuildCommandTest.java View source code
@SuppressWarnings("unchecked")
private AbstractProject<?, ?> mockProject(JobProvider jobProvider) {
    @SuppressWarnings("rawtypes") AbstractProject project = mock(FreeStyleProject.class);
    when(jobProvider.getJobByNameOrDisplayName(Mockito.anyString())).thenReturn(project);
    when(project.hasPermission(Item.BUILD)).thenReturn(Boolean.TRUE);
    when(project.isBuildable()).thenReturn(true);
    return project;
}
Example 34
Project: jenkins-whitesource-plugin-master  File: WssUtils.java View source code
/**
	 * <b>Important: </b> do not remove since it is used in jelly config files to determine job type.
	 * 
	 * @param project
	 * @return True if this is a freestyle project that invoke a top maven target.
	 */
public static boolean isFreeStyleMaven(AbstractProject<?, ?> project) {
    boolean freeStyle = false;
    if (project instanceof FreeStyleProject) {
        for (Builder builder : ((FreeStyleProject) project).getBuilders()) {
            if (builder instanceof Maven) {
                freeStyle = true;
                break;
            }
        }
    }
    return freeStyle;
}
Example 35
Project: jenkow-plugin-master  File: DiagramTest.java View source code
public void testDiagramGeneration() throws Exception {
    JenkowWorkflowRepository repo = JenkowPlugin.getInstance().getRepo();
    repo.ensureWorkflowDefinition("wf1");
    FreeStyleProject launcher = createFreeStyleProject("j1");
    DescribableList<Builder, Descriptor<Builder>> bl = launcher.getBuildersList();
    bl.add(new JenkowBuilder("wf1"));
    bl.add(new Shell("echo wf.done"));
    // work around the problem in the core of not registering our builder's project actions
    configRoundtrip(launcher);
    testImage("job/j1/jenkow/graph", "default");
    testImage("job/j1/jenkow/graph/0", "0");
    testImage("job/j1/jenkow/graph/wf1", "wf1");
    testError("job/j1/jenkow/graph/1");
    testError("job/j1/jenkow/graph/no-such-workflow");
    testError("job/j1/jenkow/graph/WF1");
}
Example 36
Project: jobConfigHistory-plugin-master  File: JobConfigHistoryRootActionIT.java View source code
/**
	 * Tests whether info gets displayed correctly for filter parameter
	 * none/system/jobs/deleted/created.
	 */
public void testFilterWithData() throws Exception {
    // create some config history data
    final FreeStyleProject project = createFreeStyleProject("Test1");
    Thread.sleep(SLEEP_TIME);
    project.disable();
    Thread.sleep(SLEEP_TIME);
    jenkins.setSystemMessage("Testmessage");
    Thread.sleep(SLEEP_TIME);
    final FreeStyleProject secondProject = createFreeStyleProject("Test2");
    Thread.sleep(SLEEP_TIME);
    secondProject.delete();
    // check page with system history entries
    checkSystemPage(webClient.goTo(JobConfigHistoryConsts.URLNAME));
    checkSystemPage(webClient.goTo(JobConfigHistoryConsts.URLNAME + "/?filter=system"));
    // check page with job history entries
    final HtmlPage htmlPageJobs = webClient.goTo(JobConfigHistoryConsts.URLNAME + "/?filter=jobs");
    Assert.assertTrue("Verify history entry for job is listed.", htmlPageJobs.getAnchorByText("Test1") != null);
    final String htmlPageJobsBody = htmlPageJobs.asXml();
    Assert.assertTrue("Verify history entry for deleted job is listed.", htmlPageJobsBody.contains(DeletedFileFilter.DELETED_MARKER));
    Assert.assertFalse("Verify that no history entry for system change is listed.", htmlPageJobsBody.contains("config (system)"));
    Assert.assertTrue("Check link to job page.", htmlPageJobsBody.contains("job/Test1/" + JobConfigHistoryConsts.URLNAME));
    // check page with 'created' history entries
    final HtmlPage htmlPageCreated = webClient.goTo("jobConfigHistory/?filter=created");
    Assert.assertTrue("Verify history entry for job is listed.", htmlPageCreated.getAnchorByText("Test1") != null);
    Assert.assertFalse("Verify history entry for deleted job is not listed.", htmlPageCreated.asText().contains(DeletedFileFilter.DELETED_MARKER));
    Assert.assertFalse("Verify that no history entry for system change is listed.", htmlPageCreated.asText().contains("config (system)"));
    Assert.assertTrue("Check link to job page exists.", htmlPageJobs.asXml().contains("job/Test1/" + JobConfigHistoryConsts.URLNAME));
    Assert.assertFalse("Verify that only \'Created\' entries are listed.", htmlPageCreated.asXml().contains("Deleted</td>") || htmlPageCreated.asXml().contains("Changed</td>"));
    // check page with 'deleted' history entries
    final HtmlPage htmlPageDeleted = webClient.goTo("jobConfigHistory/?filter=deleted");
    final String page = htmlPageDeleted.asXml();
    System.out.println(page);
    Assert.assertTrue("Verify history entry for deleted job is listed.", page.contains(DeletedFileFilter.DELETED_MARKER));
    Assert.assertFalse("Verify no history entry for existing job is listed.", page.contains("Test1"));
    Assert.assertFalse("Verify no history entry for system change is listed.", page.contains("(system)"));
    Assert.assertTrue("Check link to historypage exists.", page.contains("history?name"));
    Assert.assertFalse("Verify that only \'Deleted\' entries are listed.", page.contains("Created</td>") || page.contains("Changed</td>"));
}
Example 37
Project: SCM-master  File: MigrateIDAndCredentialTest.java View source code
@Before
public void setUp() throws Exception {
    AccurevServer server = new AccurevServer(null, "test", "localhost", 5050, "bob", "OBF:1rwf1x1b1rwf");
    scm = new AccurevSCM(null, "test", "test");
    scm.setServerName("test");
    FreeStyleProject accurevTest = j.createFreeStyleProject("accurevTest");
    accurevTest.setScm(scm);
    descriptor = scm.getDescriptor();
    List<AccurevServer> servers = new ArrayList<>();
    servers.add(server);
    descriptor.setServers(servers);
}
Example 38
Project: branch-api-plugin-master  File: EventsTest.java View source code
@Test
public void given_multibranch_when_inspectingProjectFactory_then_ProjectTypeCorrectlyInferred() throws Exception {
    try (MockSCMController c = MockSCMController.create()) {
        c.createRepository("foo");
        BasicMultiBranchProject prj = r.jenkins.createProject(BasicMultiBranchProject.class, "foo");
        assertThat(prj.getProjectFactory().getProjectClass(), equalTo((Class) FreeStyleProject.class));
    }
}
Example 39
Project: cloudbees-deployer-plugin-master  File: CloudbeesDeployWarTest.java View source code
public void testFreestyleAnt() throws Exception {
    FreeStyleProject p = createFreeStyleProject();
    p.setScm(new ExtractResourceSCM(getClass().getResource("test-project.zip")));
    String antName = configureDefaultAnt().getName();
    p.getBuildersList().add(new Ant("", antName, null, null, "vBAR=<xml/>\n"));
    p.getBuildersList().add(new DeployBuilder(Arrays.asList(new RunHostImpl("test@test.test", "test-account", Collections.singletonList(new RunTargetImpl(EndPoints.runAPI(), "test-app", null, null, null, new WildcardPathDeploySource("**/translate-puzzle-webapp*.war"), false, null, null, null))))));
    FreeStyleBuild build = buildAndAssertSuccess(p);
    assertOnFileItems(build.getFullDisplayName());
}
Example 40
Project: cobertura-plugin-master  File: CoberturaFunctionalTest.java View source code
@Test
public void doNotWaitForPreviousBuild() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setConcurrentBuild(true);
    final OneShotEvent firstRunning = new OneShotEvent();
    final OneShotEvent firstBlocked = new OneShotEvent();
    p.getPublishersList().add(new BlockingCoberturaPublisher(firstRunning, firstBlocked));
    p.scheduleBuild2(0).getStartCondition().get();
    firstRunning.block();
    p.getPublishersList().clear();
    CoberturaPublisher publisher = new CoberturaPublisher();
    p.getPublishersList().add(publisher);
    p.scheduleBuild2(0).get();
    assertTrue(p.getBuildByNumber(1).getLog(), p.getBuildByNumber(1).isBuilding());
    assertFalse(p.getBuildByNumber(2).getLog(), p.getBuildByNumber(2).isBuilding());
}
Example 41
Project: credentials-binding-plugin-master  File: UsernamePasswordBindingTest.java View source code
@Test
public void basics() throws Exception {
    String username = "bob";
    String password = "s3cr3t";
    UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "sample", username, password);
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
    FreeStyleProject p = r.createFreeStyleProject();
    p.getBuildWrappersList().add(new SecretBuildWrapper(Collections.<Binding<?>>singletonList(new UsernamePasswordBinding("AUTH", c.getId()))));
    p.getBuildersList().add(new Shell("set +x\necho $AUTH > auth.txt"));
    r.configRoundtrip(p);
    SecretBuildWrapper wrapper = p.getBuildWrappersList().get(SecretBuildWrapper.class);
    assertNotNull(wrapper);
    List<? extends MultiBinding<?>> bindings = wrapper.getBindings();
    assertEquals(1, bindings.size());
    MultiBinding<?> binding = bindings.get(0);
    assertEquals(c.getId(), binding.getCredentialsId());
    assertEquals(UsernamePasswordBinding.class, binding.getClass());
    assertEquals("AUTH", ((UsernamePasswordBinding) binding).getVariable());
    FreeStyleBuild b = r.buildAndAssertSuccess(p);
    r.assertLogNotContains(password, b);
    assertEquals(username + ':' + password, b.getWorkspace().child("auth.txt").readToString().trim());
    assertEquals("[AUTH]", b.getSensitiveBuildVariables().toString());
}
Example 42
Project: credentials-plugin-master  File: CredentialsUnavailableExceptionTest.java View source code
@Test
public void buildFailure() throws Exception {
    systemStore.addCredentials(Domain.global(), new UsernameUnavailablePasswordImpl("buildFailure", "test", "foo"));
    FreeStyleProject project = r.createFreeStyleProject();
    project.getBuildersList().add(new PasswordBuildStep("buildFailure"));
    FreeStyleBuild build = project.scheduleBuild2(0).get();
    this.r.assertBuildStatus(Result.FAILURE, build);
    this.r.assertLogContains("username: foo", build);
    this.r.assertLogContains("Property 'password' is currently unavailable", build);
    this.r.assertLogNotContains("Could not find", build);
    this.r.assertLogNotContains("Extracted secret", build);
}
Example 43
Project: docker-commons-plugin-master  File: DockerServerEndpointTest.java View source code
@Test
public void smokes() throws Exception {
    DumbSlave slave = j.createOnlineSlave();
    VirtualChannel channel = slave.getChannel();
    FreeStyleProject item = j.createFreeStyleProject();
    CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next();
    assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
    Domain domain = new Domain("docker", "A domain for docker credentials", Collections.<DomainSpecification>singletonList(new DockerServerDomainSpecification()));
    DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", "a", "b", "c");
    store.addDomain(domain, credentials);
    DockerServerEndpoint endpoint = new DockerServerEndpoint("tcp://localhost:2736", credentials.getId());
    FilePath dotDocker = DockerServerEndpoint.dotDocker(channel);
    List<FilePath> dotDockerKids = dotDocker.list();
    int initialSize = dotDockerKids == null ? 0 : dotDockerKids.size();
    KeyMaterialFactory factory = endpoint.newKeyMaterialFactory(item, channel);
    KeyMaterial keyMaterial = factory.materialize();
    FilePath path = null;
    try {
        assertThat(keyMaterial.env().get("DOCKER_HOST", "missing"), is("tcp://localhost:2736"));
        assertThat(keyMaterial.env().get("DOCKER_TLS_VERIFY", "missing"), is("1"));
        assertThat(keyMaterial.env().get("DOCKER_CERT_PATH", "missing"), not("missing"));
        path = new FilePath(channel, keyMaterial.env().get("DOCKER_CERT_PATH", "missing"));
        assertThat(path.child("key.pem").readToString(), is("a"));
        assertThat(path.child("cert.pem").readToString(), is("b"));
        assertThat(path.child("ca.pem").readToString(), is("c"));
    } finally {
        keyMaterial.close();
    }
    assertThat(path.child("key.pem").exists(), is(false));
    assertThat(path.child("cert.pem").exists(), is(false));
    assertThat(path.child("ca.pem").exists(), is(false));
    assertThat(dotDocker.list().size(), is(initialSize));
}
Example 44
Project: dockerhub-notification-plugin-master  File: CoordinatorTest.java View source code
@Test
public void testTwoTriggered() throws Exception {
    FreeStyleProject one = j.createFreeStyleProject();
    one.addTrigger(new DockerHubTrigger(new TriggerOnSpecifiedImageNames(Arrays.asList("csanchez/jenkins-swarm-slave"))));
    one.getBuildersList().add(new MockBuilder(Result.SUCCESS));
    FreeStyleProject two = j.createFreeStyleProject();
    two.addTrigger(new DockerHubTrigger(new TriggerOnSpecifiedImageNames(Arrays.asList("csanchez/jenkins-swarm-slave"))));
    two.getBuildersList().add(new MockBuilder(Result.SUCCESS));
    JSONObject json = JSONObject.fromObject(IOUtils.toString(getClass().getResourceAsStream("/own-repository-payload.json")));
    json.put("callback_url", j.getURL() + "fake-dockerhub/respond");
    String url = j.getURL() + DockerHubWebHook.URL_NAME + "/notify";
    assertEquals(302, Http.post(url, json));
    synchronized (resp) {
        resp.wait();
    }
    JSONObject callback = resp.json;
    assertNotNull(callback);
    //{"state":"success","description":"Build result SUCCESS","context":"Jenkins","target_url":"http://localhost:49951/jenkins/dockerhub-webhook/details/b23e9f77fb91cb92a873488eb18e5b1001cfe4d0"}
    assertEquals("success", callback.getString("state"));
    String target_url = callback.getString("target_url");
    assertThat(target_url, containsString("/dockerhub-webhook/details/"));
    String sha = target_url.substring(target_url.lastIndexOf('/') + 1);
    TriggerStore.TriggerEntry entry = TriggerStore.getInstance().getEntry(sha);
    assertNotNull(entry);
    assertThat(entry.getEntries(), allOf(hasSize(2), containsInAnyOrder(allOf(hasProperty("job", sameInstance(one)), hasProperty("run", sameInstance(one.getLastBuild()))), allOf(hasProperty("job", sameInstance(two)), hasProperty("run", sameInstance(two.getLastBuild()))))));
}
Example 45
Project: durable-task-plugin-master  File: ContinuedTaskTest.java View source code
@Test
public void basics() throws Exception {
    FreeStyleProject p = r.createFreeStyleProject();
    Label label = Label.get("test");
    p.setAssignedLabel(label);
    final AtomicInteger cntA = new AtomicInteger();
    final AtomicInteger cntB = new AtomicInteger();
    p.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            assertEquals(0, cntA.get());
            assertEquals(1, cntB.get());
            return true;
        }
    });
    QueueTaskFuture<FreeStyleBuild> b1 = p.scheduleBuild2(0);
    r.jenkins.getQueue().schedule(new TestTask(cntA, false), 0);
    r.jenkins.getQueue().schedule(new TestTask(cntB, true), 1);
    // cntB task ought to run first, then b1, then the cntA task
    r.createSlave(label);
    r.assertBuildStatusSuccess(b1);
    r.waitUntilNoActivity();
    assertEquals(1, cntA.get());
    assertEquals(1, cntB.get());
}
Example 46
Project: flaky-test-handler-plugin-master  File: HistoryAggregatedFlakyTestResultActionTest.java View source code
@Test
public void testAggregateFlakyRunsWithRevisions() throws Exception {
    FreeStyleProject project = jenkins.createFreeStyleProject("project");
    List<AbstractBuild> buildList = new ArrayList<AbstractBuild>();
    for (FlakyTestResultAction action : setUpFlakyTestResultAction()) {
        FreeStyleBuild build = new FreeStyleBuild(project);
        build.addAction(action);
        buildList.add(build);
    }
    HistoryAggregatedFlakyTestResultAction action = new HistoryAggregatedFlakyTestResultAction(null);
    for (AbstractBuild build : buildList) {
        action.aggregateOneBuild(build);
    }
    Map<String, Map<String, SingleTestFlakyStats>> statsMapOverRevision = action.getAggregatedTestFlakyStatsWithRevision();
    // TEST_ONE
    SingleTestFlakyStats testOneRevisionOneStats = statsMapOverRevision.get(TEST_ONE).get(REVISION_ONE);
    assertEquals("wrong number passes", 2, testOneRevisionOneStats.getPass());
    assertEquals("wrong number fails", 0, testOneRevisionOneStats.getFail());
    assertEquals("wrong number flakes", 0, testOneRevisionOneStats.getFlake());
    SingleTestFlakyStats testOneRevisionTwoStats = statsMapOverRevision.get(TEST_ONE).get(REVISION_TWO);
    assertEquals("wrong number passes", 1, testOneRevisionTwoStats.getPass());
    assertEquals("wrong number fails", 1, testOneRevisionTwoStats.getFail());
    assertEquals("wrong number flakes", 0, testOneRevisionTwoStats.getFlake());
    // TEST_TWO
    SingleTestFlakyStats testTwoRevisionOneStats = statsMapOverRevision.get(TEST_TWO).get(REVISION_ONE);
    assertEquals("wrong number passes", 1, testTwoRevisionOneStats.getPass());
    assertEquals("wrong number fails", 3, testTwoRevisionOneStats.getFail());
    assertEquals("wrong number flakes", 0, testTwoRevisionOneStats.getFlake());
    SingleTestFlakyStats testTwoRevisionTwoStats = statsMapOverRevision.get(TEST_TWO).get(REVISION_TWO);
    assertEquals("wrong number passes", 1, testTwoRevisionTwoStats.getPass());
    assertEquals("wrong number fails", 0, testTwoRevisionTwoStats.getFail());
    assertEquals("wrong number flakes", 0, testTwoRevisionTwoStats.getFlake());
    // TEST_THREE
    SingleTestFlakyStats testThreeRevisionOneStats = statsMapOverRevision.get(TEST_THREE).get(REVISION_ONE);
    assertEquals("wrong number passes", 1, testThreeRevisionOneStats.getPass());
    assertEquals("wrong number fails", 2, testThreeRevisionOneStats.getFail());
    assertEquals("wrong number flakes", 0, testThreeRevisionOneStats.getFlake());
    SingleTestFlakyStats testThreeRevisionTwoStats = statsMapOverRevision.get(TEST_THREE).get(REVISION_TWO);
    assertEquals("wrong number passes", 0, testThreeRevisionTwoStats.getPass());
    assertEquals("wrong number fails", 2, testThreeRevisionTwoStats.getFail());
    assertEquals("wrong number flakes", 0, testThreeRevisionTwoStats.getFlake());
    // TEST_FOUR
    SingleTestFlakyStats testFourRevisionOneStats = statsMapOverRevision.get(TEST_FOUR).get(REVISION_ONE);
    assertEquals("wrong number passes", 1, testFourRevisionOneStats.getPass());
    assertEquals("wrong number fails", 3, testFourRevisionOneStats.getFail());
    assertEquals("wrong number flakes", 0, testFourRevisionOneStats.getFlake());
    SingleTestFlakyStats testFourRevisionTwoStats = statsMapOverRevision.get(TEST_FOUR).get(REVISION_TWO);
    assertEquals("wrong number passes", 1, testFourRevisionTwoStats.getPass());
    assertEquals("wrong number fails", 0, testFourRevisionTwoStats.getFail());
    assertEquals("wrong number flakes", 0, testFourRevisionTwoStats.getFlake());
}
Example 47
Project: github-plugin-master  File: GitHubHookRegisterProblemMonitorTest.java View source code
@Test
public void shouldReportAboutHookProblemOnRegister() throws IOException {
    FreeStyleProject job = jRule.createFreeStyleProject();
    job.addTrigger(new GitHubPushTrigger());
    job.setScm(REPO_GIT_SCM);
    WebhookManager.forHookUrl(WebhookManagerTest.HOOK_ENDPOINT).registerFor((Item) job).run();
    assertThat("should reg problem", monitor.isProblemWith(REPO), is(true));
}
Example 48
Project: phing-plugin-master  File: PhingBuilderConfigSubmitTest.java View source code
@Test
public void testConfigsubmit() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    PhingBuilder builder = new PhingBuilder("Default", "build.xml", "install", null, true, null);
    p.getBuildersList().add(builder);
    HtmlForm form = webClient.goTo(p.getUrl() + "/configure").getFormByName("config");
    HtmlCheckBoxInput useModuleRootCheckBox = form.getInputByName("_.useModuleRoot");
    assertThat(useModuleRootCheckBox.isChecked(), is(true));
    useModuleRootCheckBox.setChecked(false);
    form.submit((HtmlButton) last(form.getHtmlElementsByTagName("button")));
    DescribableList<Builder, Descriptor<Builder>> builders = p.getBuildersList();
    PhingBuilder b = builders.get(PhingBuilder.class);
    assertThat(b.isUseModuleRoot(), is(false));
}
Example 49
Project: slave-squatter-plugin-master  File: LoadPredictorImplTest.java View source code
public void testFoo() throws Exception {
    Date now = new Date();
    // make a 15min reservation for 2 slaves 10 mins from now  
    hudson.getNodeProperties().add(new NodePropertyImpl(Arrays.asList(new CronSquatter("2 : " + (now.getMinutes() + 10) % 60 + " * * * * : 15"))));
    // this build should succeed, given that it has no estimate
    FreeStyleProject p = createFreeStyleProject();
    assertTrue(p.getEstimatedDuration() < 0);
    assertBuildStatusSuccess(p.scheduleBuild2(0));
    // another one should succeed as well, since we have a very short ETA
    assertTrue(p.getEstimatedDuration() > 0);
    FreeStyleBuild b = assertBuildStatusSuccess(p.scheduleBuild2(0));
    // now artificially inflate the build execution time to make a longer ETA
    Field f = Run.class.getDeclaredField("duration");
    f.setAccessible(true);
    long THREE_HOURS = TimeUnit2.HOURS.toMillis(3);
    f.set(b, THREE_HOURS);
    // build should block because it collides with the upcoming reservation
    Future<FreeStyleBuild> task = p.scheduleBuild2(0);
    Thread.sleep(3000);
    assertFalse("build should be blocked", task.isDone());
    // remove the property and we should be building
    hudson.getNodeProperties().clear();
    // emulates the effect of saving configuration
    hudson.getQueue().scheduleMaintenance();
    assertBuildStatusSuccess(task);
}
Example 50
Project: support-core-plugin-master  File: BuildQueueTest.java View source code
@Ignore("Unit test fails when performing a release. The queue has a race condition" + "which is resolved in 1.607+ (TODO).")
@Test
public void verifyMinimumBuildQueue() throws Exception {
    // Given
    QueueTaskFuture<FreeStyleBuild> build;
    String assignedLabel = "foo";
    FreeStyleProject p = j.createFreeStyleProject("bar");
    p.setAssignedLabel(new LabelAtom(assignedLabel));
    BuildQueue queue = new BuildQueue();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // When
    build = p.scheduleBuild2(0);
    queue.addContents(createContainer(baos));
    // Then
    build.cancel(true);
    List<String> output = new ArrayList<String>(Arrays.asList(baos.toString().split("\n")));
    assertContains(output, "1 item");
    assertContains(output, p.getDisplayName());
    assertContains(output, "Waiting for next available executor");
}
Example 51
Project: testng-plugin-plugin-master  File: TestNGTestResultBuildActionTest.java View source code
/**
     * Test using precheckins xml
     *
     * @throws Exception
     */
@Test
public void testBuildAction_1() throws Exception {
    FreeStyleProject p = r.createFreeStyleProject();
    Publisher publisher = new Publisher();
    publisher.setReportFilenamePattern("testng.xml");
    p.getPublishersList().add(publisher);
    //to setup project action
    p.onCreatedFromScratch();
    p.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            String contents = CommonUtil.getContents(Constants.TESTNG_XML_PRECHECKINS);
            build.getWorkspace().child("testng.xml").write(contents, "UTF-8");
            return true;
        }
    });
    //run build
    FreeStyleBuild build = p.scheduleBuild2(0).get();
    TestNGResult testngResult = (TestNGResult) build.getAction(AbstractTestResultAction.class).getResult();
    //Get page
    HtmlPage page = r.createWebClient().goTo(build.getUrl() + PluginImpl.URL);
    //make sure no cell is empty
    List<HtmlElement> elements = DomNodeUtil.selectNodes(page, "//table[substring(@id, string-length(@id)- string-length('-tbl') +1)]/*/tr/td");
    for (HtmlElement element : elements) {
        assertTrue(!element.getTextContent().isEmpty());
    }
    //ensure only one failed test
    //there are three links in the cell, we pick the one without any id attr
    elements = DomNodeUtil.selectNodes(page, "//table[@id='fail-tbl']/tbody/tr/td/a[not(@id)]");
    assertEquals(1, elements.size());
    MethodResult mr = testngResult.getFailedTests().get(0);
    assertEquals(r.getURL() + mr.getRun().getUrl() + mr.getId(), elements.get(0).getAttribute("href"));
    assertEquals(((ClassResult) mr.getParent()).getCanonicalName() + "." + mr.getName(), elements.get(0).getTextContent());
    //ensure only one failed config method
    elements = DomNodeUtil.selectNodes(page, "//table[@id='fail-config-tbl']/tbody/tr/td/a");
    //asserting to 3, because a link for >>>, one for <<< and another for the method itself
    assertEquals(3, elements.size());
    mr = testngResult.getFailedConfigs().get(0);
    assertEquals(r.getURL() + mr.getRun().getUrl() + mr.getId(), elements.get(2).getAttribute("href"));
    assertEquals(((ClassResult) mr.getParent()).getCanonicalName() + "." + mr.getName(), elements.get(2).getTextContent());
    //ensure only one skipped test method
    elements = DomNodeUtil.selectNodes(page, "//table[@id='skip-tbl']/tbody/tr/td/a");
    assertEquals(1, elements.size());
    mr = testngResult.getSkippedTests().get(0);
    assertEquals(r.getURL() + mr.getRun().getUrl() + mr.getId(), elements.get(0).getAttribute("href"));
    assertEquals(((ClassResult) mr.getParent()).getCanonicalName() + "." + mr.getName(), elements.get(0).getTextContent());
    //ensure no skipped config
    elements = DomNodeUtil.selectNodes(page, "//table[@id='skip-config-tbl']");
    assertEquals(0, elements.size());
    //check list of packages and links
    elements = DomNodeUtil.selectNodes(page, "//table[@id='all-tbl']/tbody/tr/td/a");
    Map<String, PackageResult> pkgMap = testngResult.getPackageMap();
    assertEquals(pkgMap.keySet().size(), elements.size());
    //verify links to packages
    List<String> linksInPage = new ArrayList<String>();
    for (HtmlElement element : elements) {
        linksInPage.add(element.getAttribute("href"));
    }
    Collections.sort(linksInPage);
    List<String> linksFromResult = new ArrayList<String>();
    for (PackageResult pr : pkgMap.values()) {
        linksFromResult.add(pr.getName());
    }
    Collections.sort(linksFromResult);
    assertEquals(linksFromResult, linksInPage);
    //verify bar
    HtmlElement element = page.getElementById("fail-skip", true);
    r.assertStringContains(element.getTextContent(), "1 failure");
    assertFalse(element.getTextContent().contains("failures"));
    r.assertStringContains(element.getTextContent(), "1 skipped");
    element = page.getElementById("pass", true);
    r.assertStringContains(element.getTextContent(), "38 tests");
}
Example 52
Project: yaml-project-plugin-master  File: BinderTest.java View source code
@Test
public void testBindJob_EmptyWithClass() throws Exception {
    JSONObject json = (JSONObject) JSONSerializer.toJSON(EMPTY_JSON);
    json.put("$class", FreeStyleProject.class.getName());
    Job job = underTest.bindJob(Jenkins.getInstance(), NAME, json);
    assertNotNull(job);
    assertThat(job, instanceOf(FreeStyleProject.class));
    assertEquals(NAME, job.getName());
}
Example 53
Project: async-http-client-plugin-master  File: AHCTest.java View source code
@Test
public void worksOnJenkinsClasspath() throws Exception {
    final Random entropy = new Random();
    final String jobName = String.format("Random job name %d", entropy.nextLong());
    final String systemMessage = String.format("Random system message %d", entropy.nextLong());
    j.jenkins.setSystemMessage(systemMessage);
    j.getInstance().createProject(j.getInstance().getDescriptorByType(FreeStyleProject.DescriptorImpl.class), jobName);
    final ListenableFuture<Response> response = AHC.instance().executeRequest(new RequestBuilder("GET").setUrl(j.getURL().toURI().toString()).build());
    assertThat(response.get().getResponseBody(), allOf(containsString(Jenkins.getVersion().toString()), containsString(systemMessage), containsString(jobName)));
}
Example 54
Project: bulk-builder-plugin-master  File: BuilderTest.java View source code
/**
     * Test user has necessary permission to build job.
     */
//    @Test
@Ignore("PresetData isn't working correctly")
@PresetData(DataSet.ANONYMOUS_READONLY)
public void atestInsufficientBuildPermission() throws Exception {
    FreeStyleProject project = createFreeStyleProject("restricted");
    project.scheduleBuild2(0).get();
    waitUntilNoActivity();
    builder = new Builder(BuildAction.valueOf("IMMEDIATE_BUILD"));
    builder.setPattern("restricted");
    assertEquals(0, builder.buildAll());
    assertEquals(1, project.getNextBuildNumber());
}
Example 55
Project: clearcase-plugin-master  File: ItemListenerImpl.java View source code
/**
     * Delete the view when the job is renamed
     */
@Override
public void onRenamed(Item item, String oldName, String newName) {
    Hudson hudson = Hudson.getInstance();
    if (item instanceof AbstractProject<?, ?>) {
        @SuppressWarnings("unchecked") AbstractProject project = (AbstractProject) item;
        SCM scm = project.getScm();
        if (scm instanceof AbstractClearCaseScm) {
            try {
                AbstractClearCaseScm ccScm = (AbstractClearCaseScm) scm;
                if (!ccScm.isRemoveViewOnRename()) {
                    return;
                }
                StreamTaskListener listener = StreamTaskListener.fromStdout();
                Launcher launcher = hudson.createLauncher(listener);
                AbstractBuild<?, ?> build = project.getSomeBuildWithWorkspace();
                if (build != null) {
                    VariableResolver<String> variableResolver = new JobNameOverrideBuildVariableResolver(oldName, build, ccScm.getBuildComputer(build));
                    String normalizedViewName = ccScm.generateNormalizedViewName(variableResolver);
                    FilePath workspace;
                    if (isFreeStyleProjectAndHasCustomWorkspace(project)) {
                        workspace = new FilePath(launcher.getChannel(), ((FreeStyleProject) project).getCustomWorkspace());
                    } else {
                        if (build.getBuiltOn() == hudson) {
                            workspace = build.getWorkspace().getParent().getParent().child(newName).child("workspace");
                        } else {
                            workspace = build.getWorkspace();
                        }
                    }
                    ClearTool ct = ccScm.createClearTool(null, ccScm.createClearToolLauncher(listener, workspace, launcher));
                    if (ct.doesViewExist(normalizedViewName)) {
                        String viewPath = ccScm.getViewPath(new VariableResolver.ByMap<String>(build.getEnvironment(listener)));
                        if (workspace.child(viewPath).exists()) {
                            ct.rmview(viewPath);
                        } else {
                            ct.rmviewtag(normalizedViewName);
                        }
                    }
                }
            } catch (Exception e) {
                Logger.getLogger(AbstractClearCaseScm.class.getName()).log(Level.WARNING, "Failed to remove ClearCase view", e);
            }
        }
    }
}
Example 56
Project: cloudbees-folder-plugin-master  File: ComputedFolderTest.java View source code
@Issue("JENKINS-32179")
@Test
public void duplicateEntries() throws Exception {
    SampleComputedFolder d = r.jenkins.createProject(SampleComputedFolder.class, "d");
    d.recompute(Result.SUCCESS);
    d.assertItemNames(1);
    d.kids.addAll(Arrays.asList("A", "B", "A", "C"));
    d.recompute(Result.SUCCESS);
    d.assertItemNames(2, "A", "B", "C");
    assertEquals("[A, B, C]", d.created.toString());
    // ComputedFolder page opens correctly
    try {
        r.createWebClient().getPage(d);
    } catch (Exception ex) {
        Assert.fail("ComputedFolder<FreeStyleProject> cannot be opened: " + ex.getMessage());
    }
    d.recompute(Result.SUCCESS);
    d.assertItemNames(3, "A", "B", "C");
    assertEquals("[A, B, C]", d.created.toString());
    d.kids.remove("B");
    d.recompute(Result.SUCCESS);
    d.assertItemNames(4, "A", "C");
    assertEquals("[A, B, C]", d.created.toString());
    assertEquals("[B]", d.deleted.toString());
    d.kids.addAll(Arrays.asList("D", "B"));
    d.recompute(Result.SUCCESS);
    d.assertItemNames(5, "A", "B", "C", "D");
    assertEquals("[A, B, C, D, B]", d.created.toString());
    assertEquals("[B]", d.deleted.toString());
    Map<String, String> descriptions = new TreeMap<String, String>();
    for (FreeStyleProject p : d.getItems()) {
        descriptions.put(p.getName(), p.getDescription());
    }
    assertEquals("{A=updated in round #5, B=created in round #5, C=updated in round #5, D=created in round #5}", descriptions.toString());
}
Example 57
Project: customtools-plugin-master  File: ToolVersionParameterDefinitionTest.java View source code
private FreeStyleProject setupJobWithVersionParam(Slave targetSlave) throws Exception {
    FreeStyleProject project = j.createFreeStyleProject("foo");
    ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(new StringParameterDefinition("string", "defaultValue", "description"), new ToolVersionParameterDefinition(TEST_TOOL_NAME));
    project.addProperty(pdp);
    project.setAssignedNode(targetSlave);
    return project;
}
Example 58
Project: external-resource-dispatcher-plugin-master  File: ExternalResourceJenkinsTest.java View source code
/**
     * Tests that the environment variables for the locked resource is available to the build.
     *
     * @throws Exception if so.
     */
public void testLockedResourceEnvironment() throws Exception {
    setUpSlave();
    TreeStructureUtil.addValue(resource, "USB", "the type of connector", "connector", "type");
    FreeStyleProject project = createFreeStyleProject();
    project.setAssignedLabel(new LabelAtom("TEST"));
    StringResourceSelection selection = new StringResourceSelection("is.matching", "yes");
    List<AbstractResourceSelection> list = new LinkedList<AbstractResourceSelection>();
    list.add(selection);
    SelectionCriteria selectionCriteria = new SelectionCriteria(true, list);
    project.addProperty(selectionCriteria);
    final HashMap<Object, String> environment = new HashMap<Object, String>();
    project.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            EnvVars vars = build.getEnvironment(listener);
            environment.putAll(vars);
            return true;
        }
    });
    FreeStyleBuild build = this.buildAndAssertSuccess(project);
    assertNotNull(build);
    assertEquals("USB", environment.get("MD_EXTERNAL_RESOURCES_LOCKED_CONNECTOR_TYPE"));
    assertEquals("yes", environment.get("MD_EXTERNAL_RESOURCES_LOCKED_IS_MATCHING"));
    assertEquals(resource.getId(), environment.get("MD_EXTERNAL_RESOURCES_LOCKED_ID"));
}
Example 59
Project: gatekeeper-plugin-master  File: CompleteProcessTest.java View source code
@Test
public void testGatekeeperingAndUpmergingMercurial() throws Exception {
    /*
         * So:
         * set up a repo with 3 releases and 1 feature branch
         * inject parameters TARGET_BRANCH and stuff
         * run job with gatekeeper, upmerge and push tasks
         * assert file from feature branch is in latest release branch
         */
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new MercurialSCM(null, repo.getPath(), "tip", null, null, null, false));
    // Init repo with 3 releases and feature branch.
    m.hg(repo, "init");
    m.touchAndCommit(repo, "base");
    m.hg(repo, "branch", "r1336");
    m.touchAndCommit(repo, "r1336");
    m.hg(repo, "branch", "r1338");
    m.touchAndCommit(repo, "r1338");
    m.hg(repo, "branch", "r1340");
    m.touchAndCommit(repo, "r1340");
    m.hg(repo, "update", "r1336");
    m.hg(repo, "branch", "c3");
    m.touchAndCommit(repo, "c3");
    GatekeeperMerge mergeBuilder = new GatekeeperMerge("JenkinsTestRunner <test@runner.com>", null, null);
    GatekeeperCommit commitBuilder = new GatekeeperCommit("JenkinsTestRunner <test@runner.com>");
    UpmergeBuilder upmergeBuilder = new UpmergeBuilder("JenkinsTestRunner <test@runner.com>");
    GatekeeperPush pushBuilder = new GatekeeperPush();
    ArrayList<ParameterValue> parameters = new ArrayList<ParameterValue>();
    parameters.add(new StringParameterValue("TARGET_BRANCH", "r1336"));
    parameters.add(new StringParameterValue("ORIGINAL_BRANCH", "r1336"));
    parameters.add(new StringParameterValue("FEATURE_BRANCH", "c3"));
    p.getBuildersList().add(mergeBuilder);
    p.getBuildersList().add(commitBuilder);
    p.getBuildersList().add(upmergeBuilder);
    p.getBuildersList().add(pushBuilder);
    m.buildAndCheck(p, "c3", new ParametersAction(parameters));
    // Check more files, we can do this on original repo, so we make sure that builder pushed changes.
    m.hg(repo, "update", "r1336");
    assert new File(repo, "c3").exists();
    assert new File(repo, "r1336").exists();
    m.hg(repo, "update", "r1338");
    assert new File(repo, "c3").exists();
    assert new File(repo, "r1336").exists();
    assert new File(repo, "r1338").exists();
    m.hg(repo, "update", "r1340");
    assert new File(repo, "c3").exists();
    assert new File(repo, "r1336").exists();
    assert new File(repo, "r1338").exists();
    assert new File(repo, "r1340").exists();
    m.hg(repo, "update", "default");
    assert new File(repo, "c3").exists();
    assert new File(repo, "r1336").exists();
    assert new File(repo, "r1338").exists();
    assert new File(repo, "r1340").exists();
    assert !m.searchLog(repo, "[Jenkins Integration Merge] Merged c3 into r1336").isEmpty();
    assert !m.searchLog(repo, "[Jenkins Upmerging] Merged r1336 into r1338").isEmpty();
    assert !m.searchLog(repo, "[Jenkins Upmerging] Merged r1338 into r1340").isEmpty();
    //check that c3 feature branch is closed
    assertArrayEquals(new String[] { "default", "r1336", "r1338", "r1340" }, m.getBranches(repo));
}
Example 60
Project: gitbucket-plugin-master  File: GitBucketWebHookTest.java View source code
@Test
public void testPushTrigger_GitSCM() throws Exception {
    // Repository URL
    String repo = j.createTmpDir().getAbsolutePath();
    // Setup FreeStyle Project
    FreeStyleProject fsp = j.createFreeStyleProject("GitSCM Project");
    // Setup Trigger
    GitBucketPushTrigger trigger = mock(GitBucketPushTrigger.class);
    fsp.addTrigger(trigger);
    // Setup SCM
    SCM scm = new GitSCM(repo);
    fsp.setScm(scm);
    // Setup WebHook request
    String payload = createPayload(repo, "jenkins");
    StaplerRequest req = mock(StaplerRequest.class);
    when(req.getParameter("payload")).thenReturn(payload);
    when(req.getHeader("X-Github-Event")).thenReturn("push");
    // Post WebHook
    GitBucketWebHook hook = new GitBucketWebHook();
    hook.doIndex(req);
    verify(trigger, times(1)).onPost((GitBucketPushRequest) anyObject());
}
Example 61
Project: hudson-2.x-master  File: CascadingUtilTest.java View source code
@Test
@PrepareForTest(Hudson.class)
public void testUnlinkProjectFromCascadingParents() throws Exception {
    //Prepare data
    FreeStyleProject project1 = new FreeStyleProjectMock("project1");
    FreeStyleProjectMock child1 = new FreeStyleProjectMock("child1");
    String cascadingName = "newCascadingProject";
    FreeStyleProjectMock child = new FreeStyleProjectMock(cascadingName);
    child1.setCascadingProject(project1);
    CascadingUtil.linkCascadingProjectsToChild(child1, cascadingName);
    List<Job> jobs = new ArrayList<Job>();
    jobs.add(project1);
    jobs.add(child1);
    jobs.add(child);
    Hudson hudson = createMock(Hudson.class);
    mockStatic(Hudson.class);
    expect(hudson.getAllItems(Job.class)).andReturn(jobs).anyTimes();
    expect(Hudson.getInstance()).andReturn(hudson).anyTimes();
    replay(Hudson.class, hudson);
    //Can't unlink from null project
    assertFalse(CascadingUtil.unlinkProjectFromCascadingParents(null, cascadingName));
    //Can't unlink null cascading name
    assertFalse(CascadingUtil.unlinkProjectFromCascadingParents(project1, null));
    //Verify whether cascadingName is present in parent and child
    assertTrue(project1.getCascadingChildrenNames().contains(cascadingName));
    assertTrue(child1.getCascadingChildrenNames().contains(cascadingName));
    boolean result = CascadingUtil.unlinkProjectFromCascadingParents(child1, cascadingName);
    assertTrue(result);
    //Name should disappear from hierarchy.
    assertFalse(project1.getCascadingChildrenNames().contains(cascadingName));
    assertFalse(child1.getCascadingChildrenNames().contains(cascadingName));
    CascadingUtil.linkCascadingProjectsToChild(project1, cascadingName);
    assertTrue(project1.getCascadingChildrenNames().contains(cascadingName));
    result = CascadingUtil.unlinkProjectFromCascadingParents(child1, cascadingName);
    assertTrue(result);
    assertFalse(project1.getCascadingChildrenNames().contains(cascadingName));
}
Example 62
Project: hudson.core-master  File: CascadingUtilTest.java View source code
@Test
@PrepareForTest(Hudson.class)
public void testUnlinkProjectFromCascadingParents() throws Exception {
    //Prepare data
    FreeStyleProject project1 = new FreeStyleProjectMock("project1");
    FreeStyleProjectMock child1 = new FreeStyleProjectMock("child1");
    String cascadingName = "newCascadingProject";
    FreeStyleProjectMock child = new FreeStyleProjectMock(cascadingName);
    child1.setCascadingProject(project1);
    CascadingUtil.linkCascadingProjectsToChild(child1, cascadingName);
    List<Job> jobs = new ArrayList<Job>();
    jobs.add(project1);
    jobs.add(child1);
    jobs.add(child);
    Hudson hudson = createMock(Hudson.class);
    mockStatic(Hudson.class);
    expect(Hudson.getInstance()).andReturn(hudson).anyTimes();
    expect(hudson.getItem("newCascadingProject")).andReturn(project1).anyTimes();
    replay(Hudson.class, hudson);
    //Can't unlink from null project
    assertFalse(CascadingUtil.unlinkProjectFromCascadingParents(null, cascadingName));
    //Can't unlink null cascading name
    assertFalse(CascadingUtil.unlinkProjectFromCascadingParents(project1, null));
    //Verify whether cascadingName is present in parent and child
    assertTrue(project1.getCascadingChildrenNames().contains(cascadingName));
    assertTrue(child1.getCascadingChildrenNames().contains(cascadingName));
    boolean result = CascadingUtil.unlinkProjectFromCascadingParents(child1, cascadingName);
    assertTrue(result);
    //Name should disappear from hierarchy.
    assertFalse(project1.getCascadingChildrenNames().contains(cascadingName));
    assertFalse(child1.getCascadingChildrenNames().contains(cascadingName));
    CascadingUtil.linkCascadingProjectsToChild(project1, cascadingName);
    assertTrue(project1.getCascadingChildrenNames().contains(cascadingName));
    result = CascadingUtil.unlinkProjectFromCascadingParents(child1, cascadingName);
    assertTrue(result);
    assertFalse(project1.getCascadingChildrenNames().contains(cascadingName));
}
Example 63
Project: jenkins-publish-over-ftp-plugin-master  File: IntegrationTest.java View source code
//    @TODO test that we get the expected result when in a promotion
@Test
public void testIntegration() throws Exception {
    final FTPClient mockFTPClient = mock(FTPClient.class);
    final int port = 21;
    final int timeout = 3000;
    final BapFtpHostConfiguration testHostConfig = new BapFtpHostConfiguration("testConfig", "testHostname", "testUsername", TEST_PASSWORD, "/testRemoteRoot", port, timeout, false) {

        @Override
        public FTPClient createFTPClient() {
            return mockFTPClient;
        }
    };
    new JenkinsTestHelper().setGlobalConfig(testHostConfig);
    final String dirToIgnore = "target";
    final BapFtpTransfer transfer = new BapFtpTransfer("**/*", null, "sub-home", dirToIgnore, true, false, false, false);
    final ArrayList transfers = new ArrayList(Collections.singletonList(transfer));
    final BapFtpPublisher publisher = new BapFtpPublisher(testHostConfig.getName(), false, transfers, false, false, null, null);
    final ArrayList publishers = new ArrayList(Collections.singletonList(publisher));
    final BapFtpPublisherPlugin plugin = new BapFtpPublisherPlugin(publishers, 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(mockFTPClient.getReplyCode()).thenReturn(FTPReply.SERVICE_READY);
    when(mockFTPClient.login(testHostConfig.getUsername(), TEST_PASSWORD)).thenReturn(true);
    when(mockFTPClient.changeWorkingDirectory(testHostConfig.getRemoteRootDir())).thenReturn(true);
    when(mockFTPClient.setFileType(FTPClient.ASCII_FILE_TYPE)).thenReturn(true);
    when(mockFTPClient.changeWorkingDirectory(transfer.getRemoteDirectory())).thenReturn(false).thenReturn(true);
    when(mockFTPClient.makeDirectory(transfer.getRemoteDirectory())).thenReturn(true);
    when(mockFTPClient.changeWorkingDirectory(buildDirectory)).thenReturn(false).thenReturn(true);
    when(mockFTPClient.makeDirectory(buildDirectory)).thenReturn(true);
    when(mockFTPClient.storeFile(eq(buildFileName), (InputStream) anyObject())).thenReturn(true);
    assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    verify(mockFTPClient).connect(testHostConfig.getHostname(), testHostConfig.getPort());
    verify(mockFTPClient).storeFile(eq(buildFileName), (InputStream) anyObject());
    verify(mockFTPClient).setDefaultTimeout(testHostConfig.getTimeout());
    verify(mockFTPClient).setDataTimeout(testHostConfig.getTimeout());
}
Example 64
Project: jobcopy-builder-master  File: JobcopyBuilderJenkinsTest.java View source code
public void testDescriptorDoFillFromJobNameItems() throws IOException {
    JobcopyBuilder.DescriptorImpl descriptor = getDescriptor();
    // Job will be added after new job created.
    ComboBoxModel beforeList = descriptor.doFillFromJobNameItems();
    FreeStyleProject project = createFreeStyleProject("testDescriptorDoFillFromJobNameItems1");
    String newJobname = project.getName();
    ComboBoxModel afterList = descriptor.doFillFromJobNameItems();
    assertEquals("new job created", beforeList.size() + 1, afterList.size());
    assertTrue("new job created", afterList.contains(newJobname));
}
Example 65
Project: mask-passwords-plugin-master  File: PasswordParameterTest.java View source code
@Test
@Issue("JENKINS-41955")
public void passwordParameterShouldBeMaskedInFreestyleProject() throws Exception {
    final String clearTextPassword = "myClearTextPassword";
    final String logWithClearTextPassword = "printed " + clearTextPassword + " oops";
    final String logWithHiddenPassword = "printed ******** oops";
    FreeStyleProject project = j.jenkins.createProject(FreeStyleProject.class, "testPasswordParameter");
    PasswordParameterDefinition passwordParameterDefinition = new PasswordParameterDefinition("Password1", null);
    ParametersDefinitionProperty parametersDefinitionProperty = new ParametersDefinitionProperty(passwordParameterDefinition);
    project.addProperty(parametersDefinitionProperty);
    MaskPasswordsBuildWrapper maskPasswordsBuildWrapper = new MaskPasswordsBuildWrapper(Collections.<MaskPasswordsBuildWrapper.VarPasswordPair>emptyList());
    project.getBuildWrappersList().add(maskPasswordsBuildWrapper);
    project.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            listener.getLogger().println(logWithClearTextPassword);
            build.setResult(Result.SUCCESS);
            return true;
        }
    });
    FreeStyleBuild build = project.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction(passwordParameterDefinition.createValue(Secret.fromString(clearTextPassword)))).get();
    j.assertBuildStatusSuccess(j.waitForCompletion(build));
    j.assertLogContains(logWithHiddenPassword, build);
    j.assertLogNotContains(logWithClearTextPassword, build);
}
Example 66
Project: nodejs-plugin-master  File: NodeJSCommandInterpreterTest.java View source code
@Issue("JENKINS-41947")
@Test
public void test_inject_path_variable() throws Exception {
    NodeJSInstallation installation = mockInstaller();
    NodeJSCommandInterpreter builder = CIBuilderHelper.createMock("test_executable_value", installation, null, new CIBuilderHelper.Verifier() {

        @Override
        public void verify(AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener) throws Exception {
            assertFalse("No Environments", build.getEnvironments().isEmpty());
            EnvVars env = build.getEnvironment(listener);
            assertThat(env.keySet(), CoreMatchers.hasItems(NodeJSConstants.ENVVAR_NODEJS_PATH, NodeJSConstants.ENVVAR_NODEJS_HOME));
            assertEquals(getTestHome(), env.get(NodeJSConstants.ENVVAR_NODEJS_HOME));
            assertEquals(getTestBin(), env.get(NodeJSConstants.ENVVAR_NODEJS_PATH));
        }
    });
    FreeStyleProject job = j.createFreeStyleProject();
    job.getBuildersList().add(builder);
    j.assertBuildStatusSuccess(job.scheduleBuild2(0));
}
Example 67
Project: phabricator-jenkins-plugin-master  File: TestUtils.java View source code
public static void addCopyBuildStep(FreeStyleProject p, final String fileName, final Class resourceClass, final String resourceName) {
    p.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild build, Launcher launcher, BuildListener buildListener) throws InterruptedException, IOException {
            build.getWorkspace().child(fileName).copyFrom(resourceClass.getResourceAsStream(resourceName));
            return true;
        }
    });
}
Example 68
Project: statusmonitor-plugin-master  File: MonitorActionTest.java View source code
public void testGetProjectsArray_shouldGetProjectFreeStyleProjectWithAMonitorPublisher() throws Exception {
    FreeStyleProject freeStyleProject = createFreeStyleProject();
    addMonitorPublisher(freeStyleProject);
    AbstractProject[][] projects = monitorAction.getProjectsArray();
    assertTrue("Free-style project should be in array since one of its publishers is a MonitorPublisher.", isInArray(projects, freeStyleProject));
}
Example 69
Project: testopia-plugin-master  File: TestopiaBuilderDescriptor.java View source code
/**
	 * Adds all buid steps to the list of build steps.
	 * @param source build step.
	 * @param list list of build steps.
	 */
private static void addTo(List<? extends Descriptor<? extends BuildStep>> source, List<Descriptor<? extends BuildStep>> list) {
    for (Descriptor<? extends BuildStep> d : source) {
        if (d instanceof BuildStepDescriptor) {
            BuildStepDescriptor<?> bsd = (BuildStepDescriptor<?>) d;
            if (bsd.isApplicable(FreeStyleProject.class)) {
                list.add(d);
            }
        }
    }
}
Example 70
Project: throttle-concurrent-builds-plugin-master  File: ThrottleStepTest.java View source code
@Override
public void evaluate() throws Throwable {
    setupAgentsAndCategories();
    WorkflowJob firstJob = story.j.jenkins.createProject(WorkflowJob.class, "first-job");
    firstJob.setDefinition(getJobFlow("first", ONE_PER_NODE, "first-agent"));
    WorkflowRun firstJobFirstRun = firstJob.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("wait-first-job/1", firstJobFirstRun);
    FreeStyleProject freeStyleProject = story.j.createFreeStyleProject("f");
    freeStyleProject.addProperty(new ThrottleJobProperty(// maxConcurrentPerNode
    null, // maxConcurrentTotal
    null, // categories
    Arrays.asList(ONE_PER_NODE), // throttleEnabled
    true, // throttleOption
    "category", false, null, ThrottleMatrixProjectOptions.DEFAULT));
    freeStyleProject.setAssignedLabel(Label.get("first-agent"));
    freeStyleProject.getBuildersList().add(new TestBuilder() {

        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            semaphore.acquire();
            return true;
        }
    });
    semaphore.acquire();
    QueueTaskFuture<FreeStyleBuild> futureBuild = freeStyleProject.scheduleBuild2(0);
    assertFalse(story.j.jenkins.getQueue().isEmpty());
    assertEquals(1, story.j.jenkins.getQueue().getItems().length);
    Queue.Item i = story.j.jenkins.getQueue().getItems()[0];
    assertTrue(i.task instanceof FreeStyleProject);
    Node n = story.j.jenkins.getNode("first-agent");
    assertNotNull(n);
    assertEquals(1, n.toComputer().countBusy());
    hasPlaceholderTaskForRun(n, firstJobFirstRun);
    SemaphoreStep.success("wait-first-job/1", null);
    story.j.assertBuildStatusSuccess(story.j.waitForCompletion(firstJobFirstRun));
    FreeStyleBuild freeStyleBuild = futureBuild.waitForStart();
    assertEquals(1, n.toComputer().countBusy());
    for (Executor e : n.toComputer().getExecutors()) {
        if (e.isBusy()) {
            assertEquals(freeStyleBuild, e.getCurrentExecutable());
        }
    }
    WorkflowJob secondJob = story.j.jenkins.createProject(WorkflowJob.class, "second-job");
    secondJob.setDefinition(getJobFlow("second", ONE_PER_NODE, "first-agent"));
    WorkflowRun secondJobFirstRun = secondJob.scheduleBuild2(0).waitForStart();
    story.j.waitForMessage("Still waiting to schedule task", secondJobFirstRun);
    assertFalse(story.j.jenkins.getQueue().isEmpty());
    assertEquals(1, n.toComputer().countBusy());
    for (Executor e : n.toComputer().getExecutors()) {
        if (e.isBusy()) {
            assertEquals(freeStyleBuild, e.getCurrentExecutable());
        }
    }
    semaphore.release();
    story.j.assertBuildStatusSuccess(story.j.waitForCompletion(freeStyleBuild));
    SemaphoreStep.waitForStart("wait-second-job/1", secondJobFirstRun);
    assertTrue(story.j.jenkins.getQueue().isEmpty());
    assertEquals(1, n.toComputer().countBusy());
    hasPlaceholderTaskForRun(n, secondJobFirstRun);
    SemaphoreStep.success("wait-second-job/1", null);
    story.j.assertBuildStatusSuccess(story.j.waitForCompletion(secondJobFirstRun));
}
Example 71
Project: cloudfoundry-jenkins-master  File: CloudFoundryPushPublisherTest.java View source code
@Test
public void testPerformSimplePushManifestFile() throws Exception {
    FreeStyleProject project = j.createFreeStyleProject();
    project.setScm(new ExtractResourceSCM(getClass().getResource("hello-java.zip")));
    CloudFoundryPushPublisher cf = new CloudFoundryPushPublisher(TEST_TARGET, TEST_ORG, TEST_SPACE, "testCredentialsId", false, false, 0, null, ManifestChoice.defaultManifestFileConfig());
    project.getPublishersList().add(cf);
    FreeStyleBuild build = project.scheduleBuild2(0).get();
    System.out.println(build.getDisplayName() + " completed");
    String log = FileUtils.readFileToString(build.getLogFile());
    System.out.println(log);
    assertTrue("Build did not succeed", build.getResult().isBetterOrEqualTo(Result.SUCCESS));
    assertTrue("Build did not display staging logs", log.contains("Downloaded app package"));
    System.out.println("App URI : " + cf.getAppURIs().get(0));
    String uri = cf.getAppURIs().get(0);
    Request request = Request.Get(uri);
    HttpResponse response = request.execute().returnResponse();
    int statusCode = response.getStatusLine().getStatusCode();
    assertEquals("Get request did not respond 200 OK", 200, statusCode);
    String content = EntityUtils.toString(response.getEntity());
    System.out.println(content);
    assertTrue("App did not send back correct text", content.contains("Hello from"));
}
Example 72
Project: cucumber-testresult-plugin-master  File: CucumberJSONSupportPluginIT.java View source code
@Test
@Issue("JENKINS-28588")
public void testSerializationOnSlave() throws Exception {
    DumbSlave slave = jenkinsRule.createOnlineSlave();
    SingleFileSCM scm = new SingleFileSCM("test.json", getResource("passWithEmbeddedItem.json").toURI().toURL());
    FreeStyleProject project = jenkinsRule.createFreeStyleProject("cucumber-plugin-IT");
    project.setAssignedNode(slave);
    project.setScm(scm);
    CucumberTestResultArchiver resultArchiver = new CucumberTestResultArchiver("test.json");
    project.getPublishersList().add(resultArchiver);
    project.save();
    FreeStyleBuild build = jenkinsRule.buildAndAssertSuccess(project);
    jenkinsRule.assertLogContains("test.json", build);
    // check we built on the slave not the master...
    assertThat("Needs to build on the salve to check serialization", build.getBuiltOn(), is((Node) slave));
}
Example 73
Project: ghprb-plugin-master  File: GhprbRootActionTest.java View source code
@Test
public void testUrlEncoded() throws Exception {
    // GIVEN
    FreeStyleProject project = jenkinsRule.createFreeStyleProject("testUrlEncoded");
    doReturn(project).when(trigger).getActualProject();
    doReturn(true).when(trigger).getUseGitHubHooks();
    given(commitPointer.getSha()).willReturn("sha1");
    GhprbTestUtil.setupGhprbTriggerDescriptor(null);
    project.addProperty(new GithubProjectProperty("https://github.com/user/dropwizard"));
    given(ghPullRequest.getId()).willReturn(prId);
    given(ghPullRequest.getNumber()).willReturn(prId);
    given(ghRepository.getPullRequest(prId)).willReturn(ghPullRequest);
    Ghprb ghprb = spy(new Ghprb(trigger));
    doReturn(ghprbGitHub).when(ghprb).getGitHub();
    doReturn(true).when(ghprb).isAdmin(Mockito.any(GHUser.class));
    trigger.start(project, true);
    trigger.setHelper(ghprb);
    project.addTrigger(trigger);
    GitSCM scm = GhprbTestUtil.provideGitSCM();
    project.setScm(scm);
    GhprbTestUtil.triggerRunAndWait(10, trigger, project);
    assertThat(project.getBuilds().toArray().length).isEqualTo(0);
    BufferedReader br = new BufferedReader(new StringReader("payload=" + URLEncoder.encode(GhprbTestUtil.PAYLOAD, "UTF-8")));
    given(req.getContentType()).willReturn("application/x-www-form-urlencoded");
    given(req.getParameter("payload")).willReturn(GhprbTestUtil.PAYLOAD);
    given(req.getHeader("X-GitHub-Event")).willReturn("issue_comment");
    given(req.getReader()).willReturn(br);
    given(req.getCharacterEncoding()).willReturn("UTF-8");
    StringReader brTest = new StringReader(GhprbTestUtil.PAYLOAD);
    IssueComment issueComment = spy(GitHub.connectAnonymously().parseEventPayload(brTest, IssueComment.class));
    brTest.close();
    GHIssueComment ghIssueComment = spy(issueComment.getComment());
    Mockito.when(issueComment.getComment()).thenReturn(ghIssueComment);
    Mockito.doReturn(ghUser).when(ghIssueComment).getUser();
    given(trigger.getGitHub().parseEventPayload(Mockito.any(Reader.class), Mockito.eq(IssueComment.class))).willReturn(issueComment);
    GhprbRootAction ra = new GhprbRootAction();
    ra.doIndex(req, null);
    // handles race condition around starting and finishing builds. Give the system time
    // to finish indexing, create a build, queue it, and run it.
    int count = 0;
    while (count < 5 && project.getBuilds().toArray().length == 0) {
        GhprbTestUtil.waitForBuildsToFinish(project);
        Thread.sleep(50);
        count = count + 1;
    }
    assertThat(project.getBuilds().toArray().length).isEqualTo(1);
}
Example 74
Project: git-plugin-master  File: GitSCMTest.java View source code
/**
     * Basic test - create a GitSCM based project, check it out and build for the first time.
     * Next test that polling works correctly, make another commit, check that polling finds it,
     * then build it and finally test the build culprits as well as the contents of the workspace.
     *
     * @throws Exception if an exception gets thrown.
     */
public void testBasic() throws Exception {
    FreeStyleProject project = setupSimpleProject("master");
    // create initial commit and then run the build against it:
    final String commitFile1 = "commitFile1";
    commit(commitFile1, johnDoe, "Commit number 1");
    build(project, Result.SUCCESS, commitFile1);
    assertFalse("scm polling should not detect any more changes after build", project.pollSCMChanges(listener));
    final String commitFile2 = "commitFile2";
    commit(commitFile2, janeDoe, "Commit number 2");
    assertTrue("scm polling did not detect commit2 change", project.pollSCMChanges(listener));
    //... and build it...
    final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
    final Set<User> culprits = build2.getCulprits();
    assertEquals("The build should have only one culprit", 1, culprits.size());
    assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
    assertTrue(build2.getWorkspace().child(commitFile2).exists());
    assertBuildStatusSuccess(build2);
    assertFalse("scm polling should not detect any more changes after build", project.pollSCMChanges(listener));
}
Example 75
Project: htmlpublisher-plugin-master  File: PublishHTMLStepTest.java View source code
private void configRoundTrip(@NonNull PublishHTMLStep step) throws Exception {
    FreeStyleProject p = r.createFreeStyleProject();
    p.getBuildersList().add(new StepBuilder(step));
    // workaround for eclipse compiler Ambiguous method call
    p.save();
    r.jenkins.reload();
    FreeStyleProject reloaded = r.jenkins.getItemByFullName(p.getFullName(), FreeStyleProject.class);
    assertNotNull(reloaded);
    StepBuilder b = reloaded.getBuildersList().get(StepBuilder.class);
    assertNotNull(b);
    Step after = b.s;
    assertNotNull(after);
    assertEquals(step.getClass(), after.getClass());
    assertEquals("Initial and reloaded target configurations differ", step.getTarget(), ((PublishHTMLStep) after).getTarget());
}
Example 76
Project: hudson-perforce-plugin-master  File: PerforceSCMTest.java View source code
/**
     * Makes sure that the configuration survives the round-trip.
     */
public void testConfigRoundtrip() throws Exception {
    FreeStyleProject project = createFreeStyleProject();
    P4Web browser = new P4Web(new URL("http://localhost/"));
    PerforceSCM scm = new PerforceSCM("user", "pass", "client", "port", "path", "", "exe", "sysRoot", "sysDrive", "label", "counter", "shared", "charset", "charset2", false, true, true, true, false, false, true, false, false, false, false, "${basename}", 0, browser, "exclude_user", "exclude_file");
    project.setScm(scm);
    // config roundtrip
    submit(new WebClient().getPage(project, "configure").getFormByName("config"));
    // verify that the data is intact
    assertEqualBeans(scm, project.getScm(), "p4User,p4Client,p4Port,p4Label,projectPath,p4Exe,p4SysRoot,p4SysDrive,forceSync,alwaysForceSync,dontUpdateClient,updateView,slaveClientNameFormat,lineEndValue,firstChange,p4Counter,updateCounterValue,exposeP4Passwd,useViewMaskForPolling,viewMask,useViewMaskForSyncing,p4Charset,p4CommandCharset");
    assertEquals("exclude_user", scm.getExcludedUsers());
    assertEquals("exclude_file", scm.getExcludedFiles());
//assertEqualBeans(scm.getBrowser(),p.getScm().getBrowser(),"URL");
}
Example 77
Project: hudson.plugins.subversion-master  File: SubversionCommonTest.java View source code
//TODO Investigate why System user is used instead of anonymous after migration to 2.0.0 version
@PresetData(PresetData.DataSet.ANONYMOUS_READONLY)
@Bug(2380)
public void testTaggingPermission() throws Exception {
    // create a build
    FreeStyleProject p = createFreeStyleProject();
    //Set anonymous user for authentication.
    SecurityContextHolder.getContext().setAuthentication(Hudson.ANONYMOUS);
    p.setScm(loadSvnRepo());
    FreeStyleBuild b = p.scheduleBuild2(0, new Cause.UserCause()).get();
    System.out.println(b.getLog(LOG_LIMIT));
    assertBuildStatus(Result.SUCCESS, b);
    SubversionTagAction action = b.getAction(SubversionTagAction.class);
    assertFalse(b.hasPermission(action.getPermission()));
    WebClient wc = new WebClient();
    HtmlPage html = wc.getPage(b);
    // make sure there's no link to the 'tag this build'
    Document dom = new DOMReader().read(html);
    assertNull(dom.selectSingleNode("//A[text()='Tag this build']"));
    for (HtmlAnchor a : html.getAnchors()) {
        assertFalse(a.getHrefAttribute().contains("/tagBuild/"));
    }
    // and no tag form on tagBuild page
    html = wc.getPage(b, "tagBuild/");
    try {
        html.getFormByName("tag");
        fail("should not have been found");
    } catch (ElementNotFoundException e) {
    }
    // and that tagging would fail
    try {
        wc.getPage(b, "tagBuild/submit?name0=test&Submit=Tag");
        fail("should have been denied");
    } catch (FailingHttpStatusCodeException e) {
        assertEquals(e.getResponse().getStatusCode(), 403);
    }
    // now login as alice and make sure that the tagging would succeed
    wc = new WebClient();
    wc.login("alice", "alice");
    html = wc.getPage(b, "tagBuild/");
    HtmlForm form = html.getFormByName("tag");
    submit(form);
}
Example 78
Project: jenkins-config-cloner-master  File: RecipeTest.java View source code
@Test
public void failedCloneShouldFailRecipe() throws IOException {
    j.jenkins.createProject(FreeStyleProject.class, "src_job");
    String url = j.jenkins.getRootUrl();
    run(recipe("clone.job '" + url + "job/src_job', '" + url + "job/src_job'\n"));
    assertThat(rsp, not(succeeded()));
    run(recipe("clone.job '" + url + "job/src_job', '" + url + "job/dst_job'\n" + "clone.job '" + url + "job/src_job', '" + url + // fail here
    "job/dst_job'\n"));
    assertThat(rsp, not(succeeded()));
    run(recipe(// fail here
    "clone.job '" + url + "job/src_job', '" + url + "job/src_job'\n" + "clone.job '" + url + "job/src_job', '" + url + "job/dst_job2'\n"));
    assertThat(rsp, not(succeeded()));
}
Example 79
Project: mail-watcher-plugin-master  File: NodeStatusTest.java View source code
@Test
@Issue("JENKINS-23496")
public void notifyWhenSlaveBecomesAwailable() throws Exception {
    MailWatcherMailer mailer = mock(MailWatcherMailer.class);
    installAwailabilityListener(mailer);
    OneShotEvent started = new OneShotEvent();
    OneShotEvent running = new OneShotEvent();
    User user = User.get("a_user", true);
    user.addProperty(new Mailer.UserProperty("a_user@example.com"));
    ACL.impersonate(user.impersonate());
    DumbSlave slave = j.createOnlineSlave();
    FreeStyleProject project = j.jenkins.createProject(FreeStyleProject.class, "a_project");
    project.getBuildersList().add(new SlaveOccupyingBuildStep(started, running));
    project.setAssignedNode(slave);
    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    started.block();
    slave.toComputer().doToggleOffline("Taking offline so no further builds are scheduled");
    verify(mailer, never()).send(any(MailWatcherNotification.class));
    running.signal();
    future.get();
    ArgumentCaptor<MailWatcherNotification> captor = ArgumentCaptor.forClass(MailWatcherNotification.class);
    verify(mailer).send(captor.capture());
    final MailWatcherNotification notification = captor.getValue();
    assertEquals("a_user@example.com", notification.getRecipients());
    assertThat(notification.getUrl(), endsWith(slave.toComputer().getUrl()));
    assertEquals(user, notification.getInitiator());
    assertEquals("Jenkins computer '" + slave.getDisplayName() + "' you have put offline is no longer occupied", notification.getSubject());
}
Example 80
Project: plot-plugin-master  File: PlotTest.java View source code
@Test
public void discardPlotSamplesForOldBuilds() throws Exception {
    FreeStyleProject p = jobArchivingBuilds(1);
    plotBuilds(p, "2", false);
    j.buildAndAssertSuccess(p);
    assertSampleCount(p, 1);
    j.buildAndAssertSuccess(p);
    // Truncated to 1
    assertSampleCount(p, 1);
    j.buildAndAssertSuccess(p);
    // Still 1
    assertSampleCount(p, 1);
}
Example 81
Project: ssh-agent-plugin-master  File: SSHAgentBuildWrapperTest.java View source code
@Test
public void sshAgentAvailable() throws Exception {
    startMockSSHServer();
    List<String> credentialIds = new ArrayList<String>();
    credentialIds.add(CREDENTIAL_ID);
    SSHUserPrivateKey key = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, credentialIds.get(0), "cloudbees", new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(getPrivateKey()), "cloudbees", "test");
    SystemCredentialsProvider.getInstance().getCredentials().add(key);
    SystemCredentialsProvider.getInstance().save();
    FreeStyleProject job = r.createFreeStyleProject();
    job.setAssignedNode(r.createSlave());
    SSHAgentBuildWrapper sshAgent = new SSHAgentBuildWrapper(credentialIds, false);
    job.getBuildWrappersList().add(sshAgent);
    Shell shell = new Shell("set | grep SSH_AUTH_SOCK " + "&& ssh-add -l " + "&& ssh -o NoHostAuthenticationForLocalhost=yes -o StrictHostKeyChecking=no -p " + getAssignedPort() + " -v -l cloudbees " + SSH_SERVER_HOST);
    job.getBuildersList().add(shell);
    r.assertBuildStatusSuccess(job.scheduleBuild2(0));
    stopMockSSHServer();
}
Example 82
Project: starteam-plugin-master  File: StarTeamSCMTest.java View source code
/**
     * Makes sure that checking out on the slave will work.
     */
@Bug(7967)
@Test
public void testRemoteCheckOut() throws Exception {
    DumbSlave s = createSlave();
    FreeStyleProject p = createFreeStyleProject();
    p.setAssignedLabel(s.getSelfLabel());
    boolean promotionState = false;
    p.setScm(new StarTeamSCM(hostName, port, projectName, viewName, folderName, userName, password, labelName, promotionState));
    FreeStyleBuild b = assertBuildStatusSuccess(p.scheduleBuild2(0, new Cause.UserCause()).get());
    // use a file that is in the root directory of your project
    assertTrue(b.getWorkspace().child(testFile).exists());
    b = assertBuildStatusSuccess(p.scheduleBuild2(0).get());
}
Example 83
Project: teamconcert-plugin-master  File: RTCScmIT.java View source code
@Test
public void testDoCheckCredentials() throws Exception {
    if (Config.DEFAULT.isConfigured()) {
        FreeStyleProject project = r.createFreeStyleProject();
        RTCScm rtcScm = createEmptyRTCScm();
        project.setScm(rtcScm);
        DescriptorImpl descriptor = (DescriptorImpl) project.getDescriptorByName(RTCScm.class.getName());
        assertDoCheckCredentials(descriptor, FormValidation.Kind.ERROR, null, null, null, null);
        assertDoCheckCredentials(descriptor, FormValidation.Kind.ERROR, null, "", null, null);
        assertDoCheckCredentials(descriptor, FormValidation.Kind.ERROR, null, null, "", null);
        assertDoCheckCredentials(descriptor, FormValidation.Kind.ERROR, null, null, null, "");
        assertDoCheckCredentials(descriptor, FormValidation.Kind.ERROR, "", "", "", "");
        assertDoCheckCredentials(descriptor, FormValidation.Kind.OK, null, null, null, TEST_CRED_ID);
        assertDoCheckCredentials(descriptor, FormValidation.Kind.OK, "", "", "", TEST_CRED_ID);
    }
}
Example 84
Project: testlink-plugin-master  File: TestLinkBuilderDescriptor.java View source code
private static void addTo(List<? extends Descriptor<? extends BuildStep>> source, List<Descriptor<? extends BuildStep>> list) {
    for (Descriptor<? extends BuildStep> d : source) {
        if (d instanceof BuildStepDescriptor) {
            BuildStepDescriptor<?> bsd = (BuildStepDescriptor<?>) d;
            if (bsd.isApplicable(FreeStyleProject.class)) {
                list.add(d);
            }
        }
    }
}
Example 85
Project: artifactory-plugin-master  File: Maven3Builder.java View source code
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
    return hudson.model.FreeStyleProject.class.isAssignableFrom(jobType) || hudson.matrix.MatrixProject.class.isAssignableFrom(jobType) || (Jenkins.getInstance().getPlugin(PluginsUtils.MULTIJOB_PLUGIN_ID) != null && com.tikal.jenkins.plugins.multijob.MultiJobProject.class.isAssignableFrom(jobType));
}
Example 86
Project: docker-traceability-plugin-master  File: DockerTraceabilityRootActionTest.java View source code
/**
     * Prepare a run with Fingerprints and referenced facets.
     * @param imageId image Id to refer
     * @param jobName job name
     * @return Run marked by the facet
     */
private FreeStyleBuild createTestBuildRefFacet(String imageId, String jobName) throws Exception {
    FreeStyleProject prj = j.jenkins.getItemByFullName(jobName, FreeStyleProject.class);
    if (prj == null) {
        prj = j.createFreeStyleProject(jobName);
    }
    FreeStyleBuild bld = j.buildAndAssertSuccess(prj);
    FingerprintTestUtil.injectFromFacet(bld, imageId);
    return bld;
}
Example 87
Project: Hudson-GIT-plugin-master  File: GitSCMTest.java View source code
/**
     * Basic test - create a GitSCM based project, check it out and build for the first time.
     * Next test that polling works correctly, make another commit, check that polling finds it,
     * then build it and finally test the build culprits as well as the contents of the workspace.
     * @throws Exception if an exception gets thrown.
     */
public void testBasic() throws Exception {
    FreeStyleProject project = setupSimpleProject("master");
    // create initial commit and then run the build against it:
    final String commitFile1 = "commitFile1";
    commit(commitFile1, johnDoe, "Commit number 1");
    build(project, Result.SUCCESS, commitFile1);
    assertFalse("scm polling should not detect any more changes after build", project.pollSCMChanges(listener));
    final String commitFile2 = "commitFile2";
    commit(commitFile2, janeDoe, "Commit number 2");
    assertTrue("scm polling did not detect commit2 change", project.pollSCMChanges(listener));
    //... and build it...
    final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
    final Set<User> culprits = build2.getCulprits();
    assertEquals("The build should have only one culprit", 1, culprits.size());
    assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
    assertTrue(build2.getWorkspace().child(commitFile2).exists());
    assertBuildStatusSuccess(build2);
    assertFalse("scm polling should not detect any more changes after build", project.pollSCMChanges(listener));
}
Example 88
Project: hudson-master  File: GitSCMTest.java View source code
/**
     * Basic test - create a GitSCM based project, check it out and build for the first time.
     * Next test that polling works correctly, make another commit, check that polling finds it,
     * then build it and finally test the build culprits as well as the contents of the workspace.
     * @throws Exception if an exception gets thrown.
     */
public void testBasic() throws Exception {
    FreeStyleProject project = setupSimpleProject("master");
    // create initial commit and then run the build against it:
    final String commitFile1 = "commitFile1";
    commit(commitFile1, johnDoe, "Commit number 1");
    build(project, Result.SUCCESS, commitFile1);
    assertFalse("scm polling should not detect any more changes after build", project.pollSCMChanges(listener));
    final String commitFile2 = "commitFile2";
    commit(commitFile2, janeDoe, "Commit number 2");
    assertTrue("scm polling did not detect commit2 change", project.pollSCMChanges(listener));
    //... and build it...
    final FreeStyleBuild build2 = build(project, Result.SUCCESS, commitFile2);
    final Set<User> culprits = build2.getCulprits();
    assertEquals("The build should have only one culprit", 1, culprits.size());
    assertEquals("", janeDoe.getName(), culprits.iterator().next().getFullName());
    assertTrue(build2.getWorkspace().child(commitFile2).exists());
    assertBuildStatusSuccess(build2);
    assertFalse("scm polling should not detect any more changes after build", project.pollSCMChanges(listener));
}
Example 89
Project: mailer-plugin-master  File: MailerTest.java View source code
private void verifyRoundtrip(Mailer before) throws Exception {
    FreeStyleProject p = rule.createFreeStyleProject();
    p.getPublishersList().add(before);
    rule.submit(rule.createWebClient().getPage(p, "configure").getFormByName("config"));
    Mailer after = p.getPublishersList().get(Mailer.class);
    assertNotSame(before, after);
    rule.assertEqualBeans(before, after, "recipients,dontNotifyEveryUnstableBuild,sendToIndividuals");
}
Example 90
Project: uno-choice-plugin-master  File: TestPersistingParameters.java View source code
/**
     * Test persisting jobs with parameters.
     *
     * @throws Exception in Jenkins rule
     */
@Test
public void testSaveParameters() throws Exception {
    FreeStyleProject project = j.createFreeStyleProject();
    GroovyScript scriptParam001 = new GroovyScript(new SecureGroovyScript(SCRIPT_PARAM001, false, null), new SecureGroovyScript(SCRIPT_FALLBACK_PARAM001, false, null));
    ChoiceParameter param001 = new ChoiceParameter("param001", "param001 description", "random-name", scriptParam001, AbstractUnoChoiceParameter.PARAMETER_TYPE_SINGLE_SELECT, true);
    GroovyScript scriptParam002 = new GroovyScript(new SecureGroovyScript(SCRIPT_PARAM002, false, null), new SecureGroovyScript(SCRIPT_FALLBACK_PARAM002, false, null));
    CascadeChoiceParameter param002 = new CascadeChoiceParameter("param002", "param002 description", "random-name", scriptParam002, AbstractUnoChoiceParameter.PARAMETER_TYPE_SINGLE_SELECT, "param001", true);
    ParametersDefinitionProperty param001Def = new ParametersDefinitionProperty(Arrays.<ParameterDefinition>asList(param001, param002));
    project.addProperty(param001Def);
    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    FreeStyleBuild build = future.get();
    // even though the cascaded parameter will fail to evaluate, we should
    // still get a success here.
    assertEquals(Result.SUCCESS, build.getResult());
    XmlFile configXml = project.getConfigFile();
    FreeStyleProject reReadProject = (FreeStyleProject) configXml.read();
    int found = 0;
    for (Entry<JobPropertyDescriptor, JobProperty<? super FreeStyleProject>> entry : reReadProject.getProperties().entrySet()) {
        JobProperty<? super FreeStyleProject> jobProperty = entry.getValue();
        if (jobProperty instanceof ParametersDefinitionProperty) {
            ParametersDefinitionProperty paramDef = (ParametersDefinitionProperty) jobProperty;
            List<ParameterDefinition> parameters = paramDef.getParameterDefinitions();
            for (ParameterDefinition parameter : parameters) {
                if (parameter instanceof AbstractScriptableParameter) {
                    found++;
                    AbstractScriptableParameter choiceParam = (AbstractScriptableParameter) parameter;
                    String scriptText = ((GroovyScript) choiceParam.getScript()).getScript().getScript();
                    String fallbackScriptText = ((GroovyScript) choiceParam.getScript()).getFallbackScript().getScript();
                    assertTrue("Found an empty script!", StringUtils.isNotBlank(scriptText));
                    assertTrue("Found an empty fallback script!", StringUtils.isNotBlank(fallbackScriptText));
                    if (parameter.getName().equals("param001")) {
                        assertEquals(SCRIPT_PARAM001, scriptText);
                        assertEquals(SCRIPT_FALLBACK_PARAM001, fallbackScriptText);
                    } else {
                        assertEquals(SCRIPT_PARAM002, scriptText);
                        assertEquals(SCRIPT_FALLBACK_PARAM002, fallbackScriptText);
                    }
                }
            }
        }
    }
    // We have two parameters before saving. We must have two now.
    assertEquals("Didn't find all parameters after persisting xml", 2, found);
}
Example 91
Project: rebuild-plugin-master  File: RebuildValidatorTest.java View source code
/**
	 * Creates a new freestyle project and builds the project with a string
	 * parameter. If the build is succesful, a rebuild of the last build is
	 * done. The rebuild on the project level should point to the last build
	 *
	 * @throws Exception
	 *             Exception
	 */
public void testWhenProjectWithNoParamsDefinedThenRebuildofBuildWithParamsShouldShowParams() throws Exception {
    FreeStyleProject project = createFreeStyleProject();
    // Build (#1)
    project.scheduleBuild2(0, new Cause.UserIdCause(), new ParametersAction(new StringParameterValue("name", "ABC"))).get();
    HtmlPage rebuildConfigPage = createWebClient().getPage(project, "1/rebuild");
    WebAssert.assertElementPresentByXPath(rebuildConfigPage, "//div[@name='parameter']/input[@value='ABC']");
}
Example 92
Project: packer-plugin-master  File: PackerJenkinsPluginTest.java View source code
@Test
public void testPluginInJobPathExec() throws Exception {
    final String jsonText = "{ \"here\": \"i am\"}";
    PackerInstallation installation = new PackerInstallation(name, home, params, createTemplateModeJson(TemplateMode.TEXT, jsonText), emptyFileEntries, null);
    final String pluginHome = "bin";
    PackerPublisher placeHolder = new PackerPublisher(name, null, null, pluginHome, localParams, emptyFileEntries, false, null);
    PackerInstallation[] installations = new PackerInstallation[1];
    installations[0] = installation;
    placeHolder.getDescriptor().setInstallations(installations);
    StaplerRequest mockReq = mock(StaplerRequest.class);
    when(mockReq.bindJSON(any(Class.class), any(JSONObject.class))).thenReturn(placeHolder);
    JSONObject formJson = new JSONObject();
    formJson.put("templateMode", createTemplateModeJson(TemplateMode.TEXT, jsonText));
    PackerPublisher plugin = placeHolder.getDescriptor().newInstance(mockReq, formJson);
    assertEquals(pluginHome, plugin.getPackerHome());
    assertEquals(localParams, plugin.getParams());
    assertTrue(plugin.isTextTemplate());
    assertFalse(plugin.isFileTemplate());
    assertFalse(plugin.isGlobalTemplate());
    assertEquals(jsonText, plugin.getJsonTemplateText());
    FreeStyleProject project = jenkins.createFreeStyleProject();
    FreeStyleBuild build = project.scheduleBuild2(0).get();
    Launcher launcherMock = mock(Launcher.class);
    TaskListener listenerMock = mock(TaskListener.class);
    String exec = plugin.getRemotePackerExec(build, launcherMock, listenerMock);
    assertEquals(build.getWorkspace().getRemote() + "/" + pluginHome + "/packer", exec);
}
Example 93
Project: perforce-plugin-master  File: PerforceSCMTest.java View source code
/**
     * Makes sure that the configuration survives the round-trip.
     */
public void testConfigRoundtrip() throws Exception {
    FreeStyleProject project = createFreeStyleProject();
    PerforceSCM scm = createPerforceSCMStub();
    scm.setProjectPath("path");
    project.setScm(scm);
    // config roundtrip
    submit(new WebClient().getPage(project, "configure").getFormByName("config"));
    // verify that the data is intact
    assertEqualBeans(scm, project.getScm(), "p4User,p4Client,p4Port,p4Label,projectPath,p4Exe,p4SysRoot,p4SysDrive,forceSync,alwaysForceSync,dontUpdateClient,createWorkspace,updateView,slaveClientNameFormat,lineEndValue,firstChange,p4Counter,updateCounterValue,exposeP4Passwd,useViewMaskForPolling,viewMask,useViewMaskForSyncing,p4Charset,p4CommandCharset,p4Stream,useStreamDepot,showIntegChanges,fileLimit");
    assertEquals("exclude_user", scm.getExcludedUsers());
    assertEquals("exclude_file", scm.getExcludedFiles());
//assertEqualBeans(scm.getBrowser(),p.getScm().getBrowser(),"URL");
}
Example 94
Project: Pipeline-master  File: SnippetizerTest.java View source code
@Issue("JENKINS-26093")
@Test
public void generateSnippetForBuildTrigger() throws Exception {
    MockFolder d1 = r.createFolder("d1");
    FreeStyleProject ds = d1.createProject(FreeStyleProject.class, "ds");
    MockFolder d2 = r.createFolder("d2");
    // Really this would be a WorkflowJob, but we cannot depend on that here, and it should not matter since we are just looking for Job:
    FreeStyleProject us = d2.createProject(FreeStyleProject.class, "us");
    ds.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("key", ""), new BooleanParameterDefinition("flag", false, "")));
    String snippet;
    if (StringParameterDefinition.DescriptorImpl.class.isAnnotationPresent(Symbol.class)) {
        snippet = "build job: '../d1/ds', parameters: [string(name: 'key', value: 'stuff'), booleanParam(name: 'flag', value: true)]";
    } else {
        // TODO 2.x delete
        snippet = "build job: '../d1/ds', parameters: [[$class: 'StringParameterValue', name: 'key', value: 'stuff'], [$class: 'BooleanParameterValue', name: 'flag', value: true]]";
    }
    st.assertGenerateSnippet("{'stapler-class':'" + BuildTriggerStep.class.getName() + "', 'job':'../d1/ds', 'parameter': [{'name':'key', 'value':'stuff'}, {'name':'flag', 'value':true}]}", snippet, us.getAbsoluteUrl() + "configure");
}
Example 95
Project: m2eclipse-hudson-master  File: SummaryPage.java View source code
private String getTypeStrings(ProjectDTO job) {
    String type = job.getType();
    if (//$NON-NLS-1$
    "hudson.model.FreeStyleProject".equals(type)) {
        return Messages.SummaryPage_freestyle;
    }
    if (//$NON-NLS-1$
    "hudson.XXX".equals(type)) {
        // TODO
        return Messages.SummaryPage_external;
    }
    if (HudsonUtils.isMatrixType(job)) {
        return Messages.SummaryPage_matrix;
    }
    if (HudsonUtils.isMatrixConfig(job)) {
        return Messages.SummaryPage_configuration;
    }
    return Messages.SummaryPage_unknown + type;
}
Example 96
Project: ci-game-plugin-master  File: DefaultCheckstyleRuleIntegrationTest.java View source code
@LocalData
public void testNoPointsAwardedForFirstBuild() throws Exception {
    FreeStyleBuild build = ((FreeStyleProject) hudson.getItem("checkstyle-first")).scheduleBuild2(0).get();
    assertBuildStatusSuccess(build);
    assertPointsForBuildEquals(build, 1);
    assertPointsForRuleEquals(build, Messages.CheckstyleRuleSet_Title(), 0);
}
Example 97
Project: docker-build-step-plugin-master  File: DockerPostBuilder.java View source code
@Override
public boolean isApplicable(@SuppressWarnings("rawtypes") Class<? extends AbstractProject> jobType) {
    return FreeStyleProject.class.equals(jobType) || MatrixProject.class.equals(jobType);
}
Example 98
Project: gitlab-auth-plugin-master  File: MockFreeStyleProjectBuilder.java View source code
/**
     * Creates a new free style project.
     *
     * @param name the name of the project
     * @return the project
     */
public static FreeStyleProject freeStyleProject(String name) {
    return mockFreeStyleProject().name(name).build();
}
Example 99
Project: debian-package-builder-plugin-master  File: SmokeTest.java View source code
/**
	 * Build this ``builder`` in a basic project and check that build results in success
	 *
	 * @param builder
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
private void fire(DebianPackageBuilder builder) throws IOException, InterruptedException, ExecutionException {
    FreeStyleProject project = j.createFreeStyleProject();
    project.getBuildersList().add(builder);
    project.scheduleBuild2(0).get();
}
Example 100
Project: sicci_for_xcode-master  File: XcodeBuilder.java View source code
@SuppressWarnings("rawtypes")
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
    return jobType == FreeStyleProject.class;
}