Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/specify_cli/bundles/yamlio.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ def load_json(path: Path) -> Any:
raise BundlerError(f"File not found: {path}")
try:
with path.open("r", encoding="utf-8") as handle:
return json.load(handle)
text = handle.read()
return json.loads(text.removeprefix("\ufeff"))
# JSONDecodeError stays FIRST: it and UnicodeDecodeError are sibling
# ValueError subclasses (neither subsumes the other), so malformed-but-
# decodable JSON keeps its more specific "Invalid JSON" message while a
Expand All @@ -128,7 +129,7 @@ def unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
return result

try:
return json.loads(text, object_pairs_hook=unique_object)
return json.loads(text.removeprefix("\ufeff"), object_pairs_hook=unique_object)
except json.JSONDecodeError as exc:
raise BundlerError(f"Invalid JSON from {origin}: {exc}") from exc

Expand Down
17 changes: 16 additions & 1 deletion tests/specify_cli/bundles/catalog/test_command_add.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import io # noqa: F401
import json # noqa: F401
import json
from pathlib import Path
from unittest.mock import patch # noqa: F401

Expand Down Expand Up @@ -40,3 +40,18 @@ def test_catalog_add_and_remove(project: Path):

removed = runner.invoke(app, ["bundle", "catalog", "remove", "local"])
assert removed.exit_code == 0


def test_catalog_add_and_search_accept_utf8_bom(project: Path):
catalog = project / "bom-catalog.json"
write_catalog_file(catalog, {"demo": catalog_entry_dict("demo")})
catalog.write_bytes(b"\xef\xbb\xbf" + catalog.read_bytes())

added = runner.invoke(
app, ["bundle", "catalog", "add", str(catalog), "--id", "bom"]
)
assert added.exit_code == 0, added.output

searched = runner.invoke(app, ["bundle", "search", "demo", "--offline", "--json"])
assert searched.exit_code == 0, searched.output
assert any(entry["id"] == "demo" for entry in json.loads(searched.output))
57 changes: 56 additions & 1 deletion tests/specify_cli/bundles/test_yamlio.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import pytest

from specify_cli.bundler import BundlerError
from specify_cli.bundles.yamlio import dump_yaml, load_json, load_yaml
from specify_cli.bundles.yamlio import dump_yaml, load_json, load_yaml, loads_json


def test_dump_yaml_preserves_unicode(tmp_path: Path):
Expand Down Expand Up @@ -56,3 +56,58 @@ def test_load_json_malformed_still_reports_invalid_json(tmp_path: Path):
path.write_text('{"bundles": [', encoding="utf-8")
with pytest.raises(BundlerError, match="Invalid JSON"):
load_json(path)


def test_load_json_accepts_single_utf8_bom(tmp_path: Path):
path = tmp_path / "records.json"
path.write_bytes(b"\xef\xbb\xbf" + '{"name": "café", "note": "\ufeff"}'.encode())
assert load_json(path) == {"name": "café", "note": "\ufeff"}


def test_load_json_reads_symlinked_file_outside_parent(tmp_path: Path):
target = tmp_path / "records.json"
target.write_text('{"name": "café"}', encoding="utf-8")
link_dir = tmp_path / "links"
link_dir.mkdir()
link = link_dir / "records.json"
try:
link.symlink_to(target)
except (OSError, NotImplementedError) as exc:
pytest.skip(f"cannot create symlink: {exc}")
assert load_json(link) == {"name": "café"}


@pytest.mark.parametrize(
"text",
[
'\ufeff\ufeff{"name": 1}',
' \ufeff{"name": 1}',
'\ufeff{"name": ',
],
)
def test_load_json_bom_does_not_hide_invalid_json(tmp_path: Path, text: str):
path = tmp_path / "records.json"
path.write_bytes(text.encode("utf-8"))
with pytest.raises(BundlerError, match="Invalid JSON"):
load_json(path)


def test_loads_json_accepts_single_leading_bom():
assert loads_json('\ufeff{"name": "café", "note": "\ufeff"}') == {
"name": "café",
"note": "\ufeff",
}


@pytest.mark.parametrize(
"text",
[
'\ufeff\ufeff{"name": 1}',
' \ufeff{"name": 1}',
'\ufeff{"name": ',
'\ufeff{"name": 1, "name": 2}',
],
)
def test_loads_json_bom_does_not_hide_invalid_json(text: str):
with pytest.raises(BundlerError, match="Invalid JSON"):
loads_json(text)
Loading