diff --git a/.github/workflows/build-ultraplot.yml b/.github/workflows/build-ultraplot.yml index 7778a0a5b..e7dc129d9 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,20 @@ jobs: exit "$status" fi - # Return the html output of the comparison even if failed + # 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' + 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 diff --git a/tools/ci/collect_failed_comparisons.py b/tools/ci/collect_failed_comparisons.py new file mode 100644 index 000000000..0e6cab493 --- /dev/null +++ b/tools/ci/collect_failed_comparisons.py @@ -0,0 +1,197 @@ +"""Collect failed pytest-mpl comparisons into a small HTML artifact. + +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 + +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 + +_IMAGE_FIELDS = ( + ("baseline_image", "Baseline"), + ("result_image", "Actual"), + ("diff_image", "Difference"), +) + + +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 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: + """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: + 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" + counts, junit_failures = junit_report(junit) + + 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" + ) + + 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
' + ) + 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) + alt = html.escape(f"{label} image for {name}", quote=True) + images.append( + f'
{html.escape(label)}
' + f'' + f'{alt}
' + ) + + def numeric(field: str) -> str: + value = item.get(field) + 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 = "Failed" + 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_list = "".join( + f"
  • {html.escape(name)}
  • " for name in junit_failures + ) + junit_details = ( + '
    JUnit failures / errors ' + f'({len(junit_failures)})
    ' + 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_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 "" + ), + }.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) + + +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() diff --git a/tools/ci/failed_comparisons_template.html b/tools/ci/failed_comparisons_template.html new file mode 100644 index 000000000..d63bb2f7c --- /dev/null +++ b/tools/ci/failed_comparisons_template.html @@ -0,0 +1,168 @@ + + + + + + UltraPlot Image comparison + + + +
    + +
    +
    +
    +

    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__ +
    +
    + + diff --git a/tools/ci/test_collect_failed_comparisons.py b/tools/ci/test_collect_failed_comparisons.py new file mode 100644 index 000000000..1501b4d32 --- /dev/null +++ b/tools/ci/test_collect_failed_comparisons.py @@ -0,0 +1,136 @@ +"""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()) + report = (self.output / "index.html").read_text(encoding="utf-8") + self.assertIn("

    UltraPlot Image comparison

    ", 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) + 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_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( + '', + encoding="utf-8", + ) + self.assertEqual(collect(self.results, self.output), 0) + self.assertTrue((self.output / "junit.xml").is_file()) + 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__": + unittest.main()