From 66fa924d776fb0c7feae15ff3b8fda131dbd35d8 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Fri, 9 Oct 2026 09:19:09 -0500 Subject: [PATCH] test: cover Printer and the floci update flow PrinterTest pins where text, errors and warnings go, what --quiet hides, and the JSON and YAML rendering. UpdateCommandTest drives floci update against a stub release server: a verified replacement, a checksum mismatch, --check, up to date, a Homebrew install and a non-version API response. UpdateCommand takes the binary path and the release URLs through a constructor for this, replacing a package-private field. Signed-off-by: Hector Ventura --- .../io/floci/cli/commands/UpdateCommand.java | 23 ++- .../io/floci/cli/update/ReleaseChannel.java | 14 +- .../java/io/floci/cli/unit/PrinterTest.java | 90 +++++++++ .../io/floci/cli/unit/UpdateCommandTest.java | 191 ++++++++++++++++++ 4 files changed, 310 insertions(+), 8 deletions(-) create mode 100644 src/test/java/io/floci/cli/unit/PrinterTest.java create mode 100644 src/test/java/io/floci/cli/unit/UpdateCommandTest.java diff --git a/src/main/java/io/floci/cli/commands/UpdateCommand.java b/src/main/java/io/floci/cli/commands/UpdateCommand.java index a6d2c72..2428a5b 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -72,8 +72,21 @@ public class UpdateCommand implements Callable { return http; } - /** The binary to replace; {@code null} means "resolve the running executable". Test seam. */ - Path selfPath; + /** The binary to replace; {@code null} means "resolve the running executable". */ + private final Path selfPath; + private final String latestReleaseUrl; + private final String downloadBase; + + public UpdateCommand() { + this(null, ReleaseChannel.latestReleaseUrl(), ReleaseChannel.downloadBase()); + } + + /** Test seam: replace {@code selfPath}, resolving releases and assets from the given URLs. */ + public UpdateCommand(Path selfPath, String latestReleaseUrl, String downloadBase) { + this.selfPath = selfPath; + this.latestReleaseUrl = latestReleaseUrl; + this.downloadBase = downloadBase; + } @Override public Integer call() { @@ -111,8 +124,8 @@ public class UpdateCommand implements Callable { try { printer.println("downloading " + asset + " " + target + "..."); Path fresh = work.resolve(asset); - fetchFile(ReleaseChannel.assetUrl(target, asset), fresh); - verifyChecksum(fresh, asset, fetchString(ReleaseChannel.assetUrl(target, "sha256sums.txt"))); + fetchFile(ReleaseChannel.assetUrl(downloadBase, target, asset), fresh); + verifyChecksum(fresh, asset, fetchString(ReleaseChannel.assetUrl(downloadBase, target, "sha256sums.txt"))); printer.println(Ansi.green("✓") + " checksum verified"); replaceAtomically(fresh, binary); } finally { @@ -135,7 +148,7 @@ public class UpdateCommand implements Callable { private String fetchLatestVersion() { try { - JsonNode release = JSON.readTree(fetchString(ReleaseChannel.latestReleaseUrl())); + JsonNode release = JSON.readTree(fetchString(latestReleaseUrl)); String tag = release.path("tag_name").asText(""); // Same shape-check as UpdateNotifier: a captive portal or proxy error page must // not end up spliced into a download URL. diff --git a/src/main/java/io/floci/cli/update/ReleaseChannel.java b/src/main/java/io/floci/cli/update/ReleaseChannel.java index 950fecb..a921b3a 100644 --- a/src/main/java/io/floci/cli/update/ReleaseChannel.java +++ b/src/main/java/io/floci/cli/update/ReleaseChannel.java @@ -25,8 +25,16 @@ public final class ReleaseChannel { /** Download URL for one asset of one release, e.g. {@code floci-darwin-arm64}. */ public static String assetUrl(String version, String asset) { - String base = System.getenv().getOrDefault( - DOWNLOAD_ENV, "https://github.com/" + REPO + "/releases/download"); - return base + "/" + version + "/" + asset; + return assetUrl(downloadBase(), version, asset); + } + + /** Same, under an explicit download base (see {@link #downloadBase()}). */ + public static String assetUrl(String downloadBase, String version, String asset) { + return downloadBase + "/" + version + "/" + asset; + } + + /** Where release assets are downloaded from: GitHub, or {@code FLOCI_UPDATE_DOWNLOAD_URL}. */ + public static String downloadBase() { + return System.getenv().getOrDefault(DOWNLOAD_ENV, "https://github.com/" + REPO + "/releases/download"); } } diff --git a/src/test/java/io/floci/cli/unit/PrinterTest.java b/src/test/java/io/floci/cli/unit/PrinterTest.java new file mode 100644 index 0000000..633b051 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/PrinterTest.java @@ -0,0 +1,90 @@ +package io.floci.cli.unit; + +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-074: where each kind of output goes, and how structured output is rendered. */ +class PrinterTest { + + private final ByteArrayOutputStream out = new ByteArrayOutputStream(); + private final ByteArrayOutputStream err = new ByteArrayOutputStream(); + + @BeforeAll + static void plainText() { + Ansi.disable(); + } + + private Printer printer(OutputFormat format, boolean quiet) { + return new Printer(new PrintStream(out), new PrintStream(err), format, quiet); + } + + private static Map sample() { + Map data = new LinkedHashMap<>(); + data.put("status", "running"); + data.put("services", List.of("s3", "sqs")); + return data; + } + + @Test + void textGoesToStdoutAndProblemsToStderr() { + Printer p = printer(OutputFormat.text, false); + + p.println("hello"); + p.error("broken\nRun 'floci doctor'."); + p.warn("careful"); + + assertEquals("hello\n", out.toString()); + assertEquals("Error: broken\nRun 'floci doctor'.\nWarning: careful\n", err.toString()); + } + + /** --quiet silences ordinary output, never errors or warnings. */ + @Test + void quietKeepsErrorsAndWarnings() { + Printer p = printer(OutputFormat.text, true); + + p.println("hello"); + p.print("partial"); + p.error("broken\nFix it."); + p.warn("careful"); + + assertEquals("", out.toString()); + assertTrue(err.toString().contains("Error: broken")); + assertTrue(err.toString().contains("Warning: careful")); + } + + @Test + void jsonIsIndentedAndKeepsKeyOrder() { + printer(OutputFormat.json, false).structured(sample()); + + String json = out.toString(); + assertTrue(json.startsWith("{\n"), json); + assertTrue(json.indexOf("\"status\"") < json.indexOf("\"services\""), json); + assertTrue(json.contains("\"s3\", \"sqs\"") || json.contains("\"s3\",\"sqs\""), json); + } + + @Test + void yamlHasNoDocumentMarker() { + printer(OutputFormat.yaml, false).structured(sample()); + + assertEquals("status: \"running\"\nservices:\n- \"s3\"\n- \"sqs\"\n", out.toString()); + } + + /** Structured output is the command's result, so --quiet does not hide it. */ + @Test + void quietStillPrintsStructuredOutput() { + printer(OutputFormat.json, true).structured(Map.of("ok", true)); + + assertTrue(out.toString().contains("\"ok\" : true"), out.toString()); + } +} diff --git a/src/test/java/io/floci/cli/unit/UpdateCommandTest.java b/src/test/java/io/floci/cli/unit/UpdateCommandTest.java new file mode 100644 index 0000000..85b0ed6 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/UpdateCommandTest.java @@ -0,0 +1,191 @@ +package io.floci.cli.unit; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.floci.cli.CliVersion; +import io.floci.cli.commands.UpdateCommand; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * BL-074: floci update against a stub release server. The installed binary is a file in a temp + * directory, so a test can see whether it was replaced. Windows is out: update refuses to run there. + */ +@DisabledOnOs(OS.WINDOWS) +class UpdateCommandTest { + + private static final String NEWER = "99.0.0"; + private static final byte[] FRESH = "fresh binary".getBytes(StandardCharsets.UTF_8); + private static final byte[] OLD = "old binary".getBytes(StandardCharsets.UTF_8); + + @TempDir + Path tempDir; + + private HttpServer server; + private final AtomicReference latest = new AtomicReference<>("{\"tag_name\":\"" + NEWER + "\"}"); + private final AtomicReference checksum = new AtomicReference<>(sha256(FRESH)); + private final List downloads = new CopyOnWriteArrayList<>(); + + private record Run(int exit, String out, String err) {} + + @BeforeEach + void start() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/api/latest", exchange -> respond(exchange, latest.get().getBytes(StandardCharsets.UTF_8))); + server.createContext("/download/", exchange -> { + String path = exchange.getRequestURI().getPath(); + downloads.add(path); + if (path.endsWith("/sha256sums.txt")) { + StringBuilder sums = new StringBuilder(); + for (String platform : List.of("darwin-arm64", "darwin-amd64", "linux-arm64", "linux-amd64")) { + sums.append(checksum.get()).append(" ./floci-").append(platform).append("/floci-").append(platform).append('\n'); + } + respond(exchange, sums.toString().getBytes(StandardCharsets.UTF_8)); + } else { + respond(exchange, FRESH); + } + }); + server.start(); + } + + @AfterEach + void stop() { + server.stop(0); + } + + private static void respond(HttpExchange exchange, byte[] body) throws IOException { + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + exchange.close(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private Path installed(Path dir) throws Exception { + Files.createDirectories(dir); + Path binary = dir.resolve("floci"); + Files.write(binary, OLD); + return binary; + } + + private Run update(Path binary, String... args) { + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + UpdateCommand command = new UpdateCommand(binary, base + "/api/latest", base + "/download"); + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + try { + int exit = new CommandLine(command).execute(args); + return new Run(exit, outBuf.toString(), errBuf.toString()); + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void replacesTheBinaryWithTheVerifiedDownload() throws Exception { + Path binary = installed(tempDir.resolve("bin")); + + Run r = update(binary); + + assertEquals(0, r.exit(), r.err()); + assertArrayEquals(FRESH, Files.readAllBytes(binary)); + assertTrue(r.out().contains("checksum verified"), r.out()); + try (var left = Files.list(binary.getParent())) { + assertEquals(List.of("floci"), left.map(p -> p.getFileName().toString()).toList(), "no staging file left behind"); + } + } + + @Test + void aChecksumMismatchLeavesTheBinaryAlone() throws Exception { + Path binary = installed(tempDir.resolve("bin")); + checksum.set(sha256("something else".getBytes(StandardCharsets.UTF_8))); + + Run r = update(binary); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("checksum mismatch"), r.err()); + assertArrayEquals(OLD, Files.readAllBytes(binary)); + } + + @Test + void checkReportsWithoutDownloading() throws Exception { + Path binary = installed(tempDir.resolve("bin")); + + Run r = update(binary, "--check"); + + assertEquals(1, r.exit()); + assertTrue(r.out().contains("update available"), r.out()); + assertEquals(List.of(), downloads); + assertArrayEquals(OLD, Files.readAllBytes(binary)); + } + + @Test + void theCurrentVersionIsUpToDate() throws Exception { + Path binary = installed(tempDir.resolve("bin")); + latest.set("{\"tag_name\":\"" + CliVersion.CLI_VERSION + "\"}"); + + Run r = update(binary); + + assertEquals(0, r.exit(), r.err()); + assertTrue(r.out().contains("is up to date"), r.out()); + assertEquals(List.of(), downloads); + } + + @Test + void aHomebrewInstallIsLeftToBrew() throws Exception { + Path binary = installed(tempDir.resolve("Cellar").resolve("floci").resolve("0.3.0").resolve("bin")); + + Run r = update(binary); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("brew upgrade floci"), r.err()); + assertArrayEquals(OLD, Files.readAllBytes(binary)); + } + + /** A captive portal or proxy page instead of the GitHub API must not become a download URL. */ + @Test + void aLatestReleaseResponseWithoutAVersionIsRefused() throws Exception { + Path binary = installed(tempDir.resolve("bin")); + latest.set("Sign in to the network"); + + Run r = update(binary); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("cannot determine the latest version"), r.err()); + assertEquals(List.of(), downloads); + } +}