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
16 changes: 15 additions & 1 deletion .github/tests/coverage.sh
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,23 @@ scenario -- 'a*b.py'; multi_report 'a*b.py=1'; run_chec
scenario -- ; : > empty.py; git add . && git commit -q -m empty; multi_report other.py=1; run_check pass 'new empty file is not flagged'
scenario -- new.md; multi_report other.py=1; run_check pass 'new non-source file is not flagged'
scenario old.py -- old.py; multi_report other.py=1; run_check pass 'modified file absent from the reports is skipped'
scenario util.py -- util.py; multi_report api/util.py=1 web/util.py=1; run_check fail 'ambiguous suffix match'
scenario util.py -- util.py; multi_report api/util.py=1 web/util.py=1; run_check pass 'longer report paths collapse onto the tracked file'
scenario pkg/a/util.py pkg/b/util.py -- pkg/a/util.py; multi_report util.py=1; run_check fail 'ambiguous suffix match against tracked files'
grep -q 'matches several tracked files' "$work/out" || { echo 'FAIL: ambiguous suffix message' >&2; cat "$work/out" >&2; exit 1; }
scenario pkg/a/util.py -- pkg/a/util.py; multi_report util.py=0; run_check fail 'unique suffix match resolves the changed file'
scenario pkg/web/util.py -- pkg/web/util.py; multi_report util.py=0 web/util.py=1; run_check pass 'longest suffix match wins'
scenario web/util.py -- web/util.py; multi_report util.py=0 web/util.py=1; run_check pass 'exact match wins over a suffix match'
scenario 'dir é/a b.py' -- 'dir é/a b.py'; multi_report 'dir é/a b.py=0'; run_check fail 'uncovered changes in a path with spaces and non-ASCII'
scenario 'dir é/a b.py' -- 'dir é/a b.py'; multi_report 'dir é/a b.py=1'; run_check pass 'covered changes in a path with spaces and non-ASCII'
cobertura 10 10 yes; printf '<testsuites/>' > reports/junit.xml; run_check fail 'non-Cobertura XML in the reports'
grep -q 'not a Cobertura report' "$work/out" || { echo 'FAIL: non-Cobertura message' >&2; cat "$work/out" >&2; exit 1; }
cobertura 10 10 yes; printf '<coverage' > reports/bad.xml; run_check fail 'invalid XML in the reports'
grep -q 'not valid XML' "$work/out" || { echo 'FAIL: invalid XML message' >&2; cat "$work/out" >&2; exit 1; }
scenario util.py pkg/util.py -- pkg/util.py
multi_report util.py=1
sed -i.bak "s|<packages>|<sources><source>$(pwd -P)/pkg</source></sources><packages>|" reports/cov.xml; rm -f reports/cov.xml.bak
run_check pass 'source root resolves the covered file'
multi_report util.py=0
sed -i.bak "s|<packages>|<sources><source>$(pwd -P)/pkg</source></sources><packages>|" reports/cov.xml; rm -f reports/cov.xml.bak
run_check fail 'source root wins over a same-named file at the root'
echo 'all coverage tests passed'
73 changes: 44 additions & 29 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,41 @@ jobs:
workspace = os.getcwd().rstrip('/') + '/'
lines, branches = {}, {} # file -> {line: hits}, file -> {(line, branch): taken}

def git(*args):
# -z and quotePath=false keep paths with spaces or non-ASCII characters verbatim.
return subprocess.run(['git', '--literal-pathspecs', '-c', 'core.quotePath=false', *args], capture_output=True,
text=True, encoding='utf-8', errors='replace', check=True).stdout

tracked = set(git('ls-files', '-z').split('\0')) - {''}
tracked_by_name = {}
for t in tracked:
tracked_by_name.setdefault(t.rsplit('/', 1)[-1], []).append(t)

def norm(path):
path = path.replace('\\', '/')
return path[len(workspace):] if path.startswith(workspace) else path.removeprefix('./')

def canonical(path, report, sources=()):
# Map a report path onto the tracked file it names, so every later lookup is an exact match.
p = norm(path)
# Cobertura filenames are relative to their <source>, so the source roots win over a same-named file at the root.
for source in sources:
c = norm(os.path.join(source, path))
if c in tracked:
return c
if p in tracked:
return p
same_name = tracked_by_name.get(p.rsplit('/', 1)[-1], [])
shorter = [t for t in same_name if t.endswith('/' + p)]
if len(shorter) == 1:
return shorter[0]
if shorter:
errors.append(f'{report}: report path {p} matches several tracked files ({", ".join(sorted(shorter)[:5])}); '
'emit repository-relative paths (coverage.py relative_files = true)')
return None
longer = [t for t in same_name if p.endswith('/' + t)]
return max(longer, key=len) if longer else p

def add_line(f, n, hits):
d = lines.setdefault(f, {})
d[n] = max(d.get(n, 0), hits)
Expand All @@ -82,17 +113,12 @@ jobs:
d = branches.setdefault(f, {})
d[key] = d.get(key, False) or taken

def read_cobertura(path):
root = ET.parse(path).getroot()
def read_cobertura(path, root):
sources = [s.text.strip() for s in root.iter('source') if s.text and s.text.strip()]
for cls in root.iter('class'):
name = cls.get('filename')
f = norm(name)
for source in sources:
candidate = norm(os.path.join(source, name))
if os.path.isfile(candidate):
f = candidate
break
f = canonical(cls.get('filename'), path, sources)
if f is None:
continue
for ln in cls.iter('line'):
n, hits = int(ln.get('number')), int(ln.get('hits'))
add_line(f, n, hits)
Expand All @@ -106,7 +132,7 @@ jobs:
f = None
for raw in Path(path).read_text().splitlines():
if raw.startswith('SF:'):
f = norm(raw[3:])
f = canonical(raw[3:], path)
elif raw.startswith('DA:') and f:
n, hits = raw[3:].split(',')[:2]
add_line(f, int(n), int(hits))
Expand All @@ -117,7 +143,13 @@ jobs:
found = 0
for path in sorted(Path(os.environ['REPORTS_DIR']).rglob('*')):
if path.suffix == '.xml':
read_cobertura(path)
try:
root = ET.parse(path).getroot()
except ET.ParseError as error:
sys.exit(f'coverage: {path}: not valid XML ({error})')
if root.tag != 'coverage':
sys.exit(f'coverage: {path}: not a Cobertura report (root <{root.tag}>); upload only coverage reports in the coverage-* artifacts')
read_cobertura(path, root)
elif path.name == 'lcov.info' or path.suffix == '.lcov':
read_lcov(path)
else:
Expand All @@ -143,23 +175,8 @@ jobs:

base = os.environ.get('BASE_REF', '').strip()
if base:
def git(*args):
# -z and quotePath=false keep paths with spaces or non-ASCII characters verbatim.
return subprocess.run(['git', '--literal-pathspecs', '-c', 'core.quotePath=false', *args], capture_output=True,
text=True, encoding='utf-8', errors='replace', check=True).stdout

def resolve(path):
if path in lines:
return path
candidates = [f for f in lines if f.endswith('/' + path) or path.endswith('/' + f)]
if not candidates:
return None
best = max(min(len(f), len(path)) for f in candidates)
top = [f for f in candidates if min(len(f), len(path)) == best]
if len(top) > 1:
errors.append(f'patch coverage: {path} matches several report paths ({", ".join(sorted(top))}); make the report paths unambiguous')
return ''
return top[0]
return path if path in lines else None

base_range = f'origin/{base}...HEAD'
tokens = git('diff', '--name-status', '--no-renames', '-z', '--diff-filter=AM', base_range).split('\0')
Expand All @@ -174,8 +191,6 @@ jobs:
missed, unreported = [], []
for status, path in zip(tokens[0::2], tokens[1::2]):
match = resolve(path)
if match == '':
continue
added = set()
for raw in git('diff', '-U0', '--no-color', base_range, '--', path).splitlines():
m = re.match(r'@@ .* \+(\d+)(?:,(\d+))? @@', raw)
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- `coverage.yml` resolves report paths against the repository's tracked files (exact, `<source>` roots, or a unique suffix) instead of matching only the changed files, so an ambiguous suffix outside the diff is no longer missed and one file reported under several prefixes counts once. A `.xml` file in a coverage artifact that is not valid Cobertura XML now fails the job.
- The concurrency conformance check treats a workflow in which any job calls a release workflow as a release caller and expects the event form, so `examples/release-please-python.yml` (release jobs mixed with build and publish jobs) passes instead of being steered to a form that can lose a version bump.
- `examples/pr-title.yml` declares the CI concurrency form and a `# Place at` header; a new CI step checks that every example passes the shipped conformance checks.

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,8 @@ Enforces the organization coverage standard in one place: global lines ≥ 80 %,

The job fails when no report is found or when the reports hold no branch data. Cobertura reports only carry per-line branch counts, so reports of sharded test runs for the same code (unit and e2e, a matrix) must be combined into one report before upload (`coverage combine`, lcov merge); otherwise the branch figure is the per-line maximum and under-reports.

Report paths are resolved against the files tracked by the repository (exact path, the Cobertura `<source>` roots, or a unique suffix match), so the same file reported under several prefixes counts once. A report path that is a suffix of several tracked files, or a `.xml` file in a `coverage-*` artifact that is not a Cobertura report (invalid XML, or a root other than `<coverage>`), fails the job: emit repository-relative paths (`relative_files = true` in coverage.py) and upload only coverage reports.

```yaml
jobs:
coverage:
Expand Down