Java Code Examples for hudson.tasks.Shell

The following examples show how to use hudson.tasks.Shell. 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: PipelineApiTest.java    License: MIT License 8 votes vote down vote up
@Test
public void findPipelineRunsForAPipelineTest() throws Exception {
    FreeStyleProject p1 = j.createFreeStyleProject("pipeline1");
    FreeStyleProject p2 = j.createFreeStyleProject("pipeline2");
    p1.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    p2.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    Stack<FreeStyleBuild> builds = new Stack<FreeStyleBuild>();
    FreeStyleBuild b11 = p1.scheduleBuild2(0).get();
    FreeStyleBuild b12 = p1.scheduleBuild2(0).get();
    builds.push(b11);
    builds.push(b12);

    j.assertBuildStatusSuccess(b11);
    j.assertBuildStatusSuccess(b12);

    List<Map> resp = get("/search?q=type:run;organization:jenkins;pipeline:pipeline1", List.class);

    assertEquals(builds.size(), resp.size());
    for(int i=0; i< builds.size(); i++){
        Map p = resp.get(i);
        FreeStyleBuild b = builds.pop();
        validateRun(b, p);
    }
}
 
Example #2
Source Project: warnings-ng-plugin   Author: jenkinsci   File: DockerContainerITest.java    License: MIT License 6 votes vote down vote up
/**
 * Runs a make file to compile a cpp file 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 shouldBuildMakefileOnAgent() throws IOException, InterruptedException {
    assumeThat(isWindows()).as("Running on Windows").isFalse();

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

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

    createFileInAgentWorkspace(agent, project, "test.cpp", getSampleCppFile());
    createFileInAgentWorkspace(agent, project, "makefile", getSampleMakefileFile());
    project.getBuildersList().add(new Shell("make"));
    enableWarnings(project, createTool(new Gcc4(), ""));

    scheduleSuccessfulBuild(project);

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

    assertThat(result).hasTotalSize(1);
    assertThat(lastBuild.getBuiltOn().getLabelString()).isEqualTo(((Node) agent).getLabelString());
}
 
Example #3
Source Project: jenkins-client-java   Author: jenkins-zh   File: JobsTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getLogText() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject project = j.createFreeStyleProject();
    FreeStyleBuild build = project.scheduleBuild2(0).waitForStart();
    j.waitForCompletion(build);

    String log = jobs.getLogText(project.getName(), 1);
    assertNotNull(log);
    assertThat(log, containsString("Finished:"));

    project.getBuildersList().add(new Shell("echo hello"));
    build = project.scheduleBuild2(0).waitForStart();
    j.waitForCompletion(build);
    log = jobs.getLogText(project.getName(), 2);
    assertThat(log, containsString("hello"));
}
 
Example #4
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getPipelinesTest() throws Exception {

    Project p2 = j.createFreeStyleProject("pipeline2");
    Project p1 = j.createFreeStyleProject("pipeline1");

    List<Map> responses = get("/search/?q=type:pipeline", List.class);
    assertEquals(2, responses.size());
    validatePipeline(p1, responses.get(0));
    validatePipeline(p2, responses.get(1));

    p1.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    FreeStyleBuild b = (FreeStyleBuild) p1.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b);


}
 
Example #5
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getFreeStyleJobTest() throws Exception {
    Project p1 = j.createFreeStyleProject("pipeline1");
    Project p2 = j.createFreeStyleProject("pipeline2");
    p1.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    FreeStyleBuild b = (FreeStyleBuild) p1.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b);

    List<Map> resp = get("/organizations/jenkins/pipelines/", List.class);
    Project[] projects = {p1,p2};

    assertEquals(projects.length, resp.size());

    for(int i=0; i<projects.length; i++){
        Map p = resp.get(i);
        validatePipeline(projects[i], p);
    }
}
 
Example #6
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getPipelineRunWithTestResult() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pipeline4");
    p.getBuildersList().add(new Shell("echo '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<testsuite xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd\" name=\"io.jenkins.blueocean.jsextensions.JenkinsJSExtensionsTest\" time=\"35.7\" tests=\"1\" errors=\"0\" skipped=\"0\" failures=\"0\">\n" +
        "  <properties>\n" +
        "  </properties>\n" +
        "  <testcase name=\"test\" classname=\"io.jenkins.blueocean.jsextensions.JenkinsJSExtensionsTest\" time=\"34.09\"/>\n" +
        "</testsuite>' > test-result.xml"));

    p.getPublishersList().add(new JUnitResultArchiver("*.xml"));
    FreeStyleBuild b = p.scheduleBuild2(0).get();
    TestResultAction resultAction = b.getAction(TestResultAction.class);
    assertEquals("io.jenkins.blueocean.jsextensions.JenkinsJSExtensionsTest",resultAction.getResult().getSuites().iterator().next().getName());
    j.assertBuildStatusSuccess(b);
    Map resp = get("/organizations/jenkins/pipelines/pipeline4/runs/"+b.getId());

    //discover TestResultAction super classes
    get("/classes/hudson.tasks.junit.TestResultAction/");

    // get junit rest report
    get("/organizations/jenkins/pipelines/pipeline4/runs/"+b.getId()+"/testReport/result/");
}
 
Example #7
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getPipelineRunLatestTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pipeline5");
    p.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    FreeStyleBuild b = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b);

    List<Map> resp = get("/search?q=type:run;organization:jenkins;pipeline:pipeline5;latestOnly:true", List.class);
    Run[] run = {b};

    assertEquals(run.length, resp.size());

    for(int i=0; i<run.length; i++){
        Map lr = resp.get(i);
        validateRun(run[i], lr);
    }
}
 
Example #8
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void getPipelineRunsStopTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("p1");
    p.getBuildersList().add(new Shell("sleep 600000"));
    FreeStyleBuild b = p.scheduleBuild2(0).waitForStart();

    //wait till its running
    do{
        Thread.sleep(10); //sleep for 10ms
    }while(b.hasntStartedYet());

    Map resp = put("/organizations/jenkins/pipelines/p1/runs/"+b.getId()+"/stop/?blocking=true", Map.class);

    // we can't actually guarantee that jenkins will stop it
    assertTrue(resp.get("result").equals("ABORTED") || resp.get("result").equals("UNKNOWN"));
}
 
Example #9
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void findPipelineRunsForAllPipelineTest() throws IOException, ExecutionException, InterruptedException {
    FreeStyleProject p1 = j.createFreeStyleProject("pipeline11");
    FreeStyleProject p2 = j.createFreeStyleProject("pipeline22");
    p1.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    p2.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    Stack<FreeStyleBuild> p1builds = new Stack<FreeStyleBuild>();
    p1builds.push(p1.scheduleBuild2(0).get());
    p1builds.push(p1.scheduleBuild2(0).get());

    Stack<FreeStyleBuild> p2builds = new Stack<FreeStyleBuild>();
    p2builds.push(p2.scheduleBuild2(0).get());
    p2builds.push(p2.scheduleBuild2(0).get());

    Map<String, Stack<FreeStyleBuild>> buildMap = ImmutableMap.of(p1.getName(), p1builds, p2.getName(), p2builds);

    List<Map> resp = get("/search?q=type:run;organization:jenkins", List.class);

    assertEquals(4, resp.size());
    for(int i=0; i< 4; i++){
        Map p = resp.get(i);
        String pipeline = (String) p.get("pipeline");
        assertNotNull(pipeline);
        validateRun(buildMap.get(pipeline).pop(), p);
    }
}
 
Example #10
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testPipelineQueue() throws Exception {
    FreeStyleProject p1 = j.createFreeStyleProject("pipeline1");

    p1.setConcurrentBuild(true);
    p1.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("test","test")));
    p1.getBuildersList().add(new Shell("echo hello!\nsleep 300"));

    p1.scheduleBuild2(0).waitForStart();
    p1.scheduleBuild2(0).waitForStart();
    Jenkins.getInstance().getQueue().schedule(p1, 0, new ParametersAction(new StringParameterValue("test","test1")), new CauseAction(new Cause.UserIdCause()));
    Jenkins.getInstance().getQueue().schedule(p1, 0, new ParametersAction(new StringParameterValue("test","test2")), new CauseAction(new Cause.UserIdCause()));

    List queue = request().get("/organizations/jenkins/pipelines/pipeline1/queue").build(List.class);
    Assert.assertEquals(2, queue.size());
    Assert.assertEquals(4, ((Map) queue.get(0)).get("expectedBuildNumber"));
    Assert.assertEquals(3, ((Map) queue.get(1)).get("expectedBuildNumber"));
    Assert.assertEquals("Waiting for next available executor", ((Map) queue.get(0)).get("causeOfBlockage"));
    Assert.assertEquals("Waiting for next available executor", ((Map) queue.get(1)).get("causeOfBlockage"));

    Run r = QueueUtil.getRun(p1, Long.parseLong((String)((Map)queue.get(0)).get("id")));
    assertNull(r); //its not moved out of queue yet
}
 
Example #11
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void parameterizedFreestyleTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pp");
    p.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition("version", "1.0", "version number")));
    p.getBuildersList().add(new Shell("echo hello!"));

    Map resp = get("/organizations/jenkins/pipelines/pp/");

    List<Map<String,Object>> parameters = (List<Map<String, Object>>) resp.get("parameters");
    assertEquals(1, parameters.size());
    assertEquals("version", parameters.get(0).get("name"));
    assertEquals("StringParameterDefinition", parameters.get(0).get("type"));
    assertEquals("version number", parameters.get(0).get("description"));
    assertEquals("1.0", ((Map)parameters.get(0).get("defaultParameterValue")).get("value"));
    validatePipeline(p, resp);

    resp = post("/organizations/jenkins/pipelines/pp/runs/",
            ImmutableMap.of("parameters",
                    ImmutableList.of(ImmutableMap.of("name", "version", "value", "2.0"))
            ), 200);
    assertEquals("pp", resp.get("pipeline"));
    Thread.sleep(1000);
    resp = get("/organizations/jenkins/pipelines/pp/runs/1/");
    assertEquals("SUCCESS", resp.get("result"));
    assertEquals("FINISHED", resp.get("state"));
}
 
Example #12
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void parameterizedFreestyleTestWithoutDefaultParam() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pp");
    p.addProperty(new ParametersDefinitionProperty(new TestStringParameterDefinition("version", null, "version number")));
    p.getBuildersList().add(new Shell("echo hello!"));

    Map resp = get("/organizations/jenkins/pipelines/pp/");

    List<Map<String,Object>> parameters = (List<Map<String, Object>>) resp.get("parameters");
    assertEquals(1, parameters.size());
    assertEquals("version", parameters.get(0).get("name"));
    assertEquals("TestStringParameterDefinition", parameters.get(0).get("type"));
    assertEquals("version number", parameters.get(0).get("description"));
    assertNull(parameters.get(0).get("defaultParameterValue"));
    validatePipeline(p, resp);

    resp = post("/organizations/jenkins/pipelines/pp/runs/",
            ImmutableMap.of("parameters",
                    ImmutableList.of()
            ), 400);
}
 
Example #13
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void actionsTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pipeline1");
    p.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    FreeStyleBuild b = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b);

    Map resp = get("/organizations/jenkins/pipelines/pipeline1/", Map.class);
    List<Map> actions = (List<Map>) resp.get("actions");
    Assert.assertTrue(actions.isEmpty());
    actions = (List<Map>) ((Map)resp.get("latestRun")).get("actions");

    resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/", Map.class);
    actions = (List<Map>) resp.get("actions");
    Assert.assertTrue(actions.isEmpty());

    resp = get("/organizations/jenkins/pipelines/pipeline1/runs/1/?tree=*[*]", Map.class);
    actions = (List<Map>) resp.get("actions");
    Assert.assertFalse(actions.isEmpty());
}
 
Example #14
Source Project: blueocean-plugin   Author: jenkinsci   File: ArtifactContainerImplTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testArtifactsListing() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject(JOB_NAME);
    p.getBuildersList().add(new Shell("#!/bin/bash\nmkdir -p test/me/out; cd test/me/out; touch {0..105}.txt"));
    p.getPublishersList().add(new ArtifactArchiver("**/*"));
    Run r = p.scheduleBuild2(0).waitForStart();

    r = j.waitForCompletion(r);

    List artifacts = request().get("/organizations/jenkins/pipelines/"+JOB_NAME+"/runs/"+r.getId()+"/artifacts").build(List.class);

    Assert.assertEquals(100, artifacts.size());
    Assert.assertEquals(0, ((Map) artifacts.get(0)).get("size"));
    Assert.assertEquals("test/me/out/0.txt", ((Map) artifacts.get(0)).get("path"));
    Assert.assertEquals("/job/artifactTest/1/artifact/test/me/out/0.txt", ((Map) artifacts.get(0)).get("url"));
 }
 
Example #15
Source Project: marathon-plugin   Author: jenkinsci   File: MarathonRecorderTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test that when "marathon.json" is not present the build is failed
 * and no requests are made to the configured Marathon instance.
 *
 * @throws Exception
 */
@Test
public void testRecorderNoFile() throws Exception {
    final FreeStyleProject project = j.createFreeStyleProject();
    project.getBuildersList().add(new Shell("echo hello"));

    // add recorder
    project.getPublishersList().add(new MarathonRecorder(TestUtils.getHttpAddresss(httpServer)));

    // run a build with the shell step and recorder publisher
    final FreeStyleBuild build = j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
    // assert things
    j.assertLogContains("[Marathon]", build);
    j.assertLogContains("marathon.json", build);
    assertEquals("No web requests were made", 0, httpServer.getRequestCount());
}
 
Example #16
Source Project: yet-another-docker-plugin   Author: KostyaSha   File: FreestyleTest.java    License: MIT License 6 votes vote down vote up
@Override
public Boolean call() throws Throwable {
    final Jenkins jenkins = Jenkins.getInstance();

    // prepare job
    final FreeStyleProject project = jenkins.createProject(FreeStyleProject.class, "freestyle-project");
    final Shell env = new Shell("env");
    project.getBuildersList().add(env);
    project.setAssignedLabel(new LabelAtom(DOCKER_CLOUD_LABEL));
    project.save();

    LOG.trace("trace test.");
    project.scheduleBuild(new TestCause());

    // image pull may take time
    waitUntilNoActivityUpTo(jenkins, 10 * 60 * 1000);

    final FreeStyleBuild lastBuild = project.getLastBuild();
    assertThat(lastBuild, not(nullValue()));
    assertThat(lastBuild.getResult(), is(Result.SUCCESS));

    assertThat(getLog(lastBuild), Matchers.containsString(TEST_VALUE));
    assertThat(getLog(lastBuild), Matchers.containsString(CLOUD_ID + "=" + DOCKER_CLOUD_NAME));

    return true;
}
 
Example #17
Source Project: yet-another-docker-plugin   Author: KostyaSha   File: DockerSimpleBuildWrapperTest.java    License: MIT License 6 votes vote down vote up
@Ignore("For local experiments")
@Test
public void testWrapper() throws Exception {
    final FreeStyleProject project = jRule.createProject(FreeStyleProject.class, "freestyle");

    final DockerConnector connector = new DockerConnector("tcp://" + ADDRESS + ":2376/");
    connector.setConnectorType(JERSEY);

    final DockerSlaveConfig config = new DockerSlaveConfig();
    config.getDockerContainerLifecycle().setImage("java:8-jdk-alpine");
    config.setLauncher(new NoOpDelegatingComputerLauncher(new DockerComputerSingleJNLPLauncher()));
    config.setRetentionStrategy(new DockerOnceRetentionStrategy(10));

    final DockerSimpleBuildWrapper dockerSimpleBuildWrapper = new DockerSimpleBuildWrapper(connector, config);
    project.getBuildWrappersList().add(dockerSimpleBuildWrapper);
    project.getBuildersList().add(new Shell("sleep 30"));

    final QueueTaskFuture<FreeStyleBuild> taskFuture = project.scheduleBuild2(0);

    jRule.waitUntilNoActivity();
    jRule.pause();
}
 
Example #18
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 #19
Source Project: DotCi   Author: groupon   File: ShellScriptRunner.java    License: MIT License 6 votes vote down vote up
public Result runScript(final ShellCommands commands) throws IOException, InterruptedException {
    Result r = Result.FAILURE;
    //Todo: use VitualChannel to figure out OS
    final String shellInterpreter = Functions.isWindows() ? "sh" : "/bin/bash";
    final Run run = this.buildExecutionContext.getRun();
    addExecutionInfoAction(run, commands);
    try {
        final Shell execution = new Shell("#!" + shellInterpreter + " -le \n" + commands.toShellScript());
        if (this.buildExecutionContext.performStep(execution, this.listener)) {
            r = Result.SUCCESS;
        }
    } catch (final InterruptedException e) {
        r = Executor.currentExecutor().abortResult();
        throw e;
    } finally {
        this.buildExecutionContext.setResult(r);
    }
    return r;
}
 
Example #20
Source Project: credentials-binding-plugin   Author: jenkinsci   File: AlmquistShellSecretPatternFactoryTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("ash"));
    project = j.createProject(WorkflowJob.class);
    credentialsId = UUID.randomUUID().toString();

    project.setDefinition(new CpsFlowDefinition(
            "node {\n" +
                    "  withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
                    "    sh '''\n" +
                    "       echo begin0 $CREDENTIALS end0\n" +
                    // begin2 => 2 for double quotes
                    "       echo \"begin2 $CREDENTIALS end2\"\n" +
                    "    '''\n" +
                    "  }\n" +
                    "}", true));
}
 
Example #21
Source Project: credentials-binding-plugin   Author: jenkinsci   File: BuildWrapperOrderCredentialsBindingTest.java    License: MIT License 6 votes vote down vote up
@Issue("JENKINS-37871")
@Test public void secretBuildWrapperRunsBeforeNormalWrapper() throws Exception {
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample1", Secret.fromString(password));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding(bindingKey, credentialsId)));

    FreeStyleProject f = r.createFreeStyleProject("buildWrapperOrder");

    f.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo $PASS_1"));
    f.getBuildWrappersList().add(new BuildWrapperOrder());
    f.getBuildWrappersList().add(wrapper);

    // configRoundtrip makes sure the ordinal of SecretBuildWrapper extension is applied correctly.
    r.configRoundtrip(f);

    FreeStyleBuild b = r.buildAndAssertSuccess(f);
    r.assertLogContains("Secret found!", b);
}
 
Example #22
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 #23
Source Project: audit-log-plugin   Author: jenkinsci   File: BuildListenerTest.java    License: MIT License 5 votes vote down vote up
@Issue("JENKINS-55608, JENKINS-56645")
@Test
public void testAuditOnBuildStartAndFinish() throws Exception{
    project.getBuildersList().add(new Shell("echo Test audit-log-plugin"));
    project.scheduleBuild2(0).get();

    List<LogEvent> events = app.getEvents();

    assertThat(events).hasSize(3);
    assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).containsSequence("createItem", "buildStart", "buildFinish");
}
 
Example #24
Source Project: marathonv5   Author: jalian-systems   File: MarathonBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    if (OS.indexOf("win") >= 0) {
        return new BatchFile(marathonHome + "marathon.bat " + getCommand()).perform(build, launcher, listener);
    } else if (OS.indexOf("mac") >= 0 || OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0) {
        return new Shell(marathonHome + "marathon " + getCommand()).perform(build, launcher, listener);
    } else {
        listener.getLogger().println("Your system is not supported");
        return false;
    }

}
 
Example #25
Source Project: jenkins-client-java   Author: jenkins-zh   File: JobsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void stop() throws Exception {
    FreeStyleProject project = j.createFreeStyleProject();

    project.getBuildersList().add(new Shell("sleep 160"));
    project.scheduleBuild2(0).waitForStart();

    assertTrue(project.isBuilding());
    jobs.stop(project.getName(), 1);
    j.waitUntilNoActivityUpTo(6000);
    assertFalse(project.isBuilding());
}
 
Example #26
Source Project: jenkins-client-java   Author: jenkins-zh   File: JobsTest.java    License: MIT License 5 votes vote down vote up
@Test
public void buildWithParams() throws Exception {
    MatrixProject project = j.createProject(MatrixProject.class);

    final String name = "NAME";
    project.addProperty(new ParametersDefinitionProperty(new StringParameterDefinition(name, "")));

    project.getBuildersList().add(new Shell("echo env." + name));

    final Map<String, String> params = Collections.singletonMap(name, System.currentTimeMillis() + "-hello");
    jobs.buildWithParams(project.getName(), params);
    j.waitUntilNoActivity();
    assertEquals(1, project.getBuilds().size());
    assertThat(project.getBuild("1").getLog(), containsString(params.get(name)));
}
 
Example #27
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 5 votes vote down vote up
@Test
public void getPipelineRunTest() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("pipeline4");
    p.getBuildersList().add(new Shell("echo hello!\nsleep 1"));
    FreeStyleBuild b = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(b);
    Map resp = get("/organizations/jenkins/pipelines/pipeline4/runs/"+b.getId());
    validateRun(b,resp);
    String log = get("/organizations/jenkins/pipelines/pipeline4/runs/"+b.getId()+"/log", String.class);
    System.out.println(log);
    assertNotNull(log);
}
 
Example #28
Source Project: blueocean-plugin   Author: jenkinsci   File: PipelineApiTest.java    License: MIT License 5 votes vote down vote up
@Test
public void getPipelineRunsTest() 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);

    List<Map> resp = get("/organizations/jenkins/pipelines/pipeline6/runs", List.class);
    assertEquals(1, resp.size());

    Map lr = resp.get(0);
    validateRun(b, lr);
}
 
Example #29
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 #30
Source Project: blueocean-plugin   Author: jenkinsci   File: ArtifactContainerImplTest.java    License: MIT License 5 votes vote down vote up
@Test @Ignore
public void testArtifact() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject(JOB_NAME);
    p.getBuildersList().add(new Shell("mkdir -p test/me/out; touch test/me/out/{{a..z},{A..Z},{0..99}}.txt"));
    p.getPublishersList().add(new ArtifactArchiver("**/*"));
    Run r = p.scheduleBuild2(0).waitForStart();

    r = j.waitForCompletion(r);

    Map artifact = request().get("/organizations/jenkins/pipelines/"+JOB_NAME+"/runs/"+r.getId()+"/artifacts/test%252Fme%252Fout%252F0.txt").build(Map.class);

    Assert.assertEquals(100, artifact.size());
}