hudson.util.StreamTaskListener Java Examples

The following examples show how to use hudson.util.StreamTaskListener. 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 File: FromFingerprintStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
private void assertBuild(final String projectName, final String pipelineCode, final String fromImage) throws Exception {
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            assumeDocker();

            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, projectName);
            p.setDefinition(new CpsFlowDefinition(pipelineCode, true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            DockerClient client = new DockerClient(new LocalLauncher(StreamTaskListener.NULL), null, null);
            String ancestorImageId = client.inspect(new EnvVars(), fromImage, ".Id");
            story.j.assertLogContains(ancestorImageId.replaceFirst("^sha256:", "").substring(0, 12), b);
            Fingerprint f = DockerFingerprints.of(ancestorImageId);
            assertNotNull(f);
            DockerDescendantFingerprintFacet descendantFacet = f.getFacet(DockerDescendantFingerprintFacet.class);
            assertNotNull(descendantFacet);
        }
    });
}
 
Example #2
Source File: ContainerExecDecoratorTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
private ProcReturn execCommandInContainer(String containerName, Node node, boolean quiet, String... cmd) throws Exception {
    if (containerName != null && ! containerName.isEmpty()) {
        decorator.setContainerName(containerName);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Launcher launcher = decorator
            .decorate(new DummyLauncher(new StreamTaskListener(new TeeOutputStream(out, System.out))), node);
    Map<String, String> envs = new HashMap<>(100);
    for (int i = 0; i < 50; i++) {
        envs.put("aaaaaaaa" + i, "bbbbbbbb");
    }
    envs.put("workingDir1", "/home/jenkins/agent");

    ContainerExecProc proc = (ContainerExecProc) launcher
            .launch(launcher.new ProcStarter().pwd("/tmp").cmds(cmd).envs(envs).quiet(quiet));
    // wait for proc to finish (shouldn't take long)
    for (int i = 0; proc.isAlive() && i < 200; i++) {
        Thread.sleep(100);
    }
    assertFalse("proc is alive", proc.isAlive());
    int exitCode = proc.join();
    return new ProcReturn(proc, exitCode, out.toString());
}
 
Example #3
Source File: MavenPublisherStrategyTest.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Test
public void listMavenPublishers() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    List<MavenPublisher> mavenPublishers = MavenPublisherStrategy.IMPLICIT.buildPublishersList(Collections.<MavenPublisher>emptyList(), new StreamTaskListener(baos));
    Assert.assertThat(mavenPublishers.size(), CoreMatchers.is(12));

    Map<String, MavenPublisher> reportersByDescriptorId = new HashMap<>();
    for(MavenPublisher mavenPublisher : mavenPublishers) {
        reportersByDescriptorId.put(mavenPublisher.getDescriptor().getId(), mavenPublisher);
    }
    assertThat(reportersByDescriptorId.containsKey(new GeneratedArtifactsPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new FindbugsAnalysisPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new SpotBugsAnalysisPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new JunitTestsPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new TasksScannerPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new PipelineGraphPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new InvokerRunsPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new ConcordionTestsPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new JGivenTestsPublisher.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new MavenLinkerPublisher2.DescriptorImpl().getId()), is(true));
    assertThat(reportersByDescriptorId.containsKey(new JacocoReportPublisher.DescriptorImpl().getId()), is(true));
}
 
Example #4
Source File: SmartCredentialsProviderTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    listener = StreamTaskListener.fromStdout();
    provider = new SmartCredentialsProvider(listener);
    username = new CredentialItem.Username();
    password = new CredentialItem.Password();

    maskedUsername = new StandardUsernameCredentialsCredentialItem(MASKED_USER_NAME_PROMPT, true);
    unmaskedUsername = new StandardUsernameCredentialsCredentialItem(UNMASKED_USER_NAME_PROMPT, false);

    maskedStringType = new CredentialItem.StringType(MASKED_STRING_TYPE_PROMPT, true);
    unmaskedStringType = new CredentialItem.StringType(UNMASKED_STRING_TYPE_PROMPT, false);
    specialStringType = new CredentialItem.StringType(SPECIAL_STRING_TYPE_PROMPT, false);

    assertNull(username.getValue());
    assertNull(password.getValue());
    assertNull(maskedUsername.getValue());
    assertNull(unmaskedUsername.getValue());
    assertNull(maskedStringType.getValue());
    assertNull(unmaskedStringType.getValue());
}
 
Example #5
Source File: PushTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Before
public void createWorkingRepository() throws IOException, InterruptedException, URISyntaxException {
    hudson.EnvVars env = new hudson.EnvVars();
    TaskListener listener = StreamTaskListener.fromStderr();
    List<RefSpec> refSpecs = new ArrayList<>();
    workingRepo = temporaryFolder.newFolder();
    workingGitClient = Git.with(listener, env).in(workingRepo).using(gitImpl).getClient();
    workingGitClient.clone_()
            .url(bareRepo.getAbsolutePath())
            .repositoryName("origin")
            .execute();
    workingGitClient.checkout()
            .branch(branchName)
            .deleteBranchIfExist(true)
            .ref("origin/" + branchName)
            .execute();
    assertNotNull(bareFirstCommit);
    assertTrue("Clone does not contain " + bareFirstCommit,
            workingGitClient.revList("origin/" + branchName).contains(bareFirstCommit));
    ObjectId workingHead = workingGitClient.getHeadRev(workingRepo.getAbsolutePath(), branchName);
    ObjectId bareHead = bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), branchName);
    assertEquals("Initial checkout of " + branchName + " has different HEAD than bare repo", bareHead, workingHead);
}
 
Example #6
Source File: DockerToolInstallerTest.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
private FilePath downloadDocker(DumbSlave slave, FilePath toolDir, String version) throws IOException, InterruptedException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TeeOutputStream tee = new TeeOutputStream(baos, new PlainTextConsoleOutputStream(System.err));
    TaskListener l = new StreamTaskListener(tee);

    FilePath exe = toolDir.child(version+"/bin/docker");
    // Download for first time:
    assertEquals(exe.getRemote(), DockerTool.getExecutable(version, slave, l, null));
    assertTrue(exe.exists());
    assertThat(baos.toString(), containsString(Messages.DockerToolInstaller_downloading_docker_client_(version)));
    // Next time we do not need to download:
    baos.reset();
    assertEquals(exe.getRemote(), DockerTool.getExecutable(version, slave, l, null));
    assertTrue(exe.exists());
    assertThat(baos.toString(), not(containsString(Messages.DockerToolInstaller_downloading_docker_client_(version))));
    // Version check:
    baos.reset();
    assertEquals(0, slave.createLauncher(l).launch().cmds(exe.getRemote(), "version", "--format", "{{.Client.Version}}").quiet(true).stdout(tee).stderr(System.err).join());
    if (!version.equals("latest")) {
        assertEquals(version, baos.toString().trim());
    }
    return exe;
}
 
Example #7
Source File: GitClientCliCloneTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@BeforeClass
public static void loadLocalMirror() throws Exception {
    /* Prime the local mirror cache before other tests run */
    TaskListener mirrorListener = StreamTaskListener.fromStdout();
    File tempDir = Files.createTempDirectory("PrimeCliCloneTest").toFile();
    WorkspaceWithRepo cache = new WorkspaceWithRepo(tempDir, "git", mirrorListener);
    cache.localMirror();
    Util.deleteRecursive(tempDir);
}
 
Example #8
Source File: DockerToolTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test public void getExecutable() throws Exception {
    assertEquals(DockerTool.COMMAND, DockerTool.getExecutable(null, null, null, null));
    DockerTool.DescriptorImpl descriptor = r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class);
    String name = "docker15";
    descriptor.setInstallations(new DockerTool(name, "/usr/local/docker15", Collections.<ToolProperty<?>>emptyList()));
    // TODO r.jenkins.restart() does not reproduce need for get/setInstallations; use RestartableJenkinsRule in 1.567+
    assertEquals("/usr/local/docker15/bin/docker", DockerTool.getExecutable(name, null, null, null));
    DumbSlave slave = r.createOnlineSlave();
    slave.getNodeProperties().add(new ToolLocationNodeProperty(new ToolLocationNodeProperty.ToolLocation(descriptor, name, "/opt/docker")));
    assertEquals("/usr/local/docker15/bin/docker", DockerTool.getExecutable(name, null, null, null));
    assertEquals("/opt/docker/bin/docker", DockerTool.getExecutable(name, slave, StreamTaskListener.fromStderr(), null));
}
 
Example #9
Source File: AbstractGitTestCase.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();

  listener = StreamTaskListener.fromStderr();

  testRepo = new TestGitRepo("unnamed", this, listener);
  johnDoe = testRepo.johnDoe;
  janeDoe = testRepo.janeDoe;
  workDir = testRepo.gitDir;
  workspace = testRepo.gitDirPath;
  git = testRepo.git;
}
 
Example #10
Source File: DockerComputerConnectorTest.java    From docker-plugin with MIT License 5 votes vote down vote up
private void terminateAllDockerNodes() {
    final TaskListener tl = new StreamTaskListener(System.out, Charset.forName("UTF-8"));
    for( final Node n : j.jenkins.getNodes() ) {
        if( n instanceof DockerTransientNode ) {
            final DockerTransientNode dn = (DockerTransientNode)n;
            dn.terminate(tl);
        }
    }
}
 
Example #11
Source File: GitToolTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testForNode() throws Exception {
    DumbSlave agent = j.createSlave();
    agent.setMode(Node.Mode.EXCLUSIVE);
    TaskListener log = StreamTaskListener.fromStdout();
    GitTool newTool = gitTool.forNode(agent, log);
    assertEquals(gitTool.getGitExe(), newTool.getGitExe());
}
 
Example #12
Source File: GitClientCloneTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@BeforeClass
public static void loadLocalMirror() throws Exception {
    /* Prime the local mirror cache before other tests run */
    /* Allow 3-7 second delay before priming the cache */
    /* Allow other tests a better chance to prime the cache */
    /* 3-7 second delay is small compared to execution time of this test */
    Random random = new Random();
    Thread.sleep((3 + random.nextInt(5)) * 1000L); // Wait 3-7 seconds before priming the cache
    TaskListener mirrorListener = StreamTaskListener.fromStdout();
    File tempDir = Files.createTempDirectory("PrimeCloneTest").toFile();
    WorkspaceWithRepo cache = new WorkspaceWithRepo(tempDir, "git", mirrorListener);
    cache.localMirror();
    Util.deleteRecursive(tempDir);
}
 
Example #13
Source File: GitClientFetchTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@BeforeClass
public static void loadLocalMirror() throws Exception {
    /* Prime the local mirror cache before other tests run */
    /* Allow 2-5 second delay before priming the cache */
    /* Allow other tests a better chance to prime the cache */
    /* 2-5 second delay is small compared to execution time of this test */
    Random random = new Random();
    Thread.sleep((2 + random.nextInt(4)) * 1000L); // Wait 2-5 seconds before priming the cache
    TaskListener mirrorListener = StreamTaskListener.fromStdout();
    File tempDir = Files.createTempDirectory("PrimeFetchTest").toFile();
    WorkspaceWithRepo cache = new WorkspaceWithRepo(tempDir, "git", mirrorListener);
    cache.localMirror();
    Util.deleteRecursive(tempDir);
}
 
Example #14
Source File: GitClientSampleRepoRule.java    From git-client-plugin with MIT License 5 votes vote down vote up
public boolean gitVersionAtLeast(int neededMajor, int neededMinor, int neededPatch) {
    final TaskListener procListener = StreamTaskListener.fromStderr();
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        int returnCode = new Launcher.LocalLauncher(procListener).launch().cmds("git", "--version").stdout(out).join();
        if (returnCode != 0) {
            LOGGER.log(Level.WARNING, "Command 'git --version' returned " + returnCode);
        }
    } catch (IOException | InterruptedException ex) {
        LOGGER.log(Level.WARNING, "Exception checking git version " + ex);
    }
    final String versionOutput = out.toString().trim();
    final String[] fields = versionOutput.split(" ")[2].replaceAll("msysgit.", "").replaceAll("windows.", "").split("\\.");
    final int gitMajor = Integer.parseInt(fields[0]);
    final int gitMinor = Integer.parseInt(fields[1]);
    final int gitPatch = Integer.parseInt(fields[2]);
    if (gitMajor < 1 || gitMajor > 3) {
        LOGGER.log(Level.WARNING, "Unexpected git major version " + gitMajor + " parsed from '" + versionOutput + "', field:'" + fields[0] + "'");
    }
    if (gitMinor < 0 || gitMinor > 50) {
        LOGGER.log(Level.WARNING, "Unexpected git minor version " + gitMinor + " parsed from '" + versionOutput + "', field:'" + fields[1] + "'");
    }
    if (gitPatch < 0 || gitPatch > 20) {
        LOGGER.log(Level.WARNING, "Unexpected git patch version " + gitPatch + " parsed from '" + versionOutput + "', field:'" + fields[2] + "'");
    }

    return gitMajor >  neededMajor ||
            (gitMajor == neededMajor && gitMinor >  neededMinor) ||
            (gitMajor == neededMajor && gitMinor == neededMinor  && gitPatch >= neededPatch);
}
 
Example #15
Source File: CredentialsProviderImplTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    Secret secret = Secret.fromString(SECRET_VALUE);
    listener = StreamTaskListener.fromStdout();
    StandardUsernameCredentials cred = new StandardUsernamePasswordCredentialsImpl(USER_NAME, secret);
    provider = new CredentialsProviderImpl(listener, cred);
}
 
Example #16
Source File: CredentialsProviderImplTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testSupportsDisallowed() {
    Secret secret = Secret.fromString(SECRET_VALUE);
    listener = StreamTaskListener.fromStdout();
    StandardUsernameCredentials badCred = new MyUsernameCredentialsImpl(USER_NAME);
    CredentialsProviderImpl badProvider = new CredentialsProviderImpl(listener, badCred);
    CredentialItem.Username username = new CredentialItem.Username();
    assertNull(username.getValue());
    assertFalse(badProvider.supports(username));
    assertFalse(badProvider.get(uri, username));
    assertNull(username.getValue());
}
 
Example #17
Source File: PendingChecksFilterTests.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);

  g.getClient()
      .when(
          HttpRequest.request("/a/plugins/checks/checks.pending/")
              .withQueryStringParameters(query)
              .withMethod("GET"))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(pendingChecksInfos)));

  GerritSCMSource source =
      new GerritSCMSource(
          String.format(
              "https://%s:%s/a/test",
              g.getClient().remoteAddress().getHostName(),
              g.getClient().remoteAddress().getPort()));
  source.setInsecureHttps(true);
  source.setCredentialsId("cid");
  request = context.newRequest(source, new StreamTaskListener());
}
 
Example #18
Source File: SQSTriggerBuilder.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
public SQSTriggerBuilder(final SQSJob job, final Message message, List<String> userarns) throws IOException {
    this.job = job;
    this.message = message;

    SQSActivityAction activityAction = this.job.getJenkinsJob().getAction(SQSActivityAction.class);
    this.listener = new StreamTaskListener(activityAction.getActivityLogFile(), true, Charset.forName("UTF-8"));
    this.log = Log.get(SQSTriggerBuilder.class, this.listener.getLogger(), true);

    this.messageId = message.getMessageId();
    this.userarns = org.apache.commons.lang.StringUtils.join(userarns, "");
    this.log.info("Try to trigger the build for message: %s", messageId);
    this.log.debug("Print out message-body: %s", message.getBody());
}
 
Example #19
Source File: DockerClientTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    DockerTestUtil.assumeDocker();

    // Set stuff up for the test
    TaskListener taskListener = StreamTaskListener.fromStderr();
    Launcher.LocalLauncher launcher = new Launcher.LocalLauncher(taskListener);

    dockerClient = new DockerClient(launcher, null, null);
}
 
Example #20
Source File: DockerTestUtil.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
public static void assumeDocker(VersionNumber minimumVersion) throws Exception {
    Launcher.LocalLauncher localLauncher = new Launcher.LocalLauncher(StreamTaskListener.NULL);
    try {
        int status = localLauncher
            .launch()
            .cmds(DockerTool.getExecutable(null, null, null, null), "ps")
            .start()
            .joinWithTimeout(DockerClient.CLIENT_TIMEOUT, TimeUnit.SECONDS, localLauncher.getListener());
        Assume.assumeTrue("Docker working", status == 0);
    } catch (IOException x) {
        Assume.assumeNoException("have Docker installed", x);
    }
    DockerClient dockerClient = new DockerClient(localLauncher, null, null);
    Assume.assumeFalse("Docker version not < " + minimumVersion.toString(), dockerClient.version().isOlderThan(minimumVersion));
}
 
Example #21
Source File: DockerDSLTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test public void buildArguments() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            assumeDocker();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                    "node {\n" +
                    "  sh 'mkdir -p child'\n" +
                    "  writeFile file: 'child/stuff1', text: 'hello'\n" +
                    "  writeFile file: 'child/stuff2', text: 'world'\n" +
                    "  writeFile file: 'child/stuff3', text: env.BUILD_NUMBER\n" +
                    "  writeFile file: 'child/Dockerfile.other', text: '# This is a test.\\n\\nFROM hello-world\\nARG stuff4=4\\nARG stuff5=5\\nCOPY stuff1 /\\nCOPY stuff2 /\\nCOPY stuff3 /\\n'\n" +
                    "  def built = docker.build 'hello-world-stuff-arguments', '-f child/Dockerfile.other --pull --build-arg stuff4=build4 --build-arg stuff5=build5 child'\n" +
                    "  echo \"built ${built.id}\"\n" +
                    "}", true));

            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            DockerClient client = new DockerClient(new Launcher.LocalLauncher(StreamTaskListener.NULL), null, null);
            String descendantImageId1 = client.inspect(new EnvVars(), "hello-world-stuff-arguments", ".Id");
            story.j.assertLogContains("built hello-world-stuff-arguments", b);
            story.j.assertLogContains(" --pull ", b);
            story.j.assertLogNotContains(" --no-cache ", b);
            story.j.assertLogContains(descendantImageId1.replaceFirst("^sha256:", "").substring(0, 12), b);
            story.j.assertLogContains(" --build-arg stuff4=build4 ", b);
            story.j.assertLogContains(" --build-arg stuff5=build5 ", b);
        }
    });
}
 
Example #22
Source File: DockerDSLTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test public void buildWithMultiStage() {
        story.addStep(new Statement() {
            @Override public void evaluate() throws Throwable {
                assumeDocker(new VersionNumber("17.05"));
                WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
                p.setDefinition(new CpsFlowDefinition(
                        "node {\n" +
                                "  sh 'mkdir -p child'\n" +
                                "  writeFile file: 'child/stuff1', text: 'hello'\n" +
                                "  writeFile file: 'child/stuff2', text: 'world'\n" +
                                "  writeFile file: 'child/stuff3', text: env.BUILD_NUMBER\n" +
                                "  writeFile file: 'child/Dockerfile.other', " +
                                     "text: '# This is a test.\\n" +
                                            "\\n" +
                                            "FROM hello-world AS one\\n" +
                                            "ARG stuff4=4\\n" +
                                            "ARG stuff5=5\\n" +
                                            "COPY stuff1 /\\n" +
                                            "FROM scratch\\n" +
                                            "COPY --from=one /stuff1 /\\n" +
                                            "COPY stuff2 /\\nCOPY stuff3 /\\n'\n" +
                                "  def built = docker.build 'hello-world-stuff-arguments', '-f child/Dockerfile.other --build-arg stuff4=build4 --build-arg stuff5=build5 child'\n" +
                                "  echo \"built ${built.id}\"\n" +
                                "}", true));

// Note the absence '--pull' in the above docker build ags as compared to other tests.
// This is due to a Docker bug: https://github.com/docker/for-mac/issues/1751
// It can be re-added when that is fixed

                WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
                DockerClient client = new DockerClient(new Launcher.LocalLauncher(StreamTaskListener.NULL), null, null);
                String descendantImageId1 = client.inspect(new EnvVars(), "hello-world-stuff-arguments", ".Id");
                story.j.assertLogContains("built hello-world-stuff-arguments", b);
                story.j.assertLogNotContains(" --no-cache ", b);
                story.j.assertLogContains(descendantImageId1.replaceFirst("^sha256:", "").substring(0, 12), b);
                story.j.assertLogContains(" --build-arg stuff4=build4 ", b);
                story.j.assertLogContains(" --build-arg stuff5=build5 ", b);
            }
        });
    }
 
Example #23
Source File: DockerDSLTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test public void build() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            assumeDocker();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                "node {\n" +
                "  writeFile file: 'stuff1', text: 'hello'\n" +
                "  writeFile file: 'stuff2', text: 'world'\n" +
                "  writeFile file: 'stuff3', text: env.BUILD_NUMBER\n" +
                "  writeFile file: 'Dockerfile', text: '# This is a test.\\n\\nFROM hello-world\\nCOPY stuff1 /\\nCOPY stuff2 /\\nCOPY stuff3 /\\n'\n" +
                "  def built = docker.build 'hello-world-stuff'\n" +
                "  echo \"built ${built.id}\"\n" +
                "}", true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            DockerClient client = new DockerClient(new Launcher.LocalLauncher(StreamTaskListener.NULL), null, null);

            String descendantImageId1 = client.inspect(new EnvVars(), "hello-world-stuff", ".Id");
            story.j.assertLogContains("built hello-world-stuff", b);
            story.j.assertLogContains(descendantImageId1.replaceFirst("^sha256:", "").substring(0, 12), b);

            b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            String descendantImageId2 = client.inspect(new EnvVars(), "hello-world-stuff", ".Id");
            story.j.assertLogContains("built hello-world-stuff", b);
            story.j.assertLogContains(descendantImageId2.replaceFirst("^sha256:", "").substring(0, 12), b);
        }
    });
}
 
Example #24
Source File: CachesTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testBranchCacheLoaderNoMetadata() throws Exception {
    sampleRepo1.init();
    sampleRepo1.write("Jenkinsfile", "node { echo 'hi'; }");
    sampleRepo1.git("add", "Jenkinsfile");
    sampleRepo1.git("commit", "--all", "--message=buildable");

    WorkflowMultiBranchProject project = r.jenkins.createProject(WorkflowMultiBranchProject.class, "Repo");
    GitSCMSource source = new GitSCMSource(sampleRepo1.toString());
    source.setTraits(new ArrayList<>(Arrays.asList(new BranchDiscoveryTrait())));

    BranchSource branchSource = new BranchSource(source);
    branchSource.setStrategy(new DefaultBranchPropertyStrategy(null));

    TaskListener listener = StreamTaskListener.fromStderr();
    assertEquals("[SCMHead{'master'}]", source.fetch(listener).toString());
    project.setSourcesList(new ArrayList<>(Arrays.asList(branchSource)));

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

    Caches.BranchCacheLoader loader = new Caches.BranchCacheLoader(r.jenkins);
    BranchImpl.Branch branch = loader.load(project.getFullName() + "/master").orNull();

    // if branch is defined, it'll be sorted by branch
    assertNotNull(branch);
    assertTrue(branch.isPrimary());
    assertEquals("master", branch.getUrl());
}
 
Example #25
Source File: KubernetesTestUtil.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
public static String miniKubeIp() {
    if (ip == null) {
        for (String cmd : MINIKUBE_COMMANDS) {
            String s = miniKubeIp(new Launcher.LocalLauncher(StreamTaskListener.NULL), cmd);
            if (s != null) {
                ip = s.trim();
                LOGGER.log(Level.INFO, "Using minikube at {0}", ip);
                return ip;
            }
        }
        LOGGER.warning("Minikube was not found or is stopped");
        ip = "";
    }
    return ip;
}
 
Example #26
Source File: WindowsDockerClientTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    DockerTestUtil.assumeDocker();

    TaskListener taskListener = StreamTaskListener.fromStderr();
    Launcher.LocalLauncher launcher = new Launcher.LocalLauncher(taskListener);

    dockerClient = new WindowsDockerClient(launcher, null, null);
}
 
Example #27
Source File: InvokerRunsPublisherTest.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
/**
 * projectsDirectory = src/it -> relative path
 * cloneProjectsTo = /path/to/khmarbaise/maui/src/main/resources/mp-it-1/target/it -> absolute path
 * reportsDirectory = ${invoker.reportsDirectory} -> variabilized path
 */
protected void test_relative_path_and_absolute_path_and_variabilized_path_run_goal(String mavenSpyLogs, String goal) throws Exception {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(mavenSpyLogs);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
    InvokerRunsPublisher invokerRunsPublisher = new InvokerRunsPublisher();
    List<Element> invokerRunEvents = XmlUtils.getExecutionEventsByPlugin(doc.getDocumentElement(), InvokerRunsPublisher.GROUP_ID, InvokerRunsPublisher.ARTIFACT_ID, goal, "MojoSucceeded");

    FilePath workspace = new FilePath(new File("/path/to/khmarbaise/maui/src/main/resources/mp-it-1"));
    TaskListener listener = new StreamTaskListener(System.out, StandardCharsets.UTF_8);

    System.out.println(invokerRunEvents.size());
    List<Element> invokerRunSucceededEvents = new ArrayList<>();
    for (Element invokerRunEvent : invokerRunEvents) {
        String eventType = invokerRunEvent.getAttribute("type");
        if (eventType.equals("MojoSucceeded")) {
            invokerRunSucceededEvents.add(invokerRunEvent);
        }
    }
    Assert.assertThat(invokerRunSucceededEvents.size(), Matchers.is(1));
    Element invokerRunSucceedEvent = invokerRunSucceededEvents.get(0);

    Element projectElt = XmlUtils.getUniqueChildElement(invokerRunSucceedEvent, "project");
    Element pluginElt = XmlUtils.getUniqueChildElement(invokerRunSucceedEvent, "plugin");
    Element reportsDirectoryElt = XmlUtils.getUniqueChildElementOrNull(pluginElt, "reportsDirectory");
    Element cloneProjectsToElt = XmlUtils.getUniqueChildElementOrNull(pluginElt, "cloneProjectsTo");
    Element projectsDirectoryElt = XmlUtils.getUniqueChildElementOrNull(pluginElt, "projectsDirectory");

    String reportsDirectory = invokerRunsPublisher.expandAndRelativize(reportsDirectoryElt, "reportsDirectory", invokerRunSucceedEvent, projectElt, workspace, listener);
    Assert.assertThat(reportsDirectory, Matchers.is("target/invoker-reports"));
    String projectsDirectory = invokerRunsPublisher.expandAndRelativize(projectsDirectoryElt, "projectsDirectory", invokerRunSucceedEvent, projectElt, workspace, listener);
    Assert.assertThat(projectsDirectory, Matchers.is("src/it"));
    String cloneProjectsTo = invokerRunsPublisher.expandAndRelativize(cloneProjectsToElt, "cloneProjectsTo", invokerRunSucceedEvent, projectElt, workspace, listener);
    Assert.assertThat(cloneProjectsTo, Matchers.is("target/it"));
}
 
Example #28
Source File: HudsonTestCase.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Creates {@link LocalLauncher}. Useful for launching processes.
 */
protected LocalLauncher createLocalLauncher() {
    return new LocalLauncher(StreamTaskListener.fromStdout());
}
 
Example #29
Source File: PushTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
@BeforeClass
public static void createBareRepository() throws Exception {
    /* Command line git commands fail unless certain default values are set */
    CliGitCommand gitCmd = new CliGitCommand(null);
    gitCmd.setDefaults();

    /* Randomly choose git implementation to create bare repository */
    final String[] gitImplementations = {"git", "jgit"};
    Random random = new Random();
    String gitImpl = gitImplementations[random.nextInt(gitImplementations.length)];

    /* Create the bare repository */
    bareRepo = staticTemporaryFolder.newFolder();
    bareURI = new URIish(bareRepo.getAbsolutePath());
    hudson.EnvVars env = new hudson.EnvVars();
    TaskListener listener = StreamTaskListener.fromStderr();
    bareGitClient = Git.with(listener, env).in(bareRepo).using(gitImpl).getClient();
    bareGitClient.init_().workspace(bareRepo.getAbsolutePath()).bare(true).execute();

    /* Clone the bare repository into a working copy */
    File cloneRepo = staticTemporaryFolder.newFolder();
    GitClient cloneGitClient = Git.with(listener, env).in(cloneRepo).using(gitImpl).getClient();
    cloneGitClient.clone_()
            .url(bareRepo.getAbsolutePath())
            .repositoryName("origin")
            .execute();

    for (String branchName : BRANCH_NAMES) {
        /* Add a file with random content to the current branch of working repo */
        File added = File.createTempFile("added-", ".txt", cloneRepo);
        String randomContent = java.util.UUID.randomUUID().toString();
        String addedContent = "Initial commit to branch " + branchName + " content '" + randomContent + "'";
        FileUtils.writeStringToFile(added, addedContent, "UTF-8");
        cloneGitClient.add(added.getName());
        cloneGitClient.commit("Initial commit to " + branchName + " file " + added.getName() + " with " + randomContent);
        // checkoutOldBranchAndCommitFile needs at least two commits to the branch
        FileUtils.writeStringToFile(added, "Another revision " + randomContent, "UTF-8");
        cloneGitClient.add(added.getName());
        cloneGitClient.commit("Second commit to " + branchName);

        /* Push HEAD of current branch to branchName on the bare repository */
        cloneGitClient.push().to(bareURI).ref("HEAD:" + branchName).execute();
    }

    /* Remember the SHA1 of the first commit */
    bareFirstCommit = bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), "master");
}
 
Example #30
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
/**
 * Creates {@link hudson.Launcher.LocalLauncher}. Useful for launching processes.
 */
public Launcher.LocalLauncher createLocalLauncher() {
    return new Launcher.LocalLauncher(StreamTaskListener.fromStdout());
}