|
| 1 | +package org.example.itest.k3s.simple; |
| 2 | + |
| 3 | +import lombok.SneakyThrows; |
| 4 | +import org.junit.jupiter.api.BeforeAll; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | +import org.testcontainers.k3s.K3sContainer; |
| 7 | +import org.testcontainers.utility.DockerImageName; |
| 8 | + |
| 9 | +import java.io.File; |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.nio.file.Files; |
| 12 | +import java.nio.file.Path; |
| 13 | +import java.util.Arrays; |
| 14 | +import java.util.Objects; |
| 15 | +import java.util.Optional; |
| 16 | + |
| 17 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 18 | + |
| 19 | +class SimpleK3sITest { |
| 20 | + |
| 21 | + private static File k3sYaml; |
| 22 | + |
| 23 | + @SneakyThrows |
| 24 | + @BeforeAll |
| 25 | + static void setup() { |
| 26 | + @SuppressWarnings("resource") |
| 27 | + K3sContainer k3sContainer = new K3sContainer(DockerImageName.parse("rancher/k3s:v1.30.1-k3s1")); |
| 28 | + k3sContainer.start(); |
| 29 | + |
| 30 | + k3sYaml = File.createTempFile("k3sYaml", ".yaml"); |
| 31 | + k3sYaml.deleteOnExit(); |
| 32 | + Files.writeString(k3sYaml.toPath(), k3sContainer.getKubeConfigYaml(), StandardCharsets.UTF_8); |
| 33 | + } |
| 34 | + |
| 35 | + @SuppressWarnings("SameParameterValue") |
| 36 | + static String which(String executable) { |
| 37 | + for (String folder : System.getenv().getOrDefault("PATH", "").split(File.pathSeparator)) { |
| 38 | + File folderFile = new File(folder); |
| 39 | + if (!folderFile.exists() || !folderFile.isDirectory()) continue; |
| 40 | + if (Arrays.asList(Objects.requireNonNull(folderFile.list(), "list is null")).contains(executable)) { |
| 41 | + return new File(folderFile, folder).getPath(); |
| 42 | + } |
| 43 | + } |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + @SneakyThrows |
| 48 | + @Test |
| 49 | + void test() { |
| 50 | + String kubectl = Optional.ofNullable(which("kubectl")) |
| 51 | + .orElse( |
| 52 | + Path.of(System.getProperty("user.home")) |
| 53 | + .resolve(Path.of(".asdf/shims/kubectl")) |
| 54 | + .toString() |
| 55 | + ); |
| 56 | + |
| 57 | + var pb = new ProcessBuilder(kubectl, "run", "busybox", "--image=busybox"); |
| 58 | + pb.environment().put("KUBECONFIG", k3sYaml.getPath()); |
| 59 | + pb.inheritIO(); |
| 60 | + Process kubectlRun = pb.start(); |
| 61 | + int exit = kubectlRun.waitFor(); |
| 62 | + assertEquals(0, exit); |
| 63 | + } |
| 64 | +} |
0 commit comments