Search in sources :

Example 31 with StringParameterDefinition

use of hudson.model.StringParameterDefinition in project github-branch-source-plugin by jenkinsci.

the class GithubAppCredentialsTest method testAgentRefresh.

@Test
public void testAgentRefresh() throws Exception {
    long notStaleSeconds = GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS;
    try {
        appCredentials.setApiUri(githubApi.baseUrl());
        // We want to demonstrate successful caching without waiting for a the default 1 minute
        // Must set this to a large enough number to avoid flaky test
        GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS = 5;
        // Ensure we are working from sufficiently clean cache state
        Thread.sleep(Duration.ofSeconds(GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS + 2).toMillis());
        final String gitCheckoutStep = String.format("    git url: REPO, credentialsId: '%s'", myAppCredentialsId);
        final String jenkinsfile = String.join("\n", "// run checkout several times", "node ('my-agent') {", "    echo 'First Checkout on agent should use cached token passed via remoting'", gitCheckoutStep, "    echo 'Multiple checkouts in quick succession should use cached token'", gitCheckoutStep, "    sleep " + (GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS + 2), "    echo 'Checkout after token is stale refreshes via remoting - fallback due to unexpired token'", gitCheckoutStep, "    echo 'Checkout after error will refresh again on controller - new token expired but not stale'", gitCheckoutStep, "    sleep " + (GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS + 2), "    echo 'Checkout after token is stale refreshes via remoting - error on controller is not catastrophic'", gitCheckoutStep, "    echo 'Checkout after error will refresh again on controller - new token expired but not stale'", gitCheckoutStep, "    echo 'Multiple checkouts in quick succession should use cached token'", gitCheckoutStep, "}");
        // Create a repo with the above Jenkinsfile
        sampleRepo.init();
        sampleRepo.write("Jenkinsfile", jenkinsfile);
        sampleRepo.git("add", "Jenkinsfile");
        sampleRepo.git("commit", "--message=init");
        // Create a pipeline job that points the above repo
        WorkflowJob job = r.createProject(WorkflowJob.class, "test-creds");
        job.setDefinition(new CpsFlowDefinition(jenkinsfile, false));
        job.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("REPO", sampleRepo.toString())));
        WorkflowRun run = job.scheduleBuild2(0).waitForStart();
        r.waitUntilNoActivity();
        System.out.println(JenkinsRule.getLog(run));
        List<String> credentialsLog = getOutputLines();
        // Verify correct messages from GitHubAppCredential logger indicating token was retrieved on
        // agent
        assertThat("Creds should cache on master, pass to agent, and refresh agent from master once", credentialsLog, contains(// 1
        "Generating App Installation Token for app ID 54321 on agent", // 2
        "Failed to generate new GitHub App Installation Token for app ID 54321 on agent: cached token is stale but has not expired", // 3
        "Generating App Installation Token for app ID 54321 on agent", // checkout scm
        "Generating App Installation Token for app ID 54321", // checkout scm
        "Generating App Installation Token for app ID 54321", // (error forced by wiremock)
        "Failed to generate new GitHub App Installation Token for app ID 54321: cached token is stale but has not expired", // "Generating App Installation Token for app ID 54321 on agent", // 1
        "Generating App Installation Token for app ID 54321 for agent", // checkout scm - refresh on controller
        "Generating App Installation Token for app ID 54321", // checkout scm
        "Generating App Installation Token for app ID 54321", // (error forced by wiremock)
        "Failed to update stale GitHub App installation token for app ID 54321 before sending to agent", // "Generating App Installation Token for app ID 54321 on agent", // 3
        "Generating App Installation Token for app ID 54321 for agent", // checkout scm - refresh on controller
        "Generating App Installation Token for app ID 54321"));
        // Check success after output.  Output will be more informative if something goes wrong.
        assertThat(run.getResult(), equalTo(Result.SUCCESS));
        // Getting the token for via AuthorizationProvider on controller should not check rate_limit
        // Getting the token for agents via remoting to the controller should not check rate_limit
        githubApi.verify(0, RequestPatternBuilder.newRequestPattern(RequestMethod.GET, urlPathEqualTo("/rate_limit")));
    } finally {
        GitHubAppCredentials.AppInstallationToken.NOT_STALE_MINIMUM_SECONDS = notStaleSeconds;
        logRecorder.doClear();
    }
}
Also used : StringParameterDefinition(hudson.model.StringParameterDefinition) CpsFlowDefinition(org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition) ParametersDefinitionProperty(hudson.model.ParametersDefinitionProperty) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Test(org.junit.Test)

Example 32 with StringParameterDefinition

use of hudson.model.StringParameterDefinition in project mercurial-plugin by jenkinsci.

the class SCMTestBase method pollingExpandsParameterDefaults.

@Issue("JENKINS-9686")
@Test
public void pollingExpandsParameterDefaults() throws Exception {
    m.hg(repo, "init");
    m.touchAndCommit(repo, "trunk");
    m.hg(repo, "update", "null");
    m.hg(repo, "branch", "b");
    m.touchAndCommit(repo, "variant");
    FreeStyleProject p = j.createFreeStyleProject();
    p.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("branch", "default")));
    p.setScm(new MercurialSCM(hgInstallation(), repo.getPath(), "${branch}", null, null, null, false));
    String log = m.buildAndCheck(p, "trunk", new ParametersAction(new StringParameterValue("branch", "default")));
    assertTrue(log, log.contains("--rev default"));
    /* TODO cannot behave sensibly when workspace contains a branch build because the *current* trunk revision will be seen as new; would need to compare to all historical build records, or keep a separate workspace per branch:
        log = m.buildAndCheck(p, "variant", new ParametersAction(new StringParameterValue("branch", "b")));
        assertTrue(log, log.contains("--rev b"));
        */
    assertEquals(PollingResult.Change.NONE, m.pollSCMChanges(p).change);
    m.hg(repo, "update", "default");
    m.touchAndCommit(repo, "trunk2");
    assertEquals(PollingResult.Change.SIGNIFICANT, m.pollSCMChanges(p).change);
}
Also used : StringParameterDefinition(hudson.model.StringParameterDefinition) ParametersDefinitionProperty(hudson.model.ParametersDefinitionProperty) StringParameterValue(hudson.model.StringParameterValue) FreeStyleProject(hudson.model.FreeStyleProject) ParametersAction(hudson.model.ParametersAction) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Example 33 with StringParameterDefinition

use of hudson.model.StringParameterDefinition in project http-request-plugin by jenkinsci.

the class HttpRequestTest method replaceParametersInCustomHeaders.

@Test
public void replaceParametersInCustomHeaders() throws Exception {
    // Prepare the server
    registerCustomHeadersResolved();
    // Prepare HttpRequest
    HttpRequest httpRequest = new HttpRequest(baseURL() + "/customHeadersResolved");
    httpRequest.setConsoleLogResponseBody(true);
    // Activate requsetBody
    httpRequest.setHttpMode(HttpMode.POST);
    // Add some custom headers
    List<HttpRequestNameValuePair> customHeaders = new ArrayList<>();
    customHeaders.add(new HttpRequestNameValuePair("resolveCustomParam", "${Tag}"));
    customHeaders.add(new HttpRequestNameValuePair("resolveEnvParam", "${WORKSPACE}"));
    httpRequest.setCustomHeaders(customHeaders);
    // Activate passBuildParameters
    httpRequest.setPassBuildParameters(true);
    // Run build
    FreeStyleProject project = this.j.createFreeStyleProject();
    project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("Tag", "default"), new StringParameterDefinition("WORKSPACE", "default")));
    project.getBuildersList().add(httpRequest);
    FreeStyleBuild build = project.scheduleBuild2(0, new UserIdCause(), new ParametersAction(new StringParameterValue("Tag", "trunk"), new StringParameterValue("WORKSPACE", "C:/path/to/my/workspace"))).get();
    // Check expectations
    this.j.assertBuildStatusSuccess(build);
    this.j.assertLogContains(ALL_IS_WELL, build);
    this.j.assertLogContains("Success: Status code 200 is in the accepted range: 100:399", build);
}
Also used : StringParameterDefinition(hudson.model.StringParameterDefinition) ParametersDefinitionProperty(hudson.model.ParametersDefinitionProperty) ArrayList(java.util.ArrayList) StringParameterValue(hudson.model.StringParameterValue) HttpRequestNameValuePair(jenkins.plugins.http_request.util.HttpRequestNameValuePair) FreeStyleBuild(hudson.model.FreeStyleBuild) FreeStyleProject(hudson.model.FreeStyleProject) ParametersAction(hudson.model.ParametersAction) UserIdCause(hudson.model.Cause.UserIdCause) Test(org.junit.Test)

Example 34 with StringParameterDefinition

use of hudson.model.StringParameterDefinition in project throttle-concurrent-builds-plugin by jenkinsci.

the class ThrottleJobPropertyPipelineTest method limitOneJobWithMatchingParams.

@Issue("JENKINS-37809")
@Test
public void limitOneJobWithMatchingParams() throws Exception {
    Node agent = TestUtil.setupAgent(j, firstAgentTmp, agents, null, 2, null);
    WorkflowJob project = j.createProject(WorkflowJob.class);
    ParametersDefinitionProperty pdp = new ParametersDefinitionProperty(new StringParameterDefinition("FOO", "foo", ""), new StringParameterDefinition("BAR", "bar", ""));
    project.addProperty(pdp);
    project.setConcurrentBuild(true);
    project.setDefinition(getJobFlow(project.getName(), agent.getNodeName()));
    project.addProperty(new ThrottleJobProperty(// maxConcurrentPerNode
    null, // maxConcurrentTotal
    null, Collections.emptyList(), // throttleEnabled
    true, // throttleOption
    TestUtil.THROTTLE_OPTION_PROJECT, true, "FOO,BAR", ThrottleMatrixProjectOptions.DEFAULT));
    WorkflowRun firstRun = project.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("wait-" + project.getName() + "-job/1", firstRun);
    QueueTaskFuture<WorkflowRun> secondRunFuture = project.scheduleBuild2(0);
    j.jenkins.getQueue().maintain();
    assertFalse(j.jenkins.getQueue().isEmpty());
    List<Queue.Item> queuedItemList = Arrays.stream(j.jenkins.getQueue().getItems()).collect(Collectors.toList());
    assertEquals(1, queuedItemList.size());
    Queue.Item queuedItem = queuedItemList.get(0);
    Set<String> blockageReasons = TestUtil.getBlockageReasons(queuedItem.getCauseOfBlockage());
    assertThat(blockageReasons, hasItem(Messages._ThrottleQueueTaskDispatcher_OnlyOneWithMatchingParameters().toString()));
    assertEquals(1, agent.toComputer().countBusy());
    TestUtil.hasPlaceholderTaskForRun(agent, firstRun);
    SemaphoreStep.success("wait-" + project.getName() + "-job/1", null);
    j.assertBuildStatusSuccess(j.waitForCompletion(firstRun));
    WorkflowRun secondRun = secondRunFuture.waitForStart();
    SemaphoreStep.waitForStart("wait-" + project.getName() + "-job/2", secondRun);
    j.jenkins.getQueue().maintain();
    assertTrue(j.jenkins.getQueue().isEmpty());
    assertEquals(1, agent.toComputer().countBusy());
    TestUtil.hasPlaceholderTaskForRun(agent, secondRun);
    SemaphoreStep.success("wait-" + project.getName() + "-job/2", null);
    j.assertBuildStatusSuccess(j.waitForCompletion(secondRun));
}
Also used : StringParameterDefinition(hudson.model.StringParameterDefinition) Node(hudson.model.Node) WorkflowRun(org.jenkinsci.plugins.workflow.job.WorkflowRun) Matchers.hasItem(org.hamcrest.Matchers.hasItem) ParametersDefinitionProperty(hudson.model.ParametersDefinitionProperty) WorkflowJob(org.jenkinsci.plugins.workflow.job.WorkflowJob) Queue(hudson.model.Queue) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Example 35 with StringParameterDefinition

use of hudson.model.StringParameterDefinition in project branch-api-plugin by jenkinsci.

the class OrganizationFolderTest method verifyBranchPropertiesAppliedOnNewProjects.

@Issue("JENKINS-48837")
@Test
public void verifyBranchPropertiesAppliedOnNewProjects() throws Exception {
    try (MockSCMController c = MockSCMController.create()) {
        c.createRepository("stuff");
        OrganizationFolder top = r.jenkins.createProject(OrganizationFolder.class, "top");
        List<MultiBranchProjectFactory> projectFactories = top.getProjectFactories();
        assertThat(projectFactories, extracting(f -> f.getDescriptor(), hasItem(ExtensionList.lookupSingleton(ConfigRoundTripDescriptor.class))));
        top.getNavigators().add(new SingleSCMNavigator("stuff", Collections.<SCMSource>singletonList(new SingleSCMSource("stuffy", new MockSCM(c, "stuff", new MockSCMHead("master"), null)))));
        OrganizationFolderBranchProperty instance = new OrganizationFolderBranchProperty();
        instance.setParameterDefinitions(Collections.<ParameterDefinition>singletonList(new StringParameterDefinition("PARAM_STR", "PARAM_DEFAULT_0812673", "The param")));
        top.setStrategy(new DefaultBranchPropertyStrategy(new BranchProperty[] { instance }));
        top = r.configRoundtrip(top);
        top.scheduleBuild(0);
        r.waitUntilNoActivity();
        // get the child project produced by the factory after scan
        MultiBranchImpl prj = (MultiBranchImpl) top.getItem("stuff");
        // verify new multibranch project have branch properties inherited from folder
        assertThat(prj.getSources().get(0).getStrategy(), instanceOf(DefaultBranchPropertyStrategy.class));
        DefaultBranchPropertyStrategy strategy = (DefaultBranchPropertyStrategy) prj.getSources().get(0).getStrategy();
        assertThat(strategy.getProps().get(0), instanceOf(OrganizationFolderBranchProperty.class));
        OrganizationFolderBranchProperty property = (OrganizationFolderBranchProperty) strategy.getProps().get(0);
        assertThat(property.getParameterDefinitions(), contains(allOf(instanceOf(StringParameterDefinition.class), hasProperty("name", is("PARAM_STR")), hasProperty("defaultValue", is("PARAM_DEFAULT_0812673")), hasProperty("description", is("The param")))));
    }
}
Also used : Arrays(java.util.Arrays) Issue(org.jvnet.hudson.test.Issue) View(hudson.model.View) DataBoundConstructor(org.kohsuke.stapler.DataBoundConstructor) ChildObserver(com.cloudbees.hudson.plugins.folder.computed.ChildObserver) BasicMultiBranchProjectFactory(integration.harness.BasicMultiBranchProjectFactory) Map(java.util.Map) Item(hudson.model.Item) MockSCMNavigator(jenkins.scm.impl.mock.MockSCMNavigator) ComputedFolder(com.cloudbees.hudson.plugins.folder.computed.ComputedFolder) TestExtension(org.jvnet.hudson.test.TestExtension) Set(java.util.Set) BasicMultiBranchProject(integration.harness.BasicMultiBranchProject) ItemGroup(hudson.model.ItemGroup) MockSCMDiscoverTags(jenkins.scm.impl.mock.MockSCMDiscoverTags) List(java.util.List) Assert.assertFalse(org.junit.Assert.assertFalse) Result(hudson.model.Result) Permission(hudson.security.Permission) StringParameterDefinition(hudson.model.StringParameterDefinition) Extracting.extracting(jenkins.branch.matchers.Extracting.extracting) Assume.assumeThat(org.junit.Assume.assumeThat) MockSCMDiscoverBranches(jenkins.scm.impl.mock.MockSCMDiscoverBranches) Level(java.util.logging.Level) HashSet(java.util.HashSet) SCMSource(jenkins.scm.api.SCMSource) LoggerRule(org.jvnet.hudson.test.LoggerRule) User(hudson.model.User) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ParameterDefinition(hudson.model.ParameterDefinition) TaskListener(hudson.model.TaskListener) Authentication(org.acegisecurity.Authentication) MockSCMHead(jenkins.scm.impl.mock.MockSCMHead) MockSCMDiscoverChangeRequests(jenkins.scm.impl.mock.MockSCMDiscoverChangeRequests) Matchers(org.hamcrest.Matchers) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) SCMNavigator(jenkins.scm.api.SCMNavigator) NullSCM(hudson.scm.NullSCM) MockSCM(jenkins.scm.impl.mock.MockSCM) SingleSCMNavigator(jenkins.scm.impl.SingleSCMNavigator) Rule(org.junit.Rule) SingleSCMSource(jenkins.scm.impl.SingleSCMSource) MultiBranchImpl(jenkins.branch.harness.MultiBranchImpl) JenkinsRule(org.jvnet.hudson.test.JenkinsRule) Collections(java.util.Collections) ExtensionList(hudson.ExtensionList) Assert.assertEquals(org.junit.Assert.assertEquals) MockSCMController(jenkins.scm.impl.mock.MockSCMController) StringParameterDefinition(hudson.model.StringParameterDefinition) BasicMultiBranchProjectFactory(integration.harness.BasicMultiBranchProjectFactory) SingleSCMNavigator(jenkins.scm.impl.SingleSCMNavigator) SCMSource(jenkins.scm.api.SCMSource) SingleSCMSource(jenkins.scm.impl.SingleSCMSource) MockSCMController(jenkins.scm.impl.mock.MockSCMController) MultiBranchImpl(jenkins.branch.harness.MultiBranchImpl) SingleSCMSource(jenkins.scm.impl.SingleSCMSource) MockSCMHead(jenkins.scm.impl.mock.MockSCMHead) MockSCM(jenkins.scm.impl.mock.MockSCM) Issue(org.jvnet.hudson.test.Issue) Test(org.junit.Test)

Aggregations

StringParameterDefinition (hudson.model.StringParameterDefinition)95 ParametersDefinitionProperty (hudson.model.ParametersDefinitionProperty)82 Test (org.junit.Test)77 FreeStyleProject (hudson.model.FreeStyleProject)69 ParametersAction (hudson.model.ParametersAction)45 StringParameterValue (hudson.model.StringParameterValue)44 FreeStyleBuild (hudson.model.FreeStyleBuild)43 Issue (org.jvnet.hudson.test.Issue)26 ParameterDefinition (hudson.model.ParameterDefinition)24 WorkflowJob (org.jenkinsci.plugins.workflow.job.WorkflowJob)16 FileWriteBuilder (hudson.plugins.copyartifact.testutils.FileWriteBuilder)15 ArtifactArchiver (hudson.tasks.ArtifactArchiver)15 Shell (hudson.tasks.Shell)15 Cause (hudson.model.Cause)12 ArrayList (java.util.ArrayList)11 CIMessageNotifier (com.redhat.jenkins.plugins.ci.CIMessageNotifier)10 CpsFlowDefinition (org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition)10 BooleanParameterDefinition (hudson.model.BooleanParameterDefinition)9 PromotionProcess (hudson.plugins.promoted_builds.PromotionProcess)9 WorkflowRun (org.jenkinsci.plugins.workflow.job.WorkflowRun)9