From 081fa306d2203a017d3e9ae70531c8d4e57675e0 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 09:40:55 +1000 Subject: [PATCH 01/16] CI: generate failure-only image summaries --- .github/workflows/build-ultraplot.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build-ultraplot.yml b/.github/workflows/build-ultraplot.yml index 7778a0a5b..12f1ff5e4 100644 --- a/.github/workflows/build-ultraplot.yml +++ b/.github/workflows/build-ultraplot.yml @@ -299,7 +299,7 @@ jobs: --mpl \ --mpl-baseline-path=./ultraplot/tests/baseline \ --mpl-results-path=./results/ \ - --mpl-generate-summary=html \ + --mpl-generate-summary=json \ --mpl-default-style="./ultraplot.yml" \ --junitxml=./results/junit.xml \ "${FILTERED_NODEIDS[@]}" @@ -333,7 +333,7 @@ jobs: --mpl \ --mpl-baseline-path=./ultraplot/tests/baseline \ --mpl-results-path=./results/ \ - --mpl-generate-summary=html \ + --mpl-generate-summary=json \ --mpl-default-style="./ultraplot.yml" \ --junitxml=./results/junit.xml \ ultraplot/tests @@ -360,11 +360,15 @@ jobs: exit "$status" fi - # Return the html output of the comparison even if failed + # JSON mode does not save images for passing comparisons. + - name: Collect failed image comparisons + if: always() && steps.baseline-support.outputs.baseline-supported == 'true' + run: python tools/ci/collect_failed_comparisons.py --results results --output failed-comparisons + - name: Upload comparison failures if: always() uses: actions/upload-artifact@v7 with: name: failed-comparisons-${{ inputs.python-version }}-${{ inputs.matplotlib-version }}-${{ github.sha }} - path: results/* + path: failed-comparisons/ if-no-files-found: ignore From 2c3df9a6b5f502147b25b4edf74fc98ba5521792 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 09:41:26 +1000 Subject: [PATCH 02/16] CI: package only failed plots with compact HTML diagnostics --- tools/ci/collect_failed_comparisons.py | 126 +++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 tools/ci/collect_failed_comparisons.py diff --git a/tools/ci/collect_failed_comparisons.py b/tools/ci/collect_failed_comparisons.py new file mode 100644 index 000000000..7cb835ed7 --- /dev/null +++ b/tools/ci/collect_failed_comparisons.py @@ -0,0 +1,126 @@ +"""Create an artifact with only failed pytest-mpl image comparisons. + +Run pytest-mpl with --mpl-generate-summary=json (not HTML). The latter +implicitly enables --mpl-results-always and saves passing test images. +""" + +from __future__ import annotations + +import argparse +import html +import json +import shutil +import xml.etree.ElementTree as ET +from pathlib import Path +from urllib.parse import quote + +_IMAGE_FIELDS = ( + ("baseline_image", "Baseline"), + ("result_image", "Actual"), + ("diff_image", "Difference"), +) + + +def junit_failures(path: Path) -> list[str]: + """Include non-image failures, for which pytest-mpl has no image result.""" + if not path.is_file(): + return [] + root = ET.parse(path).getroot() + return [ + f"{case.get('classname', '')}.{case.get('name', '')}".lstrip(".") + for case in root.iter("testcase") + if case.find("failure") is not None or case.find("error") is not None + ] + + +def collect(results_dir: Path, output_dir: Path) -> int: + """Return the number of failed pytest-mpl comparisons copied.""" + results_dir = results_dir.resolve() + output_dir = output_dir.resolve() + if output_dir == results_dir or results_dir in output_dir.parents: + raise ValueError("Artifact output must not be inside the pytest-mpl results directory") + + summary = results_dir / "results.json" + results = json.loads(summary.read_text(encoding="utf-8")) if summary.is_file() else {} + if not isinstance(results, dict): + raise ValueError("Unexpected pytest-mpl JSON summary format") + failed = {name: item for name, item in results.items() if item.get("status") == "failed"} + junit = results_dir / "junit.xml" + test_failures = junit_failures(junit) + + # An entirely green run should not produce an artifact, even an empty zip. + if not failed and not test_failures: + print("No failed image comparisons or JUnit tests; no artifact to upload.") + return 0 + + output_dir.mkdir(parents=True, exist_ok=True) + if junit.is_file(): + shutil.copy2(junit, output_dir / "junit.xml") + + (output_dir / "results.json").write_text( + json.dumps(failed, indent=2) + "\n", encoding="utf-8" + ) + + cards = [] + for name, item in failed.items(): + images = [] + for field, label in _IMAGE_FIELDS: + raw_path = item.get(field) + if not raw_path: + continue + relative_path = Path(raw_path) + source = (results_dir / relative_path).resolve() + if not source.is_relative_to(results_dir) or not source.is_file(): + raise ValueError(f"Unexpected {field} path in pytest-mpl results: {raw_path}") + destination = output_dir / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, destination) + url = html.escape(quote(relative_path.as_posix(), safe="/"), quote=True) + images.append( + f'
{html.escape(label)}' + f'
{html.escape(label)}
' + ) + rms = item.get("rms") + tolerance = item.get("tolerance") + metrics = f"RMS: {rms}; tolerance: {tolerance}" if rms is not None else "" + cards.append( + f'

{html.escape(name)}

{html.escape(metrics)}

' + f'
{"".join(images)}
' + f'
{html.escape(item.get("status_msg") or "")}
' + ) + + # Test errors unrelated to MPL may not produce an image; retain their names + # and the complete JUnit diagnostics rather than silently hiding them. + junit_list = "".join(f"
  • {html.escape(name)}
  • " for name in test_failures) + markup = f""" + +Failed UltraPlot image comparisons +

    Failed UltraPlot image comparisons

    +

    {len(failed)} image comparisons failed; {len(test_failures)} JUnit failures/errors. +See results.json and junit.xml for diagnostics.

    +
    Failed JUnit test names
      {junit_list}
    +{"".join(cards)} +""" + (output_dir / "index.html").write_text(markup, encoding="utf-8") + print(f"Prepared {len(failed)} failed image comparisons in {output_dir}") + return len(failed) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--results", type=Path, default=Path("results")) + parser.add_argument("--output", type=Path, default=Path("failed-comparisons")) + args = parser.parse_args() + collect(args.results, args.output) + + +if __name__ == "__main__": + main() From 62c2d47d5a7ef39b0f7da291f4ef64cd129a561b Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 09:42:11 +1000 Subject: [PATCH 03/16] CI: test filtering of passed and failed comparison artifacts --- tools/ci/test_collect_failed_comparisons.py | 76 +++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 tools/ci/test_collect_failed_comparisons.py diff --git a/tools/ci/test_collect_failed_comparisons.py b/tools/ci/test_collect_failed_comparisons.py new file mode 100644 index 000000000..dce49c593 --- /dev/null +++ b/tools/ci/test_collect_failed_comparisons.py @@ -0,0 +1,76 @@ +"""Unit tests for the CI's failure-only image artifact collector.""" + +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +from collect_failed_comparisons import collect + + +class TestFailureArtifacts(unittest.TestCase): + def setUp(self) -> None: + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.results = self.root / "results" + self.results.mkdir() + self.output = self.root / "artifacts" + + def test_passing_run_creates_no_artifact(self) -> None: + (self.results / "results.json").write_text( + json.dumps({"test_ok": {"status": "passed"}}), encoding="utf-8" + ) + (self.results / "junit.xml").write_text( + '', encoding="utf-8" + ) + + self.assertEqual(collect(self.results, self.output), 0) + self.assertFalse(self.output.exists()) + + def test_failed_images_are_selected_and_linked(self) -> None: + failed = "module.test_failed" + for filename in ("baseline.png", "result.png", "result-failed-diff.png"): + target = self.results / failed / filename + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(b"image data") + + (self.results / "results.json").write_text( + json.dumps({ + "module.test_passed": {"status": "passed", "result_image": "passed/result.png"}, + failed: { + "status": "failed", + "status_msg": "Image mismatch", + "baseline_image": f"{failed}/baseline.png", + "result_image": f"{failed}/result.png", + "diff_image": f"{failed}/result-failed-diff.png", + }, + }), + encoding="utf-8", + ) + (self.results / "junit.xml").write_text( + '', + encoding="utf-8", + ) + + self.assertEqual(collect(self.results, self.output), 1) + self.assertFalse((self.output / "passed").exists()) + self.assertEqual(set(json.loads((self.output / "results.json").read_text())), {failed}) + for filename in ("baseline.png", "result.png", "result-failed-diff.png"): + self.assertTrue((self.output / failed / filename).is_file()) + self.assertIn(filename, (self.output / "index.html").read_text()) + + def test_non_image_junit_failure_keeps_diagnostics(self) -> None: + (self.results / "junit.xml").write_text( + '', + encoding="utf-8", + ) + self.assertEqual(collect(self.results, self.output), 0) + self.assertTrue((self.output / "junit.xml").is_file()) + self.assertIn("module.test_crash", (self.output / "index.html").read_text()) + + +if __name__ == "__main__": + unittest.main() From 7e629f7e5edc9464be4cebfe2dd2c8e3829829eb Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 09:54:40 +1000 Subject: [PATCH 04/16] test(ci): intentionally mismatch inset image to verify failure artifact (TEMPORARY) --- ultraplot/tests/test_inset.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/ultraplot/tests/test_inset.py b/ultraplot/tests/test_inset.py index a0b8a52a9..54033b659 100644 --- a/ultraplot/tests/test_inset.py +++ b/ultraplot/tests/test_inset.py @@ -22,7 +22,7 @@ def test_inset_basic(): ylabel="ylabel", xticks=0.2, yticks=0.2, - title="Title", + title="CI ARTIFACT SMOKE TEST — INTENTIONAL IMAGE MISMATCH", suptitle="Complex arrangement of panels", toplabels=("Column 1", "Column 2"), abc=True, @@ -30,6 +30,17 @@ def test_inset_basic(): titleloc="uc", titleabove=False, ) + # TEMPORARY: Force a visible mismatch against the base-branch image so + # PR #850 produces an image-comparison artifact. REMOVE BEFORE MERGING. + fig.text( + 0.5, + 0.5, + "EXPECTED CI IMAGE FAILURE", + ha="center", + va="center", + fontsize=28, + color="magenta", + ) return fig From 1da142f667921f749e915e119515cfeb745a2a98 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 10:09:43 +1000 Subject: [PATCH 05/16] CI: add polished standalone visual regression report template --- tools/ci/failed_comparisons_template.html | 192 ++++++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 tools/ci/failed_comparisons_template.html diff --git a/tools/ci/failed_comparisons_template.html b/tools/ci/failed_comparisons_template.html new file mode 100644 index 000000000..40950342e --- /dev/null +++ b/tools/ci/failed_comparisons_template.html @@ -0,0 +1,192 @@ + + + + + + + Visual regression report · UltraPlot + + + +
    +
    +
    + ∿UltraPlot / CI diagnostics + VISUAL REGRESSION DETECTED +
    +
    IMAGE COMPARISON RESULTS
    +

    See what changed.

    +

    A focused report of failing image tests, with the reference render, actual render, and pixel difference side by side. Passing images are not archived.

    +
    +
    +
    +
    +
    __ULTRAPLOT_IMAGE_COUNT__Failed comparisons
    +
    __ULTRAPLOT_JUNIT_COUNT__JUnit failures / errors
    +
    __ULTRAPLOT_RETAINED_COUNT__Images retained
    +
    +
    +
    +

    Failed test cases

    +

    Showing __ULTRAPLOT_IMAGE_COUNT__ image comparisons

    +
    +
    + + ↓ JSON report + __ULTRAPLOT_JUNIT_DOWNLOAD__ +
    +
    +
    + __ULTRAPLOT_CARDS__ +
    + + __ULTRAPLOT_JUNIT_DETAILS__ +
    +
    UltraPlot · Visual regression diagnosticsLocal, dependency-free report · click any image to inspect
    + + + Enlarged comparison + + + + From 5cce2975f7ab46dc782028bde5922a6afc83d9cb Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 10:10:23 +1000 Subject: [PATCH 06/16] CI: render rich searchable HTML with side-by-side failure images --- tools/ci/collect_failed_comparisons.py | 97 ++++++++++++++++++-------- 1 file changed, 68 insertions(+), 29 deletions(-) diff --git a/tools/ci/collect_failed_comparisons.py b/tools/ci/collect_failed_comparisons.py index 7cb835ed7..43f558733 100644 --- a/tools/ci/collect_failed_comparisons.py +++ b/tools/ci/collect_failed_comparisons.py @@ -61,12 +61,26 @@ def collect(results_dir: Path, output_dir: Path) -> int: json.dumps(failed, indent=2) + "\n", encoding="utf-8" ) + # The report is static and intentionally self-contained: it also works + # directly from an extracted GitHub Actions artifact without a web server. cards = [] - for name, item in failed.items(): + retained_images = 0 + for name, item in sorted( + failed.items(), + key=lambda entry: ( + -(float(entry[1]["rms"]) if entry[1].get("rms") is not None else -1), + entry[0], + ), + ): images = [] for field, label in _IMAGE_FIELDS: raw_path = item.get(field) if not raw_path: + images.append( + f'
    ' + f'
    {html.escape(label)}Not available
    ' + f'
    No image
    ' + ) continue relative_path = Path(raw_path) source = (results_dir / relative_path).resolve() @@ -75,40 +89,65 @@ def collect(results_dir: Path, output_dir: Path) -> int: destination = output_dir / relative_path destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) + retained_images += 1 url = html.escape(quote(relative_path.as_posix(), safe="/"), quote=True) + escaped_label = html.escape(label, quote=True) images.append( - f'
    {html.escape(label)}' - f'
    {html.escape(label)}
    ' + f'
    {escaped_label}' + f'Click to enlarge ↗
    ' + f'' + f'{escaped_label} image for '
+                f'{html.escape(name, quote=True)}
    ' ) - rms = item.get("rms") - tolerance = item.get("tolerance") - metrics = f"RMS: {rms}; tolerance: {tolerance}" if rms is not None else "" + + metrics = [] + for field, label in (("rms", "RMS difference"), ("tolerance", "Tolerance")): + value = item.get(field) + if value is not None: + display = f"{value:.3f}" if isinstance(value, (int, float)) else str(value) + metrics.append( + f'{label}' + f'{html.escape(display)}' + ) + if not metrics: + metrics.append('No numerical comparison available') + comparison_status = str(item.get("image_status") or "failed").upper() cards.append( - f'

    {html.escape(name)}

    {html.escape(metrics)}

    ' - f'
    {"".join(images)}
    ' - f'
    {html.escape(item.get("status_msg") or "")}
    ' + f'
    ' + f'
    ' + f'

    FAILING TEST

    {html.escape(name)}

    ' + f'
    {html.escape(comparison_status)}
    ' + f'
    {"".join(metrics)}
    ' + f'
    {"".join(images)}
    ' + f'
    Diagnostic output' + f'
    {html.escape(str(item.get("status_msg") or "No diagnostic text provided."))}
    ' + f'
    ' ) - # Test errors unrelated to MPL may not produce an image; retain their names - # and the complete JUnit diagnostics rather than silently hiding them. - junit_list = "".join(f"
  • {html.escape(name)}
  • " for name in test_failures) - markup = f""" - -Failed UltraPlot image comparisons -

    Failed UltraPlot image comparisons

    -

    {len(failed)} image comparisons failed; {len(test_failures)} JUnit failures/errors. -See results.json and junit.xml for diagnostics.

    -
    Failed JUnit test names
      {junit_list}
    -{"".join(cards)} -""" + # JUnit includes failures not covered by pytest-mpl (which have no images). + junit_list = "".join(f"
  • {html.escape(name)}
  • " for name in test_failures) + junit_details = ( + '
    All JUnit failures / errors ' + f'({len(test_failures)})
      {junit_list}
    ' + if test_failures else "" + ) + template = Path(__file__).with_name("failed_comparisons_template.html").read_text( + encoding="utf-8" + ) + markup = template + for marker, value in { + "__ULTRAPLOT_IMAGE_COUNT__": str(len(failed)), + "__ULTRAPLOT_JUNIT_COUNT__": str(len(test_failures)), + "__ULTRAPLOT_RETAINED_COUNT__": str(retained_images), + "__ULTRAPLOT_CARDS__": "\n".join(cards), + "__ULTRAPLOT_JUNIT_DETAILS__": junit_details, + "__ULTRAPLOT_JUNIT_DOWNLOAD__": ( + '↓ JUnit XML' + if junit.is_file() else "" + ), + }.items(): + markup = markup.replace(marker, value) (output_dir / "index.html").write_text(markup, encoding="utf-8") print(f"Prepared {len(failed)} failed image comparisons in {output_dir}") return len(failed) From 7f4fa7ed2435cca6ae8370c9822f82f3ddf2a42e Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 10:11:13 +1000 Subject: [PATCH 07/16] CI: test report interactions and safe escaped diagnostics --- tools/ci/test_collect_failed_comparisons.py | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tools/ci/test_collect_failed_comparisons.py b/tools/ci/test_collect_failed_comparisons.py index dce49c593..b0e785d73 100644 --- a/tools/ci/test_collect_failed_comparisons.py +++ b/tools/ci/test_collect_failed_comparisons.py @@ -61,6 +61,34 @@ def test_failed_images_are_selected_and_linked(self) -> None: for filename in ("baseline.png", "result.png", "result-failed-diff.png"): self.assertTrue((self.output / failed / filename).is_file()) self.assertIn(filename, (self.output / "index.html").read_text()) + report = (self.output / "index.html").read_text(encoding="utf-8") + self.assertIn("See what changed.", report) + self.assertIn('id="search"', report) + self.assertIn('id="lightbox"', report) + self.assertIn('data-test="module.test_failed"', report) + self.assertIn("Image mismatch", report) + self.assertIn('href="results.json"', report) + self.assertNotIn("module.test_passed", report) + self.assertNotIn("__ULTRAPLOT_", report) + + def test_html_escapes_untrusted_test_names(self) -> None: + failed = '' + (self.results / "results.json").write_text( + json.dumps({ + failed: { + "status": "failed", + "status_msg": '', + } + }), + encoding="utf-8", + ) + + self.assertEqual(collect(self.results, self.output), 1) + markup = (self.output / "index.html").read_text(encoding="utf-8") + self.assertNotIn(failed, markup) + self.assertNotIn('', markup) + self.assertIn("<script>", markup) + self.assertIn("<img src=x", markup) def test_non_image_junit_failure_keeps_diagnostics(self) -> None: (self.results / "junit.xml").write_text( From f428ebe9285a22126090d18182008fdbbc9d186e Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 10:11:23 +1000 Subject: [PATCH 08/16] CI: run standalone failure-report generator tests --- .github/workflows/build-ultraplot.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/build-ultraplot.yml b/.github/workflows/build-ultraplot.yml index 12f1ff5e4..e7dc129d9 100644 --- a/.github/workflows/build-ultraplot.yml +++ b/.github/workflows/build-ultraplot.yml @@ -360,6 +360,11 @@ jobs: exit "$status" fi + # Validate the standalone report rendering on each CI environment. + - name: Test failed-comparison report generator + if: always() && steps.baseline-support.outputs.baseline-supported == 'true' + run: python -m unittest discover -s tools/ci -p 'test_collect_failed_comparisons.py' + # JSON mode does not save images for passing comparisons. - name: Collect failed image comparisons if: always() && steps.baseline-support.outputs.baseline-supported == 'true' From 33dd9f46f578980295871f86f18dbcbabec2b7d5 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 10:26:30 +1000 Subject: [PATCH 09/16] CI: simplify image comparison report to plain results layout --- tools/ci/failed_comparisons_template.html | 222 +++++----------------- 1 file changed, 47 insertions(+), 175 deletions(-) diff --git a/tools/ci/failed_comparisons_template.html b/tools/ci/failed_comparisons_template.html index 40950342e..cbc001229 100644 --- a/tools/ci/failed_comparisons_template.html +++ b/tools/ci/failed_comparisons_template.html @@ -3,190 +3,62 @@ - - Visual regression report · UltraPlot + UltraPlot Image comparison -
    -
    -
    - ∿UltraPlot / CI diagnostics - VISUAL REGRESSION DETECTED -
    -
    IMAGE COMPARISON RESULTS
    -

    See what changed.

    -

    A focused report of failing image tests, with the reference render, actual render, and pixel difference side by side. Passing images are not archived.

    -
    -
    -
    -
    -
    __ULTRAPLOT_IMAGE_COUNT__Failed comparisons
    -
    __ULTRAPLOT_JUNIT_COUNT__JUnit failures / errors
    -
    __ULTRAPLOT_RETAINED_COUNT__Images retained
    -
    -
    -
    -

    Failed test cases

    -

    Showing __ULTRAPLOT_IMAGE_COUNT__ image comparisons

    -
    -
    - - ↓ JSON report - __ULTRAPLOT_JUNIT_DOWNLOAD__ -
    -
    -
    - __ULTRAPLOT_CARDS__ -
    - +

    UltraPlot Image comparison

    +

    __ULTRAPLOT_IMAGE_COUNT__ failed image comparisons; __ULTRAPLOT_JUNIT_COUNT__ JUnit failures/errors.

    +

    results.json__ULTRAPLOT_JUNIT_DOWNLOAD__

    +
    + __ULTRAPLOT_CARDS__ __ULTRAPLOT_JUNIT_DETAILS__
    -
    UltraPlot · Visual regression diagnosticsLocal, dependency-free report · click any image to inspect
    - - - Enlarged comparison - - From 2f67260bcca366c55386d4fbf487c0191482522b Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 10:26:59 +1000 Subject: [PATCH 10/16] CI: generate compact baseline, actual, and diff sections --- tools/ci/collect_failed_comparisons.py | 63 +++++++++----------------- 1 file changed, 21 insertions(+), 42 deletions(-) diff --git a/tools/ci/collect_failed_comparisons.py b/tools/ci/collect_failed_comparisons.py index 43f558733..27e3eef46 100644 --- a/tools/ci/collect_failed_comparisons.py +++ b/tools/ci/collect_failed_comparisons.py @@ -61,27 +61,19 @@ def collect(results_dir: Path, output_dir: Path) -> int: json.dumps(failed, indent=2) + "\n", encoding="utf-8" ) - # The report is static and intentionally self-contained: it also works - # directly from an extracted GitHub Actions artifact without a web server. - cards = [] - retained_images = 0 - for name, item in sorted( - failed.items(), - key=lambda entry: ( - -(float(entry[1]["rms"]) if entry[1].get("rms") is not None else -1), - entry[0], - ), - ): + # Copy only failed comparisons. Linked images can be opened at full size. + comparisons = [] + for name, item in sorted(failed.items()): images = [] for field, label in _IMAGE_FIELDS: raw_path = item.get(field) if not raw_path: images.append( - f'
    ' - f'
    {html.escape(label)}Not available
    ' - f'
    No image
    ' + f'
    {html.escape(label)}
    ' + '

    Not available

    ' ) continue + relative_path = Path(raw_path) source = (results_dir / relative_path).resolve() if not source.is_relative_to(results_dir) or not source.is_file(): @@ -89,40 +81,28 @@ def collect(results_dir: Path, output_dir: Path) -> int: destination = output_dir / relative_path destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) - retained_images += 1 + url = html.escape(quote(relative_path.as_posix(), safe="/"), quote=True) - escaped_label = html.escape(label, quote=True) + alt = html.escape(f"{label} image for {name}", quote=True) images.append( - f'
    {escaped_label}' - f'Click to enlarge ↗
    ' - f'' - f'{escaped_label} image for '
-                f'{html.escape(name, quote=True)}
    ' + f'
    {html.escape(label)}
    ' + f'{alt}
    ' ) metrics = [] - for field, label in (("rms", "RMS difference"), ("tolerance", "Tolerance")): + for field, label in (("rms", "RMS"), ("tolerance", "Tolerance")): value = item.get(field) if value is not None: display = f"{value:.3f}" if isinstance(value, (int, float)) else str(value) - metrics.append( - f'{label}' - f'{html.escape(display)}' - ) - if not metrics: - metrics.append('No numerical comparison available') - comparison_status = str(item.get("image_status") or "failed").upper() - cards.append( - f'
    ' - f'
    ' - f'

    FAILING TEST

    {html.escape(name)}

    ' - f'
    {html.escape(comparison_status)}
    ' - f'
    {"".join(metrics)}
    ' - f'
    {"".join(images)}
    ' - f'
    Diagnostic output' + metrics.append(f"{label}: {html.escape(display)}") + + comparisons.append( + f'

    {html.escape(name)}

    ' + f'

    {" · ".join(metrics) if metrics else "No numerical comparison available"}

    ' + f'
    {"".join(images)}
    ' + f'
    Error details' f'
    {html.escape(str(item.get("status_msg") or "No diagnostic text provided."))}
    ' - f'
    ' + f'' ) # JUnit includes failures not covered by pytest-mpl (which have no images). @@ -139,11 +119,10 @@ def collect(results_dir: Path, output_dir: Path) -> int: for marker, value in { "__ULTRAPLOT_IMAGE_COUNT__": str(len(failed)), "__ULTRAPLOT_JUNIT_COUNT__": str(len(test_failures)), - "__ULTRAPLOT_RETAINED_COUNT__": str(retained_images), - "__ULTRAPLOT_CARDS__": "\n".join(cards), + "__ULTRAPLOT_CARDS__": "\n".join(comparisons), "__ULTRAPLOT_JUNIT_DETAILS__": junit_details, "__ULTRAPLOT_JUNIT_DOWNLOAD__": ( - '↓ JUnit XML' + ' · junit.xml' if junit.is_file() else "" ), }.items(): From 1f8fae74e8852b6a5bcd2ecebfecb91f1f3342ea Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 10:27:11 +1000 Subject: [PATCH 11/16] CI: align report tests with simple scientific layout --- tools/ci/test_collect_failed_comparisons.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tools/ci/test_collect_failed_comparisons.py b/tools/ci/test_collect_failed_comparisons.py index b0e785d73..6706b3f74 100644 --- a/tools/ci/test_collect_failed_comparisons.py +++ b/tools/ci/test_collect_failed_comparisons.py @@ -62,10 +62,13 @@ def test_failed_images_are_selected_and_linked(self) -> None: self.assertTrue((self.output / failed / filename).is_file()) self.assertIn(filename, (self.output / "index.html").read_text()) report = (self.output / "index.html").read_text(encoding="utf-8") - self.assertIn("See what changed.", report) - self.assertIn('id="search"', report) - self.assertIn('id="lightbox"', report) - self.assertIn('data-test="module.test_failed"', report) + self.assertIn("

    UltraPlot Image comparison

    ", report) + self.assertIn("1 failed image comparisons; 1 JUnit failures/errors.", report) + self.assertIn("
    Baseline
    ", report) + self.assertIn("
    Actual
    ", report) + self.assertIn("
    Difference
    ", report) + self.assertNotIn('id="search"', report) + self.assertNotIn('id="lightbox"', report) self.assertIn("Image mismatch", report) self.assertIn('href="results.json"', report) self.assertNotIn("module.test_passed", report) From baaa171414ecb534b70de0b0db17da0295a151e6 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 11:11:59 +1000 Subject: [PATCH 12/16] CI: use restrained dark header and tabular image comparison report --- tools/ci/failed_comparisons_template.html | 190 +++++++++++++++++----- 1 file changed, 147 insertions(+), 43 deletions(-) diff --git a/tools/ci/failed_comparisons_template.html b/tools/ci/failed_comparisons_template.html index cbc001229..d63bb2f7c 100644 --- a/tools/ci/failed_comparisons_template.html +++ b/tools/ci/failed_comparisons_template.html @@ -5,60 +5,164 @@ UltraPlot Image comparison -

    UltraPlot Image comparison

    -

    __ULTRAPLOT_IMAGE_COUNT__ failed image comparisons; __ULTRAPLOT_JUNIT_COUNT__ JUnit failures/errors.

    -

    results.json__ULTRAPLOT_JUNIT_DOWNLOAD__

    -
    - __ULTRAPLOT_CARDS__ - __ULTRAPLOT_JUNIT_DETAILS__ -
    +
    + +
    +
    +
    +

    Failed comparisons (__ULTRAPLOT_IMAGE_COUNT__)

    +

    Only failed image comparisons are included in this artifact.

    +
    +
    + JSON results__ULTRAPLOT_JUNIT_DOWNLOAD__ +
    +
    +
    + + + + + + __ULTRAPLOT_ROWS__ + +
    Test nameStatusRMSToleranceImages
    +
    + __ULTRAPLOT_JUNIT_DETAILS__ +
    +
    From 46abb01665bdfda202f41f3f8d780cad82641955 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 11:13:03 +1000 Subject: [PATCH 13/16] CI: populate dark report table and summary counts from JUnit --- tools/ci/collect_failed_comparisons.py | 143 +++++++++++++++++-------- 1 file changed, 98 insertions(+), 45 deletions(-) diff --git a/tools/ci/collect_failed_comparisons.py b/tools/ci/collect_failed_comparisons.py index 27e3eef46..b0221331d 100644 --- a/tools/ci/collect_failed_comparisons.py +++ b/tools/ci/collect_failed_comparisons.py @@ -1,7 +1,7 @@ -"""Create an artifact with only failed pytest-mpl image comparisons. +"""Collect failed pytest-mpl comparisons into a small HTML artifact. -Run pytest-mpl with --mpl-generate-summary=json (not HTML). The latter -implicitly enables --mpl-results-always and saves passing test images. +Use --mpl-generate-summary=json, not HTML, when running pytest-mpl. Its HTML +option implicitly enables --mpl-results-always and saves passing images. """ from __future__ import annotations @@ -9,8 +9,11 @@ import argparse import html import json +import platform import shutil import xml.etree.ElementTree as ET +from datetime import datetime, timezone +from importlib.metadata import PackageNotFoundError, version from pathlib import Path from urllib.parse import quote @@ -21,20 +24,38 @@ ) -def junit_failures(path: Path) -> list[str]: - """Include non-image failures, for which pytest-mpl has no image result.""" +def junit_report(path: Path) -> tuple[dict[str, int] | None, list[str]]: + """Return counts for the whole pytest run, excluding skipped tests.""" if not path.is_file(): - return [] - root = ET.parse(path).getroot() - return [ - f"{case.get('classname', '')}.{case.get('name', '')}".lstrip(".") - for case in root.iter("testcase") - if case.find("failure") is not None or case.find("error") is not None - ] + return None, [] + + try: + root = ET.parse(path).getroot() + except ET.ParseError: + # A cancelled test run might leave a truncated JUnit XML file. + return None, [] + + counts = {"passed": 0, "failed": 0, "errors": 0} + failures = [] + for case in root.iter("testcase"): + if case.find("error") is not None: + status = "errors" + elif case.find("failure") is not None: + status = "failed" + elif case.find("skipped") is not None: + continue + else: + status = "passed" + counts[status] += 1 + if status != "passed": + failures.append( + f"{case.get('classname', '')}.{case.get('name', '')}".lstrip(".") + ) + return counts, failures def collect(results_dir: Path, output_dir: Path) -> int: - """Return the number of failed pytest-mpl comparisons copied.""" + """Copy failed image comparisons and return their count.""" results_dir = results_dir.resolve() output_dir = output_dir.resolve() if output_dir == results_dir or results_dir in output_dir.parents: @@ -44,33 +65,39 @@ def collect(results_dir: Path, output_dir: Path) -> int: results = json.loads(summary.read_text(encoding="utf-8")) if summary.is_file() else {} if not isinstance(results, dict): raise ValueError("Unexpected pytest-mpl JSON summary format") + failed = {name: item for name, item in results.items() if item.get("status") == "failed"} junit = results_dir / "junit.xml" - test_failures = junit_failures(junit) + counts, junit_failures = junit_report(junit) - # An entirely green run should not produce an artifact, even an empty zip. - if not failed and not test_failures: - print("No failed image comparisons or JUnit tests; no artifact to upload.") + if not failed and not junit_failures: + print("No failed tests; no artifact to upload.") return 0 + if counts is None: + # The fallback covers image tests only; full-suite counts require JUnit. + counts = { + "passed": sum(item.get("status") == "passed" for item in results.values()), + "failed": len(failed), + "errors": 0, + } + output_dir.mkdir(parents=True, exist_ok=True) if junit.is_file(): shutil.copy2(junit, output_dir / "junit.xml") - (output_dir / "results.json").write_text( json.dumps(failed, indent=2) + "\n", encoding="utf-8" ) - # Copy only failed comparisons. Linked images can be opened at full size. - comparisons = [] - for name, item in sorted(failed.items()): + rows = [] + for index, (name, item) in enumerate(sorted(failed.items())): images = [] for field, label in _IMAGE_FIELDS: raw_path = item.get(field) if not raw_path: images.append( f'
    {html.escape(label)}
    ' - '

    Not available

    ' + 'Not available' ) continue @@ -86,47 +113,73 @@ def collect(results_dir: Path, output_dir: Path) -> int: alt = html.escape(f"{label} image for {name}", quote=True) images.append( f'
    {html.escape(label)}
    ' - f'{alt}
    ' + f'' + f'{alt}' ) - metrics = [] - for field, label in (("rms", "RMS"), ("tolerance", "Tolerance")): + def numeric(field: str) -> str: value = item.get(field) - if value is not None: - display = f"{value:.3f}" if isinstance(value, (int, float)) else str(value) - metrics.append(f"{label}: {html.escape(display)}") - - comparisons.append( - f'

    {html.escape(name)}

    ' - f'

    {" · ".join(metrics) if metrics else "No numerical comparison available"}

    ' - f'
    {"".join(images)}
    ' - f'
    Error details' - f'
    {html.escape(str(item.get("status_msg") or "No diagnostic text provided."))}
    ' - f'
    ' + if value is None: + return "—" + return html.escape(f"{value:.5g}" if isinstance(value, (int, float)) else str(value)) + + test_name = html.escape(name) + status_text = html.escape(str(item.get("image_status") or "Failed").capitalize()) + diagnostic = html.escape(str(item.get("status_msg") or "No diagnostic text provided.")) + expanded = " open" if index == 0 else "" + rows.extend([ + '' + f'{test_name}' + f'{status_text}' + f'{numeric("rms")}' + f'{numeric("tolerance")}' + f'
    {"".join(images)}
    ', + f'' + f'Test output
    {diagnostic}
    ' + '', + ]) + + if not rows: + rows.append( + '' + 'No failed image comparisons; see JUnit failures below.' ) - # JUnit includes failures not covered by pytest-mpl (which have no images). - junit_list = "".join(f"
  • {html.escape(name)}
  • " for name in test_failures) + junit_list = "".join( + f"
  • {html.escape(name)}
  • " for name in junit_failures + ) junit_details = ( - '
    All JUnit failures / errors ' - f'({len(test_failures)})
      {junit_list}
    ' - if test_failures else "" + '
    JUnit failures / errors ' + f'({len(junit_failures)})
      {junit_list}
    ' + if junit_failures else "" ) + + try: + matplotlib_version = version("matplotlib") + except PackageNotFoundError: + matplotlib_version = "unknown" + template = Path(__file__).with_name("failed_comparisons_template.html").read_text( encoding="utf-8" ) markup = template for marker, value in { + "__ULTRAPLOT_PASSED__": str(counts["passed"]), + "__ULTRAPLOT_FAILED__": str(counts["failed"]), + "__ULTRAPLOT_ERRORS__": str(counts["errors"]), "__ULTRAPLOT_IMAGE_COUNT__": str(len(failed)), - "__ULTRAPLOT_JUNIT_COUNT__": str(len(test_failures)), - "__ULTRAPLOT_CARDS__": "\n".join(comparisons), + "__ULTRAPLOT_GENERATED__": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"), + "__ULTRAPLOT_ENVIRONMENT__": html.escape( + f"Python {platform.python_version()} · Matplotlib {matplotlib_version}" + ), + "__ULTRAPLOT_ROWS__": "\n".join(rows), "__ULTRAPLOT_JUNIT_DETAILS__": junit_details, "__ULTRAPLOT_JUNIT_DOWNLOAD__": ( - ' · junit.xml' - if junit.is_file() else "" + ' · JUnit XML' if junit.is_file() else "" ), }.items(): markup = markup.replace(marker, value) + (output_dir / "index.html").write_text(markup, encoding="utf-8") print(f"Prepared {len(failed)} failed image comparisons in {output_dir}") return len(failed) From 7d565a148991b586ad1f66ba464a5250aa85ba72 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 11:13:20 +1000 Subject: [PATCH 14/16] CI: label all image comparison failures consistently --- tools/ci/collect_failed_comparisons.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/ci/collect_failed_comparisons.py b/tools/ci/collect_failed_comparisons.py index b0221331d..0e6cab493 100644 --- a/tools/ci/collect_failed_comparisons.py +++ b/tools/ci/collect_failed_comparisons.py @@ -124,7 +124,7 @@ def numeric(field: str) -> str: return html.escape(f"{value:.5g}" if isinstance(value, (int, float)) else str(value)) test_name = html.escape(name) - status_text = html.escape(str(item.get("image_status") or "Failed").capitalize()) + status_text = "Failed" diagnostic = html.escape(str(item.get("status_msg") or "No diagnostic text provided.")) expanded = " open" if index == 0 else "" rows.extend([ From ceee3922043fe41b0d0269a6d3f137742578e07b Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 11:13:58 +1000 Subject: [PATCH 15/16] CI: verify compact dark report layout and accurate JUnit counts --- tools/ci/test_collect_failed_comparisons.py | 35 +++++++++++++++++++-- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/tools/ci/test_collect_failed_comparisons.py b/tools/ci/test_collect_failed_comparisons.py index 6706b3f74..1501b4d32 100644 --- a/tools/ci/test_collect_failed_comparisons.py +++ b/tools/ci/test_collect_failed_comparisons.py @@ -51,7 +51,11 @@ def test_failed_images_are_selected_and_linked(self) -> None: encoding="utf-8", ) (self.results / "junit.xml").write_text( - '', + '' + '' + '' + '' + '', encoding="utf-8", ) @@ -63,10 +67,16 @@ def test_failed_images_are_selected_and_linked(self) -> None: self.assertIn(filename, (self.output / "index.html").read_text()) report = (self.output / "index.html").read_text(encoding="utf-8") self.assertIn("

    UltraPlot Image comparison

    ", report) - self.assertIn("1 failed image comparisons; 1 JUnit failures/errors.", report) + self.assertIn("

    Failed comparisons (1)

    ", report) + self.assertIn('
    1', report) + self.assertIn('
    1', report) + self.assertIn('
    0', report) + self.assertIn("RMS", report) self.assertIn("
    Baseline
    ", report) self.assertIn("
    Actual
    ", report) self.assertIn("
    Difference
    ", report) + self.assertIn('class="image-strip"', report) + self.assertIn("Test output", report) self.assertNotIn('id="search"', report) self.assertNotIn('id="lightbox"', report) self.assertIn("Image mismatch", report) @@ -93,6 +103,22 @@ def test_html_escapes_untrusted_test_names(self) -> None: self.assertIn("<script>", markup) self.assertIn("<img src=x", markup) + def test_junit_counts_include_errors_and_exclude_skips(self) -> None: + from collect_failed_comparisons import junit_report + + (self.results / "junit.xml").write_text( + '' + '' + '' + '' + '' + '', + encoding="utf-8", + ) + counts, failing = junit_report(self.results / "junit.xml") + self.assertEqual(counts, {"passed": 1, "failed": 1, "errors": 1}) + self.assertEqual(failing, ["b", "c"]) + def test_non_image_junit_failure_keeps_diagnostics(self) -> None: (self.results / "junit.xml").write_text( '', @@ -100,7 +126,10 @@ def test_non_image_junit_failure_keeps_diagnostics(self) -> None: ) self.assertEqual(collect(self.results, self.output), 0) self.assertTrue((self.output / "junit.xml").is_file()) - self.assertIn("module.test_crash", (self.output / "index.html").read_text()) + markup = (self.output / "index.html").read_text(encoding="utf-8") + self.assertIn("module.test_crash", markup) + self.assertIn("No failed image comparisons; see JUnit failures below.", markup) + self.assertIn('
    1', markup) if __name__ == "__main__": From 33ca88a93d7df31392b868843787f77412ac46ca Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 20 Oct 2026 11:50:50 +1000 Subject: [PATCH 16/16] test: remove intentional image comparison failure --- ultraplot/tests/test_inset.py | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/ultraplot/tests/test_inset.py b/ultraplot/tests/test_inset.py index 54033b659..a0b8a52a9 100644 --- a/ultraplot/tests/test_inset.py +++ b/ultraplot/tests/test_inset.py @@ -22,7 +22,7 @@ def test_inset_basic(): ylabel="ylabel", xticks=0.2, yticks=0.2, - title="CI ARTIFACT SMOKE TEST — INTENTIONAL IMAGE MISMATCH", + title="Title", suptitle="Complex arrangement of panels", toplabels=("Column 1", "Column 2"), abc=True, @@ -30,17 +30,6 @@ def test_inset_basic(): titleloc="uc", titleabove=False, ) - # TEMPORARY: Force a visible mismatch against the base-branch image so - # PR #850 produces an image-comparison artifact. REMOVE BEFORE MERGING. - fig.text( - 0.5, - 0.5, - "EXPECTED CI IMAGE FAILURE", - ha="center", - va="center", - fontsize=28, - color="magenta", - ) return fig