This is an automated email from the ASF dual-hosted git repository.

adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new d265f9b4e22 HDDS-17463. Publish GitHub Actions summary for coverage 
check (#12054)
d265f9b4e22 is described below

commit d265f9b4e22fe25392f0e27ca3ff7ef3bb0ccde1
Author: kjs1095 <[email protected]>
AuthorDate: Tue Nov 17 22:54:48 2026 +0800

    HDDS-17463. Publish GitHub Actions summary for coverage check (#12054)
    
    Co-authored-by: Claude Fable 5.1 <[email protected]>
---
 .github/workflows/ci.yml                |   7 ++
 dev-support/ci/coverage_summary.bats    |  22 ++++
 dev-support/ci/coverage_summary.py      | 161 ++++++++++++++++++++++++
 dev-support/ci/test_coverage_summary.py | 208 ++++++++++++++++++++++++++++++++
 4 files changed, 398 insertions(+)

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ed9eae7eaf3..3a5d85fbf3d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -510,8 +510,15 @@ jobs:
           GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
           DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }}
       - name: Archive build results
+        id: archive
         uses: actions/upload-artifact@v7
         with:
           name: coverage
           path: target/coverage
         continue-on-error: true
+      - name: Coverage summary
+        if: ${{ !cancelled() }}
+        continue-on-error: true
+        run: python3 dev-support/ci/coverage_summary.py >> 
"$GITHUB_STEP_SUMMARY"
+        env:
+          COVERAGE_REPORT_URL: ${{ steps.archive.outputs.artifact-url }}
diff --git a/dev-support/ci/coverage_summary.bats 
b/dev-support/ci/coverage_summary.bats
new file mode 100644
index 00000000000..61e0c8b239c
--- /dev/null
+++ b/dev-support/ci/coverage_summary.bats
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+@test "coverage_summary.py unit tests" {
+  cd "${BATS_TEST_DIRNAME}"
+  run python3 -m unittest test_coverage_summary
+  [ "$status" -eq 0 ]
+}
diff --git a/dev-support/ci/coverage_summary.py 
b/dev-support/ci/coverage_summary.py
new file mode 100755
index 00000000000..1036fa02b02
--- /dev/null
+++ b/dev-support/ci/coverage_summary.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Parse the JaCoCo XML report generated by coverage.sh and print a Markdown 
coverage summary.
+
+Intended for GitHub Actions: coverage_summary.py [--report FILE] >> 
"$GITHUB_STEP_SUMMARY"
+Exits 0: a missing or unreadable report is logged to stderr and nothing is 
written to stdout.
+
+JaCoCo XML report structure (as produced for Ozone's all.xml):
+
+<report name="...">
+  <sessioninfo id="..." start="..." dump="..."/>   # one per test JVM
+  <package name="org/apache/hadoop/ozone/om">
+    <class name="org/apache/.../OzoneManager"      # include inner classes 
(Foo$Bar)
+          sourcefilename="OzoneManager.java">
+      <method name="<init>" desc="(...)V" line="70">
+        <counter .../>
+      </method>
+      <counter .../>
+    </class>
+    <sourcefile name="OzoneManager.java">          # one per .java file
+      <line nr="30" mi="0" ci="3" mb="0" cb="0"/>  # per-line: missed/covered
+                                                   # instructions & branches
+      <counter .../>
+    </sourcefile>
+    <counter .../>                                 # package totals
+  </package>
+  <counter .../>                                   # report (overall) totals
+</report>
+
+<counter type="LINE" missed="27270" covered="148570"/>
+  type: INSTRUCTION | BRANCH | COMPLEXITY | LINE | METHOD | CLASS
+  Ref: https://www.jacoco.org/jacoco/trunk/doc/counters.html
+
+A counter is omitted when its total is 0 (e.g. a method with no branches), so a
+missing counter means n/a, not 0% coverage.
+
+Every level carries its own aggregated <counter> elements, so we read the 
direct
+children of <report> and of each <package> instead of summing.
+"""
+import argparse
+import dataclasses
+import os
+import sys
+import xml.etree.ElementTree as ET
+
+DEFAULT_REPORT = os.path.join("target", "coverage", "all.xml")
+
+# INSTRUCTION and COMPLEXITY are left out on purpose: they track LINE and 
BRANCH
+# within a fraction of a percent, so they would only add noise to the summary.
+JACOCO_LINE = "LINE"
+JACOCO_BRANCH = "BRANCH"
+JACOCO_METHOD = "METHOD"
+JACOCO_CLASS = "CLASS"
+
+
[email protected]
+class Counter:
+  missed: int = 0
+  covered: int = 0
+
+  @property
+  def total(self):
+    return self.missed + self.covered
+
+
[email protected]
+class Coverage:
+  """Counters of one JaCoCo report node, keyed by counter type."""
+  name: str
+  counters: dict
+
+  def counter(self, counter_type):
+    return self.counters.get(counter_type, Counter())
+
+  @property
+  def missed(self):
+    # sort key for the package table: amount of untested code, not ratio, so 
tiny packages do not top the list
+    return self.counter(JACOCO_LINE).missed + 
self.counter(JACOCO_BRANCH).missed
+
+  @property
+  def combined(self):
+    # same formula as SonarCloud's "coverage" metric: (covered lines + covered 
conditions) / (lines + conditions),
+    # where JaCoCo branches are Sonar's conditions
+    lines, branches = self.counter(JACOCO_LINE), self.counter(JACOCO_BRANCH)
+    return percent(lines.covered + branches.covered, lines.total + 
branches.total)
+
+
+def percent(covered, total):
+  return "%.1f%%" % (100.0 * covered / total) if total else "n/a"
+
+
+def read_counters(elem):
+  # Only the direct children: <package>, <class> and <method> nest their own 
counters.
+  return {c.get("type"): Counter(int(c.get("missed") or 0), 
int(c.get("covered") or 0))
+          for c in elem.findall("counter")}
+
+
+def parse_report(xml_path):
+  root = ET.parse(xml_path).getroot()
+  packages = [Coverage(p.get("name", "").replace("/", "."), read_counters(p)) 
for p in root.findall("package")]
+  return Coverage("", read_counters(root)), packages
+
+
+def render_summary(overall, packages):
+  lines, branches = overall.counter(JACOCO_LINE), 
overall.counter(JACOCO_BRANCH)
+  out = ["## Coverage Summary", ""]
+  out.append(f"**Overall coverage: {overall.combined}** (lines and branches 
combined, same formula as SonarCloud)")
+  out.append("")
+  out.append("|Counter|Coverage|Missed|Total|")
+  out.append("|---|---|---|---|")
+  out.append(f"|Lines|{percent(lines.covered, 
lines.total)}|{lines.missed}|{lines.total}|")
+  out.append(f"|Branches|{percent(branches.covered, 
branches.total)}|{branches.missed}|{branches.total}|")
+  out.append("")
+  out.append(f"Untested: {overall.counter(JACOCO_METHOD).missed} methods, "
+             f"{overall.counter(JACOCO_CLASS).missed} classes")
+  out.append("")
+  report_url = os.environ.get("COVERAGE_REPORT_URL")
+  if report_url:
+    out.extend([f"📦 Full HTML report: [download artifact]({report_url})", ""])
+  if packages:
+    out.extend([f"<details><summary><b>Coverage by package 
({len(packages)})</b></summary>", ""])
+    out.append("|Package|Coverage|Lines|Missed lines|Branches|Missed 
branches|")
+    out.append("|---|---|---|---|---|---|")
+    for p in sorted(packages, key=lambda p: (-p.missed, p.name)):
+      p_line, p_branch = p.counter(JACOCO_LINE), p.counter(JACOCO_BRANCH)
+      out.append(f"|{p.name}|{p.combined}|{percent(p_line.covered, 
p_line.total)}|{p_line.missed}|"
+                 f"{percent(p_branch.covered, 
p_branch.total)}|{p_branch.missed}|")
+    out.extend(["", "</details>", ""])
+  return "\n".join(out) + "\n"
+
+
+def main(argv=None):
+  parser = argparse.ArgumentParser(description="Print a Markdown summary of a 
JaCoCo XML coverage report.")
+  parser.add_argument("--report", default=DEFAULT_REPORT, help="path to the 
JaCoCo XML report")
+  args = parser.parse_args(argv)
+  try:
+    overall, packages = parse_report(args.report)
+    print(render_summary(overall, packages), end="")
+  except Exception as e:
+    print(f"coverage_summary failed: {e}", file=sys.stderr)
+  return 0
+
+
+if __name__ == "__main__":
+  sys.exit(main())
diff --git a/dev-support/ci/test_coverage_summary.py 
b/dev-support/ci/test_coverage_summary.py
new file mode 100644
index 00000000000..802ec1d93bb
--- /dev/null
+++ b/dev-support/ci/test_coverage_summary.py
@@ -0,0 +1,208 @@
+#!/usr/bin/env python3
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tests for coverage_summary.py. Run: cd dev-support/ci && python3 -m 
unittest test_coverage_summary -v"""
+import contextlib
+import io
+import os
+import tempfile
+import unittest
+from unittest import mock
+
+import coverage_summary
+
+SAMPLE_XML = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!DOCTYPE report PUBLIC "-//JACOCO//DTD Report 1.1//EN" "report.dtd">
+<report name="JaCoCo Coverage Report">
+  <sessioninfo id="localhost-6cb2dcd8" start="1794287847378" 
dump="1794287848330"/>
+  <package name="org/apache/hadoop/ozone/om/snapshot/diff/helper">
+    <counter type="INSTRUCTION" missed="85" covered="0"/>
+    <counter type="LINE" missed="15" covered="0"/>
+    <counter type="COMPLEXITY" missed="5" covered="0"/>
+    <counter type="METHOD" missed="5" covered="0"/>
+    <counter type="CLASS" missed="2" covered="0"/>
+  </package>
+  <package name="org/apache/hadoop/ozone/recon/persistence">
+    <class name="org/apache/hadoop/ozone/recon/persistence/ContainerHistory" 
sourcefilename="ContainerHistory.java">
+      <method name="getLastBcsId" desc="()J" line="55">
+        <counter type="INSTRUCTION" missed="0" covered="3"/>
+        <counter type="LINE" missed="0" covered="1"/>
+        <counter type="COMPLEXITY" missed="0" covered="1"/>
+        <counter type="METHOD" missed="0" covered="1"/>
+      </method>
+      <counter type="INSTRUCTION" missed="0" covered="82"/>
+      <counter type="LINE" missed="0" covered="34"/>
+      <counter type="COMPLEXITY" missed="0" covered="17"/>
+      <counter type="METHOD" missed="0" covered="17"/>
+      <counter type="CLASS" missed="0" covered="1"/>
+    </class>
+    <sourcefile name="ContainerHistory.java">
+      <line nr="39" mi="0" ci="2" mb="0" cb="0"/>
+      <line nr="40" mi="0" ci="3" mb="0" cb="0"/>
+      <line nr="41" mi="0" ci="3" mb="0" cb="0"/>
+      <counter type="INSTRUCTION" missed="0" covered="82"/>
+      <counter type="LINE" missed="0" covered="34"/>
+      <counter type="COMPLEXITY" missed="0" covered="17"/>
+      <counter type="METHOD" missed="0" covered="17"/>
+      <counter type="CLASS" missed="0" covered="1"/>
+    </sourcefile>
+    <counter type="INSTRUCTION" missed="285" covered="1036"/>
+    <counter type="BRANCH" missed="34" covered="54"/>
+    <counter type="LINE" missed="75" covered="286"/>
+    <counter type="COMPLEXITY" missed="31" covered="84"/>
+    <counter type="METHOD" missed="3" covered="68"/>
+    <counter type="CLASS" missed="0" covered="11"/>
+  </package>
+  <package name="org/apache/ozone/hdfs/web">
+    <counter type="INSTRUCTION" missed="0" covered="11"/>
+    <counter type="LINE" missed="0" covered="2"/>
+    <counter type="COMPLEXITY" missed="0" covered="1"/>
+    <counter type="METHOD" missed="0" covered="1"/>
+    <counter type="CLASS" missed="0" covered="1"/>
+  </package>
+  <counter type="INSTRUCTION" missed="115391" covered="603867"/>
+  <counter type="BRANCH" missed="14856" covered="40462"/>
+  <counter type="LINE" missed="27270" covered="148570"/>
+  <counter type="COMPLEXITY" missed="16488" covered="44829"/>
+  <counter type="METHOD" missed="4369" covered="28809"/>
+  <counter type="CLASS" missed="210" covered="3505"/>
+</report>
+"""
+
+
+def write_report(tmp, content=SAMPLE_XML, name="all.xml"):
+  path = os.path.join(tmp, name)
+  with open(path, "w", encoding="utf-8") as f:
+    f.write(content)
+  return path
+
+
+def parse_sample():
+  with tempfile.TemporaryDirectory() as tmp:
+    return coverage_summary.parse_report(write_report(tmp))
+
+
+class TestPercent(unittest.TestCase):
+  def test_percent(self):
+    self.assertEqual(coverage_summary.percent(2, 3), "66.7%")
+    self.assertEqual(coverage_summary.percent(0, 0), "n/a")
+
+
+class TestParseReport(unittest.TestCase):
+  def test_overall_counters(self):
+    overall, _ = parse_sample()
+    lines = overall.counter(coverage_summary.JACOCO_LINE)
+    self.assertEqual((lines.missed, lines.covered, lines.total), (27270, 
148570, 175840))
+    self.assertEqual(overall.counter(coverage_summary.JACOCO_CLASS).missed, 
210)
+    self.assertEqual(overall.counter("NO_SUCH_TYPE").total, 0)
+
+  def test_packages_counters(self):
+    _, packages = parse_sample()
+    by_name = {p.name: p for p in packages}
+    self.assertEqual(sorted(by_name),
+                     ["org.apache.hadoop.ozone.om.snapshot.diff.helper",
+                      "org.apache.hadoop.ozone.recon.persistence",
+                      "org.apache.ozone.hdfs.web"])
+    package_persistence = by_name["org.apache.hadoop.ozone.recon.persistence"]
+    
self.assertEqual(package_persistence.counter(coverage_summary.JACOCO_LINE).missed,
 75)
+    self.assertEqual(package_persistence.missed, 75 + 34)
+    package_web = by_name["org.apache.ozone.hdfs.web"]
+    
self.assertEqual(package_web.counter(coverage_summary.JACOCO_BRANCH).total, 0)
+    self.assertEqual(package_web.missed, 0)
+
+  def test_combined_uses_sonar_formula(self):
+    _, packages = parse_sample()
+    by_name = {p.name: p for p in packages}
+    # (286 + 54) / (361 + 88)
+    
self.assertEqual(by_name["org.apache.hadoop.ozone.recon.persistence"].combined, 
"75.7%")
+    # no branches: falls back to line coverage, 2 / 2
+    self.assertEqual(by_name["org.apache.ozone.hdfs.web"].combined, "100.0%")
+
+
+class TestRenderSummary(unittest.TestCase):
+  def render(self):
+    return coverage_summary.render_summary(*parse_sample())
+
+  def table_rows(self, text):
+    return [line for line in text.splitlines() if line.startswith("|") and not 
line.startswith("|---")]
+
+  def test_overall_section(self):
+    out = self.render()
+    self.assertTrue(out.startswith("## Coverage Summary\n"))
+    # (covered_lines + covered_branches)/(total_lines + total_branches)
+    self.assertIn("**Overall coverage: 81.8%**", out)
+    rows = self.table_rows(out)
+    self.assertEqual(rows[:3], ["|Counter|Coverage|Missed|Total|",
+                                "|Lines|84.5%|27270|175840|",
+                                "|Branches|73.1%|14856|55318|"])
+    self.assertIn("\nUntested: 4369 methods, 210 classes\n", out)
+
+  def test_report_url(self):
+    with mock.patch.dict(os.environ, {"COVERAGE_REPORT_URL": 
"https://example.com/artifact"}):
+      self.assertIn("📦 Full HTML report: [download 
artifact](https://example.com/artifact)", self.render())
+    with mock.patch.dict(os.environ, {}, clear=True):
+      self.assertNotIn("📦 Full HTML report: [download artifact]", 
self.render())
+
+  def test_package_table_sorted_by_missed(self):
+    out = self.render()
+    self.assertIn("<details><summary><b>Coverage by package 
(3)</b></summary>\n\n|Package|", out)
+    rows = self.table_rows(out)[3:]
+    # most untested code first: persistence misses 75 lines + 34 branches, 
helper misses 15 lines, web misses 0 lines
+    self.assertEqual(rows, ["|Package|Coverage|Lines|Missed 
lines|Branches|Missed branches|",
+                            
"|org.apache.hadoop.ozone.recon.persistence|75.7%|79.2%|75|61.4%|34|",
+                            
"|org.apache.hadoop.ozone.om.snapshot.diff.helper|0.0%|0.0%|15|n/a|0|",
+                            
"|org.apache.ozone.hdfs.web|100.0%|100.0%|0|n/a|0|"])
+    self.assertTrue(out.endswith("|\n\n</details>\n\n"))
+
+  def test_no_packages(self):
+    overall, _ = parse_sample()
+    out = coverage_summary.render_summary(overall, [])
+    self.assertNotIn("<details>", out)
+    self.assertTrue(out.endswith("\nUntested: 4369 methods, 210 classes\n\n"))
+
+
+class TestMain(unittest.TestCase):
+  def run_main(self, argv):
+    out, err = io.StringIO(), io.StringIO()
+    with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+      code = coverage_summary.main(argv)
+    return code, out.getvalue(), err.getvalue()
+
+  def test_prints_summary(self):
+    with tempfile.TemporaryDirectory() as tmp:
+      code, out, err = self.run_main(["--report", write_report(tmp)])
+    self.assertEqual(code, 0)
+    self.assertIn("|Lines|84.5%|27270|175840|", out)
+    self.assertEqual(err, "")
+
+  def test_missing_report(self):
+    with tempfile.TemporaryDirectory() as tmp:
+      code, out, err = self.run_main(["--report", os.path.join(tmp, 
"missing.xml")])
+    self.assertEqual(code, 0)
+    self.assertEqual(out, "")
+    self.assertIn("coverage_summary failed", err)
+
+  def test_invalid_report(self):
+    with tempfile.TemporaryDirectory() as tmp:
+      code, out, err = self.run_main(["--report", write_report(tmp, 
"<report>")])
+    self.assertEqual(code, 0)
+    self.assertEqual(out, "")
+    self.assertIn("coverage_summary failed", err)
+
+
+if __name__ == "__main__":
+  unittest.main()


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to