diff --git a/evm/test/Timba.t.sol b/evm/test/Timba.t.sol index dd914b0..5af1f18 100644 --- a/evm/test/Timba.t.sol +++ b/evm/test/Timba.t.sol @@ -6,6 +6,8 @@ import {Timba} from "../src/Timba.sol"; import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol"; +import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol"; +import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract Token is ERC20 { constructor() ERC20("Test", "TST") {} @@ -31,25 +33,29 @@ contract TaxToken is Token { } } -contract CallbackToken is Token { - Timba public target; - bytes32 public game; - bool public blocked; +/// Calls `target` with `data` from inside its next transfer, and passes on that call's revert, +/// so a test sees why the nested call failed. +contract ReentrantToken is Token { + address public target; + bytes public data; - function arm(Timba t, bytes32 id) external { - target = t; - game = id; + function arm(address next, bytes memory call) external { + target = next; + data = call; } - function transferFrom(address from, address to, uint256 amount) public override returns (bool) { - if (address(target) != address(0)) { - try target.joinGame(game, 0, "") { - revert("reentered"); - } catch { - blocked = true; + function _update(address from, address to, uint256 amount) internal override { + address next = target; + if (next != address(0) && from != address(0)) { + target = address(0); + (bool ok, bytes memory reason) = next.call(data); + if (!ok) { + assembly { + revert(add(reason, 32), mload(reason)) + } } } - return super.transferFrom(from, to, amount); + super._update(from, to, amount); } } @@ -76,14 +82,15 @@ contract TimbaV2 is Timba { } // A test-only entropy source exercises exhaustion deterministically. The deployed -// Timba implementation continues to use keccak256 for every rehash. +// Timba implementation continues to use keccak256 for every rehash. Only the last rehash +// (round 31) gives usable entropy, and the budget of 32 samples never reads it. contract ExhaustedEntropyTimba is Timba { function sample(bytes32 entropy, uint256 entries) external pure returns (uint256) { return _sampleWinner(entropy, entries); } - function _rehashWinnerEntropy(bytes32, uint256) internal pure override returns (bytes32) { - return bytes32(0); + function _rehashWinnerEntropy(bytes32, uint256 round) internal pure override returns (bytes32) { + return round == 31 ? bytes32(type(uint256).max) : bytes32(0); } } @@ -498,12 +505,17 @@ contract TimbaTest is Test { Timba.CreateRequest memory r = request(Timba.GameType.Coinflip); r.isPrivate = true; bytes32 game = create(r, true); - bytes memory signature = sign(timba.joinDigest(game, bob, block.timestamp + 10)); + uint256 deadline = block.timestamp + 10; + bytes memory signature = sign(timba.joinDigest(game, bob, deadline)); vm.prank(bob); vm.expectRevert(Timba.InvalidAuthorization.selector); - timba.joinGame(game, block.timestamp + 11, signature); + timba.joinGame(game, deadline + 1, signature); + // The signature is still good at its deadline. + vm.warp(deadline); + vm.expectEmit(true, true, false, true, address(timba)); + emit Timba.PlayerJoined(game, bob, 1, block.number); vm.prank(bob); - timba.joinGame(game, block.timestamp + 10, signature); + timba.joinGame(game, deadline, signature); vm.prank(operator); timba.transferOwnership(bob); vm.prank(bob); @@ -612,15 +624,79 @@ contract TimbaTest is Test { assertEq(tax.balanceOf(address(timba)), 100 ether); } - function testReentrancyBlockedDuringDeposit() public { - CallbackToken callback = new CallbackToken(); - fund(alice, callback); - Timba.CreateRequest memory r = request(Timba.GameType.Coinflip); - r.token = address(callback); - callback.arm(timba, timba.gameIdFor(alice, r.nonce)); - bytes32 game = create(r, true); - assertTrue(callback.blocked()); - assertEq(timba.getGame(game).participants.length, 1); + /// Each entry point that moves tokens, and the upgrade, holds the guard while it runs: a + /// token that calls back into Timba from its transfer cannot join a game. The last lines + /// show the nested join is otherwise valid, so only the guard stops it. + function testReentryFromTransfersAndUpgradesIsBlocked() public { + ReentrantToken hook = new ReentrantToken(); + fund(alice, hook); + fund(bob, hook); + // An open, public giveaway: any address joins it without a transfer. + Timba.CreateRequest memory open = request(Timba.GameType.Giveaway); + open.timeout = 1 days; + bytes32 target = create(open, false); + bytes memory reenter = abi.encodeCall(Timba.joinGame, (target, 0, "")); + bytes4 blocked = ReentrancyGuardTransient.ReentrancyGuardReentrantCall.selector; + + // createGame: the giveaway's deposit. + Timba.CreateRequest memory r = request(Timba.GameType.Giveaway); + r.token = address(hook); + bytes memory signature = sign(timba.creationDigest(r)); + hook.arm(address(timba), reenter); + vm.prank(alice); + vm.expectRevert(blocked); + timba.createGame(r, signature, false); + hook.arm(address(0), ""); + bytes32 giveaway = create(r, false); + + // closeGame: the creator's refund. + hook.arm(address(timba), reenter); + vm.prank(alice); + vm.expectRevert(blocked); + timba.closeGame(giveaway); + + // joinGame: the ticket deposit. + r = request(Timba.GameType.Coinflip); + r.token = address(hook); + hook.arm(address(0), ""); + bytes32 coinflip = create(r, false); + hook.arm(address(timba), reenter); + vm.prank(bob); + vm.expectRevert(blocked); + timba.joinGame(coinflip, 0, ""); + + // completeGame: the prize. + hook.arm(address(0), ""); + join(coinflip, alice); + join(coinflip, bob); + hook.arm(address(timba), reenter); + vm.prank(operator); + vm.expectRevert(blocked); + timba.completeGame(coinflip, SECRET); + + // refundPlayer: an underfilled coinflip that expired. + r = request(Timba.GameType.Coinflip); + r.token = address(hook); + r.timeout = 1; + hook.arm(address(0), ""); + bytes32 expired = create(r, true); + vm.warp(block.timestamp + 1); + hook.arm(address(timba), reenter); + vm.prank(alice); + vm.expectRevert(blocked); + timba.refundPlayer(expired, alice); + + // upgradeToAndCall: its call runs in the proxy while the guard is held. + address next = address(new Timba()); + vm.prank(address(0xad)); + vm.expectRevert(blocked); + timba.upgradeToAndCall(next, reenter); + + vm.prank(address(hook)); + timba.joinGame(target, 0, ""); + vm.prank(address(0xad)); + timba.joinGame(target, 0, ""); + assertEq(timba.getGame(target).participants.length, 2); } function testFuzzAccounting(uint96 rawAmount, uint8 rawFee) public { @@ -651,6 +727,16 @@ contract TimbaTest is Test { vm.prank(operator); vm.expectRevert(Timba.InvalidAuthorization.selector); timba.transferOwnership(address(timba)); + // A stranger is stopped by the owner check before the operator rules. + vm.prank(alice); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, alice)); + timba.renounceOwnership(); + vm.prank(alice); + vm.expectRevert(abi.encodeWithSelector(OwnableUpgradeable.OwnableUnauthorizedAccount.selector, alice)); + timba.transferOwnership(address(timba)); + c.minTimeout = c.maxTimeout; + vm.prank(operator); + timba.configure(c); for (uint256 i; i < 5; i++) { c = defaults(); if (i == 0) c.feePercentage = 11; @@ -690,6 +776,22 @@ contract TimbaTest is Test { assertEq(uint256(timba.getGame(timba.gameIdFor(alice, 0)).status), uint256(Timba.Status.Missing)); } + /// Each creation limit is inclusive: a request at the limit itself is accepted. + function testCreationAcceptsEachLimitItself() public { + for (uint256 i; i < 4; i++) { + Timba.CreateRequest memory r = request(Timba.GameType.Coinflip); + if (i == 0) r.deadline = block.timestamp; + if (i == 1) r.timeout = defaults().minTimeout; + if (i == 2) r.timeout = defaults().maxTimeout; + if (i == 3) r.amount = type(uint256).max / r.maxPlayers; + create(r, false); + } + // The latest start whose expiry and buffer still fit in uint48. + vm.warp(type(uint48).max - 1 hours - timba.MAX_BUFFER()); + create(request(Timba.GameType.Coinflip), false); + assertEq(timba.creationNonces(alice), 5); + } + function testReadyGiveawayCannotCloseEarlyAndRecoversAtLiveBoundary() public { bytes32 game = create(request(Timba.GameType.Giveaway), true); join(game, bob); diff --git a/scripts/check-coverage.test.ts b/scripts/check-coverage.test.ts index 83296d1..e4f93fe 100644 --- a/scripts/check-coverage.test.ts +++ b/scripts/check-coverage.test.ts @@ -65,3 +65,139 @@ test("enforces the threshold and validates merged LCOV reports", async () => { await rm(root, { recursive: true, force: true }); } }); + +/** A git repository with these tracked files, each one line long. */ +async function trackedRepository(files: string[]): Promise { + const root = await mkdtemp(join(tmpdir(), "timba-coverage-scope-")); + for (const file of files) { + await mkdir(join(root, file, ".."), { recursive: true }); + await writeFile(join(root, file), "synthetic\n"); + } + await git(root, "init", "-q"); + await git(root, "add", "."); + return root; +} + +/** Full coverage for each file: one hit line. */ +const covering = (...files: string[]) => + files.map((file) => `SF:${file}\nDA:1,1\nend_of_record\n`).join(""); + +async function gate( + root: string, + config: Parameters[0], + lcov: string, +): Promise>> { + await writeFile(join(root, "report.info"), lcov); + return checkCoverage(config, ["report.info"], root); +} + +test("the scope takes every root, file roots, nested roots and globs", async () => { + const files = [ + "src/a.ts", + "srcx/b.ts", + "lib/c.js", + "pkg/src/d.ts", + "one.ts", + "src/gen-1.ts", + "src/q1.ts", + "src/qq1.ts", + ]; + const root = await trackedRepository(files); + try { + // Missing from the report, so each scoped file is listed. + const scope = async (config: Parameters[0]) => + (await gate(root, config, covering("src/a.ts"))).missing.sort(); + + expect(await scope({ roots: ["src"], extensions: [".ts"] })).toEqual([ + "src/gen-1.ts", + "src/q1.ts", + "src/qq1.ts", + ]); + // Any of several roots, and a root may name a file. + expect(await scope({ roots: ["src", "one.ts"], extensions: [".ts"] })).toEqual([ + "one.ts", + "src/gen-1.ts", + "src/q1.ts", + "src/qq1.ts", + ]); + // Trailing slashes of a nested root do not matter. + expect(await scope({ roots: ["src", "pkg/src//"], extensions: [".ts"] })).toEqual([ + "pkg/src/d.ts", + "src/gen-1.ts", + "src/q1.ts", + "src/qq1.ts", + ]); + // "." is the whole repository, and any of several extensions counts. + expect(await scope({ roots: ["."], extensions: [".js", ".ts"] })).toEqual( + files.filter((file) => file !== "src/a.ts").sort(), + ); + // "*" matches any text and "?" one character. + expect( + await scope({ roots: ["src"], extensions: [".ts"], exclude: ["src/gen-*.ts", "src/q?.ts"] }), + ).toEqual(["src/qq1.ts"]); + await expect(gate(root, { roots: ["none"], extensions: [".ts"] }, "")).rejects.toThrow( + "No source files matched the coverage scope", + ); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("report paths resolve from the report base, and paths outside the root are ignored", async () => { + const root = await trackedRepository(["solana/src/a.rs"]); + try { + const config = { roots: ["solana"], extensions: [".rs"], reportBase: "solana" }; + expect((await gate(root, config, covering("src/a.rs"))).passed).toBe(true); + const unbased = { roots: ["solana"], extensions: [".rs"] }; + expect((await gate(root, unbased, covering("solana/src/a.rs"))).passed).toBe(true); + expect((await gate(root, config, covering(join(root, "solana/src/a.rs")))).passed).toBe(true); + await expect(gate(root, config, covering("../src/a.rs", "/elsewhere/a.rs"))).rejects.toThrow( + "No scoped line data", + ); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("line data is a positive line number, a hit count and maybe a checksum", async () => { + const root = await trackedRepository(["src/a.ts"]); + try { + const config = { roots: ["src"], extensions: [".ts"] }; + const result = await gate(root, config, "SF:src/a.ts\nDA:12,0\nDA:3,10,abc\nend_of_record\n"); + expect([result.covered, result.total]).toEqual([1, 2]); + for (const data of ["x,1", "1,x", "a1,1", "1a,1", "1,1a", "1,a1", "1", "0,1", "-1,1", "1,-1"]) { + await expect(gate(root, config, `SF:src/a.ts\nDA:${data}\nend_of_record\n`)).rejects.toThrow( + "Invalid LCOV line data", + ); + } + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("only a record's own lines count for its file", async () => { + const root = await trackedRepository(["src/a.ts"]); + try { + const config = { roots: ["src"], extensions: [".ts"] }; + // Other entries in a record do not end it, end_of_record does. + const result = await gate( + root, + config, + "SF:src/a.ts\nFN:1,main\nLF:1\nDA:1,1\nend_of_record\nDA:2,0\n", + ); + expect([result.covered, result.total]).toEqual([1, 1]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a directory that is not a git repository has no tracked files", async () => { + const root = await mkdtemp(join(tmpdir(), "timba-coverage-nogit-")); + try { + await expect(checkCoverage({ roots: ["."], extensions: [".ts"] }, [], root)).rejects.toThrow( + "Unable to list tracked source files", + ); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/check-coverage.ts b/scripts/check-coverage.ts index 5035e8e..6f1b6ec 100644 --- a/scripts/check-coverage.ts +++ b/scripts/check-coverage.ts @@ -28,7 +28,7 @@ function isInScope(path: string, config: CoverageConfig): boolean { const normalized = prefix.replace(/\/+$/, ""); return normalized === "." || path === normalized || path.startsWith(`${normalized}/`); }); - return rooted && !(config.exclude ?? []).some((pattern) => globMatches(path, pattern)); + return rooted && !config.exclude?.some((pattern) => globMatches(path, pattern)); } function trackedFiles(root: string): string[] { @@ -36,17 +36,15 @@ function trackedFiles(root: string): string[] { if (result.exitCode !== 0) { throw new Error("Unable to list tracked source files"); } - return new TextDecoder() - .decode(result.stdout) - .split("\0") - .filter(Boolean) - .map((path) => path.replaceAll("\\", "/")); + // git separates paths with "/" and sorts them. The empty name after the last NUL matches no + // extension, so the scope drops it. + return new TextDecoder().decode(result.stdout).split("\0"); } +// A path outside the root starts with "..", which no tracked file does, so it is out of scope. function reportSourcePath(source: string, root: string, reportBase: string): string { const absolute = isAbsolute(source) ? resolve(source) : resolve(root, reportBase, source); - const relativePath = relative(resolve(root), absolute).replaceAll("\\", "/"); - return relativePath === ".." || relativePath.startsWith("../") ? "" : relativePath; + return relative(resolve(root), absolute); } export async function checkCoverage( @@ -68,23 +66,21 @@ export async function checkCoverage( const seen = new Set(); for (const report of reports) { let current: string | undefined; - let reportLines = 0; + let scoped = false; const contents = await Bun.file(resolve(root, report)).text(); for (const entry of contents.split(/\r?\n/)) { if (entry.startsWith("SF:")) { - const name = reportSourcePath(entry.slice(3), root, config.reportBase ?? "."); + const name = reportSourcePath(entry.slice(3), root, config.reportBase ?? ""); current = sources.has(name) ? name : undefined; } else if (entry.startsWith("DA:") && current) { - const [lineNumber, hitCount] = entry.slice(3).split(","); - if (!/^-?\d+$/.test(lineNumber ?? "") || !/^-?\d+$/.test(hitCount ?? "")) { + // DA:,[,] + const data = /^(\d+),(\d+)(?:,|$)/.exec(entry.slice(3)); + const number = Number(data?.[1]); + if (!data || number === 0) { throw new Error("Invalid LCOV line data"); } - const number = Number(lineNumber); - const hits = Number(hitCount); - if (number <= 0 || hits < 0) { - throw new Error("Invalid LCOV line data"); - } - reportLines += 1; + const hits = Number(data[2]); + scoped = true; seen.add(current); const key = `${current}\0${number}`; lines.set(key, (lines.get(key) ?? false) || hits > 0); @@ -92,7 +88,7 @@ export async function checkCoverage( current = undefined; } } - if (reportLines === 0) { + if (!scoped) { throw new Error(`No scoped line data in ${report}`); } } @@ -100,7 +96,7 @@ export async function checkCoverage( if (lines.size === 0) { throw new Error("No instrumented source lines in coverage reports"); } - const missing = [...sources].filter((path) => !seen.has(path)).sort(); + const missing = [...sources].filter((path) => !seen.has(path)); const covered = [...lines.values()].filter(Boolean).length; const total = lines.size; return { @@ -136,6 +132,9 @@ export async function main(args: string[], root = process.cwd()): Promise/dev/null || true) - if [[ -z $list || $list == '[]' ]]; then - echo "cargo-mutants found no mutant to test: check examine_globs in solana/.cargo/mutants.toml." >&2 - return 1 + [[ -n $list && $list != '[]' ]] +} + +# Fails when cargo-mutants found nothing to mutate. For a part of everything that means the +# setup is broken (the scope matches no file), not that every change was caught. A part can +# also be empty because there are fewer mutants than parts: ALL_LIST, the output of the +# unsharded `cargo mutants --list`, and the number of PARTS tell the two apart. With as many +# mutants as parts, round-robin gives every part one, so an empty part is a broken run. +found() { + has_mutants "$1" && return 0 + local all=0 + if [[ -n ${2:-} ]]; then all=$(grep -c . "$2" 2>/dev/null || true); fi + if (( ${all:-0} > 0 && ${all:-0} < ${3:-0} )); then + echo "This part has no mutant: there are $all mutants for ${3} parts." + return 0 fi + echo "cargo-mutants found no mutant to test: check examine_globs in solana/.cargo/mutants.toml." >&2 + return 1 } mode=${1:-} if [[ $mode == found ]]; then - found "${2:?$usage}" + found "${2:?$usage}" "${3:-}" "${4:-}" exit 0 fi if [[ $mode == summarize ]]; then @@ -101,7 +115,10 @@ case "$mode" in args+=(--in-diff "$diff") ;; shard) - args+=(--shard "${2:?$usage}") + # Round-robin, so every part gets a share. The default gives each part a run of + # ceil(total/N) mutants, which can leave the last parts empty: 194 mutants in 64 + # parts (November 2026) gave parts 0-48 four each and parts 49-63 none. + args+=(--shard "${2:?$usage}" --sharding round-robin) ;; esac # A mutant can allocate forever. Without a limit it fills the runner's memory and @@ -121,5 +138,8 @@ if [[ $status != 0 && $status != 2 && $status != 3 ]]; then echo "cargo-mutants stopped (exit $status) before its tally." >&2 exit "$status" fi -if [[ $mode == shard ]]; then found "$raw/mutants.out"; fi +if [[ $mode == shard ]] && ! has_mutants "$raw/mutants.out"; then + (cd solana && cargo mutants --list --package timba) > "$raw/all-mutants.txt" + found "$raw/mutants.out" "$raw/all-mutants.txt" "${2#*/}" +fi summarize "$raw/mutants.out" "$out" diff --git a/scripts/mutants-rust.test.ts b/scripts/mutants-rust.test.ts index 225e3af..f92bb6e 100644 --- a/scripts/mutants-rust.test.ts +++ b/scripts/mutants-rust.test.ts @@ -74,10 +74,15 @@ describe("mutants-rust summarize", () => { }); describe("mutants-rust found", () => { - function found(list: string | null) { + function found(list: string | null, all?: string, parts = "64") { const root = mkdtempSync(join(dir, "found-")); if (list !== null) writeFileSync(join(root, "mutants.json"), list); - return spawnSync("bash", [script, "found", root], { encoding: "utf8" }); + const args = [script, "found", root]; + if (all !== undefined) { + writeFileSync(join(root, "all.txt"), all); + args.push(join(root, "all.txt"), parts); + } + return spawnSync("bash", args, { encoding: "utf8" }); } test("a list with mutants passes", () => { @@ -91,6 +96,34 @@ describe("mutants-rust found", () => { expect(run.stderr).toContain("examine_globs"); } }); + + test("an empty part passes when there are fewer mutants than parts", () => { + const run = found( + "[]", + "src/state.rs:1:1: replace f with ()\nsrc/state.rs:2:1: replace g with ()\n", + "3", + ); + expect(run.status).toBe(0); + expect(run.stdout).toContain("2 mutants for 3 parts"); + }); + + test("an empty part fails when every part should have a mutant", () => { + const run = found( + "[]", + "src/state.rs:1:1: replace f with ()\nsrc/state.rs:2:1: replace g with ()\n", + "2", + ); + expect(run.status).toBe(1); + expect(run.stderr).toContain("examine_globs"); + }); + + test("an empty part fails when the unsharded list is empty too", () => { + for (const all of ["", "\n"]) { + const run = found("[]", all); + expect(run.status).toBe(1); + expect(run.stderr).toContain("examine_globs"); + } + }); }); describe("mutants-rust memory limit", () => { diff --git a/scripts/mutants-sol/run.py b/scripts/mutants-sol/run.py index 794f18c..f2781c6 100644 --- a/scripts/mutants-sol/run.py +++ b/scripts/mutants-sol/run.py @@ -23,6 +23,15 @@ ROOT = Path(__file__).resolve().parents[2] MAX_CHANGE = 70 +# Changes that keep the same behavior, so no test can catch them: (file, the change as +# describe() writes it) -> why. The filter drops them before they run. +EQUIVALENT = { + ("evm/src/Timba.sol", "remove __Ownable2Step_init();"): ( + "OpenZeppelin's __Ownable2Step_init has an empty body and only the onlyInitializing " + "check, which always passes inside initialize. The call stays, because OpenZeppelin " + "asks every parent initializer to be called." + ), +} def parse_ranges(text): @@ -79,7 +88,8 @@ def write_results(out, rows, tally): def range_filter(base, ranges, prefix): """A vertigo-rs filter (a `base` subclass) that keeps one copy of each change that - starts on a requested line. `prefix` turns a project path into a repository path.""" + starts on a requested line and is not in EQUIVALENT. `prefix` turns a project path + into a repository path.""" class RangeFilter(base): def apply(self, mutations): @@ -90,6 +100,8 @@ def apply(self, mutations): key = (file, tuple(mutation.location), mutation.value) if key in seen or not in_ranges(ranges, file, mutation.line_number + 1): continue + if (file, describe(mutation.original_value, mutation.value)) in EQUIVALENT: + continue seen.add(key) kept.append(mutation) return kept diff --git a/scripts/mutants-sol/test_run.py b/scripts/mutants-sol/test_run.py index 6c08c78..81875a7 100644 --- a/scripts/mutants-sol/test_run.py +++ b/scripts/mutants-sol/test_run.py @@ -112,6 +112,15 @@ def test_keeps_one_copy_of_each_change_on_a_requested_line(self): kept = run.range_filter(object, ranges, "evm/").apply(mutations) self.assertEqual(kept, [mutations[1], mutations[3], mutations[4]]) + def test_drops_changes_that_keep_the_same_behavior(self): + ranges = run.parse_ranges("evm/src/Timba.sol:1-200") + other = Mutation("src/Timba.sol", 123, [1, 1, 0], "") + other.original_value = "_configure(initialConfig);" + equivalent = Mutation("src/Timba.sol", 123, [2, 1, 0], "") + equivalent.original_value = "__Ownable2Step_init();" + kept = run.range_filter(object, ranges, "evm/").apply([other, equivalent]) + self.assertEqual(kept, [other]) + class Collect(unittest.TestCase): def test_only_changes_with_a_verdict_count(self): diff --git a/scripts/supplement-sbf-coverage.test.ts b/scripts/supplement-sbf-coverage.test.ts index 7405fd1..95933e1 100644 --- a/scripts/supplement-sbf-coverage.test.ts +++ b/scripts/supplement-sbf-coverage.test.ts @@ -1,5 +1,8 @@ import { expect, test } from "bun:test"; -import { supplementSourceHits } from "./supplement-sbf-coverage"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { main, supplementSourceHits } from "./supplement-sbf-coverage"; test("supplements matching deployed source lines without dropping misses or changing inventory", () => { const sbf = "SF:programs/timba/src/state.rs\nDA:10,0\nDA:20,0\nDA:30,2\nend_of_record\n"; @@ -18,3 +21,44 @@ test("recomputes per-record LCOV summaries while preserving checksums", () => { sbf.replace("DA:1,0,abc", "DA:1,2,abc").replace("LH:1", "LH:2"), ); }); + +test("host summary lines add nothing, and every field after the count is kept", () => { + const sbf = "SF:one.rs\nDA:1,0,a,b\nDA:2,0\nLF:9\nLH:9\nend_of_record\n"; + const host = "SF:one.rs\nDA:1,2\nLF:2\nLH:1\nend_of_record\n"; + expect(supplementSourceHits(sbf, host, "/repo")).toBe( + "SF:one.rs\nDA:1,2,a,b\nDA:2,0\nLF:2\nLH:1\nend_of_record\n", + ); +}); + +test("the command line writes the supplemented report and needs all three paths", async () => { + const dir = mkdtempSync(join(tmpdir(), "timba-supplement-")); + try { + const sbf = join(dir, "sbf.lcov"); + const host = join(dir, "host.lcov"); + const output = join(dir, "out.lcov"); + writeFileSync(sbf, "SF:a.rs\nDA:1,0\nend_of_record\n"); + writeFileSync(host, "SF:a.rs\nDA:1,3\nend_of_record\n"); + await main([sbf, host, output], dir); + expect(readFileSync(output, "utf8")).toBe("SF:a.rs\nDA:1,3\nend_of_record\n"); + for (const args of [[], [sbf], [sbf, host], ["", host, output], [sbf, "", output]]) { + await expect(main(args, dir)).rejects.toThrow("Expected SBF, host and output LCOV paths"); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("the command line reads host paths relative to the solana directory by default", async () => { + const dir = mkdtempSync(join(tmpdir(), "timba-supplement-")); + try { + const sbf = join(dir, "sbf.lcov"); + const host = join(dir, "host.lcov"); + const output = join(dir, "out.lcov"); + writeFileSync(sbf, "SF:a.rs\nDA:1,0\nend_of_record\n"); + writeFileSync(host, `SF:${resolve("solana", "a.rs")}\nDA:1,3\nend_of_record\n`); + await main([sbf, host, output]); + expect(readFileSync(output, "utf8")).toBe("SF:a.rs\nDA:1,3\nend_of_record\n"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/scripts/supplement-sbf-coverage.ts b/scripts/supplement-sbf-coverage.ts index 1a20494..64626e8 100644 --- a/scripts/supplement-sbf-coverage.ts +++ b/scripts/supplement-sbf-coverage.ts @@ -5,6 +5,8 @@ import { resolve } from "path"; // for those same source lines, including guards blocked by account validation. export function supplementSourceHits(sbf: string, host: string, base: string): string { const hits = new Map(); + // Stryker disable next-line StringLiteral: a DA line before any SF line is not LCOV, and its key + // matches no source line whatever this is. let source = ""; for (const entry of host.split(/\r?\n/)) { if (entry.startsWith("SF:")) source = resolve(base, entry.slice(3)); @@ -37,15 +39,15 @@ export function supplementSourceHits(sbf: string, host: string, base: string): s .join("end_of_record"); } -if (import.meta.main) { - const [sbf, host, output] = process.argv.slice(2); +/** The command line: ` `, host paths relative to `base`. */ +export async function main(args: string[], base = resolve("solana")): Promise { + const [sbf, host, output] = args; if (!sbf || !host || !output) throw new Error("Expected SBF, host and output LCOV paths"); await Bun.write( output, - supplementSourceHits( - await Bun.file(sbf).text(), - await Bun.file(host).text(), - resolve("solana"), - ), + supplementSourceHits(await Bun.file(sbf).text(), await Bun.file(host).text(), base), ); } + +// Stryker disable next-line all: only a subprocess runs this; the tests call main. +if (import.meta.main) await main(process.argv.slice(2));