Raven-1/tests/test_utils_cairo.py
Zuyi Zhou 72fe7e4aa1
fix(*): find a homebrew libcairo and refuse an svg the ppt engine cannot draw (#719)
## Summary

On an Apple silicon Mac with Homebrew,
`ctypes.util.find_library('cairo')` returns None and `import cairosvg`
raises `OSError`; it only worked when the process was started with
`DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib`. `ppt_fetch` swallowed
that failure in `_rasterised_svg`, so a fetched SVG logo was saved as a
`.md` full of path data, with no `figure_id` and no log line. `raven
doctor` did not mention cairo at all. The design engine draws SVG
through Chromium and is not affected.

Head: b84764f33, on top of main at 8ee5ae0d8.

- **Finding libcairo.** New `raven/utils/cairo.py`. `libcairo_path()`
tries the default lookup and then `/opt/homebrew/lib`, `/usr/local/lib`
and `/opt/local/lib`. The `libcairo_reachable()` context manager adds
that directory to `DYLD_FALLBACK_LIBRARY_PATH` only while the import
runs, holding a lock, and puts back any value the user had set. This
works because `find_library` on macOS reads the variable from
`os.environ` at call time and then hands cairocffi an absolute path.
Loading the dylib by absolute path beforehand does not work (tried and
measured): dyld does not match a bare leaf name against an image that is
already loaded. The variable is set only around the import, so later
subprocesses do not inherit it. The `cairosvg` import itself lives in
the ppt engine (`_load_cairosvg`), because deptry refuses a core import
of a plugin-only dependency.
- **Clear failure instead of silent downgrade.** A download whose root
element is `<svg>` (after any XML declaration, comment or doctype) now
either becomes a PNG or is refused. If cairo cannot load, the fetch
fails with the first line of cairocffi's error and the install command.
If the SVG will not draw, the fetch fails with the parser's error. Both
cases log a warning and write nothing to the deck's sources. An HTML
page with inline `<svg>` icons stays an `.html` document and no longer
goes to the rasteriser; before, any text with `<svg` in its first 4 KB
did.
- **Doctor.** `External tools` gains a `Cairo:` row that shows the
library path, or `not found` with what that costs and the install
command. Like the LibreOffice row, it does not change the exit code.
`--json` carries `external_tools.cairo`.

Behaviour change: an SVG that cannot be drawn was kept as a text
document and is now refused. This is on purpose; path data was never
usable as a source.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Head b84764f33, rebased onto origin/main 8ee5ae0d8; the rebase replayed
both commits unchanged (`git range-diff` shows `=` for each) and the
focused command below reran at this head. The full-suite line is from
5f4051e8f on afdc04f89. The second commit answers the two review
findings: `_SVG_ROOT` allows a UTF-8 byte-order mark before the root
element (`_sniff(b"\xef\xbb\xbf<svg ...")` returned a document before,
and now returns a PNG, or a refusal without cairo), and the two
LibreOffice doctor tests read the LibreOffice row alone, so a runner
without libcairo no longer fails the healthy case on the Cairo row's
"not found".

```
uv run --frozen --python 3.12 --all-extras pytest -q tests/test_ppt_engine_fetch_tool.py tests/test_cli_doctor_commands.py tests/test_utils_cairo.py
  142 passed
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q -p no:cacheprovider
  25916 passed, 108 skipped, 1 failed: tests/test_rpc_files.py::test_a_host_without_libreoffice_says_so
  (local only and pre-existing: it fails the same way on origin/main afdc04f89 on this machine, which has
  LibreOffice installed; this branch does not touch rpc/files)
```

Revert-to-red for the second commit: without `\ufeff?` the new BOM test
fails; with `libcairo_path` forced to None across the doctor file (the
CI shape), the old LibreOffice assertion fails and the new one passes.

The numbers below are from the first head and are kept for the record.

```
uv run --frozen --all-extras pytest -q tests/test_utils_cairo.py tests/test_cli_doctor_commands.py tests/test_ppt_engine_fetch_tool.py
  141 passed
```

`test_a_brand_mark_arrives_as_svg_and_is_kept_as_a_picture` used to skip
on this machine (no DYLD variable set). It now runs and passes.
`test_cairosvg_imports_with_no_dyld_variable_where_brew_installed_cairo`
repeats the reported failure in a fresh interpreter with every `DYLD_*`
variable removed.

Revert-to-red: I restored the parent's `fetch.py` and
`doctor_commands.py`, kept the new tests, and 6 of them failed (both
doctor cairo tests, the refused-SVG tests, the declaration-prefixed SVG
test, and the end-to-end no-file-written test).

```
COLORTERM=truecolor uv run --frozen --python 3.12 --all-extras pytest -q
  25872 passed, 108 skipped   (before the rebase and the install-hint test)
make coverage
  25894 passed, 108 skipped   (at this head)
COVERAGE_BASE_REF=origin/main make coverage-diff
  Diff coverage: 100.00% (53/53 executable changed lines)
uv run --frozen --python 3.12 --extra dev ruff check raven evolver agents plugins-dist tests scripts
uv run --frozen --python 3.12 --extra dev ruff format --check raven evolver agents plugins-dist tests scripts
make lint-imports lint-deps lint-types
PYTHONPATH=. uv run --frozen --python 3.12 --extra dev python scripts/check_source_language.py origin/main...HEAD
make check-commits
COMMIT_RANGE=origin/main...HEAD make check-large-files
git diff --check origin/main...HEAD
  all clean
```

I have not run it on Linux or Windows locally. Off macOS
`libcairo_reachable()` does nothing and `libcairo_path()` is plain
`find_library`. The per-platform install hints are unit-tested.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

## Risk

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

`DYLD_FALLBACK_LIBRARY_PATH` affects the whole process, but it is only
changed inside the import block, under a lock, and is restored
afterwards. A fetched SVG that cannot be rasterised now returns `ok:
false` instead of landing as a document. Roll back by reverting this
commit.

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5-5) <noreply@anthropic.com>
2026-09-23 22:54:01 +08:00

99 lines
3.9 KiB
Python

"""Finding libcairo where Homebrew puts it, and importing cairosvg against it."""
from __future__ import annotations
import os
import subprocess
import sys
from importlib.util import find_spec
from pathlib import Path
import pytest
from raven.utils import cairo
@pytest.fixture()
def brew_prefix(monkeypatch, tmp_path: Path) -> Path:
"""A darwin host whose default lookup finds nothing and whose brew lib dir has cairo."""
lib = tmp_path / "homebrew" / "lib"
lib.mkdir(parents=True)
(lib / "libcairo.2.dylib").write_bytes(b"")
monkeypatch.setattr(cairo.sys, "platform", "darwin")
monkeypatch.setattr(cairo, "find_library", lambda name: None)
monkeypatch.setattr(cairo, "_DARWIN_LIBRARY_DIRS", (str(tmp_path / "absent"), str(lib)))
monkeypatch.delenv(cairo._FALLBACK_VAR, raising=False)
return lib
def test_a_homebrew_libcairo_the_default_lookup_misses_is_found(brew_prefix: Path) -> None:
assert cairo.libcairo_path() == str(brew_prefix / "libcairo.2.dylib")
def test_what_the_default_lookup_finds_wins(brew_prefix: Path, monkeypatch) -> None:
monkeypatch.setattr(cairo, "find_library", lambda name: "/usr/lib/libcairo.so.2" if name == "cairo" else None)
assert cairo.libcairo_path() == "/usr/lib/libcairo.so.2"
def test_no_libcairo_anywhere_is_none(monkeypatch, tmp_path: Path) -> None:
monkeypatch.setattr(cairo.sys, "platform", "darwin")
monkeypatch.setattr(cairo, "find_library", lambda name: None)
monkeypatch.setattr(cairo, "_DARWIN_LIBRARY_DIRS", (str(tmp_path),))
assert cairo.libcairo_path() is None
@pytest.mark.parametrize(
("platform", "hint"),
[("darwin", "brew install cairo"), ("linux", "apt install libcairo2"), ("win32", "GTK runtime")],
)
def test_the_install_hint_names_this_platforms_package(monkeypatch, platform: str, hint: str) -> None:
monkeypatch.setattr(cairo.sys, "platform", platform)
assert hint in cairo.install_hint()
def test_the_lookup_variable_is_held_only_inside_the_block(brew_prefix: Path) -> None:
"""Set for the import and gone after it, so a subprocess spawned later does not
inherit a library path nobody asked for."""
with cairo.libcairo_reachable():
inside = os.environ.get(cairo._FALLBACK_VAR)
assert inside == str(brew_prefix)
assert cairo._FALLBACK_VAR not in os.environ
def test_a_lookup_variable_the_user_set_is_kept_and_restored(brew_prefix: Path, monkeypatch) -> None:
monkeypatch.setenv(cairo._FALLBACK_VAR, "/their/lib")
with pytest.raises(OSError), cairo.libcairo_reachable():
inside = os.environ.get(cairo._FALLBACK_VAR)
raise OSError("the import failed")
assert inside == os.pathsep.join((str(brew_prefix), "/their/lib"))
assert os.environ[cairo._FALLBACK_VAR] == "/their/lib"
def test_a_host_whose_default_lookup_works_is_left_alone(brew_prefix: Path, monkeypatch) -> None:
monkeypatch.setattr(cairo, "find_library", lambda name: "/usr/lib/libcairo.so.2")
with cairo.libcairo_reachable():
assert cairo._FALLBACK_VAR not in os.environ
@pytest.mark.skipif(sys.platform != "darwin", reason="the dyld fallback path is macOS-only")
def test_cairosvg_imports_with_no_dyld_variable_where_brew_installed_cairo() -> None:
"""The reported failure, end to end, in a fresh interpreter: no DYLD variable set,
and a libcairo only under a Homebrew prefix."""
if find_spec("cairosvg") is None:
pytest.skip("cairosvg is the ppt engine's dependency and is not installed")
if cairo._darwin_library_dir() is None:
pytest.skip("no Homebrew or MacPorts libcairo on this host")
env = {k: v for k, v in os.environ.items() if not k.startswith("DYLD_")}
probe = "from raven.utils.cairo import libcairo_reachable\nwith libcairo_reachable():\n import cairosvg\nprint('loaded')"
result = subprocess.run([sys.executable, "-c", probe], env=env, capture_output=True, text=True)
assert result.stdout.strip() == "loaded", result.stdout + result.stderr