From 9dafcc7314f0fea3ccba81ea01695bd4bd4f9676 Mon Sep 17 00:00:00 2001 From: Hanif Koh Date: Fri, 27 Nov 2026 12:48:05 +0800 Subject: [PATCH] Compare a Pull Request's Sliced G-code With Its Base Branch in the Slice Check On a pull request, the Slice check now finds the newest build of the base branch at or before the pull request's base commit that saved fingerprints, compares them with its own, and writes report.txt into the gcode-fingerprints artifact and the report into the job summary. Every build also writes made_with.txt, the fingerprint script's hash and the runner, so a report warns when the two sides were made differently. scripts/ci_check_gcode.py reads the baseline's artifact in memory: the download and each file in it are capped, and a file compressed with anything but stored or deflate is refused, since a capped read does not bound bzip2 or LZMA. An error writes its type only, never the text of the files, and the step cannot fail the job. --- .github/workflows/build_all.yml | 26 ++- scripts/ci_check_gcode.py | 288 ++++++++++++++++++++++++++ scripts/tests/test_ci_check_gcode.py | 290 +++++++++++++++++++++++++++ 3 files changed, 601 insertions(+), 3 deletions(-) create mode 100644 scripts/ci_check_gcode.py create mode 100644 scripts/tests/test_ci_check_gcode.py diff --git a/.github/workflows/build_all.yml b/.github/workflows/build_all.yml index 4d5f3653e5..c2c38a4eba 100644 --- a/.github/workflows/build_all.yml +++ b/.github/workflows/build_all.yml @@ -279,6 +279,10 @@ jobs: if: ${{ !cancelled() && success() }} # Follows whichever Linux leg built the validator. runs-on: ${{ vars.SELF_HOSTED && 'orca-lnx-server' || 'ubuntu-24.04-arm' }} + # actions: read finds the base branch's fingerprints for the comparison below. + permissions: + actions: read + contents: read steps: - name: Checkout repository uses: actions/checkout@v7 @@ -294,8 +298,8 @@ jobs: run: | chmod +x validator-bin/OrcaSlicer_profile_validator ./validator-bin/OrcaSlicer_profile_validator -p "${{ github.workspace }}/resources/profiles" -s -l 2 -o "${{ runner.temp }}/sliced-gcode" - # The fingerprints are for comparing builds, not a check: neither step - # below may fail the job. + # The fingerprints are for comparing builds, not a check: none of the + # steps below may fail the job. - name: Fingerprint the sliced G-code id: fingerprint continue-on-error: true @@ -303,6 +307,22 @@ jobs: run: | mkdir -p "${{ runner.temp }}/gcode-fingerprints" python3 scripts/gcode_fingerprint.py fingerprint "${{ runner.temp }}/sliced-gcode" -o "${{ runner.temp }}/gcode-fingerprints/fingerprints.tsv" + python3 scripts/ci_check_gcode.py made-with -o "${{ runner.temp }}/gcode-fingerprints/made_with.txt" + # check_gcode_comment.yml posts report.txt on a pull request with the + # check-gcode label. HEAD is the merge commit, so HEAD^1 is the base. + - name: Compare with the base branch + if: ${{ github.event_name == 'pull_request' && steps.fingerprint.outcome == 'success' }} + continue-on-error: true + timeout-minutes: 5 + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + out="${{ runner.temp }}/gcode-fingerprints" + echo "$PR_NUMBER" > "$out/pr_number.txt" + git fetch --no-tags --depth=2 origin "$(git rev-parse HEAD)" + python3 scripts/ci_check_gcode.py report --repo "$GITHUB_REPOSITORY" --branch "$GITHUB_BASE_REF" \ + --base-sha "$(git rev-parse HEAD^1)" --head-dir "$out" --out "$out/report.txt" --summary "$GITHUB_STEP_SUMMARY" - name: Upload the fingerprints if: ${{ steps.fingerprint.outcome == 'success' }} continue-on-error: true @@ -310,7 +330,7 @@ jobs: uses: actions/upload-artifact@v7 with: name: gcode-fingerprints - path: ${{ runner.temp }}/gcode-fingerprints/fingerprints.tsv + path: ${{ runner.temp }}/gcode-fingerprints/ # A re-run of the job replaces the file. overwrite: true # A pull request's file is compared with its base branch's, so those are kept longer. diff --git a/scripts/ci_check_gcode.py b/scripts/ci_check_gcode.py new file mode 100644 index 0000000000..5afb799419 --- /dev/null +++ b/scripts/ci_check_gcode.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Compares a pull request's sliced G-code with its base branch's, for the check-gcode label. + +The Slice check job of build_all.yml fingerprints the G-code of every shipped printer preset +(gcode_fingerprint.py) and uploads the gcode-fingerprints artifact. On a pull request, +`report` then finds the newest build of the base branch with fingerprints, at or before the +pull request's base commit, and writes report.txt into the same artifact. Pushes and the +nightly build are the baselines; they upload only fingerprints.tsv and made_with.txt. + +Environment: GH_TOKEN, and optionally GITHUB_API_URL. +""" + +import argparse +import hashlib +import io +import json +import os +import platform +import sys +import tempfile +import urllib.error +import urllib.parse +import urllib.request +import zipfile +from dataclasses import dataclass, field + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import gcode_fingerprint # noqa: E402 + +# Must match the artifact name and the workflow file in build_all.yml. +ARTIFACT = "gcode-fingerprints" +WORKFLOW = "build_all.yml" +# How far back from the base commit a baseline is looked for. +COMMITS_BACK = 30 +# A deflated artifact is refused when it is larger than this many times the member limit. +ZIP_FACTOR = 4 +# fingerprints.tsv is about 60 KB for 1,336 slices. +FINGERPRINTS_LIMIT = 4 * 1024 * 1024 +SMALL_LIMIT = 4096 +# How many slice names are listed under each vendor. +NAMES_PER_VENDOR = 20 +# The report's baseline paragraph starts with this. It changes with every push to the base branch, +# so the commenter edits a comment in place when only that part changed. +BASELINE_LINE = "Baseline: " +# A comment holds at most 65,536 characters; the report inside it is cut well before. +FENCE_LIMIT = 50000 +FENCE = "````" +# Only these are bounded by a capped read; bzip2 and LZMA decompress a whole block at once. +READABLE_COMPRESSION = (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED) + + +class ArtifactError(Exception): + """An artifact that cannot be read. The message never holds the artifact's own text.""" + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +class Api: + def __init__(self, token, url="https://api.github.com"): + self.token = token + self.url = url.rstrip("/") + + def _request(self, method, path, params=None, body=None): + query = f"?{urllib.parse.urlencode(params)}" if params else "" + data = json.dumps(body).encode() if body is not None else None + return urllib.request.Request(f"{self.url}/{path}{query}", data=data, method=method, headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {self.token}", + "X-GitHub-Api-Version": "2022-11-28", + }) + + def get(self, path, **params): + with urllib.request.urlopen(self._request("GET", path, params), timeout=30) as response: + return json.load(response) + + def get_bytes(self, path, limit): + """The body of a download, read up to `limit` bytes. The redirect to storage is followed + without the token, which the storage host must not see.""" + opener = urllib.request.build_opener(_NoRedirect) + try: + response = opener.open(self._request("GET", path), timeout=60) + except urllib.error.HTTPError as error: + if error.code not in (301, 302, 303, 307, 308): + raise + location = error.headers["Location"] + error.close() + response = urllib.request.urlopen(location, timeout=60) + with response: + data = response.read(limit + 1) + if len(data) > limit: + raise ArtifactError("the artifact is larger than its limit") + return data + + +@dataclass +class Baseline: + sha: str + title: str + run_id: int + artifact: dict + between: list = field(default_factory=list) # (short sha, title), the base first + + +def short(sha): + return sha[:10] + + +def title_of(commit): + message = commit["commit"]["message"] + return message.splitlines()[0] if message else "" + + +def find_artifact(api, repo, run_id): + """The run's unexpired gcode-fingerprints artifact, or None.""" + body = api.get(f"repos/{repo}/actions/runs/{run_id}/artifacts", name=ARTIFACT) + for art in body["artifacts"]: + if art["name"] == ARTIFACT and not art["expired"]: + return art + return None + + +def read_artifact(api, repo, art, names, limit): + """{name: bytes} for each of `names` the artifact holds. The zip is read in memory, and its + directory is the pull request's data, so each member is read with a cap of its own.""" + if art["size_in_bytes"] > ZIP_FACTOR * limit: + raise ArtifactError("the artifact is larger than its limit") + data = api.get_bytes(f"repos/{repo}/actions/artifacts/{art['id']}/zip", limit=ZIP_FACTOR * limit) + found = {} + try: + with zipfile.ZipFile(io.BytesIO(data)) as zf: + present = {info.filename: info for info in zf.infolist()} + for name in names: + if name not in present: + continue + if present[name].compress_type not in READABLE_COMPRESSION: + raise ArtifactError("an artifact file uses a compression that is not read") + with zf.open(present[name]) as member: + content = member.read(limit + 1) + if len(content) > limit: + raise ArtifactError("an artifact file is larger than its limit") + found[name] = content + except (zipfile.BadZipFile, zipfile.LargeZipFile, NotImplementedError, EOFError, OSError) as error: + raise ArtifactError("the artifact is not a readable zip") from error + return found + + +def find_baseline(api, repo, branch, base_sha): + """The newest commit at or before base_sha whose branch build saved fingerprints, or None.""" + commits = api.get(f"repos/{repo}/commits", sha=base_sha, per_page=COMMITS_BACK) + # Asked for by event: pull request runs from forks' own branches of the same name would + # otherwise fill the window. + runs_of = {} + for event in ("push", "schedule"): + runs = api.get(f"repos/{repo}/actions/workflows/{WORKFLOW}/runs", branch=branch, event=event, per_page=100) + for run in runs["workflow_runs"]: + runs_of.setdefault(run["head_sha"], []).append(run) + for sha_runs in runs_of.values(): + sha_runs.sort(key=lambda r: r["id"], reverse=True) + for index, commit in enumerate(commits): + for run in runs_of.get(commit["sha"], []): + art = find_artifact(api, repo, run["id"]) + if art: + between = [(short(c["sha"]), title_of(c)) for c in commits[:index]] + return Baseline(commit["sha"], title_of(commit), run["id"], art, between) + return None + + +def made_with(script_path): + with open(script_path, "rb") as f: + script = hashlib.sha256(f.read()).hexdigest() + return f"fingerprint script {script}\nrunner {platform.system()} {platform.machine()}\n" + + +def build_report(baseline, base_rows, head_rows, base_made_with, head_made_with, branch): + if baseline is None: + return (f"No build of {branch} among the last {COMMITS_BACK} commits up to this pull request's " + "base has saved fingerprints, so nothing was compared.\n") + lines = [] + if not base_made_with or not head_made_with: + lines.append("Warning: one side does not say which fingerprint script and runner made it, " + "so slices may differ for that reason alone.") + elif base_made_with != head_made_with: + lines.append("Warning: the two sides were made by a different fingerprint script or runner, " + "so slices may differ for that reason alone.") + report = gcode_fingerprint.compare(base_rows, head_rows) + text = gcode_fingerprint.format_report(report, NAMES_PER_VENDOR) + if report.same_count + len(report.changed) == 0: + text = "No slice could be compared: the two sides have none in common.\n" + text.split("\n", 1)[1] + lines.append(text) + if baseline.between: + lines.append(f"{BASELINE_LINE}compared with the build of {short(baseline.sha)} ({baseline.title}). " + "These later commits up to the base have no saved fingerprints, so changes " + "they made to the G-code show here too:") + lines += [f" {sha} {title}" for sha, title in baseline.between] + else: + lines.append(f"{BASELINE_LINE}compared with the build of {short(baseline.sha)} ({baseline.title}), " + "this pull request's base commit.") + return "\n".join(lines) + "\n" + + +def fence(data): + """Text from an artifact as a Markdown code block nothing in it can close or turn into markup.""" + text = data.decode("utf-8", "replace") + text = "".join(c for c in text if c in "\n\t" or (c >= " " and c != "\x7f")) + while FENCE in text: + text = text.replace(FENCE, "```") + if len(text.encode()) > FENCE_LIMIT: + cut = text.encode()[:FENCE_LIMIT].decode("utf-8", "ignore") + if "\n" in cut: + cut = cut[:cut.rindex("\n") + 1] + text = cut + ("" if cut.endswith("\n") else "\n") + "... (report cut)\n" + if not text.endswith("\n"): + text += "\n" + return f"{FENCE}\n{text}{FENCE}\n" + + +def _rows_from_bytes(data): + with tempfile.TemporaryDirectory() as folder: + path = os.path.join(folder, "fingerprints.tsv") + with open(path, "wb") as f: + f.write(data) + return gcode_fingerprint.read_fingerprints(path) + + +def _read_text(path): + try: + with open(path, encoding="utf-8") as f: + return f.read() + except OSError: + return None + + +def report_main(args, api): + head_rows = gcode_fingerprint.read_fingerprints(os.path.join(args.head_dir, "fingerprints.tsv")) + head_made_with = _read_text(os.path.join(args.head_dir, "made_with.txt")) + baseline = find_baseline(api, args.repo, args.branch, args.base_sha) + base_rows = base_made_with = None + if baseline: + files = read_artifact(api, args.repo, baseline.artifact, ["fingerprints.tsv", "made_with.txt"], + FINGERPRINTS_LIMIT) + if "fingerprints.tsv" not in files: + raise ArtifactError("the baseline has no fingerprints.tsv") + base_rows = _rows_from_bytes(files["fingerprints.tsv"]) + base_made_with = files.get("made_with.txt", b"").decode("utf-8", "replace") or None + return build_report(baseline, base_rows, head_rows, base_made_with, head_made_with, args.branch) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + made = commands.add_parser("made-with", help="print what made a fingerprint file") + made.add_argument("-o", "--out", required=True) + report = commands.add_parser("report", help="compare this build's fingerprints with the base branch's") + report.add_argument("--repo", required=True) + report.add_argument("--branch", required=True) + report.add_argument("--base-sha", required=True) + report.add_argument("--head-dir", required=True) + report.add_argument("--out", required=True) + report.add_argument("--summary", help="a job summary file to append the report to") + args = parser.parse_args(argv) + + if args.command == "made-with": + script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gcode_fingerprint.py") + with open(args.out, "w", encoding="utf-8", newline="\n") as f: + f.write(made_with(script)) + return 0 + + api = Api(os.environ.get("GH_TOKEN", ""), os.environ.get("GITHUB_API_URL", "https://api.github.com")) + try: + text = report_main(args, api) + except (ArtifactError, urllib.error.URLError, OSError, ValueError, KeyError, TypeError) as error: + # The type only: the message of an error from the baseline's files can hold their text. + print(f"The comparison could not be made ({type(error).__name__}).") + text = f"The comparison could not be made ({type(error).__name__}).\n" + with open(args.out, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + if args.summary: + with open(args.summary, "a", encoding="utf-8", newline="\n") as f: + f.write("## Sliced G-code comparison\n\n" + fence(text.encode())) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/tests/test_ci_check_gcode.py b/scripts/tests/test_ci_check_gcode.py new file mode 100644 index 0000000000..ee8a4315fd --- /dev/null +++ b/scripts/tests/test_ci_check_gcode.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""Tests for scripts/ci_check_gcode.py (stdlib unittest, no external deps). + +Run from the repo root: python3 -m unittest discover -s scripts/tests -t scripts +""" + +import contextlib +import io +import os +import sys +import tempfile +import unittest +import zipfile +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +import ci_check_gcode as cc # noqa: E402 + +REPO = "owner/repo" +LIMIT = 1000 + + +def make_zip(members, compression=zipfile.ZIP_DEFLATED): + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression) as zf: + for name, data in members.items(): + zf.writestr(name, data) + return buffer.getvalue() + + +class FakeApi: + """Answers get() from a dict of path -> body (or a function of the params), get_bytes() from blobs.""" + + def __init__(self, gets=None, blobs=None): + self.gets = gets or {} + self.blobs = blobs or {} + self.calls = [] + + def get(self, path, **params): + self.calls.append(("GET", path, params)) + body = self.gets[path] + return body(params) if callable(body) else body + + def get_bytes(self, path, limit): + self.calls.append(("BYTES", path, limit)) + return self.blobs[path] + + +def artifact(artifact_id, size=100, expired=False): + return {"id": artifact_id, "name": cc.ARTIFACT, "size_in_bytes": size, "expired": expired} + + +def commit(sha, title): + return {"sha": sha, "commit": {"message": f"{title}\n\nBody text."}} + + +def run(run_id, sha, event="push"): + return {"id": run_id, "head_sha": sha, "event": event} + + +class ReadArtifactTest(unittest.TestCase): + def api_with(self, data, size=None): + art = artifact(7, size=len(data) if size is None else size) + return FakeApi(blobs={f"repos/{REPO}/actions/artifacts/7/zip": data}), art + + def test_reads_the_named_members_and_leaves_out_missing_ones(self): + api, art = self.api_with(make_zip({"fingerprints.tsv": "a\tb\t\n", "made_with.txt": "x\n"})) + got = cc.read_artifact(api, REPO, art, ["fingerprints.tsv", "report.txt"], LIMIT) + self.assertEqual(got, {"fingerprints.tsv": b"a\tb\t\n"}) + + def test_a_member_larger_than_the_limit_is_refused_whatever_the_directory_says(self): + data = make_zip({"report.txt": "x" * (LIMIT + 1)}) + # The directory's sizes come from the pull request, so they are not trusted. + forged = data.replace((LIMIT + 1).to_bytes(4, "little"), (10).to_bytes(4, "little")) + api, art = self.api_with(forged) + with self.assertRaises(cc.ArtifactError): + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + + def test_an_artifact_over_the_size_cap_is_refused_before_it_is_downloaded(self): + api, art = self.api_with(b"", size=cc.ZIP_FACTOR * LIMIT + 1) + with self.assertRaises(cc.ArtifactError): + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + self.assertEqual([c for c in api.calls if c[0] == "BYTES"], []) + + def test_the_download_itself_is_capped(self): + api, art = self.api_with(make_zip({"report.txt": "ok"})) + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + self.assertEqual(api.calls[-1][2], cc.ZIP_FACTOR * LIMIT) + + def test_a_member_not_asked_for_is_never_opened(self): + api, art = self.api_with(make_zip({"report.txt": "ok", "other.bin": "y" * (LIMIT * 3)})) + self.assertEqual(cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT), {"report.txt": b"ok"}) + + def test_a_member_compressed_with_bzip2_or_lzma_is_refused(self): + # read(limit + 1) does not bound how much of such a member is decompressed. + for compression in (zipfile.ZIP_BZIP2, zipfile.ZIP_LZMA): + api, art = self.api_with(make_zip({"report.txt": "ok"}, compression)) + with self.assertRaises(cc.ArtifactError): + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + + def test_a_stored_member_is_read(self): + api, art = self.api_with(make_zip({"report.txt": "ok"}, zipfile.ZIP_STORED)) + self.assertEqual(cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT), {"report.txt": b"ok"}) + + def test_a_file_that_is_not_a_zip_is_an_artifact_error(self): + api, art = self.api_with(b"not a zip") + with self.assertRaises(cc.ArtifactError): + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + + +class FindArtifactTest(unittest.TestCase): + def test_skips_an_expired_artifact(self): + api = FakeApi(gets={f"repos/{REPO}/actions/runs/5/artifacts": { + "artifacts": [artifact(1, expired=True), artifact(2)]}}) + self.assertEqual(cc.find_artifact(api, REPO, 5)["id"], 2) + + def test_none_when_the_run_has_no_artifact(self): + api = FakeApi(gets={f"repos/{REPO}/actions/runs/5/artifacts": {"artifacts": []}}) + self.assertIsNone(cc.find_artifact(api, REPO, 5)) + + +class FindBaselineTest(unittest.TestCase): + def api(self, commits, runs, artifacts): + def runs_of(params): + # GitHub filters by event; the fake does the same. + return {"workflow_runs": [r for r in runs if r["event"] == params["event"]]} + gets = { + f"repos/{REPO}/commits": commits, + f"repos/{REPO}/actions/workflows/build_all.yml/runs": runs_of, + } + for run_id, arts in artifacts.items(): + gets[f"repos/{REPO}/actions/runs/{run_id}/artifacts"] = {"artifacts": arts} + return FakeApi(gets=gets) + + COMMITS = [commit("c3" * 20, "Third"), commit("c2" * 20, "Second"), commit("c1" * 20, "First")] + + def test_the_base_commit_has_fingerprints(self): + api = self.api(self.COMMITS, [run(30, "c3" * 20)], {30: [artifact(300)]}) + baseline = cc.find_baseline(api, REPO, "main", "c3" * 20) + self.assertEqual((baseline.sha, baseline.run_id, baseline.artifact["id"], baseline.between), + ("c3" * 20, 30, 300, [])) + + def test_an_older_commit_has_them_and_the_commits_after_it_are_listed(self): + api = self.api(self.COMMITS, [run(10, "c1" * 20)], {10: [artifact(100)]}) + baseline = cc.find_baseline(api, REPO, "main", "c3" * 20) + self.assertEqual(baseline.sha, "c1" * 20) + self.assertEqual(baseline.title, "First") + self.assertEqual(baseline.between, [("c3c3c3c3c3", "Third"), ("c2c2c2c2c2", "Second")]) + + def test_a_pull_request_run_of_a_base_commit_is_not_a_baseline(self): + api = self.api(self.COMMITS, [run(31, "c3" * 20, event="pull_request"), run(20, "c2" * 20)], + {31: [artifact(310)], 20: [artifact(200)]}) + self.assertEqual(cc.find_baseline(api, REPO, "main", "c3" * 20).run_id, 20) + + def test_a_nightly_run_is_a_baseline(self): + api = self.api(self.COMMITS, [run(40, "c3" * 20, event="schedule")], {40: [artifact(400)]}) + self.assertEqual(cc.find_baseline(api, REPO, "main", "c3" * 20).run_id, 40) + + def test_a_run_without_a_live_artifact_is_skipped(self): + api = self.api(self.COMMITS, [run(30, "c3" * 20), run(20, "c2" * 20)], + {30: [artifact(300, expired=True)], 20: [artifact(200)]}) + self.assertEqual(cc.find_baseline(api, REPO, "main", "c3" * 20).run_id, 20) + + def test_none_when_no_commit_in_reach_has_fingerprints(self): + api = self.api(self.COMMITS, [run(30, "c3" * 20)], {30: []}) + self.assertIsNone(cc.find_baseline(api, REPO, "main", "c3" * 20)) + + def test_asks_for_the_commits_ending_at_the_base_on_the_named_branch(self): + api = self.api(self.COMMITS, [], {}) + cc.find_baseline(api, REPO, "release/2.5", "c3" * 20) + self.assertIn(("GET", f"repos/{REPO}/commits", {"sha": "c3" * 20, "per_page": cc.COMMITS_BACK}), api.calls) + for event in ("push", "schedule"): + self.assertIn(("GET", f"repos/{REPO}/actions/workflows/build_all.yml/runs", + {"branch": "release/2.5", "event": event, "per_page": 100}), api.calls) + + +def rows(**slices): + return {name: (digest, "") for name, digest in slices.items()} + + +MADE_WITH = "fingerprint script abc\nrunner Linux aarch64\n" + + +class FenceTest(unittest.TestCase): + def test_a_run_of_backticks_cannot_close_the_fence(self): + fenced = cc.fence(b"a ```` b ````` c\n") + body = fenced.split("\n")[1:-2] + self.assertTrue(fenced.startswith("````\n") and fenced.endswith("\n````\n")) + self.assertFalse(any("````" in line for line in body)) + + def test_control_characters_are_dropped_and_bad_utf8_replaced(self): + fenced = cc.fence(b"a\x00b\x1b[31mc\td\xff\n") + self.assertIn("ab[31mc\td\ufffd", fenced) + + def test_a_long_report_is_cut_on_a_line_boundary_inside_the_fence(self): + fenced = cc.fence(("x" * 99 + "\n").encode() * 1000) + self.assertLessEqual(len(fenced.encode()), cc.FENCE_LIMIT + 200) + self.assertIn("report cut", fenced) + self.assertTrue(fenced.endswith("\n````\n")) + lines = fenced.split("\n")[1:-3] + self.assertTrue(all(line == "x" * 99 for line in lines)) + + def test_a_single_line_longer_than_the_cut_is_cut_too(self): + fenced = cc.fence(b"y" * (cc.FENCE_LIMIT * 2)) + self.assertLessEqual(len(fenced.encode()), cc.FENCE_LIMIT + 200) + self.assertTrue(fenced.endswith("\n````\n")) + + def test_text_without_a_final_newline_still_closes_the_fence(self): + self.assertEqual(cc.fence(b"abc"), "````\nabc\n````\n") + + +class BuildReportTest(unittest.TestCase): + def baseline(self, between=()): + return cc.Baseline("b" * 40, "Base title", 1, artifact(1), list(between)) + + def test_names_the_baseline_and_says_what_changed(self): + text = cc.build_report(self.baseline(), rows(A__x="1", A__y="2"), rows(A__x="1", A__y="3"), + MADE_WITH, MADE_WITH, "main") + self.assertIn("bbbbbbbbbb (Base title), this pull request's base commit", text) + # The baseline moves with every push to the branch, so it comes last, after its own line. + self.assertLess(text.index("G-code changed"), text.index("\n" + cc.BASELINE_LINE)) + self.assertIn("G-code changed for 1 of 2 compared slices", text) + self.assertNotIn("Warning", text) + + def test_lists_the_commits_between_an_older_baseline_and_the_base(self): + text = cc.build_report(self.baseline([("c3c3c3c3c3", "Third")]), rows(A__x="1"), rows(A__x="1"), + MADE_WITH, MADE_WITH, "main") + self.assertIn("c3c3c3c3c3 Third", text) + self.assertIn("show here too", text) + self.assertNotIn("base commit,", text) + + def test_warns_when_the_script_or_runner_differs(self): + text = cc.build_report(self.baseline(), rows(A__x="1"), rows(A__x="1"), + MADE_WITH, MADE_WITH.replace("aarch64", "x86_64"), "main") + self.assertIn("Warning", text) + + def test_warns_when_the_baseline_does_not_say_what_made_it(self): + text = cc.build_report(self.baseline(), rows(A__x="1"), rows(A__x="1"), None, MADE_WITH, "main") + self.assertIn("Warning", text) + + def test_says_so_when_no_slice_could_be_compared(self): + text = cc.build_report(self.baseline(), rows(A__x="1"), rows(B__y="1"), MADE_WITH, MADE_WITH, "main") + self.assertNotIn("the same for all 0", text) + self.assertIn("No slice could be compared", text) + self.assertIn("Only in base (1)", text) + + def test_without_a_baseline_says_nothing_was_compared(self): + text = cc.build_report(None, None, rows(A__x="1"), None, MADE_WITH, "release/2.5") + self.assertIn("No build of release/2.5", text) + self.assertIn("nothing was compared", text) + + +class ReportCommandTest(unittest.TestCase): + def run_report(self, folder, error=None, text="report\n"): + out, summary = os.path.join(folder, "report.txt"), os.path.join(folder, "summary.md") + stdout = io.StringIO() + side = {"side_effect": error} if error else {"return_value": text} + with mock.patch.object(cc, "report_main", **side), contextlib.redirect_stdout(stdout): + code = cc.main(["report", "--repo", REPO, "--branch", "main", "--base-sha", "b" * 40, + "--head-dir", folder, "--out", out, "--summary", summary]) + with open(out, encoding="utf-8") as f, open(summary, encoding="utf-8") as g: + return code, stdout.getvalue(), f.read(), g.read() + + def test_an_error_writes_its_type_only_and_exits_zero(self): + with tempfile.TemporaryDirectory() as folder: + code, stdout, report, summary = self.run_report(folder, ValueError("line from the artifact")) + self.assertEqual(code, 0) + for text in (stdout, report, summary): + self.assertNotIn("line from the artifact", text) + self.assertIn("could not be made (ValueError)", report) + + def test_the_summary_holds_the_report_inside_a_fence(self): + with tempfile.TemporaryDirectory() as folder: + _, _, report, summary = self.run_report(folder, text="G-code is the same\n") + self.assertEqual(report, "G-code is the same\n") + self.assertIn("````\nG-code is the same\n````\n", summary) + + def test_made_with_names_the_script_and_the_runner(self): + with tempfile.TemporaryDirectory() as folder: + out = os.path.join(folder, "made_with.txt") + self.assertEqual(cc.main(["made-with", "-o", out]), 0) + with open(out, encoding="utf-8") as f: + lines = f.read().splitlines() + self.assertRegex(lines[0], r"^fingerprint script [0-9a-f]{64}$") + self.assertTrue(lines[1].startswith("runner ")) + + +if __name__ == "__main__": + unittest.main()