From 6a74d7d2d5316c78c2eae4e35bc7936035570790 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 10 Oct 2026 22:30:07 -0500 Subject: [PATCH] test: cover Printer and the floci update flow (#57) * 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 * test: check the exact release files requested and the version check itself The stub release server serves only the expected release's files, the replacement test asserts the two requests made, valid JSON without a usable version is covered, and the Printer assertions use the platform line separator. Signed-off-by: Hector Ventura --------- 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 | 92 +++++++ .../io/floci/cli/unit/UpdateCommandTest.java | 259 ++++++++++++++++++ 4 files changed, 380 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 20bf338..990ecf3 100644 --- a/src/main/java/io/floci/cli/commands/UpdateCommand.java +++ b/src/main/java/io/floci/cli/commands/UpdateCommand.java @@ -74,8 +74,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() { @@ -117,8 +130,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 { @@ -141,7 +154,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..2385657 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/PrinterTest.java @@ -0,0 +1,92 @@ +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"); + + // println ends a line the platform's way; the newline inside the message is the caller's. + String newline = System.lineSeparator(); + assertEquals("hello" + newline, out.toString()); + assertEquals("Error: broken\nRun 'floci doctor'." + newline + "Warning: careful" + newline, 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("{" + System.lineSeparator()), 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..b174019 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/UpdateCommandTest.java @@ -0,0 +1,259 @@ +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 org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +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 java.util.regex.Pattern; + +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); + private static final String SUMS_PATH = "/download/" + NEWER + "/sha256sums.txt"; + private static final Pattern ASSET_PATH = + Pattern.compile("/download/" + Pattern.quote(NEWER) + "/floci-(darwin|linux)-(arm64|amd64)"); + + @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); + // Like the real release host: only this release's own files exist. + if (path.equals(SUMS_PATH)) { + 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 if (ASSET_PATH.matcher(path).matches()) { + respond(exchange, FRESH); + } else { + exchange.sendResponseHeaders(404, -1); + exchange.close(); + } + }); + 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()); + // Exactly the release's binary for this platform, then its checksums: nothing else. + assertEquals(2, downloads.size(), downloads.toString()); + assertTrue(ASSET_PATH.matcher(downloads.get(0)).matches(), downloads.toString()); + assertEquals(SUMS_PATH, downloads.get(1)); + 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, or JSON without a usable release version, must not become a + * download URL. The JSON cases reach the version check itself, not just the parser. + */ + @ParameterizedTest + @ValueSource(strings = { + "Sign in to the network", + "{}", + "{\"tag_name\":\"\"}", + "{\"tag_name\":\"not-a-version\"}", + "{\"tag_name\":\"../../evil\"}", + "{\"message\":\"API rate limit exceeded\"}"}) + void aLatestReleaseResponseWithoutAVersionIsRefused(String response) throws Exception { + Path binary = installed(tempDir.resolve("bin")); + latest.set(response); + + Run r = update(binary); + + assertEquals(1, r.exit()); + assertTrue(r.err().contains("cannot determine the latest version"), r.err()); + assertEquals(List.of(), downloads); + assertArrayEquals(OLD, Files.readAllBytes(binary)); + } + + /** A release whose files are not on the download host fails the update and leaves the binary alone. */ + @Test + void aReleaseWithoutItsFilesLeavesTheBinaryAlone() throws Exception { + Path binary = installed(tempDir.resolve("bin")); + latest.set("{\"tag_name\":\"98.0.0\"}"); // newer than this build, but the stub has no such release + + Run r = update(binary); + + assertEquals(1, r.exit()); + assertArrayEquals(OLD, Files.readAllBytes(binary)); + assertEquals(1, downloads.size(), downloads.toString()); + assertTrue(downloads.get(0).startsWith("/download/98.0.0/floci-"), downloads.toString()); + } + + /** --check tells "the check failed" (2) from "an update is available" (1). */ + @Test + void aCheckThatCannotBeMadeExitsTwo() throws Exception { + Path binary = installed(tempDir.resolve("bin")); + latest.set("{}"); + + Run r = update(binary, "--check"); + + assertEquals(2, r.exit()); + assertTrue(r.err().contains("cannot determine the latest version"), r.err()); + assertEquals(List.of(), downloads); + } + + /** The whole update through a symlinked install: the real file is replaced, the link stays a link. */ + @Test + void anInstallBehindASymlinkIsUpdatedInPlace() throws Exception { + Path real = installed(tempDir.resolve("opt")); + Path link = Files.createSymbolicLink(Files.createDirectories(tempDir.resolve("bin")).resolve("floci"), real); + + Run r = update(link); + + assertEquals(0, r.exit(), r.err()); + assertTrue(Files.isSymbolicLink(link), "the link is still a link"); + assertArrayEquals(FRESH, Files.readAllBytes(real)); + try (var left = Files.list(real.getParent())) { + assertEquals(List.of("floci"), left.map(p -> p.getFileName().toString()).toList(), "no staging file left behind"); + } + } +}