ci: run the browser E2E suite and require every job in the aggregate
This commit is contained in:
1 parent
6c3b34f73e
commit
6c86c4e559
12 files changed
+331
-39
No files matched your search
@@ -0,0 +1,244 @@
|
||||
"""Check that each required aggregate job in .github/workflows covers every job.
|
||||
|
||||
Branch protection requires only the aggregate result of each workflow, so a
|
||||
job missing from the aggregate's needs would stop blocking merges without any
|
||||
visible failure. The parser is line-based and uses only the standard library:
|
||||
it accepts the plain block style the workflows use and raises on anything it
|
||||
does not recognize instead of passing silently.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unittest
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
WORKFLOWS_DIR = Path(__file__).resolve().parents[1] / ".github" / "workflows"
|
||||
AGGREGATE = "aggregate"
|
||||
# Workflows that must keep a required aggregate job.
|
||||
REQUIRED_AGGREGATES = ("ci.yml", "docs.yml")
|
||||
|
||||
NAME = r"[A-Za-z_][A-Za-z0-9_-]*"
|
||||
JOB_LINE = re.compile(rf"^ ({NAME}):$")
|
||||
JOB_KEY_LINE = re.compile(r"^ ([A-Za-z_][A-Za-z0-9_-]*):(?: (.*))?$")
|
||||
NEEDS_ITEM = re.compile(rf"^ - ({NAME})$")
|
||||
FLOW_LIST = re.compile(rf"^\[\s*({NAME}(?:\s*,\s*{NAME})*)?\s*\]$")
|
||||
|
||||
|
||||
class WorkflowFormatError(ValueError):
|
||||
"""The workflow uses a structure this checker does not recognize."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Job:
|
||||
needs: list[str] = field(default_factory=list)
|
||||
condition: str | None = None
|
||||
|
||||
|
||||
def strip_comment(line: str) -> str:
|
||||
# Workflow values here never contain " #", so a comment starts there.
|
||||
index = line.find(" #")
|
||||
return (line[:index] if index >= 0 else line).rstrip()
|
||||
|
||||
|
||||
def unquote(value: str) -> str:
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
||||
return value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def parse_jobs(text: str, source: str = "<workflow>") -> dict[str, Job]:
|
||||
"""Return job ids with their needs and job-level if from a workflow file."""
|
||||
|
||||
def fail(number: int, message: str) -> WorkflowFormatError:
|
||||
return WorkflowFormatError(f"{source}:{number}: {message}")
|
||||
|
||||
lines = text.splitlines()
|
||||
jobs_lines = [number for number, line in enumerate(lines) if line.rstrip() == "jobs:"]
|
||||
if len(jobs_lines) != 1:
|
||||
raise WorkflowFormatError(f"{source}: expected one top-level 'jobs:' line, found {len(jobs_lines)}")
|
||||
|
||||
jobs: dict[str, Job] = {}
|
||||
current: str | None = None
|
||||
in_needs = False
|
||||
for number in range(jobs_lines[0] + 1, len(lines)):
|
||||
raw = lines[number]
|
||||
if "\t" in raw:
|
||||
raise fail(number + 1, "tabs are not supported")
|
||||
line = strip_comment(raw)
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
indent = len(line) - len(line.lstrip(" "))
|
||||
if indent == 0:
|
||||
break # Next top-level key: the jobs mapping ended.
|
||||
if indent == 2:
|
||||
match = JOB_LINE.match(line)
|
||||
if not match:
|
||||
raise fail(number + 1, f"unrecognized job line {raw!r}")
|
||||
current = match.group(1)
|
||||
if current in jobs:
|
||||
raise fail(number + 1, f"duplicate job {current!r}")
|
||||
jobs[current] = Job()
|
||||
in_needs = False
|
||||
continue
|
||||
if current is None or indent < 4:
|
||||
raise fail(number + 1, f"unexpected indentation in {raw!r}")
|
||||
job = jobs[current]
|
||||
if indent == 4:
|
||||
match = JOB_KEY_LINE.match(line)
|
||||
if not match:
|
||||
raise fail(number + 1, f"unrecognized job key line {raw!r}")
|
||||
key, value = match.group(1), (match.group(2) or "").strip()
|
||||
in_needs = False
|
||||
if key == "needs":
|
||||
if not value:
|
||||
in_needs = True
|
||||
elif re.fullmatch(NAME, value):
|
||||
job.needs.append(value)
|
||||
elif flow := FLOW_LIST.match(value):
|
||||
job.needs.extend(re.split(r"\s*,\s*", flow.group(1)) if flow.group(1) else [])
|
||||
else:
|
||||
raise fail(number + 1, f"unrecognized needs value {value!r}")
|
||||
elif key == "if":
|
||||
if not value:
|
||||
raise fail(number + 1, "multi-line job if is not supported")
|
||||
job.condition = unquote(value)
|
||||
continue
|
||||
if in_needs:
|
||||
match = NEEDS_ITEM.match(line)
|
||||
if not match:
|
||||
raise fail(number + 1, f"unrecognized needs item {raw!r}")
|
||||
job.needs.append(match.group(1))
|
||||
if not jobs:
|
||||
raise WorkflowFormatError(f"{source}: no jobs found")
|
||||
return jobs
|
||||
|
||||
|
||||
def aggregate_problems(jobs: dict[str, Job]) -> list[str]:
|
||||
"""Describe every way the jobs break the aggregate contract."""
|
||||
problems = []
|
||||
for job_id, job in jobs.items():
|
||||
for need in job.needs:
|
||||
if need not in jobs:
|
||||
problems.append(f"job {job_id!r} needs unknown job {need!r}")
|
||||
if len(set(job.needs)) != len(job.needs):
|
||||
problems.append(f"job {job_id!r} lists a need more than once")
|
||||
aggregate = jobs.get(AGGREGATE)
|
||||
if aggregate is None:
|
||||
return problems + [f"no {AGGREGATE!r} job"]
|
||||
missing = sorted(set(jobs) - {AGGREGATE} - set(aggregate.needs))
|
||||
if missing:
|
||||
problems.append(f"{AGGREGATE!r} does not need {missing}")
|
||||
if AGGREGATE in aggregate.needs:
|
||||
problems.append(f"{AGGREGATE!r} needs itself")
|
||||
if aggregate.condition not in ("always()", "${{ always() }}"):
|
||||
problems.append(f"{AGGREGATE!r} must run with 'if: always()', found {aggregate.condition!r}")
|
||||
return problems
|
||||
|
||||
|
||||
class WorkflowAggregateTests(unittest.TestCase):
|
||||
def test_repository_aggregates_cover_every_job(self):
|
||||
workflows = sorted(WORKFLOWS_DIR.glob("*.yml")) + sorted(WORKFLOWS_DIR.glob("*.yaml"))
|
||||
self.assertTrue(workflows, f"no workflows found in {WORKFLOWS_DIR}")
|
||||
checked = []
|
||||
for path in workflows:
|
||||
with self.subTest(workflow=path.name):
|
||||
jobs = parse_jobs(path.read_text(encoding="utf-8"), path.name)
|
||||
if AGGREGATE not in jobs:
|
||||
self.assertNotIn(path.name, REQUIRED_AGGREGATES, f"{path.name} lost its {AGGREGATE!r} job")
|
||||
continue
|
||||
self.assertGreater(len(jobs), 1, f"{path.name} has no jobs besides {AGGREGATE!r}")
|
||||
self.assertEqual(aggregate_problems(jobs), [], path.name)
|
||||
checked.append(path.name)
|
||||
for name in REQUIRED_AGGREGATES:
|
||||
self.assertIn(name, checked)
|
||||
|
||||
|
||||
VALID = """\
|
||||
name: Example
|
||||
on:
|
||||
push:
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Run
|
||||
run: |
|
||||
printf 'needs: nothing\\n'
|
||||
test:
|
||||
needs: build # trailing comment
|
||||
strategy:
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
steps:
|
||||
- run: make test
|
||||
aggregate:
|
||||
name: Required result
|
||||
if: always()
|
||||
needs:
|
||||
- build
|
||||
# comment inside the list
|
||||
- test
|
||||
steps:
|
||||
- run: true
|
||||
"""
|
||||
|
||||
|
||||
class ParserTests(unittest.TestCase):
|
||||
def test_valid_workflow_is_parsed(self):
|
||||
jobs = parse_jobs(VALID)
|
||||
self.assertEqual(list(jobs), ["build", "test", "aggregate"])
|
||||
self.assertEqual(jobs["test"].needs, ["build"])
|
||||
self.assertEqual(jobs["aggregate"].needs, ["build", "test"])
|
||||
self.assertEqual(jobs["aggregate"].condition, "always()")
|
||||
self.assertEqual(aggregate_problems(jobs), [])
|
||||
|
||||
def test_flow_needs_and_quoted_condition_are_parsed(self):
|
||||
jobs = parse_jobs(VALID.replace(" needs:\n - build\n # comment inside the list\n - test\n",
|
||||
" needs: [build, test]\n").replace("if: always()", "if: '${{ always() }}'"))
|
||||
self.assertEqual(jobs["aggregate"].needs, ["build", "test"])
|
||||
self.assertEqual(aggregate_problems(jobs), [])
|
||||
|
||||
def test_missing_need_is_reported(self):
|
||||
jobs = parse_jobs(VALID.replace(" - test\n", ""))
|
||||
self.assertEqual(aggregate_problems(jobs), ["'aggregate' does not need ['test']"])
|
||||
|
||||
def test_missing_or_other_condition_is_reported(self):
|
||||
cases = {
|
||||
"missing": VALID.replace(" if: always()\n", ""),
|
||||
"success()": VALID.replace("if: always()", "if: success()"),
|
||||
}
|
||||
for title, text in cases.items():
|
||||
with self.subTest(case=title):
|
||||
problems = aggregate_problems(parse_jobs(text))
|
||||
self.assertEqual(len(problems), 1)
|
||||
self.assertIn("if: always()", problems[0])
|
||||
|
||||
def test_unknown_need_is_reported(self):
|
||||
jobs = parse_jobs(VALID.replace(" needs: build #", " needs: biuld #"))
|
||||
self.assertIn("job 'test' needs unknown job 'biuld'", aggregate_problems(jobs))
|
||||
|
||||
def test_missing_aggregate_is_reported(self):
|
||||
jobs = parse_jobs(VALID.split(" aggregate:\n")[0])
|
||||
self.assertEqual(aggregate_problems(jobs), ["no 'aggregate' job"])
|
||||
|
||||
def test_unrecognized_structure_fails_loudly(self):
|
||||
broken = {
|
||||
"no jobs key": VALID.replace("jobs:\n", "workflows:\n"),
|
||||
"flow jobs": VALID.split("jobs:\n")[0] + "jobs: {build: {}}\n",
|
||||
"inline job": VALID.replace(" build:\n", " build: {}\n"),
|
||||
"odd indentation": VALID.replace(" name: Build\n", " name: Build\n"),
|
||||
"tab": VALID.replace(" name: Build\n", "\tname: Build\n"),
|
||||
"needs mapping": VALID.replace(" - test\n", " test: true\n"),
|
||||
"needs expression": VALID.replace(" needs: build #", " needs: ${{ x }} #"),
|
||||
"empty jobs": VALID.split("jobs:\n")[0] + "jobs:\n",
|
||||
}
|
||||
for title, text in broken.items():
|
||||
with self.subTest(case=title), self.assertRaises(WorkflowFormatError):
|
||||
parse_jobs(text, title)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user