Skip to content

Commit

Permalink
Improve image compare code (scverse#2860)
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-sheep authored Feb 16, 2024
1 parent edfc7c6 commit 1ac74a7
Showing 1 changed file with 50 additions and 21 deletions.
71 changes: 50 additions & 21 deletions scanpy/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import sys
from pathlib import Path
from typing import TYPE_CHECKING
from textwrap import dedent
from typing import TYPE_CHECKING, TypedDict, Union, cast

import pytest

Expand Down Expand Up @@ -60,30 +61,58 @@ def imported_modules():
return IMPORTED


class CompareResult(TypedDict):
rms: float
expected: str
actual: str
diff: str
tol: int


@pytest.fixture
def check_same_image(add_nunit_attachment):
from matplotlib.testing.compare import compare_images, make_test_filename
from urllib.parse import quote

from matplotlib.testing.compare import compare_images

def _(pth1, pth2, *, tol: int, basename: str = ""):
def check_same_image(
expected: Path | os.PathLike,
actual: Path | os.PathLike,
*,
tol: int,
basename: str = "",
) -> None:
def fmt_descr(descr):
if basename != "":
return f"{descr} ({basename})"
else:
return descr

pth1, pth2 = Path(pth1), Path(pth2)
try:
result = compare_images(str(pth1), str(pth2), tol=tol)
assert result is None, result
except Exception as e:
diff_pth = make_test_filename(pth2, "failed-diff")
add_nunit_attachment(str(pth1), fmt_descr("Expected"))
add_nunit_attachment(str(pth2), fmt_descr("Result"))
if Path(diff_pth).is_file():
add_nunit_attachment(str(diff_pth), fmt_descr("Difference"))
raise e

return _
return f"{descr} ({basename})" if basename else descr

result = cast(
Union[CompareResult, None],
compare_images(str(expected), str(actual), tol=tol, in_decorator=True),
)
if result is None:
return

add_nunit_attachment(result["expected"], fmt_descr("Expected"))
add_nunit_attachment(result["actual"], fmt_descr("Result"))
add_nunit_attachment(result["diff"], fmt_descr("Difference"))

result_urls = {
k: f"file://{quote(v)}" if isinstance(v, str) else v
for k, v in result.items()
}
msg = dedent(
"""\
Image files did not match.
RMS Value: {rms}
Expected: {expected}
Actual: {actual}
Difference: {diff}
Tolerance: {tol}
"""
).format_map(result_urls)
raise AssertionError(msg)

return check_same_image


@pytest.fixture
Expand Down

0 comments on commit 1ac74a7

Please sign in to comment.