### Install pycobertura Source: https://github.com/aconrad/pycobertura/blob/master/README.md Install the pycobertura package using pip. This is the primary method for setting up the tool. ```shell pip install pycobertura ``` -------------------------------- ### Full CI pipeline example with git archive Source: https://context7.com/aconrad/pycobertura/llms.txt A comprehensive example for CI pipelines using `git archive` to extract source code from different branches and `pycobertura diff` to generate an HTML report. This demonstrates a complete workflow for comparing coverage between main and a feature branch. ```bash # Full CI pipeline example using git archive git archive --prefix=src_old/ origin/main | tar -xf - git archive --prefix=src_new/ HEAD | tar -xf - pycobertura diff --format html --output diff.html \ --source1 src_old/ --source2 src_new/ \ coverage.main.xml coverage.head.xml ``` -------------------------------- ### Example of Code Coverage Report (Version A) Source: https://github.com/aconrad/pycobertura/blob/master/README.md Illustrates a simple code coverage report where 4 out of 5 lines are hit, resulting in an 80% line rate and 1 uncovered line. ```shell line 1: hit line 2: hit line 3: miss line 4: hit line 5: hit ``` -------------------------------- ### Show Cobertura Report Source: https://github.com/aconrad/pycobertura/blob/master/README.md Displays a Cobertura XML report. No setup or imports are required for this command-line usage. ```bash pycobertura show tests/cobertura.xml ``` -------------------------------- ### Run Tests with Tox Source: https://github.com/aconrad/pycobertura/blob/master/README.md Installs and runs tests using Tox, a tool for automating Python testing in different environments. Ensure Tox is installed via pip. ```shell pip install tox tox ``` -------------------------------- ### Example of Code Coverage Report (Version B) Source: https://github.com/aconrad/pycobertura/blob/master/README.md Demonstrates a scenario where a covered line is deleted, causing the line rate to decrease from 80% to 75% while the number of uncovered lines remains 1. This highlights why uncovered lines are a better metric than line rate for detecting regressions. ```shell line 1: hit ### line deleted ### line 2: miss line 3: hit line 4: hit ``` -------------------------------- ### Python Code Example for Coverage Analysis Source: https://github.com/aconrad/pycobertura/blob/master/README.md This Python code snippet illustrates the structure of source code that might be analyzed for coverage. It's used in the context of explaining why source code paths are needed for `pycobertura diff` to accurately highlight changes. ```python if foo is True: # line 1 total += 1 # line 2 return total # line 3 ``` -------------------------------- ### Generate Source Archives for PyCobertura Diff Source: https://github.com/aconrad/pycobertura/blob/master/README.md Before running `pycobertura diff` with different revisions, generate archives of your source code using version control tools like git. This example shows how to archive source code for two branches/commits, run the diff, and then clean up the temporary directories. ```shell git archive --prefix=source1/ ${BRANCH_OR_COMMIT1} | tar -xf - git archive --prefix=source2/ ${BRANCH_OR_COMMIT2} | tar -xf - pycobertura diff --source1 source1/ --source2 source2/ coverage1.xml coverage2.xml -o output.html rm -rf source1/ source2/ ``` -------------------------------- ### Modified Python Code Example for Coverage Analysis Source: https://github.com/aconrad/pycobertura/blob/master/README.md This Python code snippet represents a modified version of source code, used to demonstrate how `pycobertura diff` identifies changes and highlights them. It shows new and modified lines compared to a previous version. ```python if foo is False: # line 1 # new line total -= 1 # line 2 # new line elif foo is True: # line 3 # modified line total += 1 # line 4, unchanged return total # line 5, unchanged ``` -------------------------------- ### Get Cobertura Report Information Source: https://github.com/aconrad/pycobertura/blob/master/README.md Retrieves various metrics from a Cobertura object, including version, overall line rate, and a list of files. Specific line rates for individual files can also be accessed. ```python cobertura.version == '4.0.2' cobertura.line_rate() == 1.0 # 100% cobertura.files() == [ 'pycobertura/__init__.py', 'pycobertura/cli.py', 'pycobertura/cobertura.py', 'pycobertura/reporters.py', 'pycobertura/utils.py', ] cobertura.line_rate('pycobertura/cli.py') == 1.0 ``` -------------------------------- ### CLI: Show coverage summary in various formats Source: https://context7.com/aconrad/pycobertura/llms.txt Prints coverage summaries from the command line. Supports multiple output formats, sorting, filtering, and custom delimiters. ```bash # Plain-text summary (default) pycobertura show coverage.xml ``` ```bash # HTML report with highlighted source written to file pycobertura show --format html --output coverage.html --source src/ coverage.xml ``` ```bash # Sort by most uncovered lines first, output as Markdown pycobertura show --format markdown --sort-by-uncovered-lines coverage.xml ``` ```bash # JSON output to file pycobertura show --format json --output coverage.json coverage.xml ``` ```bash # YAML output pycobertura show --format yaml coverage.xml ``` ```bash # CSV with custom delimiter pycobertura show --format csv --delimiter "," coverage.xml ``` ```bash # GitHub Actions annotation (emits ::notice workflow commands) pycobertura show --format github-annotation \ --annotation-level warning \ --annotation-title "coverage" \ --annotation-message "line not covered" \ coverage.xml ``` ```bash # Fail if more than 50 lines are uncovered (exit code 4) pycobertura show --fail-threshold 50 coverage.xml echo "Exit code: $?" ``` ```bash # Exclude files matching a Python regex pycobertura show --ignore-regex ".*test.*" coverage.xml ``` ```bash # Exclude files matching patterns in a .gitignore-style file pycobertura show --ignore-regex ".testgitignore" coverage.xml ``` ```bash # Invoke as a Python module (PEP 338) python -m pycobertura show coverage.xml ``` -------------------------------- ### Show pycobertura help Source: https://github.com/aconrad/pycobertura/blob/master/README.md Display the main help screen for the pycobertura CLI, outlining available commands. ```shell $ pycobertura --help Usage: pycobertura [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. Commands: diff The diff command compares and shows the changes between two... show show coverage summary of a Cobertura report ``` -------------------------------- ### Configure filesystem backends for Cobertura Source: https://context7.com/aconrad/pycobertura/llms.txt Abstracts how pycobertura locates source files. Supports Directory, Zip, and Git filesystems. `filesystem_factory` auto-selects the backend. ```python from pycobertura.filesystem import ( DirectoryFileSystem, ZipFileSystem, GitFileSystem, filesystem_factory, ) from pycobertura import Cobertura # Directory backend (most common) fs_dir = DirectoryFileSystem("src/", source_prefix="myapp") cov = Cobertura("coverage.xml", filesystem=fs_dir) # Zip archive backend (useful in CI artifact pipelines) fs_zip = ZipFileSystem("source.zip", source_prefix="myapp-1.0/") cov = Cobertura("coverage.xml", filesystem=fs_zip) # Git backend — reads source directly from a git object store fs_git = GitFileSystem(repo_folder="/path/to/repo", ref="main") cov = Cobertura("coverage.xml", filesystem=fs_git) # Auto-select backend fs = filesystem_factory("source.zip") # → ZipFileSystem fs = filesystem_factory("src/") # → DirectoryFileSystem fs = filesystem_factory("src/", ref="HEAD~1") # → GitFileSystem # CI artifact pipeline pattern import subprocess, os subprocess.run(["git", "archive", "--prefix=src1/", "HEAD~1", "|", "tar", "-xf", "-"], shell=True) subprocess.run(["git", "archive", "--prefix=src2/", "HEAD", "|", "tar", "-xf", "-"], shell=True) cov1 = Cobertura("coverage.old.xml", filesystem=DirectoryFileSystem("src1/")) cov2 = Cobertura("coverage.new.xml", filesystem=DirectoryFileSystem("src2/")) ``` -------------------------------- ### Basic diff with source directories Source: https://context7.com/aconrad/pycobertura/llms.txt Compares two Cobertura XML files and shows a text-based diff, including changes in statements, misses, and coverage percentage. Supply --source1 and --source2 for accurate line-level diffs. ```bash # Basic diff (text, with source directories) pycobertura diff coverage.old.xml coverage.new.xml \ --source1 src_old/ \ --source2 src_new/ # Filename Stmts Miss Cover Missing # ---------------- ------- ------ -------- --------- # myapp/models.py - -2 +50.00% -27, -28 # myapp/views.py +4 +1 -5.00% +90 # TOTAL +4 -1 +10.00% ``` -------------------------------- ### Compare Coverage Files with Source Diffs Source: https://github.com/aconrad/pycobertura/blob/master/README.md Use the diff command to compare two coverage files and show differences. Provide source code directories for accurate 'Missing' column calculation. ```shell $ pycobertura diff coverage.old.xml coverage.new.xml --source1 old_source/ --source2 new_source/ Filename Stmts Miss Cover Missing ---------------- ------- ------ -------- --------- dummy/dummy.py - -2 +50.00% -2, -5 dummy/dummy2.py +2 - +100.00% TOTAL +2 -2 +50.00% ``` -------------------------------- ### Run Tests for Dummy App Source: https://github.com/aconrad/pycobertura/blob/master/tests/README.generate-dummy-coverage-for-testing.md Navigate to the dummy application directory and execute pytest to generate coverage reports. Save the resulting `coverage.xml` file for use in pycobertura tests. ```bash cd dummy/ py.test ``` -------------------------------- ### Show pycobertura show command help Source: https://github.com/aconrad/pycobertura/blob/master/README.md Display the help screen for the 'show' command, which provides coverage summary of a Cobertura report. ```shell pycobertura show --help ``` -------------------------------- ### Download Artifacts for CI/CD Coverage Check Source: https://github.com/aconrad/pycobertura/blob/master/README.md This shell command sequence demonstrates how to download coverage and source code artifacts from a CI/CD server for a specific build. This is a prerequisite step for running `pycobertura diff` in a pipeline to check for coverage regressions. ```shell # Download artifacts of current build curl -o coverage.${BUILD_ID}.xml https://ciserver/artifacts/${BUILD_ID}/coverage.xml curl -o source.${BUILD_ID}.zip https://ciserver/artifacts/${BUILD_ID}/source.zip ``` -------------------------------- ### Download and Compare Coverage Reports with PyCobertura Source: https://github.com/aconrad/pycobertura/blob/master/README.md This script downloads coverage and source artifacts for two builds, unzips the source, and then uses pycobertura to generate an HTML diff report. Finally, it uploads the diff report as an artifact. ```shell curl -o coverage.${PROD_BUILD}.xml https://ciserver/artifacts/${PROD_BUILD}/coverage.xml curl -o source.${PROD_BUILD}.zip https://ciserver/artifacts/${PROD_BUILD}/source.zip unzip source.${BUILD_ID}.zip -d source.${BUILD_ID} unzip source.${PROD_BUILD}.zip -d source.${PROD_BUILD} # Compare pycobertura diff --format html \ --output pycobertura-diff.${BUILD_ID}.html \ --source1 source.${PROD_BUILD} \ --source2 source.${BUILD_ID} \ coverage.${PROD_BUILD}.xml \ coverage.${BUILD_ID}.xml # Upload the pycobertura report artifact curl -F filedata=@pycobertura-diff.${BUILD_ID}.html http://ciserver/artifacts/${BUILD_ID}/ ``` -------------------------------- ### Initialize Cobertura Object Source: https://github.com/aconrad/pycobertura/blob/master/README.md Initializes the Cobertura object with a path to a Cobertura XML file. This is the first step when using pycobertura as a library. ```python from pycobertura import Cobertura cobertura = Cobertura('coverage.xml') ``` -------------------------------- ### Show pycobertura diff command help Source: https://github.com/aconrad/pycobertura/blob/master/README.md Display the help screen for the 'diff' command, which compares and shows changes between two Cobertura reports. ```shell pycobertura diff --help ``` -------------------------------- ### Display Coverage Report Summary Source: https://github.com/aconrad/pycobertura/blob/master/README.md Shows a basic coverage report summary in plain text format. This is the default output when no format is specified. ```shell $ pycobertura show coverage.xml ``` -------------------------------- ### HTML Format Diff with Output File Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generate an HTML formatted diff between two coverage files and save it to a specified output file. The HTML output highlights only the parts of the code where coverage has changed. ```shell pycobertura diff --format html --output coverage.html ./master/coverage.xml ./myfeature/coverage.xml ``` -------------------------------- ### Show command with fail threshold Source: https://github.com/aconrad/pycobertura/blob/master/README.md Use the `show` command with the `--fail-threshold` option to return a non-zero exit code when the number of uncovered lines exceeds the specified value. This is useful for CI/CD pipelines. ```shell $ pycobertura show --fail-threshold=123 cobertura.xml ``` -------------------------------- ### Generate HTML Coverage Report Source: https://github.com/aconrad/pycobertura/blob/master/README.md Creates an HTML version of the coverage report, which can include highlighted source code. ```shell pycobertura show --format html --output coverage.html coverage.xml ``` -------------------------------- ### Display Coverage Report in Markdown Format Source: https://github.com/aconrad/pycobertura/blob/master/README.md Renders the coverage report in Markdown table format, suitable for documentation or README files. ```shell $ pycobertura show --format markdown coverage.xml ``` -------------------------------- ### Diff using zip archives Source: https://context7.com/aconrad/pycobertura/llms.txt Compares coverage reports from zip archives, useful for CI artifact pipelines. Generates an HTML diff report. ```bash # Diff using zip archives (common in CI artifact pipelines) pycobertura diff --format html --output diff.html \ --source1 source_old.zip --source2 source_new.zip \ coverage.old.xml coverage.new.xml ``` -------------------------------- ### Generate HTML diff report Source: https://context7.com/aconrad/pycobertura/llms.txt Generates an HTML report comparing two Cobertura XML files, highlighting differences in coverage. Requires specifying output file and source directories. ```bash # HTML diff report pycobertura diff --format html --output diff.html \ --source1 src_old/ --source2 src_new/ \ coverage.old.xml coverage.new.xml ``` -------------------------------- ### Generate GitHub Annotations Source: https://github.com/aconrad/pycobertura/blob/master/README.md Creates output in the GitHub Actions annotation format, which can be used to display warnings or notices directly in pull requests. ```shell $ pycobertura show --format github-annotation tests/cobertura.xml ``` -------------------------------- ### Ignore Regex Configuration File Source: https://github.com/aconrad/pycobertura/blob/master/README.md Specifies a file containing patterns to ignore when generating coverage reports. This file should follow standard ignore file conventions. ```bash pycobertura show tests/cobertura.xml --ignore-regex "tests/.testgitignore" ``` -------------------------------- ### Generate GitHub Actions annotations for coverage Source: https://context7.com/aconrad/pycobertura/llms.txt Emits GitHub workflow commands for check annotations. Configurable annotation level, title, and message. ```python from pycobertura import Cobertura from pycobertura.reporters import GitHubAnnotationReporter, GitHubAnnotationReporterDelta cov = Cobertura("coverage.xml") print(GitHubAnnotationReporter(cov).generate( annotation_level="warning", annotation_title="coverage", annotation_message="not covered", )) ``` ```python cov1 = Cobertura("coverage.old.xml") cov2 = Cobertura("coverage.new.xml") print(GitHubAnnotationReporterDelta(cov1, cov2).generate( annotation_level="notice", annotation_title="pycobertura", annotation_message="not covered", )) ``` -------------------------------- ### Generate YAML Coverage Report Source: https://github.com/aconrad/pycobertura/blob/master/README.md Produces the coverage report in YAML format, offering a human-readable structured data representation. ```shell $ pycobertura show --format yaml --output coverage.yaml tests/cobertura.xml ``` -------------------------------- ### Show Cobertura Report with File Exclusion Source: https://github.com/aconrad/pycobertura/blob/master/README.md Displays a Cobertura XML report while excluding files that match the provided regex pattern. Ensure the regex follows Python conventions. ```bash pycobertura show tests/cobertura.xml --ignore-regex ".*Search" ``` -------------------------------- ### Markdown Format Diff Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generate a markdown formatted diff between two coverage files. This format is useful for including coverage differences in documentation. ```shell pycobertura diff --format markdown tests/dummy.source1/coverage.xml tests/dummy.source2/coverage.xml ``` -------------------------------- ### Generate JSON Coverage Report Source: https://github.com/aconrad/pycobertura/blob/master/README.md Outputs the coverage report in JSON format, which is useful for programmatic processing. ```shell $ pycobertura show --format json --output coverage.json tests/cobertura.xml ``` -------------------------------- ### Generate HTML Coverage Report Sorted by Uncovered Lines Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generates an HTML coverage report sorted by the number of uncovered lines, helping to identify the riskiest files first. This sorting option works with all supported formats. ```shell pycobertura show --format html --sort-by-uncovered-lines --output coverage.html coverage.xml ``` -------------------------------- ### Display Coverage Report in CSV Format Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generates a coverage report in CSV format. The semicolon is used as a delimiter to avoid conflicts with the comma used in the 'Missing' column. ```shell $ pycobertura show --format csv coverage.xml --delimiter ";" ``` -------------------------------- ### Generate Plain-Text Tabular Report Source: https://context7.com/aconrad/pycobertura/llms.txt Use TextReporter to generate a plain-text table of coverage data. For comparing two reports, use TextReporterDelta to show signed deltas. ```python from pycobertura import Cobertura, TextReporter, TextReporterDelta cov = Cobertura("coverage.xml") reporter = TextReporter(cov, sort_by_uncovered_lines=True) print(reporter.generate()) # Filename Stmts Miss Cover Missing # ------------------------- ------- ------ ------- --------- # myapp/views.py 80 12 85.00% 34-36, 90 # myapp/models.py 60 5 91.67% 27-28 # myapp/__init__.py 2 0 100.00% # TOTAL 142 17 88.03% ``` ```python cov1 = Cobertura("coverage.old.xml") cov2 = Cobertura("coverage.new.xml") delta = TextReporterDelta(cov1, cov2, color=False) print(delta.generate()) # Filename Stmts Miss Cover Missing # ---------------- ------- ------ -------- --------- # myapp/models.py - -2 +50.00% -27, -28 # myapp/views.py +4 +1 -5.00% +90 # TOTAL +4 -1 +10.00% ``` -------------------------------- ### Compare same report for branch differences Source: https://context7.com/aconrad/pycobertura/llms.txt Uses the same coverage report twice with different source directories to identify uncovered lines relative to another branch. This helps visualize differences introduced by a feature branch. ```bash # Use the same report twice to see uncovered lines relative to another branch pycobertura diff coverage.xml coverage.xml \ --source1 master/ --source2 myfeature/ ``` -------------------------------- ### Diff Coverage Reports for Uncovered Changes Source: https://github.com/aconrad/pycobertura/blob/master/README.md Use this command to compare two coverage reports from different source code bases to identify uncovered changes. Ensure you provide the paths to both source directories. ```shell pycobertura diff coverage.xml coverage.xml --source1 master/ --source2 myfeature/ ``` -------------------------------- ### Generate HTML Report with Source Highlighting Source: https://context7.com/aconrad/pycobertura/llms.txt HtmlReporter creates a self-contained HTML page with coverage summaries and highlighted source code. HtmlReporterDelta highlights only changed lines between two reports. ```python from pycobertura import Cobertura from pycobertura.reporters import HtmlReporter, HtmlReporterDelta from pycobertura.filesystem import DirectoryFileSystem, ZipFileSystem # Single report → HTML with source cov = Cobertura("coverage.xml", filesystem=DirectoryFileSystem("src/")) html_reporter = HtmlReporter( cov, title="My Project Coverage", render_file_sources=True, ) with open("coverage.html", "wb") as f: f.write(html_reporter.generate().encode("utf-8")) ``` ```python cov1 = Cobertura("coverage.old.xml", filesystem=ZipFileSystem("source_old.zip")) cov2 = Cobertura("coverage.new.xml", filesystem=ZipFileSystem("source_new.zip")) html_delta = HtmlReporterDelta(cov1, cov2, show_missing=True, show_source=True) with open("diff.html", "wb") as f: f.write(html_delta.generate().encode("utf-8")) ``` -------------------------------- ### GitHub Actions annotation diff Source: https://context7.com/aconrad/pycobertura/llms.txt Generates diff output in GitHub Actions annotation format, suitable for direct integration into GitHub Actions workflows to flag coverage changes. ```bash # GitHub Actions annotation diff pycobertura diff --format github-annotation \ --source1 src_old/ --source2 src_new/ \ coverage.old.xml coverage.new.xml ``` -------------------------------- ### GitHub Annotations Diff Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generate GitHub annotations for uncovered lines based on the diff between two coverage files. This is useful for integrating coverage feedback directly into GitHub pull requests. ```shell $ pycobertura diff --format github-annotation tests/dummy.source1/coverage.xml tests/dummy.source2/coverage.xml ::notice file=dummy/dummy2.py,line=5,endLine=5,title=pycobertura::not covered ::notice file=dummy/dummy3.py,line=1,endLine=2,title=pycobertura::not covered ``` -------------------------------- ### JSON Format Diff Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generate a JSON formatted diff between two coverage files. This format is useful for programmatic processing of coverage differences. ```shell pycobertura diff --format json tests/dummy.source1/coverage.xml tests/dummy.source2/coverage.xml ``` -------------------------------- ### CSV Format Diff with Custom Delimiter Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generate a CSV formatted diff between two coverage files. A custom delimiter can be specified using the --delimiter option. Note that comma and newline delimiters are risky. ```shell pycobertura diff tests/dummy.source1/coverage.xml tests/dummy.source2/coverage.xml --format csv --delimiter ";" ``` -------------------------------- ### YAML Format Diff Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generate a YAML formatted diff between two coverage files. This format is suitable for configuration files or data serialization. ```shell pycobertura diff --format yaml tests/dummy.source1/coverage.xml tests/dummy.source2/coverage.xml ``` -------------------------------- ### Skip source-level diff Source: https://context7.com/aconrad/pycobertura/llms.txt Performs a faster diff without source-level details, omitting the 'Missing' column. Useful when only overall coverage changes are needed. ```bash # Skip source-level diff (no Missing column), faster but less detail pycobertura diff --no-source coverage.old.xml coverage.new.xml ``` -------------------------------- ### Generate CSV diff report Source: https://context7.com/aconrad/pycobertura/llms.txt Compares two Cobertura reports and generates a CSV diff. The output includes filename, statements, misses, and coverage changes. ```python cov1 = Cobertura("coverage.old.xml") cov2 = Cobertura("coverage.new.xml") print(CsvReporterDelta(cov1, cov2, color=False).generate(delimiter=";")) ``` -------------------------------- ### Generate Text Report Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generates a human-readable text report from a Cobertura object using the TextReporter. This provides a summary of coverage statistics. ```python from pycobertura import TextReporter tr = TextReporter(cobertura) tr.generate() == """ Filename Stmts Miss Cover Missing ------------------------- ------- ------ ------- --------- pycobertura/__init__.py 1 0 100.00% pycobertura/cli.py 18 0 100.00% pycobertura/cobertura.py 93 0 100.00% pycobertura/reporters.py 129 0 100.00% pycobertura/utils.py 12 0 100.00% TOTAL 253 0 100.00%""" ``` -------------------------------- ### Generate Machine-Readable JSON and YAML Reports Source: https://context7.com/aconrad/pycobertura/llms.txt JsonReporter and YamlReporter output structured coverage data. Delta variants include signed deltas and line number information for changes. ```python import json from pycobertura import Cobertura from pycobertura.reporters import JsonReporter, JsonReporterDelta, YamlReporter cov = Cobertura("coverage.xml") print(JsonReporter(cov).generate()) # { # "files": [ # {"Filename": "Main.java", "Stmts": 15, "Miss": 0, "Cover": "100.00%", "Missing": ""}, # {"Filename": "search/BinarySearch.java", "Stmts": 12, "Miss": 1, "Cover": "91.67%", "Missing": "24"} # ], # "total": {"Filename": "TOTAL", "Stmts": 34, "Miss": 3, "Cover": "90.00%"} # } ``` ```python print(YamlReporter(cov).generate().decode()) # files: # - Filename: Main.java # Stmts: 15 # Miss: 0 # Cover: 100.00% # Missing: '' # total: # Filename: TOTAL # Stmts: 34 # Miss: 3 # Cover: 90.00% ``` ```python cov1 = Cobertura("coverage.old.xml") cov2 = Cobertura("coverage.new.xml") delta_json = json.loads(JsonReporterDelta(cov1, cov2, color=False).generate()) for f in delta_json["files"]: print(f["Filename"], f["Miss"], f.get("Missing")) # myapp/models.py -2 ['-27', '-28'] # myapp/views.py +1 ['+90'] ``` -------------------------------- ### Cobertura - Parse a Cobertura XML report Source: https://context7.com/aconrad/pycobertura/llms.txt The Cobertura class is the core parser for Cobertura XML reports. It can be initialized with a file path, file object, or raw XML string and provides methods to access coverage details. ```APIDOC ## Cobertura ### Description Parses a Cobertura XML report and provides methods to query line rates, file lists, statement hit/miss counts, and source lines. An optional `filesystem` argument is required for source-level details. ### Usage ```python from pycobertura import Cobertura from pycobertura.filesystem import DirectoryFileSystem # Parse a report with an attached filesystem fs = DirectoryFileSystem("src/") cov = Cobertura("coverage.xml", filesystem=fs) # Access coverage information print(cov.version) print(cov.line_rate()) print(cov.line_rate("myapp/models.py")) print(cov.branch_rate()) print(cov.files()) print(cov.missed_statements("myapp/models.py")) print(cov.hit_statements("myapp/models.py")) print(cov.total_statements()) print(cov.total_misses()) print(cov.total_hits()) # Iterate over line statuses for lineno, status in cov.line_statuses("myapp/models.py"): print(lineno, status) # Get missed lines print(cov.missed_lines("myapp/models.py")) # Get file source details for line in cov.file_source("myapp/models.py"): print(line.number, line.status, repr(line.source)) # Filter files by regex print(cov.files(ignore_regex=".*test.* பங்க்")) print(cov.total_misses(ignore_regex="tests/.testgitignore")) ``` ### Methods - `version`: Returns the Cobertura report version. - `line_rate(filename=None)`: Returns the global line rate (0-1) or the line rate for a specific file. - `branch_rate(filename=None)`: Returns the global branch rate or the branch rate for a specific file (if available). - `files(ignore_regex=None)`: Returns a list of files in the report, optionally filtered by a regex. - `missed_statements(filename)`: Returns a list of line numbers for missed statements in a file. - `hit_statements(filename)`: Returns a list of line numbers for hit statements in a file. - `total_statements()`: Returns the total number of statements in the report. - `total_misses()`: Returns the total number of missed statements in the report. - `total_hits()`: Returns the total number of hit statements in the report. - `line_statuses(filename)`: Returns an iterable of (lineno, status) tuples for all tracked lines in a file. - `missed_lines(filename)`: Returns an iterable of (lineno, status) tuples for uncovered or partially covered lines. - `file_source(filename)`: Returns an iterable of `Line` namedtuples (number, source, status, reason) for each line in a file. - `diff_total_misses(filename=None, ignore_regex=None)`: Returns the difference in total missed statements, optionally for a specific file and with regex filtering. ``` -------------------------------- ### Generate CSV and Markdown Reports Source: https://context7.com/aconrad/pycobertura/llms.txt CsvReporter outputs semicolon-delimited data, configurable with different delimiters. MarkdownReporter generates a GitHub-flavored Markdown table. Delta variants are also available. ```python from pycobertura import Cobertura from pycobertura.reporters import CsvReporter, MarkdownReporter, CsvReporterDelta cov = Cobertura("coverage.xml") # CSV with tab delimiter print(CsvReporter(cov).generate(delimiter="\t")) # Filename\tStmts\tMiss\tCover\tMissing # myapp/models.py\t60\t5\t91.67%\t27-28 ``` ```python print(MarkdownReporter(cov).generate()) # | Filename | Stmts | Miss | Cover | Missing | # |-----------------|---------|--------|---------|-----------| # | myapp/models.py | 60 | 5 | 91.67% | 27-28 | # | TOTAL | 60 | 5 | 91.67% | | ``` -------------------------------- ### Diff Two Cobertura Reports with CoberturaDiff Source: https://context7.com/aconrad/pycobertura/llms.txt Use CoberturaDiff to compare two Cobertura reports and compute deltas. It reconciles source line numbers to attribute coverage changes correctly. ```python from pycobertura import Cobertura, CoberturaDiff from pycobertura.filesystem import DirectoryFileSystem cov1 = Cobertura("coverage.old.xml", filesystem=DirectoryFileSystem("src_old/")) cov2 = Cobertura("coverage.new.xml", filesystem=DirectoryFileSystem("src_new/")) diff = CoberturaDiff(cov1, cov2) print(diff.files()) # union of both reports' files print(diff.diff_total_statements()) # +5 print(diff.diff_total_misses()) # -2 print(diff.diff_total_hits()) # +7 print(diff.diff_line_rate()) # +0.04 # Per-file deltas print(diff.diff_total_misses("myapp/models.py")) # -1 # Coverage quality checks (used by CLI exit code logic) print(diff.has_better_coverage()) # True if no file gained uncovered lines print(diff.has_all_changes_covered()) # True if every edited line is covered # diff_missed_lines: list of (lineno, status) for lines still uncovered in cov2 for lineno, status in diff.diff_missed_lines("myapp/models.py"): print(lineno, status) # (27, 'miss') # file_source: Line namedtuples with reason="line-edit"|"cov-up"|"cov-down"|None for line in diff.file_source("myapp/models.py"): if line.reason: print(line.number, line.status, line.reason) # file_source_hunks: same but grouped into context hunks (default ±3 lines) for hunk in diff.file_source_hunks("myapp/models.py"): for line in hunk: print(line.number, line.status, line.reason, repr(line.source)) ``` -------------------------------- ### Parse Cobertura XML Report with pycobertura Source: https://context7.com/aconrad/pycobertura/llms.txt Use the Cobertura class to parse XML reports. An optional filesystem argument is required for source-level details like HTML output or diff hunks. ```python from pycobertura import Cobertura from pycobertura.filesystem import DirectoryFileSystem # Parse a report; attach a filesystem so source lines can be read fs = DirectoryFileSystem("src/") cov = Cobertura("coverage.xml", filesystem=fs) print(cov.version) # e.g. "4.0.2" print(cov.line_rate()) # 0.87 (global, 0–1) print(cov.line_rate("myapp/models.py")) # 0.75 print(cov.branch_rate()) # 0.60 or None if absent print(cov.files()) # ['myapp/__init__.py', 'myapp/models.py', 'myapp/views.py'] print(cov.missed_statements("myapp/models.py")) # [14, 27, 28, 55] print(cov.hit_statements("myapp/models.py")) # [1, 5, 9, 10, ...] print(cov.total_statements()) # 312 print(cov.total_misses()) # 40 print(cov.total_hits()) # 272 # line_statuses returns (lineno, "hit"|"miss"|"partial") for every tracked line for lineno, status in cov.line_statuses("myapp/models.py"): print(lineno, status) # missed_lines returns extrapolated (lineno, status) for uncovered/partial lines print(cov.missed_lines("myapp/models.py")) # [(14, 'miss'), (27, 'miss'), (28, 'miss'), (55, 'partial')] # file_source returns Line namedtuples (number, source, status, reason) for line in cov.file_source("myapp/models.py"): print(line.number, line.status, repr(line.source)) # 1 hit 'from django.db import models\n' # 14 miss ' raise NotImplementedError\n' # Filter out files matching a regex or .gitignore-style file print(cov.files(ignore_regex=".*test.*")) print(cov.total_misses(ignore_regex="tests/.testgitignore")) ``` -------------------------------- ### CoberturaDiff - Diff two Cobertura reports programmatically Source: https://context7.com/aconrad/pycobertura/llms.txt The CoberturaDiff class compares two Cobertura reports to calculate deltas in coverage metrics and identify changes in uncovered lines. ```APIDOC ## CoberturaDiff ### Description Compares two `Cobertura` objects to compute deltas in statements, misses, hits, and line rates. It reconciles source line numbers to attribute coverage changes accurately. ### Usage ```python from pycobertura import Cobertura, CoberturaDiff from pycobertura.filesystem import DirectoryFileSystem # Initialize Cobertura objects for old and new reports cov1 = Cobertura("coverage.old.xml", filesystem=DirectoryFileSystem("src_old/")) cov2 = Cobertura("coverage.new.xml", filesystem=DirectoryFileSystem("src_new/")) # Create a CoberturaDiff object diff = CoberturaDiff(cov1, cov2) # Access diff information print(diff.files()) print(diff.diff_total_statements()) print(diff.diff_total_misses()) print(diff.diff_total_hits()) print(diff.diff_line_rate()) # Per-file deltas print(diff.diff_total_misses("myapp/models.py")) # Coverage quality checks print(diff.has_better_coverage()) print(diff.has_all_changes_covered()) # Iterate over diff missed lines for lineno, status in diff.diff_missed_lines("myapp/models.py"): print(lineno, status) # Iterate over file source with reasons for changes for line in diff.file_source("myapp/models.py"): if line.reason: print(line.number, line.status, line.reason) # Iterate over file source hunks for hunk in diff.file_source_hunks("myapp/models.py"): for line in hunk: print(line.number, line.status, line.reason, repr(line.source)) ``` ### Methods - `files()`: Returns the union of files from both reports. - `diff_total_statements()`: Returns the difference in total statements. - `diff_total_misses()`: Returns the difference in total missed statements. - `diff_total_hits()`: Returns the difference in total hit statements. - `diff_line_rate()`: Returns the difference in the global line rate. - `diff_total_misses(filename)`: Returns the difference in missed statements for a specific file. - `has_better_coverage()`: Returns `True` if no file has introduced new uncovered lines. - `has_all_changes_covered()`: Returns `True` if every edited line is covered. - `diff_missed_lines(filename)`: Returns a list of (lineno, status) for lines still uncovered in the new report. - `file_source(filename)`: Returns `Line` namedtuples with `reason` indicating changes ('line-edit', 'cov-up', 'cov-down'). - `file_source_hunks(filename)`: Returns source lines grouped into context hunks, with reasons for changes. ``` -------------------------------- ### Capture exit code for CI pipeline Source: https://context7.com/aconrad/pycobertura/llms.txt Captures the exit code of the `pycobertura diff` command to fail a CI pipeline if coverage has regressed. Exit codes indicate the type of regression: 0 for all changes covered, 2 for worsened coverage, and 3 for new uncovered lines with overall improved coverage. ```bash # Capture exit code to fail CI pipeline on regression pycobertura diff coverage.old.xml coverage.new.xml --source1 src_old/ --source2 src_new/ EXIT_CODE=$? # 0 = all changes covered # 2 = coverage worsened # 3 = new uncovered lines but overall coverage improved ``` -------------------------------- ### Generate Text Report Delta Source: https://github.com/aconrad/pycobertura/blob/master/README.md Generates a delta report comparing two Cobertura objects using TextReporterDelta. This highlights changes in coverage between two points in time. ```python from pycobertura import TextReporterDelta coverage1 = Cobertura('coverage1.xml') coverage2 = Cobertura('coverage2.xml') delta = TextReporterDelta(coverage1, coverage2) delta.generate() == """ Filename Stmts Miss Cover Missing ---------------- ------- ------ -------- --------- dummy/dummy.py - -2 +50.00% -2, -5 dummy/dummy2.py +2 - +100.00% TOTAL +2 -2 +50.00%""" ``` -------------------------------- ### Capture Diff Exit Code Source: https://github.com/aconrad/pycobertura/blob/master/README.md Captures the exit code of a pycobertura command, typically used after a diff operation, to check the coverage status. The exit code indicates the outcome of the comparison. ```bash pycobertura ... PYCOBERTURA_EXIT_CODE=$? echo $PYCOBERTURA_EXIT_CODE ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.