Skip to content

Add defensive Cobertura XML parsing#45

Merged
leynos merged 2 commits intomainfrom
codex/add-error-handling-to-get_line_coverage_percent_from_cobertu
Jul 28, 2025
Merged

Add defensive Cobertura XML parsing#45
leynos merged 2 commits intomainfrom
codex/add-error-handling-to-get_line_coverage_percent_from_cobertu

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 28, 2025

Summary

  • handle missing lxml dependency gracefully
  • add robust Cobertura XML parser with error handling

Testing

  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_68871f6211bc8322a621281e6b25b6e7

Summary by Sourcery

Add a defensive Cobertura XML parsing function to extract overall line coverage percentage with robust error handling.

New Features:

  • Introduce get_line_coverage_percent_from_cobertura to compute line coverage from a Cobertura XML file

Enhancements:

  • Gracefully handle missing files, permission errors, invalid XML, and unexpected parsing failures
  • Fallback to attribute-based metrics when detailed line-level data is unavailable

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 28, 2025

Reviewer's Guide

This PR adds a new get_line_coverage_percent_from_cobertura function in run_rust.py that robustly parses Cobertura XML—handling missing files, permissions, invalid syntax, missing lxml dependency, and unexpected failures—then calculates and formats the overall line coverage percentage with fallback logic and two-decimal precision.

File-Level Changes

Change Details Files
Add get_line_coverage_percent_from_cobertura for defensive Cobertura parsing
  • Wrap XML parsing in try/except for FileNotFoundError, PermissionError, XMLSyntaxError, and generic errors with typer.Exit
  • Implement fallback logic: prefer detailed line counts, then attribute-based metrics when detail is unavailable
  • Format the coverage percentage to two decimal places using Decimal and ROUND_HALF_UP
.github/actions/generate-coverage/scripts/run_rust.py
Introduce defensive XPath helper functions
  • num_or_zero(): safely evaluate numeric XPath expressions and return zero on exceptions or NaN
  • lines_from_detail(): count covered and total lines via XPath, defaulting to (0, 0) on failure
.github/actions/generate-coverage/scripts/run_rust.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 28, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved accuracy of coverage percentage calculations with precise decimal rounding.
    • Enhanced error handling for XML parsing and file access issues in coverage reports.
  • New Features

    • Added internal support for parsing Cobertura XML coverage reports, removing reliance on external parsers.

Walkthrough

Replace the import of the Cobertura coverage parser in run_rust.py with a new internal implementation using lxml for XML parsing. Add robust error handling and precise decimal rounding for coverage percentage calculation. Retain the existing LCOV parser import and maintain the main function's control flow.

Changes

Cohort / File(s) Change Summary
Cobertura Parser Refactor
.github/actions/generate-coverage/scripts/run_rust.py
Remove external Cobertura parser import; implement local get_line_coverage_percent_from_cobertura using lxml, add _format_percent for decimal rounding, and enhance error handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant run_rust.py
    participant lxml.etree

    User->>run_rust.py: Run script with --format cobertura
    run_rust.py->>lxml.etree: Import lxml.etree (runtime check)
    run_rust.py->>run_rust.py: get_line_coverage_percent_from_cobertura(xml_file)
    run_rust.py->>lxml.etree: Parse XML, extract line coverage
    run_rust.py->>run_rust.py: _format_percent(covered, total)
    run_rust.py-->>User: Output coverage percentage
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

  • Improve lcov coverage parsing #42: Refactors coverage parsing by introducing and integrating external Cobertura and LCOV parser functions, which are now replaced by the new internal implementation in this PR.

Poem

Decimal points now round with care,
Cobertura parsing handled fair.
lxml checks before we start,
Robust errors play their part.
Coverage scripts, now neat and tight—
Let’s toast to code that gets it right!
🦀📈✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-error-handling-to-get_line_coverage_percent_from_cobertu

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @leynos - I've reviewed your changes and found some issues that need to be addressed.

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `.github/actions/generate-coverage/scripts/run_rust.py:88` </location>
<code_context>
+        else:
+            return 0 if math.isnan(n) else int(n)
+
+    def lines_from_detail() -> tuple[int, int]:
+        try:
+            total = int(root.xpath("count(//class/lines/line)"))
+            covered = int(
+                root.xpath("count(//class/lines/line[number(@hits) > 0])")
+            )
+        except Exception:  # noqa: BLE001 - defensive
+            return 0, 0
+        else:
+            return covered, total
</code_context>

<issue_to_address>
lines_from_detail may silently mask parsing errors.

Returning (0, 0) for any exception may hide underlying XML or data issues. Consider logging or exposing errors to aid debugging.
</issue_to_address>

### Comment 2
<location> `.github/actions/generate-coverage/scripts/run_rust.py:100` </location>
<code_context>
+            return covered, total
+
+    covered, total = lines_from_detail()
+    if total == 0:
+        covered = num_or_zero("/coverage/@lines-covered")
+        total = num_or_zero("/coverage/@lines-valid")
+
</code_context>

<issue_to_address>
Fallback to summary attributes may not always be reliable.

If both detailed and summary attributes are missing or malformed, the function returns 0.00, which may hide upstream issues. Please review whether this fallback logic is sufficient for all Cobertura XML variants.
</issue_to_address>

### Comment 3
<location> `.github/actions/generate-coverage/scripts/run_rust.py:63` </location>
<code_context>
     return match[1]


+def get_line_coverage_percent_from_cobertura(xml_file: Path) -> str:
+    """Return the overall line coverage percentage from a Cobertura XML file."""
+    try:
</code_context>

<issue_to_address>
Consider refactoring the function to use a top-level percentage formatter, specific exception handling, and direct XPath queries for clarity and maintainability.

```markdown
You can flatten and reuse logic, remove broad `except Exception` blocks, and keep your XML‐parsing logic DRY. For example:

1. Extract a small helper to format percentages at the top level.
2. Only catch the specific IO/XML exceptions in your main parser.
3. Use two clear XPath calls (one for class/lines, one for the `<coverage/>` attributes) instead of nested helpers.

```python
from decimal import Decimal, ROUND_HALF_UP
from lxml import etree
import typer
from pathlib import Path

def _format_percent(covered: int, total: int) -> str:
    pct = Decimal(covered) * Decimal("100") / Decimal(total)
    return str(pct.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))

def get_line_coverage_percent_from_cobertura(xml_file: Path) -> str:
    """Return overall line coverage % from a Cobertura XML file."""
    try:
        root = etree.parse(str(xml_file)).getroot()
    except (FileNotFoundError, PermissionError) as e:
        typer.echo(f"Could not read {xml_file}: {e}", err=True)
        raise typer.Exit(1) from e
    except etree.XMLSyntaxError as e:
        typer.echo(f"Invalid XML in {xml_file}: {e}", err=True)
        raise typer.Exit(1) from e

    # count all lines and those with hits > 0
    total   = int(root.xpath("count(//class/lines/line)"))
    covered = int(root.xpath("count(//class/lines/line[@hits>0])"))

    # fallback to root attributes if no <class> info
    if total == 0:
        total   = int(root.xpath("number(/coverage/@lines-valid)"))
        covered = int(root.xpath("number(/coverage/@lines-covered)"))

    if total == 0:
        return "0.00"

    return _format_percent(covered, total)
```

This keeps all functionality, removes nested helpers and broad catches, and uses clear XPath expressions with one small formatting utility.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread .github/actions/generate-coverage/scripts/run_rust.py Outdated
Comment thread .github/actions/generate-coverage/scripts/run_rust.py Outdated
Comment thread .github/actions/generate-coverage/scripts/run_rust.py
@leynos leynos merged commit 732d248 into main Jul 28, 2025
1 of 2 checks passed
@leynos leynos deleted the codex/add-error-handling-to-get_line_coverage_percent_from_cobertu branch July 28, 2025 19:20
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 22dfa00 and 5283d14.

📒 Files selected for processing (1)
  • .github/actions/generate-coverage/scripts/run_rust.py (2 hunks)
🔇 Additional comments (5)
.github/actions/generate-coverage/scripts/run_rust.py (5)

11-11: Import changes look good.

The addition of Decimal imports for precise percentage calculations and the removal of the external Cobertura parser import align well with the PR's objective to implement defensive parsing internally.

Also applies to: 15-16


17-24: Excellent defensive handling of the lxml dependency.

The runtime import with clear error messaging provides exactly the graceful fallback mechanism described in the PR objectives.


62-65: Well-structured percentage formatting helper.

Good extraction of the formatting logic with precise decimal arithmetic and consistent rounding behaviour.


128-129: Clean integration of the new Cobertura parser.

The local implementation seamlessly replaces the external dependency while maintaining the existing control flow.


4-4: Verify the interaction between uv dependency declaration and runtime availability.

The script header declares lxml as a dependency for uv, but the runtime import check suggests it might still be missing. Confirm that the runtime check is necessary when using uv, or document when this fallback would trigger.

Also applies to: 17-24

Comment on lines +67 to +97
def get_line_coverage_percent_from_cobertura(xml_file: Path) -> str:
"""Return overall line coverage % from a Cobertura XML file."""
try:
root = etree.parse(str(xml_file)).getroot()
except (FileNotFoundError, PermissionError) as exc:
typer.echo(f"Could not read {xml_file}: {exc}", err=True)
raise typer.Exit(1) from exc
except etree.XMLSyntaxError as exc:
typer.echo(f"Invalid XML in {xml_file}: {exc}", err=True)
raise typer.Exit(1) from exc

try:
total = int(root.xpath("count(//class/lines/line)"))
covered = int(root.xpath("count(//class/lines/line[@hits>0])"))
except etree.XPathError as exc:
typer.echo(f"Malformed Cobertura data: {exc}", err=True)
raise typer.Exit(1) from exc

if total == 0:
try:
covered = int(root.xpath("number(/coverage/@lines-covered)"))
total = int(root.xpath("number(/coverage/@lines-valid)"))
except etree.XPathError as exc:
typer.echo(f"Cobertura summary missing: {exc}", err=True)
raise typer.Exit(1) from exc

if total == 0:
return "0.00"

return _format_percent(covered, total)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Swap the order of lines 87-88 for consistency.

The implementation provides excellent error handling that addresses the past review concerns. However, maintain consistent ordering by extracting total before covered:

-            covered = int(root.xpath("number(/coverage/@lines-covered)"))
-            total = int(root.xpath("number(/coverage/@lines-valid)"))
+            total = int(root.xpath("number(/coverage/@lines-valid)"))
+            covered = int(root.xpath("number(/coverage/@lines-covered)"))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def get_line_coverage_percent_from_cobertura(xml_file: Path) -> str:
"""Return overall line coverage % from a Cobertura XML file."""
try:
root = etree.parse(str(xml_file)).getroot()
except (FileNotFoundError, PermissionError) as exc:
typer.echo(f"Could not read {xml_file}: {exc}", err=True)
raise typer.Exit(1) from exc
except etree.XMLSyntaxError as exc:
typer.echo(f"Invalid XML in {xml_file}: {exc}", err=True)
raise typer.Exit(1) from exc
try:
total = int(root.xpath("count(//class/lines/line)"))
covered = int(root.xpath("count(//class/lines/line[@hits>0])"))
except etree.XPathError as exc:
typer.echo(f"Malformed Cobertura data: {exc}", err=True)
raise typer.Exit(1) from exc
if total == 0:
try:
covered = int(root.xpath("number(/coverage/@lines-covered)"))
total = int(root.xpath("number(/coverage/@lines-valid)"))
except etree.XPathError as exc:
typer.echo(f"Cobertura summary missing: {exc}", err=True)
raise typer.Exit(1) from exc
if total == 0:
return "0.00"
return _format_percent(covered, total)
def get_line_coverage_percent_from_cobertura(xml_file: Path) -> str:
"""Return overall line coverage % from a Cobertura XML file."""
try:
root = etree.parse(str(xml_file)).getroot()
except (FileNotFoundError, PermissionError) as exc:
typer.echo(f"Could not read {xml_file}: {exc}", err=True)
raise typer.Exit(1) from exc
except etree.XMLSyntaxError as exc:
typer.echo(f"Invalid XML in {xml_file}: {exc}", err=True)
raise typer.Exit(1) from exc
try:
total = int(root.xpath("count(//class/lines/line)"))
covered = int(root.xpath("count(//class/lines/line[@hits>0])"))
except etree.XPathError as exc:
typer.echo(f"Malformed Cobertura data: {exc}", err=True)
raise typer.Exit(1) from exc
if total == 0:
try:
total = int(root.xpath("number(/coverage/@lines-valid)"))
covered = int(root.xpath("number(/coverage/@lines-covered)"))
except etree.XPathError as exc:
typer.echo(f"Cobertura summary missing: {exc}", err=True)
raise typer.Exit(1) from exc
if total == 0:
return "0.00"
return _format_percent(covered, total)
🤖 Prompt for AI Agents
In .github/actions/generate-coverage/scripts/run_rust.py between lines 67 and
97, swap the order of the XPath extraction lines so that the variable total is
assigned before covered in the block where total is zero. This means extracting
total first using the XPath expression for lines-valid, then extracting covered
using lines-covered. This change maintains consistent ordering of variable
assignments for clarity and readability.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant