Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions tests/test_progress_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,5 +656,96 @@ def test_out_as_existing_file_is_refused(self):
self.assertIn("is not a directory", err.getvalue())


class Hardening(unittest.TestCase):
@staticmethod
def _minimal_snap():
return {
"schema": pd.SCHEMA, "generated_at": "2026-11-24T10:00:00Z", "git": {},
"panels": [], "counts": {}, "components": [], "metrics": [],
"sources": [], "notes": [], "github": {}, "content_hash": "0" * 64,
}

def test_github_login_skips_null_author_and_null_body(self):
def fake_gh(args, timeout=60):
if args[:2] == ["issue", "list"] and "Coordinating" in args[args.index("--search") + 1]:
return [{"number": 14, "title": "Coordinating who works on what", "updatedAt": "2026-11-24T00:00:00Z"}]
if args[:2] == ["issue", "view"] and args[2] == "14":
fields = args[args.index("--json") + 1]
if fields == "body":
return {"body": "### Up for grabs\n| X-1 |\n"}
if fields == "comments":
return {"comments": [
{"author": None, "body": "claiming: X", "createdAt": "2026-11-24T01:00:00Z"},
{"author": {"login": "alice"}, "body": None, "createdAt": "2026-11-24T01:01:00Z"},
{"author": {"login": "alice"}, "body": "claiming: Y", "createdAt": "2026-11-24T01:02:00Z"},
]}
return []

col = pd.Collector()
with mock.patch.object(pd, "gh_json", fake_gh), mock.patch.object(pd.shutil, "which", lambda _: "/usr/bin/gh"):
summary = pd.collect_github(col, "o/r", "alice")
self.assertEqual(summary["mine"]["claims"],
[{"at": "2026-11-24T01:02:00Z", "issue": 14, "text": "claiming: Y"}])

def test_tests_flag_requires_run_tests(self):
with tempfile.TemporaryDirectory() as tmp:
err = io.StringIO()
with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as stop:
pd.main(["--out", os.path.join(tmp, "out"), "--tests", "foo"])
self.assertEqual(stop.exception.code, 2)
self.assertIn("--tests requires --run-tests", err.getvalue())

def test_ci_test_files_oserror_exits_2_cleanly(self):
with tempfile.TemporaryDirectory() as tmp:
err = io.StringIO()
with mock.patch.object(pd, "ci_test_files", side_effect=PermissionError(13, "denied", "tests/blocked")), \
contextlib.redirect_stderr(err):
rc = pd.main(["--out", os.path.join(tmp, "out"), "--run-tests"])
self.assertEqual(rc, 2)
self.assertIn("denied", err.getvalue())

def test_corrupt_non_list_and_bom_history_json(self):
snap = self._minimal_snap()
with tempfile.TemporaryDirectory() as tmp:
out = os.path.join(tmp, "out")
os.makedirs(out)
hist = Path(out, "history.json")
for bad in (
b"{bad",
b"{}",
b'[{"content_hash":"old"}]',
b'[{"content_hash":"old","metrics":null}]',
b'[{"content_hash":"old","metrics":[]}]',
b'[{"content_hash":null,"metrics":{}}]',
):
hist.write_bytes(bad)
err = io.StringIO()
with mock.patch.object(pd, "build", return_value=snap), contextlib.redirect_stderr(err):
rc = pd.main(["--out", out])
self.assertEqual(rc, 2)
self.assertIn("error:", err.getvalue())
self.assertEqual(hist.read_bytes(), bad)
self.assertFalse(Path(out, "progress.html").exists())

valid = [{"generated_at": "2026-11-24T09:00:00Z", "head": "abc", "content_hash": "0" * 16, "metrics": {}}]
hist.write_bytes(b"\xef\xbb\xbf" + json.dumps(valid).encode("utf-8"))
out_s, err = io.StringIO(), io.StringIO()
with mock.patch.object(pd, "build", return_value=snap), \
contextlib.redirect_stdout(out_s), contextlib.redirect_stderr(err):
rc = pd.main(["--out", out])
self.assertEqual(rc, 0, err.getvalue())

def test_write_outputs_oserror_exits_2_cleanly(self):
snap = self._minimal_snap()
with tempfile.TemporaryDirectory() as tmp:
err = io.StringIO()
with mock.patch.object(pd, "build", return_value=snap), \
mock.patch.object(pd, "write_outputs", side_effect=PermissionError(13, "read-only", "progress.html")), \
contextlib.redirect_stderr(err):
rc = pd.main(["--out", os.path.join(tmp, "out")])
self.assertEqual(rc, 2)
self.assertIn("read-only", err.getvalue())


if __name__ == "__main__":
unittest.main()
41 changes: 35 additions & 6 deletions tools/progress_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -951,9 +951,11 @@ def collect_github(col, repo, login, d3d_issue=None):
claims = []
for n in [num] + ([int(prev.group(1))] if prev else []):
comments = gh_json(["issue", "view", str(n), "-R", repo, "--json", "comments"]) or {}
claims += [{"at": c.get("createdAt"), "issue": n, "text": plain(c["body"].splitlines()[0])[:160]}
for c in comments.get("comments", [])
if c.get("author", {}).get("login") == login and "claiming" in c["body"].lower()]
for c in comments.get("comments", []):
body_text = c.get("body") or ""
if (c.get("author") or {}).get("login") == login and "claiming" in body_text.lower():
first_line = (body_text.splitlines() or [""])[0]
claims.append({"at": c.get("createdAt"), "issue": n, "text": plain(first_line)[:160]})
prs = gh_json(["pr", "list", "-R", repo, "--author", login, "--state", "all", "--limit", "50",
"--json", "number,title,state,isDraft,updatedAt"]) or []
summary["mine"] = {"login": login, "claims": claims,
Expand Down Expand Up @@ -1018,10 +1020,27 @@ def render_page(snap, history):
return template.replace("/*__PROGRESS_LOGO__*/", logo_src()).replace("/*__PROGRESS_DATA__*/null", payload)


def _load_history(hist_path):
if not os.path.isfile(hist_path):
return []
try:
history = json.loads(read_utf8(hist_path).lstrip("\ufeff"))
except ValueError as exc:
raise ValueError(f"{hist_path}: invalid JSON: {exc}") from None
if not isinstance(history, list) or any(
not isinstance(item, dict)
or not isinstance(item.get("content_hash"), str)
or not isinstance(item.get("metrics"), dict)
for item in history
):
raise ValueError(f"{hist_path}: expected a JSON list of snapshot summaries")
return history


def write_outputs(snap, out_dir):
os.makedirs(os.path.join(out_dir, "snapshots"), exist_ok=True)
hist_path = os.path.join(out_dir, "history.json")
history = json.loads(read_utf8(hist_path)) if os.path.isfile(hist_path) else []
history = _load_history(hist_path)
new = not history or history[-1]["content_hash"] != snap["content_hash"][:16]
if new:
stamp = snap["generated_at"].replace("-", "").replace(":", "")
Expand Down Expand Up @@ -1058,6 +1077,8 @@ def main(argv=None):
ap.error("--d3d-issue requires --github")
if args.d3d_issue is not None and args.d3d_issue < 1:
ap.error("--d3d-issue must be a positive integer")
if args.tests is not None and not args.run_tests:
ap.error("--tests requires --run-tests")
if args.jobs < 1:
ap.error("--jobs must be a positive integer")
if args.test_timeout < 1:
Expand All @@ -1075,7 +1096,12 @@ def main(argv=None):
print(f"--work {args.work} is not a folder", file=sys.stderr)
return 2
if args.run_tests:
args.test_files = [f for f in ci_test_files() if not args.tests or re.search(args.tests, f)]
try:
all_tests = ci_test_files()
except OSError as exc:
print(f"error: {exc.filename or ''}: {exc.strerror or exc}", file=sys.stderr)
return 2
args.test_files = [f for f in all_tests if not args.tests or re.search(args.tests, f)]
if args.tests and not args.test_files:
ap.error("--tests did not match any test files")
if os.path.exists(out_dir) and not os.path.isdir(out_dir):
Expand All @@ -1088,10 +1114,13 @@ def main(argv=None):
return 2
try:
snap = build(args, out_dir)
new = write_outputs(snap, out_dir)
except OSError as exc:
print(f"error: {exc.filename or ''}: {exc.strerror or exc}", file=sys.stderr)
return 2
new = write_outputs(snap, out_dir)
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
n = len(snap["components"])
print(f"{n} units, {len(snap['metrics'])} metrics -> {os.path.join(out_dir, 'progress.html')}"
+ ("" if new else " (no change since the last snapshot)"))
Expand Down
Loading