Java Code Examples for hudson.model.FreeStyleProject

The following examples show how to use hudson.model.FreeStyleProject. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: blueocean-plugin   Author: jenkinsci   File: FreeStylePipelineTest.java    License: MIT License 6 votes vote down vote up
@Test
public void findModernRun() throws Exception {
    FreeStyleProject freestyle = Mockito.spy(j.createProject(FreeStyleProject.class, "freestyle"));

    FreeStyleBuild build1 = Mockito.mock(FreeStyleBuild.class);
    FreeStyleBuild build2 = Mockito.mock(FreeStyleBuild.class);

    Mockito.when(build1.getParent()).thenReturn(freestyle);
    Mockito.when(build1.getNextBuild()).thenReturn(build2);

    Mockito.when(build2.getParent()).thenReturn(freestyle);
    Mockito.when(build2.getPreviousBuild()).thenReturn(build1);

    RunList<FreeStyleBuild> runs = RunList.fromRuns(Arrays.asList(build1, build2));
    Mockito.doReturn(runs).when(freestyle).getBuilds();
    Mockito.doReturn(build2).when(freestyle).getLastBuild();

    FreeStylePipeline freeStylePipeline = (FreeStylePipeline) BluePipelineFactory.resolve(freestyle);
    assertNotNull(freeStylePipeline);
    BlueRun blueRun = freeStylePipeline.getLatestRun();
    assertNotNull(blueRun);
    Links links = blueRun.getLinks();
    assertNotNull(links);
    assertNotNull(links.get("self"));
}
 
Example #2
Source Project: ansible-plugin   Author: jcsirot   File: DslJobRule.java    License: Apache License 2.0 6 votes vote down vote up
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 #3
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void PipelineSecureWithLoggedInUserPermissionTest() throws IOException, UnirestException {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    hudson.model.User user = User.get("alice");
    user.setFullName("Alice Cooper");


    MockFolder folder = j.createFolder("folder1");

    Project p = folder.createProject(FreeStyleProject.class, "test1");
    String token = getJwtToken(j.jenkins, "alice", "alice");
    assertNotNull(token);
    Map response = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/pipelines/folder1/pipelines/test1")
        .jwtToken(token)
        .build(Map.class);

    validatePipeline(p, response);

    Map<String,Boolean> permissions = (Map<String, Boolean>) response.get("permissions");
    assertTrue(permissions.get("create"));
    assertTrue(permissions.get("start"));
    assertTrue(permissions.get("stop"));
    assertTrue(permissions.get("read"));
}
 
Example #4
Source Project: blueocean-plugin   Author: jenkinsci   File: LinkResolverTest.java    License: MIT License 6 votes vote down vote up
@Test
public void nestedFolderJobLinkResolveTest() throws IOException {
    Project f = j.createFreeStyleProject("fstyle1");
    MockFolder folder1 = j.createFolder("folder1");
    Project p1 = folder1.createProject(FreeStyleProject.class, "test1");
    MockFolder folder2 = folder1.createProject(MockFolder.class, "folder2");
    MockFolder folder3 = folder2.createProject(MockFolder.class, "folder3");
    Project p2 = folder2.createProject(FreeStyleProject.class, "test2");
    Project p3 = folder3.createProject(FreeStyleProject.class, "test3");

    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/fstyle1/",LinkResolver.resolveLink(f).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/folder1/",LinkResolver.resolveLink(folder1).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/test1/",LinkResolver.resolveLink(p1).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/folder2/",LinkResolver.resolveLink(folder2).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/folder2/pipelines/test2/",LinkResolver.resolveLink(p2).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/folder2/pipelines/folder3/",LinkResolver.resolveLink(folder3).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/folder1/pipelines/folder2/pipelines/folder3/pipelines/test3/",LinkResolver.resolveLink(p3).getHref());
}
 
Example #5
Source Project: warnings-ng-plugin   Author: jenkinsci   File: MetricsAggregationPluginITest.java    License: MIT License 6 votes vote down vote up
/** Verifies that the metrics action is available automatically. */
@Test
public void shouldAggregateMetrics() {
    FreeStyleProject project = createFreeStyleProjectWithWorkspaceFiles("pmd.xml", "cpd.xml", "spotbugsXml.xml");

    IssuesRecorder recorder = new IssuesRecorder();
    recorder.setTools(createTool(new Pmd(), "**/pmd*.txt"),
            createTool(new Cpd(), "**/cpd*.txt"),
            createTool(new SpotBugs(), "**/spotbugs*.txt"));
    project.getPublishersList().add(recorder);

    Run<?, ?> build = buildSuccessfully(project);
    MetricsView view = (MetricsView) build.getAction(MetricsViewAction.class).getTarget();

    assertThat(view.getSupportedMetrics()).contains(
            new MetricDefinition("ERRORS"), new MetricDefinition("WARNING_HIGH"),
            new MetricDefinition("WARNING_NORMAL"), new MetricDefinition("WARNING_LOW"),
            new MetricDefinition("AUTHORS"), new MetricDefinition("COMMITS")
    );
}
 
Example #6
Source Project: lockable-resources-plugin   Author: jenkinsci   File: FreeStyleProjectTest.java    License: MIT License 6 votes vote down vote up
@Test
public void configRoundTripWithScript() throws Exception {
  FreeStyleProject withScript = j.createFreeStyleProject("withScript");
  SecureGroovyScript origScript = new SecureGroovyScript("return true", false, null);
  withScript.addProperty(new RequiredResourcesProperty(null, null, null, null, origScript));
  FreeStyleProject withScriptRoundTrip = j.configRoundtrip(withScript);

  RequiredResourcesProperty withScriptProp =
      withScriptRoundTrip.getProperty(RequiredResourcesProperty.class);
  assertNotNull(withScriptProp);
  assertNull(withScriptProp.getResourceNames());
  assertNull(withScriptProp.getResourceNamesVar());
  assertNull(withScriptProp.getResourceNumber());
  assertNull(withScriptProp.getLabelName());
  assertNotNull(withScriptProp.getResourceMatchScript());
  assertEquals("return true", withScriptProp.getResourceMatchScript().getScript());
  assertFalse(withScriptProp.getResourceMatchScript().isSandbox());
}
 
Example #7
Source Project: warnings-ng-plugin   Author: jenkinsci   File: DockerContainerITest.java    License: MIT License 6 votes vote down vote up
/**
 * Build a maven project on a docker container agent.
 *
 * @throws IOException
 *         When the node assignment of the agent fails.
 * @throws InterruptedException
 *         If the creation of the docker container fails.
 */
@Test
public void shouldBuildMavenOnAgent() throws IOException, InterruptedException {
    assumeThat(isWindows()).as("Running on Windows").isFalse();

    DumbSlave agent = createDockerContainerAgent(javaDockerRule.get());

    FreeStyleProject project = createFreeStyleProject();
    project.setAssignedNode(agent);

    createFileInAgentWorkspace(agent, project, "src/main/java/Test.java", getSampleJavaFile());
    createFileInAgentWorkspace(agent, project, "pom.xml", getSampleMavenFile());
    project.getBuildersList().add(new Maven("compile", null));
    enableWarnings(project, createTool(new Java(), ""));

    scheduleSuccessfulBuild(project);

    FreeStyleBuild lastBuild = project.getLastBuild();
    AnalysisResult result = getAnalysisResult(lastBuild);

    assertThat(result).hasTotalSize(2);
    assertThat(lastBuild.getBuiltOn().getLabelString()).isEqualTo(((Node) agent).getLabelString());
}
 
Example #8
Source Project: aws-lambda-jenkins-plugin   Author: XT-i   File: WorkSpaceZipperTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetZipFileNotExists() throws Exception {

    FreeStyleProject p = j.createFreeStyleProject();

    p.scheduleBuild2(0).get();

    JenkinsLogger logger = new JenkinsLogger(System.out);
    WorkSpaceZipper workSpaceZipper = new WorkSpaceZipper(p.getSomeWorkspace(), logger);
    try {
        workSpaceZipper.getZip("echo.zip");
        fail("Expected LambdaDeployException.");
    } catch (LambdaDeployException lde){
        assertEquals("Could not find zipfile or folder.", lde.getMessage());
    }
}
 
Example #9
Source Project: docker-plugin   Author: jenkinsci   File: DockerComputerConnectorTest.java    License: MIT License 6 votes vote down vote up
protected void should_connect_agent(DockerTemplate template) throws IOException, ExecutionException, InterruptedException, TimeoutException {

        // FIXME on CI windows nodes don't have Docker4Windows
        Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS);

        String dockerHost = SystemUtils.IS_OS_WINDOWS ? "tcp://localhost:2375" : "unix:///var/run/docker.sock";

        DockerCloud cloud = new DockerCloud(cloudName, new DockerAPI(new DockerServerEndpoint(dockerHost, null)),
                Collections.singletonList(template));

        j.jenkins.clouds.replaceBy(Collections.singleton(cloud));

        final FreeStyleProject project = j.createFreeStyleProject("test-docker-ssh");
        project.setAssignedLabel(Label.get(LABEL));
        project.getBuildersList().add(new Shell("whoami"));
        final QueueTaskFuture<FreeStyleBuild> scheduledBuild = project.scheduleBuild2(0);
        try {
            final FreeStyleBuild build = scheduledBuild.get(60L, TimeUnit.SECONDS);
            Assert.assertTrue(build.getResult() == Result.SUCCESS);
            Assert.assertTrue(build.getLog().contains("jenkins"));
        } finally {
            scheduledBuild.cancel(true);
        }
    }
 
Example #10
Source Project: warnings-ng-plugin   Author: jenkinsci   File: MiscIssuesRecorderITest.java    License: MIT License 6 votes vote down vote up
/**
 * Runs the CheckStyle and PMD tools for two corresponding files which contain 10 issues in total. Since a filter
 * afterwords removes all issues, the actual result contains no warnings. However, the two origins are still
 * reported with a total of 0 warnings per origin.
 */
@Test
public void shouldHaveOriginsIfBuildContainsWarnings() {
    FreeStyleProject project = createFreeStyleProjectWithWorkspaceFiles("checkstyle.xml", "pmd-warnings.xml");
    enableWarnings(project,
            recorder -> {
                recorder.setAggregatingResults(true);
                recorder.setFilters(Collections.singletonList(new ExcludeFile(".*")));
            },
            createTool(new CheckStyle(), "**/checkstyle-issues.txt"),
            createTool(new Pmd(), "**/pmd-warnings-issues.txt"));

    AnalysisResult result = getAnalysisResult(buildWithResult(project, Result.SUCCESS));
    assertThat(result).hasTotalSize(0);
    assertThat(result.getSizePerOrigin()).containsExactly(entry("checkstyle", 0), entry("pmd", 0));
    assertThat(result).hasId("analysis");
    assertThat(result).hasQualityGateStatus(QualityGateStatus.INACTIVE);
}
 
Example #11
Source Project: credentials-binding-plugin   Author: jenkinsci   File: UsernamePasswordBindingTest.java    License: MIT License 6 votes vote down vote up
@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(Functions.isWindows() ? new BatchFile("echo %AUTH% > auth.txt") : new Shell("echo $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 #12
Source Project: office-365-connector-plugin   Author: jenkinsci   File: WebhookJobPropertyIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDataCompatibility() throws Exception {

    // given
    FreeStyleProject foo = (FreeStyleProject) rule.jenkins.createProjectFromXML(
            "bar",
            getClass().getResourceAsStream("WebhookJobProperty/freestyleold1.xml")
    );

    // when
    WebhookJobProperty webhookJobProperty = foo.getProperty(WebhookJobProperty.class);
    assertThat(webhookJobProperty.getWebhooks()).isNotEmpty();

    // then
    rule.assertBuildStatusSuccess(foo.scheduleBuild2(0, new Cause.UserIdCause()).get());
}
 
Example #13
Source Project: gitlab-plugin   Author: jenkinsci   File: PushBuildActionTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void build() throws IOException {
    try {
        FreeStyleProject testProject = jenkins.createFreeStyleProject();
        when(trigger.getTriggerOpenMergeRequestOnPush()).thenReturn(TriggerOpenMergeRequest.never);
        testProject.addTrigger(trigger);

        exception.expect(HttpResponses.HttpResponseException.class);
        new PushBuildAction(testProject, getJson("PushEvent.json"), null).execute(response);
    } finally {
        ArgumentCaptor<PushHook> pushHookArgumentCaptor = ArgumentCaptor.forClass(PushHook.class);
        verify(trigger).onPost(pushHookArgumentCaptor.capture());
        assertThat(pushHookArgumentCaptor.getValue().getProject(), is(notNullValue()));
        assertThat(pushHookArgumentCaptor.getValue().getProject().getWebUrl(), is(notNullValue()));
        assertThat(pushHookArgumentCaptor.getValue().getUserUsername(), is(notNullValue()));
        assertThat(pushHookArgumentCaptor.getValue().getUserUsername(), containsString("jsmith"));
    }
}
 
Example #14
Source Project: gitlab-plugin   Author: jenkinsci   File: PushHookTriggerHandlerImplTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void push_ciSkip() throws IOException, InterruptedException {
    final OneShotEvent buildTriggered = new OneShotEvent();
    FreeStyleProject project = jenkins.createFreeStyleProject();
    project.getBuildersList().add(new TestBuilder() {
        @Override
        public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
            buildTriggered.signal();
            return true;
        }
    });
    project.setQuietPeriod(0);
    pushHookTriggerHandler.handle(project, pushHook()
            .withCommits(Arrays.asList(commit().withMessage("some message").build(),
                                       commit().withMessage("[ci-skip]").build()))
            .build(), true, newBranchFilter(branchFilterConfig().build(BranchFilterType.All)),
                                  newMergeRequestLabelFilter(null));

    buildTriggered.block(10000);
    assertThat(buildTriggered.isSignaled(), is(false));
}
 
Example #15
Source Project: cucumber-living-documentation-plugin   Author: jenkinsci   File: CucumberLivingDocumentationIT.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldGenerateLivingDocumentatationOnSlaveNode() throws Exception{
	DumbSlave slave = jenkins.createOnlineSlave();
	FreeStyleProject project = jenkins.createFreeStyleProject("test");
	project.setAssignedNode(slave);
	
	SingleFileSCM scm = new SingleFileSCM("asciidoctor.json",
			CucumberLivingDocumentationIT.class.getResource("/json-output/asciidoctor/asciidoctor.json").toURI().toURL());
	
	project.setScm(scm);
	CukedoctorPublisher publisher = new CukedoctorPublisher(null, FormatType.HTML, TocType.RIGHT, true, true, "Living Documentation",false,false,false,false,false);
	project.getPublishersList().add(publisher);
	project.save();

	FreeStyleBuild build = jenkins.buildAndAssertSuccess(project);
	jenkins.assertLogContains("Format: html" + NEW_LINE + "Toc: right"+NEW_LINE +
			"Title: Living Documentation"+NEW_LINE+"Numbered: true"+NEW_LINE +
			"Section anchors: true", build);
	jenkins.assertLogContains("Found 4 feature(s)...",build);
	jenkins.assertLogContains("Documentation generated successfully!",build);
	Assert.assertTrue("It should run on slave",build.getBuiltOn().equals(slave));
	
}
 
Example #16
Source Project: configuration-as-code-plugin   Author: jenkinsci   File: SeedJobTest.java    License: MIT License 6 votes vote down vote up
@Test
@ConfiguredWithCode("SeedJobTest_withSecurityConfig.yml")
@Envs(
    @Env(name = "SEED_JOB_FOLDER_FILE_PATH", value = ".")
)
public void configure_seed_job_with_security_config() throws Exception {
    final Jenkins jenkins = Jenkins.get();

    final GlobalJobDslSecurityConfiguration dslSecurity = GlobalConfiguration.all()
        .get(GlobalJobDslSecurityConfiguration.class);
    assertNotNull(dslSecurity);
    assertThat("ScriptSecurity", dslSecurity.isUseScriptSecurity(), is(false));

    FreeStyleProject seedJobWithSecurityConfig = (FreeStyleProject) jenkins.getItem("seedJobWithSecurityConfig");
    assertNotNull(seedJobWithSecurityConfig);

    assertTrue(seedJobWithSecurityConfig.isInQueue());
    FreeStyleBuild freeStyleBuild = j.buildAndAssertSuccess(seedJobWithSecurityConfig);
    j.assertLogContains("Processing DSL script testJob2.groovy", freeStyleBuild);
    j.assertLogContains("Added items:", freeStyleBuild);
    j.assertLogContains("GeneratedJob{name='testJob2'}", freeStyleBuild);
}
 
Example #17
Source Project: warnings-ng-plugin   Author: jenkinsci   File: DryITest.java    License: MIT License 6 votes vote down vote up
/**
 * Verifies that the right amount of duplicate code warnings are detected.
 */
@Test
public void shouldHaveDuplicateCodeWarnings() {
    FreeStyleProject project = createFreeStyleProjectWithWorkspaceFiles(CPD_REPORT);
    enableGenericWarnings(project, new Cpd());

    AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS);
    assertThat(result).hasTotalSize(20);
    assertThat(result).hasQualityGateStatus(QualityGateStatus.INACTIVE);

    Run<?, ?> build = result.getOwner();
    TableModel table = getDryTableModel(build);
    assertThatColumnsAreCorrect(table.getColumns());

    table.getRows().stream()
            .map(row -> (DuplicationRow) row)
            .forEach(row -> assertThat(row.getSeverity()).contains("LOW"));
}
 
Example #18
Source Project: jenkins-client-java   Author: jenkins-zh   File: QueuesTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getItems() throws IOException
{
    Queue queue = queues.getItems();
    assertNotNull(queue.getItems());
    assertEquals(0, queue.getItems().size());

    j.jenkins.setNumExecutors(0);
    FreeStyleProject project = j.createFreeStyleProject();
    project.scheduleBuild2(0);

    queue = queues.getItems();
    List<QueueItem> items = queue.getItems();
    assertEquals(1, items.size());

    QueueItem firstItem = items.get(0);
    int firstItemId = firstItem.getId();

    assertNotNull(queues.getItem(firstItemId));

    queues.cancelItem(firstItemId);
    assertEquals(0, queues.getItems().getItems().size());
}
 
Example #19
Source Project: blueocean-plugin   Author: jenkinsci   File: MultiBranchTest.java    License: MIT License 6 votes vote down vote up
@Test
public void resolveMbpLink() throws Exception {
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    FreeStyleProject f = j.jenkins.createProject(FreeStyleProject.class, "f");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
        new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    mp.scheduleBuild2(0).getFuture().get();

    j.waitUntilNoActivity();

    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/",LinkResolver.resolveLink(mp).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/master/",LinkResolver.resolveLink(mp.getBranch("master")).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature%252Fux-1/",LinkResolver.resolveLink(mp.getBranch("feature%2Fux-1")).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/p/branches/feature2/",LinkResolver.resolveLink(mp.getBranch("feature2")).getHref());
    Assert.assertEquals("/blue/rest/organizations/jenkins/pipelines/f/",LinkResolver.resolveLink(f).getHref());
}
 
Example #20
Source Project: github-integration-plugin   Author: KostyaSha   File: GHPullRequestSubscriberTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldTriggerJobOnPullRequestOpen() throws Exception {
    when(trigger.getRepoFullName(any(AbstractProject.class))).thenReturn(create(REPO_URL_FROM_PAYLOAD));
    when(trigger.getTriggerMode()).thenReturn(GitHubPRTriggerMode.HEAVY_HOOKS);

    FreeStyleProject job = jenkins.createFreeStyleProject();
    job.addProperty(new GithubProjectProperty(REPO_URL_FROM_PAYLOAD));
    job.addTrigger(trigger);

    new GHPullRequestSubscriber().onEvent(new GHSubscriberEvent(
            "",
            GHEvent.PULL_REQUEST,
            classpath("payload/pull_request.json"))
    );

    verify(trigger).queueRun(eq(job), eq(1));
}
 
Example #21
Source Project: warnings-ng-plugin   Author: jenkinsci   File: ReferenceFinderITest.java    License: MIT License 6 votes vote down vote up
/**
 * Checks if the reference is taken from the last successful build and therefore returns an unstable in the end.
 */
@Test
public void shouldCreateUnstableResultWithIgnoredUnstableInBetween() {
    // #1 SUCCESS
    FreeStyleProject project = createJob(JOB_NAME, "eclipse2Warnings.txt");
    enableWarnings(project, recorder -> recorder.addQualityGate(3, QualityGateType.NEW, QualityGateResult.UNSTABLE));
    Run<?, ?> expectedReference = scheduleBuildAndAssertStatus(project, Result.SUCCESS,
            analysisResult -> assertThat(analysisResult).hasTotalSize(2)
                    .hasNewSize(0)
                    .hasQualityGateStatus(QualityGateStatus.PASSED)).getOwner();

    // #2 UNSTABLE
    cleanAndCopy(project, "eclipse6Warnings.txt");
    scheduleBuildAndAssertStatus(project, Result.UNSTABLE,
            analysisResult -> assertThat(analysisResult).hasTotalSize(6)
                    .hasNewSize(4)
                    .hasQualityGateStatus(QualityGateStatus.WARNING));

    // #3 UNSTABLE (Reference #1)
    cleanAndCopy(project, "eclipse8Warnings.txt");
    scheduleBuildAndAssertStatus(project, Result.UNSTABLE, analysisResult -> assertThat(analysisResult)
            .hasTotalSize(8)
            .hasNewSize(6)
            .hasQualityGateStatus(QualityGateStatus.WARNING)
            .hasReferenceBuild(Optional.of(expectedReference)));
}
 
Example #22
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldFailToGetRunForInvalidRunId1() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pipeline6");
    p.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    FreeStyleBuild b = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b);
    get("/organizations/jenkins/pipelines/pipeline6/runs/xyz", 404, Map.class);
}
 
Example #23
Source Project: warnings-ng-plugin   Author: jenkinsci   File: AffectedFilesResolverITest.java    License: MIT License 5 votes vote down vote up
/**
 * Verifies that the affected source code is copied and shown in the source code view. If the file is made
 * unreadable in the build folder, then the link to open the file disappears.
 */
@Test
public void shouldShowNoLinkIfSourceCodeHasBeenMadeUnreadable() {
    FreeStyleProject project = createEclipseProject();
    AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS);

    IssuesRow row = getIssuesModel(result, ROW_NUMBER_ACTUAL_AFFECTED_FILE);
    assertThat(row.getFileName().getDisplay()).contains("<a href=").contains("Main.java:3");

    makeAffectedFilesInBuildFolderUnreadable(result);

    row = getIssuesModel(result, ROW_NUMBER_ACTUAL_AFFECTED_FILE);
    assertThat(row.getFileName().getDisplay()).isEqualTo("Main.java:3");
}
 
Example #24
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 5 votes vote down vote up
@Test
public void getFolderPipelineTest() throws IOException {
    MockFolder folder = j.createFolder("folder1");
    Project p = folder.createProject(FreeStyleProject.class, "test1");

    Map response = get("/organizations/jenkins/pipelines/folder1/pipelines/test1");
    validatePipeline(p, response);
}
 
Example #25
Source Project: phabricator-jenkins-plugin   Author: uber   File: TestUtils.java    License: MIT License 5 votes vote down vote up
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 #26
Source Project: lockable-resources-plugin   Author: jenkinsci   File: FreeStyleProjectTest.java    License: MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-34853")
public void security170fix() throws Exception {
  LockableResourcesManager.get().createResource("resource1");
  FreeStyleProject p = j.createFreeStyleProject("p");
  p.addProperty(new RequiredResourcesProperty("resource1", "resourceNameVar", null, null, null));
  p.getBuildersList().add(new PrinterBuilder());

  FreeStyleBuild b1 = p.scheduleBuild2(0).get();
  j.assertLogContains("resourceNameVar: resource1", b1);
  j.assertBuildStatus(Result.SUCCESS, b1);
}
 
Example #27
Source Project: warnings-ng-plugin   Author: jenkinsci   File: ReferenceFinderITest.java    License: MIT License 5 votes vote down vote up
/**
 * Checks if the reference only looks at the eclipse result of a build and not the overall success. Should return an
 * unstable result.
 */
@Test
public void shouldCreateUnstableResultWithOverAllMustNotBeSuccess() {
    // #1 SUCCESS
    FreeStyleProject project = createJob(JOB_NAME, "eclipse4Warnings.txt");
    IssuesRecorder issuesRecorder = enableWarnings(project, recorder -> {
        recorder.setIgnoreFailedBuilds(false);
        recorder.setEnabledForFailure(true);
    });
    scheduleBuildAndAssertStatus(project, Result.SUCCESS,
            analysisResult -> assertThat(analysisResult).hasTotalSize(4)
                    .hasNewSize(0)
                    .hasQualityGateStatus(QualityGateStatus.INACTIVE));

    // #2 FAILURE
    cleanAndCopy(project, "eclipse2Warnings.txt");
    issuesRecorder.addQualityGate(3, QualityGateType.NEW, QualityGateResult.UNSTABLE);
    Builder failureStep = addFailureStep(project);
    Run<?, ?> expectedReference = scheduleBuildAndAssertStatus(project, Result.FAILURE,
            analysisResult -> assertThat(analysisResult).hasTotalSize(2)
                    .hasNewSize(0)
                    .hasQualityGateStatus(QualityGateStatus.PASSED)).getOwner();

    cleanAndCopy(project, "eclipse6Warnings.txt");
    removeBuilder(project, failureStep);

    // #3 UNSTABLE (Reference #2)
    scheduleBuildAndAssertStatus(project, Result.UNSTABLE, analysisResult -> assertThat(analysisResult)
            .hasTotalSize(6)
            .hasNewSize(4)
            .hasQualityGateStatus(QualityGateStatus.WARNING)
            .hasReferenceBuild(Optional.of(expectedReference)));
}
 
Example #28
Source Project: warnings-ng-plugin   Author: jenkinsci   File: HealthReportITest.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a {@link HealthReport} under test with eclipse workspace file.
 *
 * @param health
 *         health threshold
 * @param unhealthy
 *         unhealthy threshold
 *
 * @return a healthReport under test
 */
private HealthReport createHealthReportTestSetupEclipse(final int health, final int unhealthy) {
    FreeStyleProject project = createFreeStyleProjectWithWorkspaceFiles("eclipse-healthReport.txt");
    enableGenericWarnings(project, publisher -> {
                publisher.setHealthy(health);
                publisher.setUnhealthy(unhealthy);
            },
            configurePattern(new Eclipse())
    );
    return scheduleBuildToGetHealthReportAndAssertStatus(project, Result.SUCCESS);
}
 
Example #29
Source Project: warnings-ng-plugin   Author: jenkinsci   File: MiscIssuesRecorderITest.java    License: MIT License 5 votes vote down vote up
/**
 * Runs the Eclipse parser on an empty workspace: the build should report 0 issues and an error message.
 */
@Test
public void shouldCreateEmptyResult() {
    FreeStyleProject project = createFreeStyleProject();
    enableEclipseWarnings(project);

    AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS);

    assertThat(result).hasTotalSize(0);
    assertThat(result).hasErrorMessages("No files found for pattern '**/*issues.txt'. Configuration error?");
}
 
Example #30
Source Project: warnings-ng-plugin   Author: jenkinsci   File: PackageDetectorsITest.java    License: MIT License 5 votes vote down vote up
/**
 * Verifies that the output is correct if there exist various namespaces (C#) and packages (Java) at the same time
 * in the expected HTML output.
 */
@Test @org.jvnet.hudson.test.Issue("JENKINS-58538")
public void shouldShowFolderDistributionRatherThanPackageDistribution() {
    FreeStyleProject project = createFreeStyleProject();

    createFileInWorkspace(project, "java-issues.txt",
            createJavaWarning("one/SampleClassWithoutPackage.java", 1)
                    + createJavaWarning("two/SampleClassWithUnconventionalPackageNaming.java", 2)
                    + createJavaWarning("three/SampleClassWithBrokenPackageNaming.java", 3)
                    + createJavaWarning("four/SampleClassWithoutNamespace.cs", 4)
    );

    copySingleFileToWorkspace(project, PACKAGE_WITH_FILES_JAVA + "SampleClassWithoutPackage.java",
            "one/SampleClassWithoutPackage.java");
    copySingleFileToWorkspace(project, PACKAGE_WITH_FILES_JAVA + "SampleClassWithUnconventionalPackageNaming.java",
            "two/SampleClassWithUnconventionalPackageNaming.java");
    copySingleFileToWorkspace(project, PACKAGE_WITH_FILES_JAVA + "SampleClassWithBrokenPackageNaming.java",
            "three/SampleClassWithBrokenPackageNaming.java");
    copySingleFileToWorkspace(project, PACKAGE_WITH_FILES_CSHARP + "SampleClassWithoutNamespace.cs",
            "four/SampleClassWithoutNamespace.cs");

    enableGenericWarnings(project, new Java());
    AnalysisResult result = scheduleBuildAndAssertStatus(project, Result.SUCCESS);

    HtmlPage details = getWebPage(JavaScriptSupport.JS_DISABLED, result);

    PropertyTable propertyTable = new PropertyTable(details, "folder");
    assertThat(propertyTable.getTitle()).isEqualTo("Folders");
    assertThat(propertyTable.getColumnName()).isEqualTo("Source Folder");
    assertThat(propertyTable.getRows()).containsExactlyInAnyOrder(
            new PropertyRow("four", 1),
            new PropertyRow("one", 1),
            new PropertyRow("three", 1),
            new PropertyRow("two", 1));
}