From 0ed2abeec2155779641f752871886dc0a83bfeb4 Mon Sep 17 00:00:00 2001 From: Zach Nelson Date: Thu, 19 Nov 2026 16:14:34 -0600 Subject: [PATCH] Report code coverage on each CI run's summary page --- .github/workflows/objective-c-xcode.yml | 11 ++- README.md | 14 ++++ Scripts/coverage_report.py | 97 +++++++++++++++++++++++++ 3 files changed, 121 insertions(+), 1 deletion(-) create mode 100755 Scripts/coverage_report.py diff --git a/.github/workflows/objective-c-xcode.yml b/.github/workflows/objective-c-xcode.yml index 539c2d4..6775573 100644 --- a/.github/workflows/objective-c-xcode.yml +++ b/.github/workflows/objective-c-xcode.yml @@ -128,7 +128,16 @@ jobs: - name: Test run: | - xcodebuild test -scheme CoreZen -project CoreZen.xcodeproj + xcodebuild test -scheme CoreZen -project CoreZen.xcodeproj \ + -enableCodeCoverage YES -resultBundlePath "$RUNNER_TEMP/Tests.xcresult" + + # Shows how much of CoreZen the tests ran, file by file, on the run's + # summary page. The report goes to a file first, since a pipe would hide + # the script failing. + - name: Report Code Coverage + run: | + Scripts/coverage_report.py "$RUNNER_TEMP/Tests.xcresult" > "$RUNNER_TEMP/coverage.md" + cat "$RUNNER_TEMP/coverage.md" >> "$GITHUB_STEP_SUMMARY" # Test again under sanitizers, which catch bugs that tests can pass despite: # Thread Sanitizer finds data races, Address Sanitizer finds memory errors, diff --git a/README.md b/README.md index b0f925f..24bebed 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,20 @@ CoreZen logs to the unified log, under the subsystem `com.zdnelson.CoreZen`, in log stream --level info --predicate 'subsystem == "com.zdnelson.CoreZen"' ``` +### Tests + +Run the tests with ⌘U in Xcode, or with `xcodebuild test -scheme CoreZen -project CoreZen.xcodeproj`. CI also runs them under Thread Sanitizer, and under Address and Undefined Behavior Sanitizers, and runs the static analyzer. + +The summary page of each CI run shows how much of CoreZen the tests ran, file by file. To see the same on your Mac: + +``` +rm -rf build/Tests.xcresult +xcodebuild test -scheme CoreZen -project CoreZen.xcodeproj -resultBundlePath build/Tests.xcresult +Scripts/coverage_report.py build/Tests.xcresult +``` + +After ⌘U, Xcode's Report navigator shows it line by line. + ### Versions CoreZen follows [Semantic Versioning](https://semver.org). Each release is a git tag such as `v0.1.0`, with a [GitHub release](https://github.com/znelson/CoreZen/releases) whose notes come from [`CHANGELOG.md`](https://github.com/znelson/CoreZen/blob/main/CHANGELOG.md). Until 1.0.0, a release that breaks the API raises the middle number (0.1.0 to 0.2.0), and any other release raises the last (0.1.0 to 0.1.1). At run time, the framework bundle's `CFBundleShortVersionString` is its version. diff --git a/Scripts/coverage_report.py b/Scripts/coverage_report.py new file mode 100755 index 0000000..b209fac --- /dev/null +++ b/Scripts/coverage_report.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +""" +Summarize how much of CoreZen the tests run, from an xcodebuild result bundle. + +While code coverage is on, xcodebuild test records which lines of +CoreZen.framework the tests ran. This prints the share of lines they ran, then +each file's, starting with the files that have the most lines left unrun, as +Markdown. CI adds it to the summary page of each run. + +Usage: + xcodebuild test -scheme CoreZen -project CoreZen.xcodeproj -resultBundlePath build/Tests.xcresult + ./coverage_report.py build/Tests.xcresult + +It needs Xcode, for xccov, and Python 3, including the one that comes with Xcode. +""" + +import argparse +import json +import os +import subprocess +import sys + +ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TARGET_NAME = 'CoreZen.framework' + + +## +def fail(message): + print(f'coverage_report.py: {message}', file=sys.stderr) + sys.exit(1) + + +## +def coverage_report(result_bundle): + """xccov's coverage report for a result bundle, as JSON.""" + try: + result = subprocess.run(['xcrun', 'xccov', 'view', '--report', '--json', result_bundle], + capture_output=True, text=True) + except FileNotFoundError: + fail('xcrun is missing; this needs Xcode') + if result.returncode != 0: + fail(f'xccov couldn\'t read {result_bundle}: {result.stderr.strip()}') + return json.loads(result.stdout) + + +## +def percent(covered, total): + """covered of total as a percentage, never rounded up to 100% unless it's all of them.""" + if total == 0: + return '-' + value = 100 * covered / total + if covered < total: + value = min(value, 99.9) + return f'{value:.1f}%' + + +## +def markdown(target): + """The report for one target, in Markdown.""" + covered, total = target['coveredLines'], target['executableLines'] + lines = [ + '### Code coverage', + '', + f'The tests ran **{percent(covered, total)}** of {TARGET_NAME}\'s lines: {covered:,} of {total:,}.', + '', + '
By file, most lines not run first', + '', + '| File | Lines run | Lines not run |', + '| --- | ---: | ---: |', + ] + files = sorted(target['files'], + key=lambda f: (f['coveredLines'] - f['executableLines'], os.path.relpath(f['path'], ROOT_PATH))) + for f in files: + not_run = f['executableLines'] - f['coveredLines'] + lines.append(f'| `{os.path.relpath(f["path"], ROOT_PATH)}` ' + f'| {percent(f["coveredLines"], f["executableLines"])} | {not_run:,} |') + lines += ['', '
'] + return '\n'.join(lines) + + +## +def main(): + parser = argparse.ArgumentParser(description='Summarize how much of CoreZen the tests run') + parser.add_argument('result_bundle', help='the .xcresult bundle from xcodebuild test') + args = parser.parse_args() + + if not os.path.isdir(args.result_bundle): + fail(f'{args.result_bundle} isn\'t a result bundle') + report = coverage_report(args.result_bundle) + target = next((t for t in report.get('targets', []) if t['name'] == TARGET_NAME), None) + if target is None: + fail(f'{args.result_bundle} has no coverage for {TARGET_NAME}; was code coverage off?') + print(markdown(target)) + + +if __name__ == '__main__': + main()